mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English (ASD-STE100): short sentences, one instruction per sentence, simple approved vocabulary, and the active voice. --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Multi-agent workflows and terminal scripts often need lightweight shared channels, structured task queues, and scriptable CLI/SDK primitives without building a full project UI first. > - Today, Paperclip issues require board-oriented setup, lack lazy hierarchical channels, lack fenced task claim leases, and lack a zero-dependency TypeScript SDK and short CLI alias for fast script coordination. > - Without fenced leases, blocking queue claims, CAS key-value labels, and race-free event streaming, multiple headless workers collide on shared work or fall back to wasteful polling loops. > - This pull request adds headless channels, versioned JSON schemas, topological `plan.json` batch creation, fenced task queues with `FOR UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI with `paperclipai up`. > - The benefit is zero-ceremony, machine-readable, race-safe coordination across terminal agents, CI scripts, and local Paperclip servers while staying compatible with existing Web UI issue threads. ## Linked Issues or Issue Description **Subsystem affected** Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`, `doc/`, `skills/`) **Problem or motivation** Agents and terminal workflows need a fast way to post updates, queue DAG tasks, claim work without double-execution, ask humans for approval, and wait on board events without browser setup or polling loops. Existing Paperclip routes assume UI-driven projects, lack fenced claim leases for pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk` client. **Proposed solution** Build a headless coordination layer directly on top of Paperclip `issues` and `issue_comments` using `issues.scope = 'channel'`: - **Database & Contracts (`packages/db`, `packages/shared`)**: Add `0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql` for lazy hierarchical `channels`, `channel_access_members`, immutable `company_schemas`, monotonic `board_events`, `scheduled_board_posts`, `issue_batch_idempotency_keys`, scoped `board_api_keys`, `agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`), including an in-memory test backend. - **Server APIs & Workers (`server/`)**: Add routes and services for progressive `--as` actor resolution (`open_local_profiles`, `delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth challenges, lazy channels, CAS `kv-labels`, versioned schemas, topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with fenced TTL renewal/release/complete/fail, one-line `ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming (`events/wait`, `events/stream`), and sleep-aware lease expiry and scheduled post workers. - **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc` binary alias and `paperclipai/sdk` export, add the zero-prompt `paperclipai up` / `pc up` local launcher, add `pc` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add `skills/paperclip-lite/SKILL.md`. **Alternatives considered** - **Separate message and queue tables outside `issues`**: Rejected because channel posts and queued tasks would lose Paperclip identifiers (`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue URLs (`/<prefix>/issues/PC-1`). - **Advisory locks or polling loops for task workers**: Rejected because advisory locks drop on reconnect across laptop sleep, and polling wastes tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)` TTL leases with `events/wait` and `waitSec` solve both safely. **Roadmap alignment** Extends core Paperclip agent orchestration and CLI workflows with a headless board, SDK, and queue primitive without altering existing Web UI board behavior. **Additional context** This PR builds on the `issues.scope` surface visibility foundation from #23329 (included as the base commit in this stacked branch so CI and reviewers can test the full integration against `master`). ## What Changed - **Schema & Migrations (`packages/db`)**: Added online-compatible migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`), and column extensions on `issues`, `issue_comments`, `companies`, `board_api_keys`, and `cli_auth_challenges`. - **Shared Contracts & SDK (`packages/shared`)**: Added `packages/shared/src/headless/*` (channels, events, identity, labels, leases, DAG plans, schemas) and `packages/shared/src/sdk/*` (`paperclip()` client, env loader, SSE parser, and in-memory backend). - **Server Routes & Services (`server/`)**: Added `headless-channels-schemas.ts`, `headless-queues-events.ts`, `headless-identity.ts` routes and supporting services (`headless-channels.ts`, `headless-common.ts`, `headless-events-schedules-interactions.ts`, `headless-identity.ts`, `headless-labels-batch.ts`, `headless-schemas.ts`, `headless-task-queue.ts`), plus `issues.scope` visibility isolation and `board-auth.ts` extensions. - **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and `paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and `cli/src/commands/board/*` commands (`post`, `reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent`). - **Docs, Skill & Runner Registry (`doc/`, `skills/`, `tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`, `doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs, `skills/paperclip-lite/SKILL.md`, and synchronized `tests/runner-e2e/source-sdk-public-inputs.json`. ## Verification - `pnpm --filter @paperclipai/shared build` — passed. - `pnpm --filter @paperclipai/db check:migrations` — passed (`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified online-compatible, 2 new migrations since `630cf0423024`, none blocked). - `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse HEAD) --check` — passed (`598` inputs, `changed: false`). - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests passed. - `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability IDs aligned). - `pnpm exec vitest run packages/shared/src/headless/headless.test.ts packages/shared/src/sdk/sdk.test.ts cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests passed. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-scope-visibility.test.ts src/__tests__/headless-channels-schemas-batch.test.ts src/__tests__/headless-identity-auth.test.ts src/__tests__/headless-queues-leases-events.test.ts src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests passed. - `pnpm --filter @paperclipai/shared typecheck && pnpm --filter @paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck && pnpm --filter paperclipai typecheck` — all passed. - `pnpm --filter paperclipai build` — passed. ## Risks - **Two new migrations (`0511`, `0512`)**: Both migrations are marked online-compatible (`NOT VALID` constraints validated afterwards, `CONCURRENTLY` index creation, idempotent statements for non-transactional execution) and checked by `check:migrations`. If #23329 lands separately with `0511` modified or renumbered, this branch will rebase on top cleanly. - **Large surface area (91 files)**: Changes are primarily additive new modules (`headless-*`, `cli/src/commands/board/*`, `packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing Web UI board behavior remains isolated via `issues.scope`. - **Full repository Vitest suite**: Only the targeted headless, SDK, CLI, server, and runner-e2e pin suites ran locally after rebasing; full cross-package CI checks will validate the remaining suite. ## Model Used - Google DeepMind Antigravity (Gemini coding agent) with tool use and code execution ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
43fedd51c5
commit
ea56320e10
100 files changed
+32616
-79
No files matched your search
@@ -36,7 +36,7 @@ describeEmbeddedPostgres("GET /api/companies/:companyId/skills statements per re
|
||||
expect(second.body).toEqual(first.body);
|
||||
expect(after.transactions - before.transactions).toBe(0);
|
||||
expect(log.filter((entry) => /pg_advisory/.test(entry.sql))).toEqual([]);
|
||||
expect(after.statements - before.statements).toBeLessThanOrEqual(45);
|
||||
expect(after.statements - before.statements).toBeLessThanOrEqual(48);
|
||||
expect(await bundledFolders(company.companyId)).toEqual(foldersAfterFirst);
|
||||
} finally {
|
||||
statements.uninstall();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
"conversationSessionGeneration": 0,
|
||||
"conversationBoundaryCommentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"channelId": null,
|
||||
"projectWorkspaceId": null,
|
||||
"goalId": null,
|
||||
"parentId": "<id:3>",
|
||||
@@ -32,7 +33,19 @@
|
||||
"executionLockedAt": null,
|
||||
"createdByAgentId": null,
|
||||
"createdByUserId": "<user>",
|
||||
"createdByProfile": null,
|
||||
"responsibleUserId": null,
|
||||
"kvLabels": {},
|
||||
"schemaBlocks": [],
|
||||
"resultSchemaRef": null,
|
||||
"claimEpoch": 0,
|
||||
"claimTokenHash": null,
|
||||
"claimHolderAgentId": null,
|
||||
"claimHolderUserId": null,
|
||||
"claimHolderProfile": null,
|
||||
"claimLeasedAt": null,
|
||||
"claimLeaseExpiresAt": null,
|
||||
"claimAttemptCount": 0,
|
||||
"issueNumber": null,
|
||||
"identifier": null,
|
||||
"originKind": "manual",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,506 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer, type IncomingMessage, type Server as HttpServer } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
createDb,
|
||||
getEmbeddedPostgresTestSupport,
|
||||
projects,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "@paperclipai/db";
|
||||
import { PaperclipError, paperclip } from "@paperclipai/shared/sdk";
|
||||
import { createApp } from "../app.js";
|
||||
import type { StorageService } from "../storage/types.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const CLI_TSX_BIN = path.resolve(__dirname, "../../../cli/node_modules/.bin/tsx");
|
||||
const CLI_ENTRY = path.resolve(__dirname, "../../../cli/src/index.ts");
|
||||
|
||||
const noopStorage: StorageService = {
|
||||
provider: "local_disk",
|
||||
putFile: async () => ({
|
||||
provider: "local_disk",
|
||||
objectKey: "noop",
|
||||
contentType: "application/octet-stream",
|
||||
byteSize: 0,
|
||||
sha256: "0".repeat(64),
|
||||
originalFilename: null,
|
||||
}),
|
||||
getObject: async () => {
|
||||
throw new Error("not used in headless e2e test");
|
||||
},
|
||||
headObject: async () => ({ exists: false }),
|
||||
deleteObject: async () => {},
|
||||
};
|
||||
|
||||
const external = process.env.PAPERCLIP_TEST_DATABASE_URL;
|
||||
const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
const databaseSuite = support.supported ? describe : describe.skip;
|
||||
|
||||
databaseSuite("Headless Paperclip full-stack E2E (createApp + SDK + pc CLI)", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let server: HttpServer;
|
||||
let apiBase: string;
|
||||
let tempHomeDir: string;
|
||||
let appShutdown: (() => Promise<void>) | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
tempHomeDir = await mkdtemp(path.join(os.tmpdir(), "pc-headless-e2e-"));
|
||||
if (external) {
|
||||
db = createDb(external);
|
||||
} else {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("headless-e2e-");
|
||||
db = createDb(temporary.connectionString);
|
||||
}
|
||||
|
||||
const app = await createApp(db, {
|
||||
uiMode: "none",
|
||||
serverPort: 0,
|
||||
storageService: noopStorage,
|
||||
deploymentMode: "local_trusted",
|
||||
deploymentExposure: "private",
|
||||
allowedHostnames: ["127.0.0.1", "localhost"],
|
||||
bindHost: "127.0.0.1",
|
||||
authReady: true,
|
||||
companyDeletionEnabled: true,
|
||||
decisionServiceOptions: {} as never,
|
||||
serverMetricsEnabled: false,
|
||||
localPluginDir: path.join(tempHomeDir, "empty-plugins"),
|
||||
});
|
||||
appShutdown = app.locals.paperclipShutdown as (() => Promise<void>) | undefined;
|
||||
|
||||
server = createServer(app);
|
||||
await new Promise<void>((resolve) => {
|
||||
server.listen(0, "127.0.0.1", () => resolve());
|
||||
});
|
||||
const addr = server.address() as AddressInfo;
|
||||
apiBase = `http://127.0.0.1:${addr.port}`;
|
||||
}, 90_000);
|
||||
|
||||
afterAll(async () => {
|
||||
if (server) {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
await appShutdown?.();
|
||||
await db?.$client.end();
|
||||
await temporary?.cleanup();
|
||||
if (tempHomeDir) {
|
||||
await rm(tempHomeDir, { recursive: true, force: true }).catch(() => {});
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("drives zero-ceremony channels, DAG queues, fenced leases, 1-liner ask/approve, CAS labels, and agent identity via paperclip() SDK", async () => {
|
||||
const pc = paperclip({ apiBase, homeDir: tempHomeDir });
|
||||
|
||||
// 1. Minute-0 post auto-resolves/creates default company + lazy #general channel
|
||||
const kickoff = await pc
|
||||
.as("lead")
|
||||
.post("general", "Ship v2\n\nAll headless primitives wired into createApp.", {
|
||||
labels: { release: "v2" },
|
||||
});
|
||||
expect(kickoff.channel).toBe("general");
|
||||
expect(kickoff.scope).toBe("channel");
|
||||
expect(kickoff.status).toBe("backlog");
|
||||
expect(kickoff.isPassivePost).toBe(true);
|
||||
expect(kickoff.actorProfile).toBe("lead");
|
||||
expect(kickoff.kvLabels).toEqual({ release: "v2" });
|
||||
|
||||
// Standard GET /api/issues/:id from a browser UI caller (with Referer) still returns the full standard Issue
|
||||
const uiRes = await fetch(`${apiBase}/api/issues/${kickoff.id}`, {
|
||||
headers: { referer: `${apiBase}/issues/${kickoff.identifier}` },
|
||||
});
|
||||
expect(uiRes.status).toBe(200);
|
||||
const uiIssue = (await uiRes.json()) as { id: string; identifier: string; scope: string };
|
||||
expect(uiIssue.id).toBe(kickoff.id);
|
||||
expect(uiIssue.scope).toBe("channel");
|
||||
|
||||
// Reply with --after optimistic concurrency
|
||||
const firstReply = await pc.as("reviewer").reply(kickoff.identifier, "Looks solid!");
|
||||
await expect(
|
||||
pc.as("other").reply(kickoff.identifier, "Stale reply", { after: "00000000-0000-0000-0000-000000000000" }),
|
||||
).rejects.toMatchObject({ status: 409, code: "stale_reply_cursor" });
|
||||
|
||||
const secondReply = await pc
|
||||
.as("lead")
|
||||
.reply(kickoff.identifier, "Confirmed after firstReply", { after: firstReply.id });
|
||||
expect(secondReply.actorProfile).toBe("lead");
|
||||
|
||||
const threadDetail = await pc.read(kickoff.identifier);
|
||||
expect(threadDetail.kind).toBe("thread");
|
||||
if (threadDetail.kind === "thread") {
|
||||
expect(threadDetail.comments.length).toBe(2);
|
||||
}
|
||||
|
||||
// 2. Create a real project so we can prove projectId resolution by slug on plan.json
|
||||
await db.insert(projects).values({
|
||||
companyId: kickoff.companyId,
|
||||
name: "Checkout Service",
|
||||
status: "in_progress",
|
||||
});
|
||||
|
||||
// 3. Register a custom immutable JSON Schema
|
||||
const schemaCreated = await pc.schemas.create({
|
||||
name: "smoke-summary",
|
||||
version: 1,
|
||||
jsonSchema: {
|
||||
type: "object",
|
||||
required: ["passed", "durationMs"],
|
||||
properties: {
|
||||
passed: { type: "boolean" },
|
||||
durationMs: { type: "integer", minimum: 0 },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
});
|
||||
expect(schemaCreated.created).toBe(true);
|
||||
|
||||
// 4. Submit a 2-step DAG plan with project slug + resultSchema
|
||||
const plan = await pc.as("planner").tasks.createPlan(
|
||||
"ci/checkout",
|
||||
[
|
||||
{
|
||||
key: "unit",
|
||||
title: "Run unit suite",
|
||||
priority: "high",
|
||||
labels: { stage: "test" },
|
||||
},
|
||||
{
|
||||
key: "e2e",
|
||||
title: "Run checkout smoke",
|
||||
needs: ["unit"],
|
||||
resultSchema: "smoke-summary@1",
|
||||
labels: { stage: "verify" },
|
||||
},
|
||||
],
|
||||
{
|
||||
projectId: "checkout-service",
|
||||
idempotencyKey: "plan-checkout-v1",
|
||||
},
|
||||
);
|
||||
expect(plan.tasks).toHaveLength(2);
|
||||
expect(plan.idempotentReplay).toBe(false);
|
||||
expect(plan.tasks[0]!.issue.projectId).toBeTruthy();
|
||||
|
||||
// Idempotent replay returns exact same tasks
|
||||
const planReplay = await pc.as("planner").tasks.createPlan(
|
||||
"ci/checkout",
|
||||
[
|
||||
{
|
||||
key: "unit",
|
||||
title: "Run unit suite",
|
||||
priority: "high",
|
||||
labels: { stage: "test" },
|
||||
},
|
||||
{
|
||||
key: "e2e",
|
||||
title: "Run checkout smoke",
|
||||
needs: ["unit"],
|
||||
resultSchema: "smoke-summary@1",
|
||||
labels: { stage: "verify" },
|
||||
},
|
||||
],
|
||||
{
|
||||
projectId: "checkout-service",
|
||||
idempotencyKey: "plan-checkout-v1",
|
||||
},
|
||||
);
|
||||
expect(planReplay.idempotentReplay).toBe(true);
|
||||
expect(planReplay.tasks[0]!.id).toBe(plan.tasks[0]!.id);
|
||||
|
||||
// 5. Claim from subtree "ci/" -> only "unit" is ready because "e2e" needs "unit"
|
||||
const claimedUnit = await pc.as("worker-a").tasks.claim({ channel: "ci/", ready: true });
|
||||
expect(claimedUnit).not.toBeNull();
|
||||
expect(claimedUnit!.task.title).toBe("Run unit suite");
|
||||
expect(await pc.as("worker-b").tasks.claim({ channel: "ci/", ready: true })).toBeNull();
|
||||
|
||||
// Start waiting for "e2e" to become ready, then complete "unit"
|
||||
const waitReadyPromise = pc.wait("ci/", {
|
||||
event: "task.ready",
|
||||
after: claimedUnit!.cursor,
|
||||
timeout: "5s",
|
||||
});
|
||||
await claimedUnit!.complete("Unit tests green");
|
||||
const readyEvent = await waitReadyPromise;
|
||||
expect(readyEvent).not.toBeNull();
|
||||
expect(readyEvent!.issueId).toBe(plan.tasks[1]!.id);
|
||||
|
||||
// 6. Claim "e2e", ask a humanOnly question (stateless pool auto-releases lease & blocks!), then approve
|
||||
const claimedE2e = await pc.as("worker-b").tasks.claim({ channel: "ci/", ready: true });
|
||||
expect(claimedE2e).not.toBeNull();
|
||||
expect(claimedE2e!.task.id).toBe(plan.tasks[1]!.id);
|
||||
|
||||
const asked = await claimedE2e!.ask("Approve production smoke target?", {
|
||||
humanOnly: true,
|
||||
});
|
||||
expect(asked.status).toBe("pending");
|
||||
|
||||
// Human approves -> requeues to todo!
|
||||
const approved = await pc.approve(claimedE2e!.task.identifier, {
|
||||
note: "Approved for staging-mirror",
|
||||
});
|
||||
expect(approved.status).toBe("answered");
|
||||
|
||||
// Re-claim unblocked "e2e" and verify resultSchema enforcement on complete
|
||||
const reclaimedE2e = await pc.as("worker-c").tasks.claim({ channel: "ci/", ready: true });
|
||||
expect(reclaimedE2e).not.toBeNull();
|
||||
expect(reclaimedE2e!.claimEpoch).toBeGreaterThan(claimedE2e!.claimEpoch);
|
||||
|
||||
await expect(
|
||||
reclaimedE2e!.complete({ data: { passed: "wrong-type" } as never }),
|
||||
).rejects.toMatchObject({ status: 422, code: "result_schema_validation_failed" });
|
||||
|
||||
const completedE2e = await reclaimedE2e!.complete({
|
||||
message: "Smoke passed",
|
||||
data: { passed: true, durationMs: 412 },
|
||||
});
|
||||
expect(completedE2e.status).toBe("done");
|
||||
|
||||
// 7. Atomic CAS label update
|
||||
const casOk = await pc.label(completedE2e.identifier, {
|
||||
set: { stage: "shipped" },
|
||||
if: { stage: "verify" },
|
||||
});
|
||||
expect(casOk.kvLabels.stage).toBe("shipped");
|
||||
|
||||
await expect(
|
||||
pc.label(completedE2e.identifier, {
|
||||
set: { stage: "duplicate" },
|
||||
if: { stage: "verify" },
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 409, code: "label_conflict" });
|
||||
|
||||
// 8. Connect a registered headless agent "@guard" -> unauthenticated --as guard fails 409!
|
||||
const connectRes = await fetch(
|
||||
`${apiBase}/api/companies/${kickoff.companyId}/agents/connect`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ name: "guard", role: "security" }),
|
||||
},
|
||||
);
|
||||
expect(connectRes.status).toBe(201);
|
||||
const connected = (await connectRes.json()) as { apiKey: string; agentId: string };
|
||||
|
||||
await expect(pc.as("guard").whoami()).rejects.toBeInstanceOf(PaperclipError);
|
||||
await expect(pc.as("guard").whoami()).rejects.toMatchObject({
|
||||
status: 409,
|
||||
code: "profile_matches_registered_agent",
|
||||
});
|
||||
|
||||
const authedGuard = paperclip({
|
||||
apiBase,
|
||||
apiKey: connected.apiKey,
|
||||
homeDir: tempHomeDir,
|
||||
});
|
||||
const guardWhoami = await authedGuard.whoami();
|
||||
expect(guardWhoami.principalType).toBe("agent");
|
||||
expect(guardWhoami.agentId).toBe(connected.agentId);
|
||||
expect(guardWhoami.agentName).toBe("guard");
|
||||
}, 90_000);
|
||||
|
||||
it("drives `pc` CLI persona including `tasks run` lease wrapper end-to-end", async () => {
|
||||
const cliEnv = {
|
||||
...process.env,
|
||||
HOME: tempHomeDir,
|
||||
PAPERCLIP_HOME: path.join(tempHomeDir, ".paperclip"),
|
||||
PAPERCLIP_API_URL: apiBase,
|
||||
PAPERCLIP_CLI_PERSONA: "pc",
|
||||
};
|
||||
|
||||
const runCli = async (args: string[]) => {
|
||||
const { stdout } = await execFileAsync(CLI_TSX_BIN, [CLI_ENTRY, ...args], {
|
||||
env: cliEnv,
|
||||
timeout: 20_000,
|
||||
});
|
||||
return stdout.trim();
|
||||
};
|
||||
|
||||
const whoamiJson = JSON.parse(await runCli(["whoami", "--json"])) as {
|
||||
companyPrefix: string;
|
||||
principalType: string;
|
||||
};
|
||||
expect(whoamiJson.companyPrefix).toBe("PC");
|
||||
expect(whoamiJson.principalType).toBe("local_trusted");
|
||||
|
||||
const posted = JSON.parse(
|
||||
await runCli([
|
||||
"post",
|
||||
"deploys",
|
||||
"Deployed commit abc1234",
|
||||
"--as",
|
||||
"release-bot",
|
||||
"--label",
|
||||
"env=staging",
|
||||
"--json",
|
||||
]),
|
||||
) as { identifier: string; channel: string; isPassivePost: boolean };
|
||||
expect(posted.channel).toBe("deploys");
|
||||
expect(posted.isPassivePost).toBe(true);
|
||||
|
||||
// Human-formatted `pc read <id>` omits `[backlog]` on passive posts and does not fail on tagLabels
|
||||
const humanReadPost = await runCli(["read", posted.identifier]);
|
||||
expect(humanReadPost).toContain(posted.identifier);
|
||||
expect(humanReadPost).not.toContain("[backlog]");
|
||||
|
||||
// `pc channels list [prefix]`, `pc label --set --if k=null`, `pc schemas` / `get` / `create --version --schema`
|
||||
const channelsOut = await runCli(["channels", "list", "deploys"]);
|
||||
expect(channelsOut).toContain("#deploys");
|
||||
const labelOut = await runCli([
|
||||
"label",
|
||||
posted.identifier,
|
||||
"--set",
|
||||
"stage=verified",
|
||||
"--if",
|
||||
"stage=null",
|
||||
]);
|
||||
expect(labelOut).toContain("stage=verified");
|
||||
await runCli([
|
||||
"schemas",
|
||||
"create",
|
||||
"cli-smoke",
|
||||
"--version",
|
||||
"1",
|
||||
"--schema",
|
||||
'{"type":"object","required":["ok"],"properties":{"ok":{"type":"boolean"}}}',
|
||||
]);
|
||||
const schemaInspect = await runCli(["schemas", "get", "cli-smoke@1"]);
|
||||
expect(schemaInspect).toContain("cli-smoke@1");
|
||||
|
||||
const createdTask = JSON.parse(
|
||||
await runCli([
|
||||
"tasks",
|
||||
"create",
|
||||
"runner-pool",
|
||||
"Execute child wrapper test",
|
||||
"--label",
|
||||
"suite=cli",
|
||||
"--json",
|
||||
]),
|
||||
) as { id: string; identifier: string; status: string };
|
||||
expect(createdTask.status).toBe("todo");
|
||||
|
||||
// `pc tasks` and `pc tasks list` without --channel include open channel tasks
|
||||
const tasksDefaultOut = await runCli(["tasks"]);
|
||||
expect(tasksDefaultOut).toContain(createdTask.identifier);
|
||||
const tasksListOut = await runCli(["tasks", "list", "--label", "suite=cli"]);
|
||||
expect(tasksListOut).toContain(createdTask.identifier);
|
||||
|
||||
// `pc ask --choices --human-only` + `pc approve --answer` + `pc schedule list` / `cancel`
|
||||
await runCli([
|
||||
"ask",
|
||||
createdTask.identifier,
|
||||
"Proceed with wrapper run?",
|
||||
"--choices",
|
||||
"yes,no",
|
||||
"--human-only",
|
||||
"--as",
|
||||
"pool-runner",
|
||||
]);
|
||||
await runCli(["approve", createdTask.identifier, "--answer", "yes"]);
|
||||
const afterApproveRead = await runCli(["read", createdTask.identifier]);
|
||||
expect(afterApproveRead).toContain("-> yes");
|
||||
|
||||
const schedId = await runCli([
|
||||
"schedule",
|
||||
"deploys",
|
||||
"Delayed check",
|
||||
"--in",
|
||||
"10m",
|
||||
"--post",
|
||||
"-q",
|
||||
]);
|
||||
const schedListOut = await runCli(["schedule", "list"]);
|
||||
expect(schedListOut).toContain(schedId);
|
||||
await runCli(["schedule", "cancel", schedId]);
|
||||
|
||||
// `pc wait` WITHOUT --after ignores historical `posted` in #deploys and blocks for the next new event!
|
||||
const livePoster = paperclip({ apiBase, homeDir: tempHomeDir }).as("cron-bot");
|
||||
let waitRequestSeen = false;
|
||||
let notifyWaitRequest: (() => void) | null = null;
|
||||
const waitRequestArrived = new Promise<void>((resolve) => {
|
||||
notifyWaitRequest = resolve;
|
||||
});
|
||||
const onServerRequest = (req: IncomingMessage) => {
|
||||
if (!waitRequestSeen && req.url?.includes("/events/wait")) {
|
||||
waitRequestSeen = true;
|
||||
notifyWaitRequest?.();
|
||||
}
|
||||
};
|
||||
server.on("request", onServerRequest);
|
||||
let postInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let waitedPing: { identifier: string | null; actor: { profile: string | null } };
|
||||
try {
|
||||
const waitPromise = runCli([
|
||||
"wait",
|
||||
"deploys",
|
||||
"--event",
|
||||
"thread.posted",
|
||||
"--timeout",
|
||||
"15s",
|
||||
"--json",
|
||||
]);
|
||||
await waitRequestArrived;
|
||||
postInterval = setInterval(() => {
|
||||
void livePoster.post("deploys", "Scheduled live ping");
|
||||
}, 250);
|
||||
waitedPing = JSON.parse(await waitPromise) as {
|
||||
identifier: string | null;
|
||||
actor: { profile: string | null };
|
||||
};
|
||||
} finally {
|
||||
server.off("request", onServerRequest);
|
||||
if (postInterval) clearInterval(postInterval);
|
||||
}
|
||||
expect(waitedPing.actor.profile).toBe("cron-bot");
|
||||
expect(waitedPing.identifier).not.toBe(posted.identifier);
|
||||
|
||||
// `pc agent connect` redacts PAPERCLIP_API_KEY on stdout while saving real key in 0600 profile
|
||||
const connectStdout = await runCli([
|
||||
"agent",
|
||||
"connect",
|
||||
"cli-scanner",
|
||||
"--role",
|
||||
"engineer",
|
||||
"--ttl",
|
||||
"7d",
|
||||
]);
|
||||
expect(connectStdout).toContain("pcp_••••••••");
|
||||
expect(connectStdout).not.toMatch(/PAPERCLIP_API_KEY='pcp_[A-Za-z0-9_-]{10,}'/);
|
||||
const scannerWho = JSON.parse(await runCli(["whoami", "--as", "cli-scanner", "--json"])) as {
|
||||
principalType: string;
|
||||
agentName: string | null;
|
||||
};
|
||||
expect(scannerWho.principalType).toBe("agent");
|
||||
expect(scannerWho.agentName).toBe("cli-scanner");
|
||||
|
||||
// `pc tasks run` claims the task, injects PAPERCLIP_* env vars, runs child with shell: false, and completes it!
|
||||
await runCli([
|
||||
"tasks",
|
||||
"run",
|
||||
"--channel",
|
||||
"runner-pool",
|
||||
"--as",
|
||||
"pool-runner",
|
||||
"--lease",
|
||||
"60s",
|
||||
"--",
|
||||
process.execPath,
|
||||
"-e",
|
||||
"if (!process.env.PAPERCLIP_TASK_ID || !process.env.PAPERCLIP_CLAIM_TOKEN) process.exit(2);",
|
||||
]);
|
||||
|
||||
const pc = paperclip({ apiBase, homeDir: tempHomeDir });
|
||||
const afterRun = await pc.read(createdTask.identifier);
|
||||
expect(afterRun.kind).toBe("thread");
|
||||
if (afterRun.kind === "thread") {
|
||||
expect(afterRun.issue.status).toBe("done");
|
||||
}
|
||||
}, 90_000);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -72,6 +72,9 @@ const apiPrefixes: Record<string, string> = {
|
||||
"folders.ts": "/api",
|
||||
"goals.ts": "/api",
|
||||
"health.ts": "/api/health",
|
||||
"headless-channels-schemas.ts": "/api",
|
||||
"headless-identity.ts": "/api",
|
||||
"headless-queues-events.ts": "/api",
|
||||
"ready.ts": "/api/ready",
|
||||
"liveness.ts": "/api/liveness",
|
||||
"inbox-agent-policy.ts": "/api",
|
||||
|
||||
@@ -1011,6 +1011,29 @@ const piLocalAdapter: ServerAdapterModule = {
|
||||
agentConfigurationDoc: piAgentConfigurationDoc,
|
||||
};
|
||||
|
||||
const headlessAdapter: ServerAdapterModule = {
|
||||
type: "headless",
|
||||
runtimeToolDelivery: "invocation_context",
|
||||
execute: async (ctx) => {
|
||||
ctx.onDispatch?.();
|
||||
return { exitCode: 0, signal: null, timedOut: false };
|
||||
},
|
||||
testEnvironment: async () => ({
|
||||
adapterType: "headless",
|
||||
status: "pass",
|
||||
checks: [],
|
||||
testedAt: new Date().toISOString(),
|
||||
}),
|
||||
models: [],
|
||||
supportsLocalAgentJwt: false,
|
||||
agentConfigurationDoc: `# headless agent configuration
|
||||
|
||||
Adapter: headless (Headless (CLI / SDK))
|
||||
|
||||
Pull-only headless identity. Headless agents pull tasks and subscribe to board events using their agent API key rather than being spawned by the heartbeat runner.
|
||||
`,
|
||||
};
|
||||
|
||||
const adaptersByType = new Map<string, ServerAdapterModule>();
|
||||
|
||||
// For builtin types that are overridden by an external adapter, we keep the
|
||||
@@ -1040,6 +1063,7 @@ function registerBuiltInAdapters() {
|
||||
openclawGatewayAdapter,
|
||||
processAdapter,
|
||||
httpAdapter,
|
||||
headlessAdapter,
|
||||
]) {
|
||||
adaptersByType.set(adapter.type, adapter);
|
||||
}
|
||||
@@ -1140,7 +1164,7 @@ export function registerServerAdapter(adapter: ServerAdapterModule): void {
|
||||
|
||||
export function unregisterServerAdapter(type: string): void {
|
||||
assertExternalAdapterCodeAllowed();
|
||||
if (type === processAdapter.type || type === httpAdapter.type) return;
|
||||
if (type === processAdapter.type || type === httpAdapter.type || type === headlessAdapter.type) return;
|
||||
if (builtinFallbacks.has(type)) {
|
||||
pausedOverrides.delete(type);
|
||||
const fallback = builtinFallbacks.get(type);
|
||||
@@ -1249,9 +1273,9 @@ export function listServerAdapters(): ServerAdapterModule[] {
|
||||
*/
|
||||
export function listEnabledServerAdapters(disabled: string[]): ServerAdapterModule[] {
|
||||
const disabledSet = disabled.length > 0 ? new Set(disabled) : null;
|
||||
return disabledSet
|
||||
? Array.from(adaptersByType.values()).filter((a) => !disabledSet.has(a.type))
|
||||
: Array.from(adaptersByType.values());
|
||||
return Array.from(adaptersByType.values()).filter(
|
||||
(a) => a.type !== headlessAdapter.type && (!disabledSet || !disabledSet.has(a.type)),
|
||||
);
|
||||
}
|
||||
|
||||
export async function detectAdapterModel(
|
||||
|
||||
@@ -131,6 +131,11 @@ import { environmentService } from "./services/environments.js";
|
||||
import { environmentRuntimeService } from "./services/environment-runtime.js";
|
||||
import { projectRoutes } from "./routes/projects.js";
|
||||
import { issueRoutes } from "./routes/issues.js";
|
||||
import { headlessIdentityRoutes } from "./routes/headless-identity.js";
|
||||
import { headlessChannelsSchemasRoutes } from "./routes/headless-channels-schemas.js";
|
||||
import { headlessQueuesEventsRoutes } from "./routes/headless-queues-events.js";
|
||||
import { createClaimLeaseExpiryWorker } from "./services/headless-task-queue.js";
|
||||
import { createScheduledBoardPostsWorker } from "./services/headless-events-schedules-interactions.js";
|
||||
import { linkPreviewRoutes } from "./routes/link-previews.js";
|
||||
import { issueTreeControlRoutes } from "./routes/issue-tree-control.js";
|
||||
import { caseRoutes } from "./routes/cases.js";
|
||||
@@ -777,6 +782,7 @@ export async function createApp(
|
||||
api.use(openApiRoutes());
|
||||
api.use("/cloud", cloudRoutes());
|
||||
api.use(cloudInferenceRoutes(db, cloudTrialInferenceController));
|
||||
api.use(headlessIdentityRoutes(db, { deploymentMode: opts.deploymentMode }));
|
||||
api.use("/companies", companyRoutes(db, opts.storageService));
|
||||
api.use(llmRoutes(db));
|
||||
api.use(folderRoutes(db));
|
||||
@@ -1003,6 +1009,11 @@ export async function createApp(
|
||||
// Issue routes are intentionally mounted after the gateway is constructed because
|
||||
// issue approval endpoints delegate to it. The intervening routers use distinct
|
||||
// route prefixes, so this dependency does not change issue-route precedence.
|
||||
api.use(headlessChannelsSchemasRoutes(db, { deploymentMode: opts.deploymentMode }));
|
||||
api.use(headlessQueuesEventsRoutes(db, {
|
||||
deploymentMode: opts.deploymentMode,
|
||||
heartbeat: heartbeatService(db, { pluginWorkerManager: workerManager }),
|
||||
}));
|
||||
api.use(issueRoutes(db, opts.storageService, {
|
||||
chatRunRetries: chatChannels,
|
||||
pluginWorkerManager: workerManager,
|
||||
@@ -1415,6 +1426,8 @@ export async function createApp(
|
||||
const importSpoolCleanup = registerImportSpoolCleanupWork(db, deliveryWork,
|
||||
resolveDefaultImportTransferSpoolRoot(), () => !isWarmStandby() && !isIdleTaskDrainActive());
|
||||
registerBrowserUseCleanup(deliveryWork, browserUse, () => !isIdleTaskDrainActive());
|
||||
deliveryWork.register(DELIVERY_QUEUES.claimLeaseExpiry, createClaimLeaseExpiryWorker(db).deliveryTask);
|
||||
deliveryWork.register(DELIVERY_QUEUES.scheduledBoardPosts, createScheduledBoardPostsWorker(db).deliveryTask);
|
||||
|
||||
|
||||
void companyTransferRunService
|
||||
|
||||
@@ -383,19 +383,32 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
|
||||
const access = await boardAuth.resolveBoardAccess(boardKey.userId);
|
||||
if (access.user) {
|
||||
await boardAuth.touchBoardApiKey(boardKey.id);
|
||||
const scopedCompanyIds = boardKey.companyId
|
||||
? access.companyIds.filter((id) => id === boardKey.companyId)
|
||||
: access.companyIds;
|
||||
const scopedMemberships = boardKey.companyId
|
||||
? access.memberships.filter((m) => m.companyId === boardKey.companyId)
|
||||
: access.memberships;
|
||||
const hasKeyRestriction = Boolean(
|
||||
boardKey.companyId || boardKey.lockedProfile || boardKey.scopes,
|
||||
);
|
||||
req.actor = {
|
||||
type: "board",
|
||||
userId: boardKey.userId,
|
||||
userName: access.user?.name ?? null,
|
||||
userEmail: access.user?.email ?? null,
|
||||
companyIds: access.companyIds,
|
||||
memberships: access.memberships,
|
||||
isInstanceAdmin: access.isInstanceAdmin,
|
||||
companyIds: scopedCompanyIds,
|
||||
memberships: scopedMemberships,
|
||||
isInstanceAdmin: hasKeyRestriction ? false : access.isInstanceAdmin,
|
||||
ignoreInstanceAdmin: hasKeyRestriction ? true : undefined,
|
||||
keyId: boardKey.id,
|
||||
keyCompanyId: boardKey.companyId ?? null,
|
||||
keyLockedProfile: boardKey.lockedProfile ?? null,
|
||||
keyScopes: boardKey.scopes ?? null,
|
||||
runId: runIdHeader || undefined,
|
||||
source: "board_key",
|
||||
};
|
||||
if (isCloudManagedInstance() && (access.isInstanceAdmin || access.companyIds.length)) {
|
||||
if (isCloudManagedInstance() && (!hasKeyRestriction && access.isInstanceAdmin || scopedCompanyIds.length)) {
|
||||
_res.once("finish", () => { if (_res.statusCode >= 200 && _res.statusCode < 400) idleApiActivity.record(); });
|
||||
}
|
||||
next();
|
||||
@@ -407,7 +420,7 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
|
||||
.select()
|
||||
.from(agentApiKeys)
|
||||
.where(and(eq(agentApiKeys.keyHash, hashToken(token)), isNull(agentApiKeys.revokedAt)))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
.then((rows) => rows.find((row) => !row.expiresAt || row.expiresAt.getTime() > Date.now()) ?? null);
|
||||
|
||||
if (!key) {
|
||||
const claims = verifiedClaims;
|
||||
|
||||
@@ -63,6 +63,45 @@ export async function requestAgentHireInTransaction(tx: Db, effects: LifecycleEf
|
||||
return records.create(...args);
|
||||
}
|
||||
|
||||
export async function createHeadlessAgentInTransaction(
|
||||
tx: Db,
|
||||
effects: LifecycleEffects,
|
||||
input: {
|
||||
companyId: string;
|
||||
name: string;
|
||||
role: string;
|
||||
createdByUserId: string | null;
|
||||
},
|
||||
) {
|
||||
if (!("nestedIndex" in tx)) {
|
||||
throw new AgentLifecycleConflict("Headless agent creation requires a database transaction");
|
||||
}
|
||||
const [inserted] = await tx
|
||||
.insert(agents)
|
||||
.values({
|
||||
companyId: input.companyId,
|
||||
name: input.name,
|
||||
role: input.role,
|
||||
adapterType: "headless",
|
||||
status: "active",
|
||||
lifecycleState: "ready",
|
||||
lifecycleVersion: 1,
|
||||
lifecycleHolds: [],
|
||||
runtimeConfig: {
|
||||
heartbeat: {
|
||||
enabled: false,
|
||||
wakeOnAssignment: false,
|
||||
wakeOnOnDemand: false,
|
||||
wakeOnAutomation: false,
|
||||
},
|
||||
},
|
||||
createdByUserId: input.createdByUserId,
|
||||
})
|
||||
.returning();
|
||||
await effects.recordCreation(tx, input.companyId, inserted!.id);
|
||||
return inserted!;
|
||||
}
|
||||
|
||||
export function createAgentLifecycle(db: Db, effects: LifecycleEffects) {
|
||||
assertRootDatabase(db);
|
||||
const records = agentRecords(db, effects);
|
||||
|
||||
+224
-11
@@ -18,11 +18,13 @@ import { fileURLToPath } from "node:url";
|
||||
import { Router } from "express";
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
import { and, desc, eq, gt, inArray, isNotNull, isNull, lte, ne } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
assets,
|
||||
agentApiKeys,
|
||||
authUsers,
|
||||
boardApiKeys,
|
||||
companies,
|
||||
companyLogos,
|
||||
companyMemberships,
|
||||
@@ -34,6 +36,7 @@ import {
|
||||
import {
|
||||
EXTERNAL_AGENT_TOOL_GUIDANCE,
|
||||
acceptInviteSchema,
|
||||
clientScopesSchema,
|
||||
createCliAuthChallengeSchema,
|
||||
claimJoinRequestApiKeySchema,
|
||||
createBoardApiKeySchema,
|
||||
@@ -60,6 +63,11 @@ import {
|
||||
badRequest,
|
||||
tooManyRequests
|
||||
} from "../errors.js";
|
||||
import {
|
||||
actionMatchesScopePattern,
|
||||
actionScopePatternCovers,
|
||||
channelScopePatternCovers,
|
||||
} from "../services/headless-common.js";
|
||||
import { getHiddenSettings } from "../services/settings-visibility.js";
|
||||
import { runtimeCanonicalOrigin } from "../services/cloud-runtime-identity.js";
|
||||
|
||||
@@ -2715,10 +2723,32 @@ export function accessRoutes(
|
||||
res.json({ claimed: true, userId: claimed.userId });
|
||||
});
|
||||
|
||||
const createCliAuthChallengeBodySchema = createCliAuthChallengeSchema
|
||||
.extend({
|
||||
challengeKind: z.enum(["board", "agent_key"]).optional().default("board"),
|
||||
agentName: z.string().trim().min(1).max(120).optional().nullable(),
|
||||
agentRole: z.string().trim().min(1).max(60).optional().nullable(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.challengeKind === "agent_key" && !value.agentName?.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "agentName is required when challengeKind is 'agent_key'",
|
||||
path: ["agentName"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const createBoardApiKeyBodySchema = createBoardApiKeySchema.extend({
|
||||
companyId: z.string().guid().optional().nullable(),
|
||||
lockedProfile: z.string().trim().min(1).max(120).optional().nullable(),
|
||||
scopes: clientScopesSchema.optional().nullable(),
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/cli-auth/challenges",
|
||||
limitCliAuth(cliAuthCreateRateLimiter),
|
||||
validate(createCliAuthChallengeSchema),
|
||||
validate(createCliAuthChallengeBodySchema),
|
||||
async (req, res) => {
|
||||
const created = await boardAuth.createCliAuthChallenge(req.body);
|
||||
const approvalPath = buildCliAuthApprovalPath(
|
||||
@@ -2770,6 +2800,43 @@ export function accessRoutes(
|
||||
});
|
||||
});
|
||||
|
||||
async function resolveCallingBoardKeyRestrictions(req: Request): Promise<{
|
||||
companyId: string | null;
|
||||
lockedProfile: string | null;
|
||||
scopes: { channels?: string[]; actions?: string[] } | null;
|
||||
}> {
|
||||
let callingKey: {
|
||||
companyId: string | null;
|
||||
lockedProfile: string | null;
|
||||
scopes: { channels?: string[]; actions?: string[] } | null;
|
||||
} | null = null;
|
||||
if (req.actor.source === "board_key" && req.actor.keyId) {
|
||||
const [row] = await db
|
||||
.select({
|
||||
companyId: boardApiKeys.companyId,
|
||||
lockedProfile: boardApiKeys.lockedProfile,
|
||||
scopes: boardApiKeys.scopes,
|
||||
})
|
||||
.from(boardApiKeys)
|
||||
.where(eq(boardApiKeys.id, req.actor.keyId));
|
||||
callingKey = row ?? null;
|
||||
}
|
||||
return {
|
||||
companyId: callingKey?.companyId ?? req.actor.keyCompanyId ?? null,
|
||||
lockedProfile:
|
||||
callingKey?.lockedProfile?.trim() || req.actor.keyLockedProfile?.trim() || null,
|
||||
scopes: callingKey?.scopes ?? req.actor.keyScopes ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function hasBoardKeyRestrictions(restrictions: {
|
||||
companyId: string | null;
|
||||
lockedProfile: string | null;
|
||||
scopes: { channels?: string[]; actions?: string[] } | null;
|
||||
}): boolean {
|
||||
return Boolean(restrictions.companyId || restrictions.lockedProfile || restrictions.scopes);
|
||||
}
|
||||
|
||||
router.post(
|
||||
"/cli-auth/challenges/:id/approve",
|
||||
validate(resolveCliAuthChallengeSchema),
|
||||
@@ -2781,6 +2848,16 @@ export function accessRoutes(
|
||||
) {
|
||||
throw unauthorized("Sign in before approving CLI access");
|
||||
}
|
||||
if (
|
||||
req.actor.source !== "session" &&
|
||||
req.actor.source !== "cloud_tenant" &&
|
||||
!isLocalImplicit(req)
|
||||
) {
|
||||
throw forbidden(
|
||||
"Board API keys cannot approve CLI authentication challenges; sign in via browser",
|
||||
{ code: "forbidden" },
|
||||
);
|
||||
}
|
||||
if (!isUuidLike(id)) throw badRequest("Invalid CLI auth challenge ID");
|
||||
|
||||
const userId = req.actor.userId ?? "local-board";
|
||||
@@ -2795,6 +2872,8 @@ export function accessRoutes(
|
||||
status: approved.status,
|
||||
userId,
|
||||
keyId: approved.challenge.boardApiKeyId ?? null,
|
||||
agentId: approved.challenge.approvedAgentId ?? null,
|
||||
companyId: approved.challenge.requestedCompanyId ?? null,
|
||||
expiresAt: approved.challenge.expiresAt.toISOString(),
|
||||
});
|
||||
},
|
||||
@@ -2819,14 +2898,33 @@ export function accessRoutes(
|
||||
throw unauthorized("Board authentication required");
|
||||
}
|
||||
const accessSnapshot = await boardAuth.resolveBoardAccess(req.actor.userId);
|
||||
let isInstanceAdmin =
|
||||
req.actor.source === "cloud_tenant"
|
||||
? req.actor.isInstanceAdmin === true
|
||||
: accessSnapshot.isInstanceAdmin;
|
||||
let companyIds = accessSnapshot.companyIds;
|
||||
let memberships = accessSnapshot.memberships;
|
||||
|
||||
if (req.actor.source === "board_key") {
|
||||
const restrictions = await resolveCallingBoardKeyRestrictions(req);
|
||||
if (hasBoardKeyRestrictions(restrictions)) {
|
||||
isInstanceAdmin = false;
|
||||
const actorCompanyIds = req.actor.companyIds ?? [];
|
||||
companyIds = restrictions.companyId
|
||||
? actorCompanyIds.filter((cid) => cid === restrictions.companyId)
|
||||
: actorCompanyIds;
|
||||
memberships = accessSnapshot.memberships.filter((m) =>
|
||||
companyIds.includes(m.companyId),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
user: accessSnapshot.user,
|
||||
userId: req.actor.userId,
|
||||
isInstanceAdmin: req.actor.source === "cloud_tenant"
|
||||
? req.actor.isInstanceAdmin === true
|
||||
: accessSnapshot.isInstanceAdmin,
|
||||
companyIds: accessSnapshot.companyIds,
|
||||
memberships: accessSnapshot.memberships,
|
||||
isInstanceAdmin,
|
||||
companyIds,
|
||||
memberships,
|
||||
source: req.actor.source ?? "none",
|
||||
keyId: req.actor.source === "board_key" ? req.actor.keyId ?? null : null,
|
||||
});
|
||||
@@ -2836,6 +2934,14 @@ export function accessRoutes(
|
||||
if (req.actor.type !== "board" || !req.actor.userId) {
|
||||
throw unauthorized("Board authentication required");
|
||||
}
|
||||
if (req.actor.source === "board_key") {
|
||||
const restrictions = await resolveCallingBoardKeyRestrictions(req);
|
||||
if (hasBoardKeyRestrictions(restrictions)) {
|
||||
throw forbidden("Restricted board API keys cannot manage other board API keys", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
const keys = await boardAuth.listBoardApiKeys(req.actor.userId, {
|
||||
includeInactive: req.query.includeInactive === "true",
|
||||
});
|
||||
@@ -2844,24 +2950,121 @@ export function accessRoutes(
|
||||
|
||||
router.post(
|
||||
"/board-api-keys",
|
||||
validate(createBoardApiKeySchema),
|
||||
validate(createBoardApiKeyBodySchema),
|
||||
async (req, res) => {
|
||||
if (req.actor.type !== "board" || !req.actor.userId) {
|
||||
throw unauthorized("Board authentication required");
|
||||
}
|
||||
|
||||
if (req.body.requestedCompanyId) {
|
||||
assertCompanyAccess(req, req.body.requestedCompanyId);
|
||||
const targetCompanyId = req.body.companyId ?? req.body.requestedCompanyId ?? null;
|
||||
if (targetCompanyId) {
|
||||
assertCompanyAccess(req, targetCompanyId);
|
||||
}
|
||||
let nextCompanyId = req.body.companyId;
|
||||
let nextLockedProfile = req.body.lockedProfile;
|
||||
let nextScopes = req.body.scopes;
|
||||
if (req.actor.source === "board_key") {
|
||||
const {
|
||||
companyId: effectiveCallerCompanyId,
|
||||
lockedProfile: effectiveCallerLockedProfile,
|
||||
scopes: effectiveCallerScopes,
|
||||
} = await resolveCallingBoardKeyRestrictions(req);
|
||||
|
||||
if (effectiveCallerScopes?.actions) {
|
||||
const allowed = effectiveCallerScopes.actions.some((pattern) =>
|
||||
actionMatchesScopePattern("board_keys.create", pattern),
|
||||
);
|
||||
if (!allowed) {
|
||||
throw forbidden("Caller scopes do not allow creating board API keys", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
if (effectiveCallerCompanyId) {
|
||||
if (req.body.companyId === null || (targetCompanyId && effectiveCallerCompanyId !== targetCompanyId)) {
|
||||
throw forbidden("Board API key is scoped to another company", {
|
||||
code: "company_scope_denied",
|
||||
});
|
||||
}
|
||||
nextCompanyId = effectiveCallerCompanyId;
|
||||
}
|
||||
if (effectiveCallerLockedProfile) {
|
||||
if (req.body.lockedProfile === null) {
|
||||
throw forbidden("Profile-locked board API key cannot mint an unlocked key", {
|
||||
code: "profile_locked",
|
||||
});
|
||||
}
|
||||
if (
|
||||
req.body.lockedProfile !== undefined &&
|
||||
req.body.lockedProfile.trim().toLowerCase() !==
|
||||
effectiveCallerLockedProfile.toLowerCase()
|
||||
) {
|
||||
throw forbidden(
|
||||
`Board API key is locked to profile '${effectiveCallerLockedProfile}'`,
|
||||
{ code: "profile_locked" },
|
||||
);
|
||||
}
|
||||
nextLockedProfile = effectiveCallerLockedProfile;
|
||||
}
|
||||
if (effectiveCallerScopes) {
|
||||
if (req.body.scopes === null) {
|
||||
throw forbidden("Scoped board API key cannot mint an unrestricted key", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
if (req.body.scopes === undefined) {
|
||||
nextScopes = effectiveCallerScopes;
|
||||
} else {
|
||||
const requestedScopes = req.body.scopes;
|
||||
if (effectiveCallerScopes.channels) {
|
||||
if (!requestedScopes.channels) {
|
||||
throw forbidden("Child key must retain caller channel restrictions", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
const allCovered = requestedScopes.channels.every((ch: string) =>
|
||||
effectiveCallerScopes.channels!.some((allowed) =>
|
||||
channelScopePatternCovers(allowed, ch),
|
||||
),
|
||||
);
|
||||
if (!allCovered) {
|
||||
throw forbidden("Child key channels exceed caller key scopes", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
if (effectiveCallerScopes.actions) {
|
||||
if (!requestedScopes.actions) {
|
||||
throw forbidden("Child key must retain caller action restrictions", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
const allCovered = requestedScopes.actions.every((act: string) =>
|
||||
effectiveCallerScopes.actions!.some((allowed) =>
|
||||
actionScopePatternCovers(allowed, act),
|
||||
),
|
||||
);
|
||||
if (!allCovered) {
|
||||
throw forbidden("Child key actions exceed caller key scopes", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const key = await boardAuth.createNamedBoardApiKey({
|
||||
userId: req.actor.userId,
|
||||
name: req.body.name,
|
||||
expiresAt: req.body.expiresAt === undefined ? undefined : req.body.expiresAt,
|
||||
...(nextCompanyId !== undefined ? { companyId: nextCompanyId } : {}),
|
||||
...(nextLockedProfile !== undefined ? { lockedProfile: nextLockedProfile } : {}),
|
||||
...(nextScopes !== undefined ? { scopes: nextScopes } : {}),
|
||||
});
|
||||
const companyIds = await boardAuth.resolveBoardActivityCompanyIds({
|
||||
userId: req.actor.userId,
|
||||
requestedCompanyId: req.body.requestedCompanyId ?? null,
|
||||
requestedCompanyId: targetCompanyId,
|
||||
boardApiKeyId: key.id,
|
||||
});
|
||||
for (const companyId of companyIds) {
|
||||
@@ -2875,7 +3078,9 @@ export function accessRoutes(
|
||||
details: {
|
||||
boardApiKeyId: key.id,
|
||||
name: key.name,
|
||||
requestedCompanyId: req.body.requestedCompanyId ?? null,
|
||||
companyId: key.companyId ?? null,
|
||||
lockedProfile: key.lockedProfile ?? null,
|
||||
requestedCompanyId: targetCompanyId,
|
||||
expiresAt: key.expiresAt?.toISOString() ?? null,
|
||||
},
|
||||
});
|
||||
@@ -2893,6 +3098,14 @@ export function accessRoutes(
|
||||
if (!isUuidLike(keyId)) {
|
||||
throw badRequest("Invalid board API key ID");
|
||||
}
|
||||
if (req.actor.source === "board_key") {
|
||||
const restrictions = await resolveCallingBoardKeyRestrictions(req);
|
||||
if (hasBoardKeyRestrictions(restrictions)) {
|
||||
throw forbidden("Restricted board API keys cannot manage other board API keys", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
const key = await boardAuth.getBoardApiKeyForUser(keyId, req.actor.userId);
|
||||
if (!key) throw notFound("Board API key not found");
|
||||
const revoked = await boardAuth.revokeBoardApiKey(key.id, { userId: req.actor.userId, revokedVia: "board_api_key_lifecycle" });
|
||||
|
||||
@@ -6243,8 +6243,17 @@ export function agentRoutes(
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
function assertBoardKeyCanManageAgentKeys(req: Request) {
|
||||
if (req.actor.source === "board_key" && (req.actor.keyLockedProfile || req.actor.keyScopes)) {
|
||||
throw forbidden("Scoped or profile-locked board API keys cannot manage agent API keys", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
router.get("/agents/:id/keys", async (req, res) => {
|
||||
assertBoard(req);
|
||||
assertBoardKeyCanManageAgentKeys(req);
|
||||
const id = req.params.id as string;
|
||||
const agent = await getAccessibleAgent(req, res, id);
|
||||
if (!agent) {
|
||||
@@ -6256,6 +6265,7 @@ export function agentRoutes(
|
||||
|
||||
router.post("/agents/:id/keys", validate(createAgentKeySchema), async (req, res) => {
|
||||
assertBoard(req);
|
||||
assertBoardKeyCanManageAgentKeys(req);
|
||||
const id = req.params.id as string;
|
||||
const agent = await getAccessibleAgent(req, res, id);
|
||||
if (!agent) {
|
||||
@@ -6285,6 +6295,7 @@ export function agentRoutes(
|
||||
|
||||
router.delete("/agents/:id/keys/:keyId", async (req, res) => {
|
||||
assertBoard(req);
|
||||
assertBoardKeyCanManageAgentKeys(req);
|
||||
const id = req.params.id as string;
|
||||
const keyId = req.params.keyId as string;
|
||||
const agent = await getAccessibleAgent(req, res, id);
|
||||
|
||||
@@ -239,6 +239,25 @@ export function assertCompanyAccess(req: Request, companyId: string) {
|
||||
}
|
||||
}
|
||||
if (req.actor.type === "board" && req.actor.source !== "local_implicit") {
|
||||
if (req.actor.source === "board_key") {
|
||||
if (req.actor.keyCompanyId && req.actor.keyCompanyId !== companyId) {
|
||||
throw forbidden("Board API key is scoped to another company", {
|
||||
code: "company_scope_denied",
|
||||
});
|
||||
}
|
||||
if (req.actor.keyScopes) {
|
||||
const hasChannelRestriction = Array.isArray(req.actor.keyScopes.channels);
|
||||
const actionsList = req.actor.keyScopes.actions;
|
||||
const allowsWildcardAction =
|
||||
Array.isArray(actionsList) &&
|
||||
actionsList.some((action) => action.trim() === "*");
|
||||
if (hasChannelRestriction || (Array.isArray(actionsList) && !allowsWildcardAction)) {
|
||||
throw forbidden("Scoped board API key cannot access unrestricted company routes", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const allowedCompanies = req.actor.companyIds ?? [];
|
||||
if (!allowedCompanies.includes(companyId)) {
|
||||
throw forbidden("User does not have access to this company");
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,68 @@
|
||||
import { Router } from "express";
|
||||
import { z } from "zod";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agentIdentityPolicySchema, type DeploymentMode } from "@paperclipai/shared";
|
||||
import { validate } from "../middleware/validate.js";
|
||||
import { headlessIdentityService } from "../services/headless-identity.js";
|
||||
|
||||
const connectAgentBodySchema = z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
role: z.string().trim().min(1).max(60).optional(),
|
||||
ttlSec: z.number().int().positive().optional(),
|
||||
});
|
||||
|
||||
const updateAgentIdentityPolicyBodySchema = z.object({
|
||||
agentIdentityPolicy: agentIdentityPolicySchema,
|
||||
});
|
||||
|
||||
export function headlessIdentityRoutes(
|
||||
db: Db,
|
||||
opts: { deploymentMode?: DeploymentMode } = {},
|
||||
) {
|
||||
const router = Router();
|
||||
const svc = headlessIdentityService(db, opts);
|
||||
|
||||
router.get("/companies/resolve-default", async (req, res) => {
|
||||
const companyQuery =
|
||||
typeof req.query.company === "string" ? req.query.company : undefined;
|
||||
const resolved = await svc.resolveDefaultCompany(req, companyQuery);
|
||||
res.json(resolved);
|
||||
});
|
||||
|
||||
router.get("/whoami", async (req, res) => {
|
||||
const companyIdQuery =
|
||||
typeof req.query.companyId === "string"
|
||||
? req.query.companyId
|
||||
: typeof req.query.company === "string"
|
||||
? req.query.company
|
||||
: undefined;
|
||||
const info = await svc.whoami(req, companyIdQuery);
|
||||
res.json(info);
|
||||
});
|
||||
|
||||
router.post(
|
||||
"/companies/:companyId/agents/connect",
|
||||
validate(connectAgentBodySchema),
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const connected = await svc.connectAgent(req, companyId, req.body);
|
||||
res.status(201).json(connected);
|
||||
},
|
||||
);
|
||||
|
||||
router.patch(
|
||||
"/companies/:companyId/agent-identity-policy",
|
||||
validate(updateAgentIdentityPolicyBodySchema),
|
||||
async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const updated = await svc.updateAgentIdentityPolicy(
|
||||
req,
|
||||
companyId,
|
||||
req.body.agentIdentityPolicy,
|
||||
);
|
||||
res.json(updated);
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,599 @@
|
||||
import { Router, type Request, type Response } from "express";
|
||||
import { type Db } from "@paperclipai/db";
|
||||
import {
|
||||
parseDurationMs,
|
||||
type BoardEventType,
|
||||
type BoardEventView,
|
||||
type DeploymentMode,
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, notFound, unauthorized } from "../errors.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import {
|
||||
assertCanonicalIssueAccess,
|
||||
assertIssueChannelScopeAccess,
|
||||
resolveHeadlessActor,
|
||||
resolveHeadlessIssueReadCondition,
|
||||
resolveIssueByIdOrIdentifier,
|
||||
subscribeCompanyBoardEvents,
|
||||
type HeadlessActorContext,
|
||||
} from "../services/headless-common.js";
|
||||
import {
|
||||
claimTask,
|
||||
completeTaskClaim,
|
||||
failTaskClaim,
|
||||
releaseTaskClaim,
|
||||
renewTaskClaim,
|
||||
} from "../services/headless-task-queue.js";
|
||||
import {
|
||||
approveOnIssue,
|
||||
cancelSchedule,
|
||||
confirmOnIssue,
|
||||
createSchedule,
|
||||
eventMatchesFiltersAndAccess,
|
||||
getCurrentCompanyMaxEventSeq,
|
||||
listSchedules,
|
||||
parseBoardEventFilters,
|
||||
queryBoardEventsAfter,
|
||||
rejectOnIssue,
|
||||
askOnIssue,
|
||||
waitForBoardEvent,
|
||||
type BoardEventFilterInput,
|
||||
} from "../services/headless-events-schedules-interactions.js";
|
||||
|
||||
function toCommaSplitStrings(value: unknown): string[] {
|
||||
if (typeof value === "string") {
|
||||
return value
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.flatMap((v) => (typeof v === "string" ? v.split(",") : []))
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function toStringList(value: unknown): string[] {
|
||||
if (typeof value === "string") {
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? [trimmed] : [];
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value
|
||||
.filter((v): v is string => typeof v === "string")
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function parseEventQuery(
|
||||
req: Request,
|
||||
fallbackAfter?: string,
|
||||
): BoardEventFilterInput {
|
||||
const channel =
|
||||
typeof req.query.channel === "string" ? req.query.channel : undefined;
|
||||
const issueId =
|
||||
typeof req.query.issueId === "string" ? req.query.issueId : undefined;
|
||||
const eventList = toCommaSplitStrings(req.query.event) as BoardEventType[];
|
||||
const labelList = toStringList(req.query.label);
|
||||
const mentions =
|
||||
typeof req.query.mentions === "string" ? req.query.mentions : undefined;
|
||||
const schema =
|
||||
typeof req.query.schema === "string" ? req.query.schema : undefined;
|
||||
const after =
|
||||
typeof req.query.after === "string" && req.query.after.trim() !== ""
|
||||
? req.query.after.trim()
|
||||
: fallbackAfter?.trim() || undefined;
|
||||
|
||||
return {
|
||||
...(channel ? { channel } : {}),
|
||||
...(issueId ? { issueId } : {}),
|
||||
...(eventList.length > 0 ? { event: eventList } : {}),
|
||||
...(labelList.length > 0 ? { label: labelList } : {}),
|
||||
...(mentions ? { mentions } : {}),
|
||||
...(schema ? { schema } : {}),
|
||||
...(after ? { after } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function parseOptionalTimeoutMs(req: Request): number | undefined {
|
||||
if (typeof req.query.timeoutMs === "string" && req.query.timeoutMs.trim() !== "") {
|
||||
const num = Number(req.query.timeoutMs);
|
||||
if (!Number.isFinite(num) || num < 0) {
|
||||
throw badRequest("Invalid timeoutMs query parameter");
|
||||
}
|
||||
return Math.floor(num);
|
||||
}
|
||||
if (typeof req.query.timeout === "string" && req.query.timeout.trim() !== "") {
|
||||
try {
|
||||
return parseDurationMs(req.query.timeout);
|
||||
} catch (err) {
|
||||
throw badRequest(
|
||||
err instanceof Error ? err.message : "Invalid timeout query parameter",
|
||||
);
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function resolveIssueAndActor(
|
||||
db: Db,
|
||||
req: Request,
|
||||
idOrIdentifier: string,
|
||||
deploymentMode: DeploymentMode | undefined,
|
||||
requiredAction: string,
|
||||
canonicalAction: "issue:read" | "issue:comment" | "issue:mutate" = "issue:mutate",
|
||||
): Promise<{ issue: Awaited<ReturnType<typeof resolveIssueByIdOrIdentifier>>; actor: HeadlessActorContext }> {
|
||||
if (!req.actor || req.actor.type === "none") {
|
||||
throw unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const expectedCompanyId =
|
||||
req.actor.type === "agent" ? req.actor.companyId ?? undefined : undefined;
|
||||
const issue = await resolveIssueByIdOrIdentifier(
|
||||
db,
|
||||
idOrIdentifier,
|
||||
expectedCompanyId,
|
||||
);
|
||||
|
||||
if (
|
||||
req.actor.type === "board" &&
|
||||
req.actor.source !== "local_implicit" &&
|
||||
!req.actor.isInstanceAdmin &&
|
||||
!(req.actor.companyIds ?? []).includes(issue.companyId)
|
||||
) {
|
||||
throw notFound(`Issue '${idOrIdentifier}' not found`);
|
||||
}
|
||||
|
||||
const actor = await resolveHeadlessActor(db, req, issue.companyId, {
|
||||
deploymentMode,
|
||||
requiredAction,
|
||||
});
|
||||
|
||||
await assertCanonicalIssueAccess(db, req, issue, canonicalAction);
|
||||
await assertIssueChannelScopeAccess(db, issue, actor);
|
||||
|
||||
return { issue, actor };
|
||||
}
|
||||
|
||||
function formatSseFrame(ev: BoardEventView): string {
|
||||
return `id: ${ev.cursor}\nevent: ${ev.type}\ndata: ${JSON.stringify(ev)}\n\n`;
|
||||
}
|
||||
|
||||
export function headlessQueuesEventsRoutes(
|
||||
db: Db,
|
||||
opts?: {
|
||||
deploymentMode?: DeploymentMode;
|
||||
heartbeat?: ReturnType<typeof heartbeatService>;
|
||||
},
|
||||
) {
|
||||
const router = Router();
|
||||
const deploymentMode = opts?.deploymentMode;
|
||||
const heartbeat = opts?.heartbeat ?? heartbeatService(db);
|
||||
|
||||
const buildWakeHandler = () => async (wake: {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
assigneeAgentId: string;
|
||||
interactionId: string;
|
||||
interactionKind: string;
|
||||
interactionStatus: string;
|
||||
sourceCommentId: string | null;
|
||||
actor: HeadlessActorContext;
|
||||
}) => {
|
||||
await heartbeat.wakeup(wake.assigneeAgentId, {
|
||||
source: "automation",
|
||||
triggerDetail: "system",
|
||||
reason: "issue_commented",
|
||||
payload: {
|
||||
issueId: wake.issueId,
|
||||
interactionId: wake.interactionId,
|
||||
interactionKind: wake.interactionKind,
|
||||
interactionStatus: wake.interactionStatus,
|
||||
sourceCommentId: wake.sourceCommentId,
|
||||
mutation: "interaction",
|
||||
},
|
||||
idempotencyKey: `interaction:${wake.interactionId}:${wake.interactionStatus}`,
|
||||
requestedByActorType: wake.actor.principalType === "agent" ? "agent" : "user",
|
||||
requestedByActorId:
|
||||
wake.actor.principalType === "agent"
|
||||
? wake.actor.agentId ?? "unknown-agent"
|
||||
: wake.actor.userId ?? "board",
|
||||
contextSnapshot: {
|
||||
issueId: wake.issueId,
|
||||
taskId: wake.issueId,
|
||||
interactionId: wake.interactionId,
|
||||
interactionKind: wake.interactionKind,
|
||||
interactionStatus: wake.interactionStatus,
|
||||
wakeReason: "issue_commented",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
router.post("/companies/:companyId/tasks/claim", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
requiredAction: "tasks.claim",
|
||||
});
|
||||
|
||||
const ac = new AbortController();
|
||||
const onClose = () => {
|
||||
if (!res.writableFinished) {
|
||||
ac.abort();
|
||||
}
|
||||
};
|
||||
res.on("close", onClose);
|
||||
|
||||
try {
|
||||
const readCondition = await resolveHeadlessIssueReadCondition(db, req);
|
||||
const claimed = await claimTask(db, companyId, actor, req.body, ac.signal, {
|
||||
readCondition,
|
||||
});
|
||||
if (res.writableFinished || ac.signal.aborted) return;
|
||||
if (!claimed) {
|
||||
res.status(204).end();
|
||||
return;
|
||||
}
|
||||
res.json(claimed);
|
||||
} finally {
|
||||
res.off("close", onClose);
|
||||
}
|
||||
});
|
||||
|
||||
router.post("/issues/:id/claim/renew", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"tasks.claim_renew",
|
||||
);
|
||||
const result = await renewTaskClaim(
|
||||
db,
|
||||
issue.id,
|
||||
actor,
|
||||
req.body,
|
||||
req.header("x-paperclip-claim-token") ?? undefined,
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/claim/release", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"tasks.claim_release",
|
||||
);
|
||||
const result = await releaseTaskClaim(
|
||||
db,
|
||||
issue.id,
|
||||
actor,
|
||||
req.body,
|
||||
req.header("x-paperclip-claim-token") ?? undefined,
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/claim/complete", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"tasks.complete",
|
||||
);
|
||||
const result = await completeTaskClaim(
|
||||
db,
|
||||
issue.id,
|
||||
actor,
|
||||
req.body,
|
||||
req.header("x-paperclip-claim-token") ?? undefined,
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/claim/fail", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"tasks.fail",
|
||||
);
|
||||
const result = await failTaskClaim(
|
||||
db,
|
||||
issue.id,
|
||||
actor,
|
||||
req.body,
|
||||
req.header("x-paperclip-claim-token") ?? undefined,
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/ask", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"interactions.create",
|
||||
);
|
||||
const result = await askOnIssue(
|
||||
db,
|
||||
issue.id,
|
||||
actor,
|
||||
req.body,
|
||||
req.header("x-paperclip-claim-token") ?? undefined,
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/confirm", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"interactions.create",
|
||||
);
|
||||
const result = await confirmOnIssue(
|
||||
db,
|
||||
issue.id,
|
||||
actor,
|
||||
req.body,
|
||||
req.header("x-paperclip-claim-token") ?? undefined,
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/approve", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"interactions.resolve",
|
||||
);
|
||||
const result = await approveOnIssue(db, issue.id, actor, req.body, {
|
||||
onWakeAssignee: buildWakeHandler(),
|
||||
});
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/issues/:id/reject", async (req, res) => {
|
||||
const { issue, actor } = await resolveIssueAndActor(
|
||||
db,
|
||||
req,
|
||||
req.params.id as string,
|
||||
deploymentMode,
|
||||
"interactions.resolve",
|
||||
);
|
||||
const result = await rejectOnIssue(db, issue.id, actor, req.body, {
|
||||
onWakeAssignee: buildWakeHandler(),
|
||||
});
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.post("/companies/:companyId/schedules", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
requiredAction: "schedules.create",
|
||||
});
|
||||
const schedule = await createSchedule(db, companyId, actor, req.body, {
|
||||
authActor: req.actor,
|
||||
});
|
||||
res.status(201).json(schedule);
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/schedules", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
requiredAction: "schedules.read",
|
||||
});
|
||||
const target =
|
||||
typeof req.query.target === "string" ? req.query.target : undefined;
|
||||
const items = await listSchedules(db, companyId, actor, { target }, {
|
||||
authActor: req.actor,
|
||||
});
|
||||
res.json({ items });
|
||||
});
|
||||
|
||||
router.delete("/companies/:companyId/schedules/:id", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
requiredAction: "schedules.cancel",
|
||||
});
|
||||
const result = await cancelSchedule(
|
||||
db,
|
||||
companyId,
|
||||
actor,
|
||||
req.params.id as string,
|
||||
{ authActor: req.actor },
|
||||
);
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/events/wait", async (req, res) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
requiredAction: "events.read",
|
||||
});
|
||||
const filters = parseEventQuery(req);
|
||||
const timeoutMs = parseOptionalTimeoutMs(req);
|
||||
|
||||
const ac = new AbortController();
|
||||
const onClose = () => {
|
||||
if (!res.writableFinished) {
|
||||
ac.abort();
|
||||
}
|
||||
};
|
||||
res.on("close", onClose);
|
||||
|
||||
try {
|
||||
let resolvedCursor: string | undefined;
|
||||
const event = await waitForBoardEvent(db, companyId, actor, filters, {
|
||||
timeoutMs,
|
||||
signal: ac.signal,
|
||||
authActor: req.actor,
|
||||
onResolvedCursor: (cursor) => {
|
||||
resolvedCursor = cursor;
|
||||
},
|
||||
});
|
||||
if (res.writableFinished || ac.signal.aborted) return;
|
||||
if (!event) {
|
||||
if (resolvedCursor) {
|
||||
res.setHeader("X-Paperclip-Cursor", resolvedCursor);
|
||||
}
|
||||
res.status(204).end();
|
||||
return;
|
||||
}
|
||||
res.json(event);
|
||||
} finally {
|
||||
res.off("close", onClose);
|
||||
}
|
||||
});
|
||||
|
||||
router.get("/companies/:companyId/events/stream", async (req, res: Response) => {
|
||||
const companyId = req.params.companyId as string;
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
requiredAction: "events.read",
|
||||
});
|
||||
const filters = parseEventQuery(
|
||||
req,
|
||||
req.header("last-event-id") ?? undefined,
|
||||
);
|
||||
const parsedFilters = parseBoardEventFilters(filters);
|
||||
|
||||
res.status(200);
|
||||
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
||||
res.setHeader("Cache-Control", "no-cache, no-transform");
|
||||
res.setHeader("Connection", "keep-alive");
|
||||
res.setHeader("X-Accel-Buffering", "no");
|
||||
res.flushHeaders?.();
|
||||
res.write(": connected\n\n");
|
||||
|
||||
let closed = false;
|
||||
let replaying = true;
|
||||
let lastSentSeq = parsedFilters.afterSeq;
|
||||
const buffered: BoardEventView[] = [];
|
||||
const issueLabelCache = new Map<
|
||||
string,
|
||||
{ kvLabels: Record<string, string>; tagLabels: string[] }
|
||||
>();
|
||||
|
||||
// Serialize live filter checks and writes so SSE frames preserve order.
|
||||
let writeChain = Promise.resolve();
|
||||
|
||||
const deliverEvent = async (ev: BoardEventView) => {
|
||||
if (ev.type === "labels.changed" && ev.issueId) {
|
||||
issueLabelCache.delete(ev.issueId);
|
||||
}
|
||||
if (closed || ev.seq <= lastSentSeq) return;
|
||||
// Evaluate channel access fresh on live events so revoked channel membership applies immediately.
|
||||
const matches = await eventMatchesFiltersAndAccess(
|
||||
db,
|
||||
companyId,
|
||||
actor,
|
||||
ev,
|
||||
parsedFilters,
|
||||
undefined,
|
||||
issueLabelCache,
|
||||
undefined,
|
||||
req.actor,
|
||||
);
|
||||
if (closed || !matches || ev.seq <= lastSentSeq) return;
|
||||
lastSentSeq = ev.seq;
|
||||
res.write(formatSseFrame(ev));
|
||||
};
|
||||
|
||||
const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => {
|
||||
if (closed) return;
|
||||
if (ev.type === "labels.changed" && ev.issueId) {
|
||||
issueLabelCache.delete(ev.issueId);
|
||||
}
|
||||
if (replaying) {
|
||||
buffered.push(ev);
|
||||
return;
|
||||
}
|
||||
writeChain = writeChain
|
||||
.then(() => deliverEvent(ev))
|
||||
.catch(() => {});
|
||||
});
|
||||
|
||||
const keepaliveTimer = setInterval(() => {
|
||||
if (!closed) {
|
||||
res.write(": keepalive\n\n");
|
||||
}
|
||||
}, 25_000);
|
||||
keepaliveTimer.unref?.();
|
||||
|
||||
const cleanup = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(keepaliveTimer);
|
||||
unsubscribe();
|
||||
res.off("close", cleanup);
|
||||
};
|
||||
|
||||
res.on("close", cleanup);
|
||||
|
||||
try {
|
||||
if (parsedFilters.hasExplicitAfter) {
|
||||
const replayPageSize = 500;
|
||||
let replayCursorSeq = parsedFilters.afterSeq;
|
||||
while (!closed) {
|
||||
const missed = await queryBoardEventsAfter(
|
||||
db,
|
||||
companyId,
|
||||
actor,
|
||||
{
|
||||
...parsedFilters,
|
||||
afterSeq: replayCursorSeq,
|
||||
},
|
||||
{ limit: replayPageSize, authActor: req.actor },
|
||||
);
|
||||
for (const ev of missed) {
|
||||
if (closed) break;
|
||||
replayCursorSeq = Math.max(replayCursorSeq, ev.seq);
|
||||
if (ev.seq > lastSentSeq) {
|
||||
lastSentSeq = ev.seq;
|
||||
res.write(formatSseFrame(ev));
|
||||
}
|
||||
}
|
||||
if (missed.length < replayPageSize) break;
|
||||
}
|
||||
} else {
|
||||
const maxSeq = await getCurrentCompanyMaxEventSeq(db, companyId);
|
||||
parsedFilters.afterSeq = maxSeq;
|
||||
lastSentSeq = maxSeq;
|
||||
}
|
||||
replaying = false;
|
||||
|
||||
if (!closed && buffered.length > 0) {
|
||||
buffered.sort((a, b) => a.seq - b.seq);
|
||||
for (const ev of buffered) {
|
||||
await deliverEvent(ev);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
cleanup();
|
||||
if (!res.writableEnded) {
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -1656,6 +1656,9 @@ const BOARD_ONLY_OPERATIONS = new Set([
|
||||
"POST /api/issues/{id}/tree-holds",
|
||||
"GET /api/issues/{id}/tree-holds/{holdId}",
|
||||
"POST /api/issues/{id}/tree-holds/{holdId}/release",
|
||||
// Headless identity enrollment and policy configuration are board-only.
|
||||
"POST /api/companies/{companyId}/agents/connect",
|
||||
"PATCH /api/companies/{companyId}/agent-identity-policy",
|
||||
]);
|
||||
|
||||
const INSTANCE_ADMIN_OPERATIONS = new Set([
|
||||
@@ -14451,3 +14454,52 @@ for (const [method, path, summary] of [
|
||||
404: r.notFound, 409: r.conflict, 422: r.unprocessable,
|
||||
},
|
||||
});
|
||||
|
||||
for (const [method, path, tag, summary, status] of [
|
||||
["get", "/api/companies/{companyId}/channels", "headless", "List accessible channels in a company", 200],
|
||||
["post", "/api/companies/{companyId}/channels", "headless", "Create or update a channel", 201],
|
||||
["post", "/api/companies/{companyId}/channels/posts", "headless", "Create a channel post or queued task", 201],
|
||||
["get", "/api/companies/{companyId}/channels/threads", "headless", "List threads and posts in a channel or subtree", 200],
|
||||
["patch", "/api/issues/{id}/kv-labels", "headless", "Atomically update key-value labels with CAS preconditions", 200],
|
||||
["get", "/api/companies/{companyId}/schemas", "headless", "List company JSON schemas", 200],
|
||||
["get", "/api/companies/{companyId}/schemas/{ref}", "headless", "Get a versioned company JSON schema", 200],
|
||||
["post", "/api/companies/{companyId}/schemas", "headless", "Create an immutable versioned JSON schema", 201],
|
||||
["post", "/api/companies/{companyId}/issues/batch", "headless", "Create a topological DAG batch of tasks", 201],
|
||||
["post", "/api/companies/{companyId}/tasks/claim", "headless", "Atomically claim a ready task from a queue", 200],
|
||||
["post", "/api/issues/{id}/claim/renew", "headless", "Renew an active fenced task claim lease", 200],
|
||||
["post", "/api/issues/{id}/claim/release", "headless", "Release an active fenced task claim lease", 200],
|
||||
["post", "/api/issues/{id}/claim/complete", "headless", "Complete a claimed task with optional structured result", 200],
|
||||
["post", "/api/issues/{id}/claim/fail", "headless", "Fail or requeue a claimed task", 200],
|
||||
["post", "/api/issues/{id}/ask", "headless", "Post a question interaction and release claim", 200],
|
||||
["post", "/api/issues/{id}/confirm", "headless", "Post a confirmation interaction and release claim", 200],
|
||||
["post", "/api/issues/{id}/approve", "headless", "Approve or answer a pending interaction", 200],
|
||||
["post", "/api/issues/{id}/reject", "headless", "Reject a pending interaction", 200],
|
||||
["post", "/api/companies/{companyId}/schedules", "headless", "Schedule a delayed or recurring board post", 201],
|
||||
["get", "/api/companies/{companyId}/schedules", "headless", "List scheduled board posts", 200],
|
||||
["delete", "/api/companies/{companyId}/schedules/{id}", "headless", "Cancel a scheduled board post", 200],
|
||||
["get", "/api/companies/{companyId}/events/wait", "headless", "Wait for the next matching board event", 200],
|
||||
["get", "/api/companies/{companyId}/events/stream", "headless", "Stream matching board events over SSE", 200],
|
||||
["get", "/api/companies/resolve-default", "headless", "Resolve or bootstrap the default company", 200],
|
||||
["get", "/api/whoami", "headless", "Inspect current authenticated board or agent identity", 200],
|
||||
["post", "/api/companies/{companyId}/agents/connect", "headless", "Create or mint an API key for a headless agent", 201],
|
||||
["patch", "/api/companies/{companyId}/agent-identity-policy", "headless", "Update company agent identity policy", 200],
|
||||
] as const) {
|
||||
registerCurrentRoute({
|
||||
method,
|
||||
path,
|
||||
tags: [tag],
|
||||
summary,
|
||||
responses: {
|
||||
[status]: r.ok(),
|
||||
...(path === "/api/companies/{companyId}/tasks/claim" || path === "/api/companies/{companyId}/events/wait"
|
||||
? { 204: { description: "No matching work or event before timeout" } }
|
||||
: {}),
|
||||
400: r.badRequest,
|
||||
401: r.unauthorized,
|
||||
403: r.forbidden,
|
||||
404: r.notFound,
|
||||
409: r.conflict,
|
||||
422: r.unprocessable,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -112,6 +112,13 @@ export function requestAgentHireInTransaction(tx: Db, publications: ActivityPubl
|
||||
return lifecycle.requestAgentHireInTransaction(tx, createAgentLifecycleEffects(), publications, ...args);
|
||||
}
|
||||
|
||||
export function createHeadlessAgentInTransaction(
|
||||
tx: Db,
|
||||
input: Parameters<typeof lifecycle.createHeadlessAgentInTransaction>[2],
|
||||
) {
|
||||
return lifecycle.createHeadlessAgentInTransaction(tx, createAgentLifecycleEffects(), input);
|
||||
}
|
||||
|
||||
function trackedDriver(driver: lifecycle.LifecycleDriver): lifecycle.LifecycleDriver {
|
||||
return { ...driver, runHost: agent => trackIdleWork(driver.runHost(agent)),
|
||||
runPlugin: (agent, pluginId) => trackIdleWork(driver.runPlugin(agent, pluginId)) };
|
||||
|
||||
@@ -12,6 +12,8 @@ import {
|
||||
approvals,
|
||||
issueApprovals,
|
||||
authUsers,
|
||||
channelAccessMembers,
|
||||
channels,
|
||||
companyMemberships,
|
||||
chatConversations,
|
||||
chatDeliveries,
|
||||
@@ -682,11 +684,26 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL<boolean>
|
||||
where p.id = n.project_id and p.company_id = n.company_id and p.visibility = 'private'
|
||||
and m.subject_type = ${principal.type} and m.subject_id = ${principal.id}
|
||||
)` : sql`false`;
|
||||
// A standalone open task without a project has no restricted ancestor.
|
||||
const issueChannelMember = principal ? sql`exists (
|
||||
select 1 from ${channels} ch
|
||||
where ch.id = ${issues.channelId} and ch.company_id = ${issues.companyId} and ch.visibility = 'private'
|
||||
and (
|
||||
${principal.type === "agent" ? sql`ch.created_by_agent_id = ${principal.id}` : sql`ch.created_by_user_id = ${principal.id}`}
|
||||
or exists (
|
||||
select 1 from ${channelAccessMembers} cm
|
||||
where cm.channel_id = ch.id and cm.subject_type = ${principal.type} and cm.subject_id = ${principal.id}
|
||||
)
|
||||
)
|
||||
)` : sql`false`;
|
||||
const channelPrivacyGate = sql<boolean>`(${issues.channelId} is null or not exists (
|
||||
select 1 from ${channels} ch
|
||||
where ch.id = ${issues.channelId} and ch.company_id = ${issues.companyId} and ch.visibility = 'private'
|
||||
) or ${issueChannelMember})`;
|
||||
// A standalone open task without a project or private channel has no restricted ancestor.
|
||||
// Keep the recursive predicate for every other shape, including inherited
|
||||
// privacy and delegated principals. This avoids one recursive walk per row
|
||||
// in large readable-child aggregates.
|
||||
return sql<boolean>`((${issues.visibility} = 'open'
|
||||
return sql<boolean>`(${channelPrivacyGate} and ((${issues.visibility} = 'open'
|
||||
and ${issues.privacyParentIssueId} is null and ${issues.projectId} is null) or exists (
|
||||
with recursive privacy_ancestors as (
|
||||
select p.id, p.company_id, p.privacy_parent_issue_id, p.visibility, p.project_id,
|
||||
@@ -708,13 +725,21 @@ function issuePrivacyPrincipalCondition(actor: AuthorizationActor): SQL<boolean>
|
||||
)
|
||||
select 1 from privacy_ancestors n
|
||||
where ${implicit} or ${grant} or ${projectMember}
|
||||
or (n.id = ${issues.id} and ${issueChannelMember}
|
||||
and not exists (select 1 from projects pp where pp.id = n.project_id and pp.company_id = n.company_id and pp.visibility = 'private')
|
||||
and not exists (
|
||||
select 1 from privacy_ancestors restricted
|
||||
left join projects private_project on private_project.id = restricted.project_id
|
||||
and private_project.company_id = restricted.company_id
|
||||
where restricted.id <> n.id and (restricted.visibility = 'private' or private_project.visibility = 'private')
|
||||
))
|
||||
or not exists (
|
||||
select 1 from privacy_ancestors restricted
|
||||
left join projects private_project on private_project.id = restricted.project_id
|
||||
and private_project.company_id = restricted.company_id
|
||||
where restricted.visibility = 'private' or private_project.visibility = 'private'
|
||||
)
|
||||
))`;
|
||||
)))`;
|
||||
}
|
||||
|
||||
function issuePrivacyCondition(actor: AuthorizationActor): SQL<boolean> {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { and, eq, gt, isNull, or, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, gt, inArray, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
activityLog,
|
||||
agentApiKeys,
|
||||
agents,
|
||||
authUsers,
|
||||
boardApiKeys,
|
||||
cliAuthChallenges,
|
||||
@@ -10,8 +12,16 @@ import {
|
||||
companyMemberships,
|
||||
instanceUserRoles,
|
||||
} from "@paperclipai/db";
|
||||
import { conflict, forbidden, notFound } from "../errors.js";
|
||||
import {
|
||||
AGENT_ROLES,
|
||||
deriveAgentUrlKey,
|
||||
type AgentRole,
|
||||
type ClientScopes,
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
import { createHeadlessAgentInTransaction } from "./agent-lifecycle.js";
|
||||
import { authorizationService } from "./authorization.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
export const BOARD_API_KEY_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
@@ -35,10 +45,22 @@ export function createBoardApiToken() {
|
||||
return `pcp_board_${randomBytes(24).toString("hex")}`;
|
||||
}
|
||||
|
||||
export function createAgentApiToken() {
|
||||
return `pcp_${randomBytes(24).toString("hex")}`;
|
||||
}
|
||||
|
||||
export function createCliAuthSecret() {
|
||||
return `pcp_cli_auth_${randomBytes(24).toString("hex")}`;
|
||||
}
|
||||
|
||||
function normalizeAgentRole(rawRole?: string | null): AgentRole {
|
||||
const candidate = rawRole?.trim().toLowerCase() ?? "";
|
||||
if ((AGENT_ROLES as readonly string[]).includes(candidate)) {
|
||||
return candidate as AgentRole;
|
||||
}
|
||||
return "general";
|
||||
}
|
||||
|
||||
export function boardApiKeyExpiresAt(nowMs: number = Date.now()) {
|
||||
return new Date(nowMs + BOARD_API_KEY_TTL_MS);
|
||||
}
|
||||
@@ -50,7 +72,12 @@ export function cliAuthChallengeExpiresAt(nowMs: number = Date.now()) {
|
||||
function challengeStatusForRow(row: typeof cliAuthChallenges.$inferSelect): CliAuthChallengeStatus {
|
||||
if (row.cancelledAt) return "cancelled";
|
||||
if (row.expiresAt.getTime() <= Date.now()) return "expired";
|
||||
if (row.approvedAt && row.boardApiKeyId) return "approved";
|
||||
if (
|
||||
row.approvedAt &&
|
||||
(row.challengeKind === "agent_key" ? Boolean(row.approvedAgentId) : Boolean(row.boardApiKeyId))
|
||||
) {
|
||||
return "approved";
|
||||
}
|
||||
return "pending";
|
||||
}
|
||||
|
||||
@@ -220,12 +247,18 @@ export function boardAuthService(db: Db) {
|
||||
userId: string;
|
||||
name: string;
|
||||
expiresAt?: Date | null;
|
||||
companyId?: string | null;
|
||||
lockedProfile?: string | null;
|
||||
scopes?: ClientScopes | null;
|
||||
}) {
|
||||
const token = createBoardApiToken();
|
||||
const created = await db
|
||||
.insert(boardApiKeys)
|
||||
.values({
|
||||
userId: input.userId,
|
||||
companyId: input.companyId ?? null,
|
||||
lockedProfile: input.lockedProfile?.trim() || null,
|
||||
scopes: input.scopes ?? null,
|
||||
name: input.name.trim(),
|
||||
keyHash: hashBearerToken(token),
|
||||
expiresAt: input.expiresAt === undefined ? boardApiKeyExpiresAt() : input.expiresAt,
|
||||
@@ -235,6 +268,9 @@ export function boardAuthService(db: Db) {
|
||||
|
||||
return {
|
||||
id: created.id,
|
||||
companyId: created.companyId,
|
||||
lockedProfile: created.lockedProfile,
|
||||
scopes: created.scopes,
|
||||
name: created.name,
|
||||
token,
|
||||
createdAt: created.createdAt,
|
||||
@@ -294,15 +330,29 @@ export function boardAuthService(db: Db) {
|
||||
clientName?: string | null;
|
||||
requestedAccess: "board" | "instance_admin_required";
|
||||
requestedCompanyId?: string | null;
|
||||
challengeKind?: "board" | "agent_key";
|
||||
agentName?: string | null;
|
||||
agentRole?: string | null;
|
||||
}) {
|
||||
const challengeKind = input.challengeKind === "agent_key" ? "agent_key" : "board";
|
||||
const requestedAgentName = input.agentName?.trim() || null;
|
||||
if (challengeKind === "agent_key" && !requestedAgentName) {
|
||||
throw badRequest("agentName is required when challengeKind is 'agent_key'");
|
||||
}
|
||||
const requestedAgentRole =
|
||||
challengeKind === "agent_key" ? input.agentRole?.trim() || "general" : null;
|
||||
|
||||
const challengeSecret = createCliAuthSecret();
|
||||
const pendingBoardToken = createBoardApiToken();
|
||||
const pendingBoardToken =
|
||||
challengeKind === "agent_key" ? createAgentApiToken() : createBoardApiToken();
|
||||
const expiresAt = cliAuthChallengeExpiresAt();
|
||||
const labelBase = input.clientName?.trim() || "paperclipai cli";
|
||||
const pendingKeyName =
|
||||
input.requestedAccess === "instance_admin_required"
|
||||
? `${labelBase} (instance admin)`
|
||||
: `${labelBase} (board)`;
|
||||
challengeKind === "agent_key"
|
||||
? `${labelBase} (@${requestedAgentName})`
|
||||
: input.requestedAccess === "instance_admin_required"
|
||||
? `${labelBase} (instance admin)`
|
||||
: `${labelBase} (board)`;
|
||||
|
||||
const created = await db
|
||||
.insert(cliAuthChallenges)
|
||||
@@ -311,6 +361,9 @@ export function boardAuthService(db: Db) {
|
||||
command: input.command.trim(),
|
||||
clientName: input.clientName?.trim() || null,
|
||||
requestedAccess: input.requestedAccess,
|
||||
challengeKind,
|
||||
requestedAgentName,
|
||||
requestedAgentRole,
|
||||
requestedCompanyId: input.requestedCompanyId?.trim() || null,
|
||||
pendingKeyHash: hashBearerToken(pendingBoardToken),
|
||||
pendingKeyName,
|
||||
@@ -353,14 +406,24 @@ export function boardAuthService(db: Db) {
|
||||
.where(eq(companies.id, challenge.requestedCompanyId!)).then(rows => rows[0] ?? null)
|
||||
: null;
|
||||
|
||||
const status = challengeStatusForRow(challenge);
|
||||
return {
|
||||
id: challenge.id,
|
||||
status: challengeStatusForRow(challenge),
|
||||
status,
|
||||
command: challenge.command,
|
||||
clientName: challenge.clientName ?? null,
|
||||
requestedAccess: challenge.requestedAccess as "board" | "instance_admin_required",
|
||||
challengeKind: (challenge.challengeKind ?? "board") as "board" | "agent_key",
|
||||
requestedAgentName: challenge.requestedAgentName ?? null,
|
||||
requestedAgentRole: challenge.requestedAgentRole ?? null,
|
||||
requestedCompanyId: challenge.requestedCompanyId ?? null,
|
||||
requestedCompanyName: company?.name ?? null,
|
||||
...(challenge.challengeKind === "agent_key" && status === "approved"
|
||||
? {
|
||||
agentId: challenge.approvedAgentId ?? null,
|
||||
companyId: challenge.requestedCompanyId ?? null,
|
||||
}
|
||||
: {}),
|
||||
approvedAt: challenge.approvedAt?.toISOString() ?? null,
|
||||
cancelledAt: challenge.cancelledAt?.toISOString() ?? null,
|
||||
expiresAt: challenge.expiresAt.toISOString(),
|
||||
@@ -406,6 +469,168 @@ export function boardAuthService(db: Db) {
|
||||
throw forbidden("Instance admin required");
|
||||
}
|
||||
|
||||
if (challenge.challengeKind === "agent_key") {
|
||||
const requestedName = challenge.requestedAgentName?.trim();
|
||||
if (!requestedName) {
|
||||
throw badRequest("Agent name is missing on agent_key challenge");
|
||||
}
|
||||
|
||||
let targetCompanyId = challenge.requestedCompanyId;
|
||||
if (!targetCompanyId) {
|
||||
const candidateCompanies =
|
||||
access.companyIds.length > 0
|
||||
? await tx
|
||||
.select({ id: companies.id })
|
||||
.from(companies)
|
||||
.where(
|
||||
and(
|
||||
inArray(companies.id, access.companyIds),
|
||||
eq(companies.status, "active"),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(companies.createdAt))
|
||||
.limit(1)
|
||||
: access.isInstanceAdmin
|
||||
? await tx
|
||||
.select({ id: companies.id })
|
||||
.from(companies)
|
||||
.where(eq(companies.status, "active"))
|
||||
.orderBy(asc(companies.createdAt))
|
||||
.limit(1)
|
||||
: [];
|
||||
targetCompanyId = candidateCompanies[0]?.id ?? null;
|
||||
}
|
||||
if (!targetCompanyId) {
|
||||
throw notFound("No accessible active company found for agent approval");
|
||||
}
|
||||
|
||||
const [targetCompany] = await tx
|
||||
.select({
|
||||
id: companies.id,
|
||||
requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents,
|
||||
})
|
||||
.from(companies)
|
||||
.where(eq(companies.id, targetCompanyId))
|
||||
.limit(1);
|
||||
if (!targetCompany) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
|
||||
const authActor = {
|
||||
type: "board" as const,
|
||||
userId,
|
||||
isInstanceAdmin: access.isInstanceAdmin,
|
||||
companyIds: access.companyIds,
|
||||
memberships: access.memberships,
|
||||
source: "session" as const,
|
||||
};
|
||||
const authz = authorizationService(tx as unknown as Db);
|
||||
const createDecision = await authz.decide({
|
||||
actor: authActor,
|
||||
action: "agents:create",
|
||||
resource: { type: "company", companyId: targetCompanyId },
|
||||
});
|
||||
if (!createDecision.allowed) {
|
||||
throw forbidden(
|
||||
createDecision.explanation ?? "Missing permission: agents:create",
|
||||
{ code: "forbidden", reason: createDecision.reason },
|
||||
);
|
||||
}
|
||||
|
||||
const existingCompanyAgents = await tx
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(
|
||||
and(
|
||||
eq(agents.companyId, targetCompanyId),
|
||||
ne(agents.status, "terminated"),
|
||||
),
|
||||
);
|
||||
const lowerTarget = requestedName.toLowerCase();
|
||||
let agent = existingCompanyAgents.find(
|
||||
(row) =>
|
||||
row.name.trim().toLowerCase() === lowerTarget ||
|
||||
deriveAgentUrlKey(row.name, row.id).toLowerCase() === lowerTarget,
|
||||
);
|
||||
|
||||
if (agent) {
|
||||
if (agent.status === "pending_approval") {
|
||||
throw conflict(
|
||||
"Agent is pending board approval and cannot receive an API key until approved.",
|
||||
{ code: "board_approval_required" },
|
||||
);
|
||||
}
|
||||
const configureDecision = await authz.decide({
|
||||
actor: authActor,
|
||||
action: "agent_config:update",
|
||||
resource: { type: "agent", companyId: targetCompanyId, agentId: agent.id },
|
||||
});
|
||||
if (!configureDecision.allowed) {
|
||||
throw forbidden(
|
||||
configureDecision.explanation ??
|
||||
"Missing permission to manage the target agent",
|
||||
{ code: "forbidden", reason: configureDecision.reason },
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (targetCompany.requireBoardApprovalForNewAgents) {
|
||||
throw conflict(
|
||||
"Direct agent creation requires board approval. Use POST /api/companies/:companyId/agent-hires to create a pending hire approval.",
|
||||
{ code: "board_approval_required" },
|
||||
);
|
||||
}
|
||||
agent = await createHeadlessAgentInTransaction(tx as unknown as Db, {
|
||||
companyId: targetCompanyId,
|
||||
name: requestedName,
|
||||
role: normalizeAgentRole(challenge.requestedAgentRole),
|
||||
createdByUserId: userId,
|
||||
});
|
||||
}
|
||||
|
||||
const [createdAgentKey] = await tx
|
||||
.insert(agentApiKeys)
|
||||
.values({
|
||||
agentId: agent.id,
|
||||
companyId: targetCompanyId,
|
||||
name: challenge.pendingKeyName,
|
||||
keyHash: challenge.pendingKeyHash,
|
||||
responsibleUserId: userId,
|
||||
})
|
||||
.returning();
|
||||
|
||||
const approvedAt = challenge.approvedAt ?? new Date();
|
||||
const updated = await tx
|
||||
.update(cliAuthChallenges)
|
||||
.set({
|
||||
approvedByUserId: userId,
|
||||
approvedAgentId: agent.id,
|
||||
requestedCompanyId: targetCompanyId,
|
||||
approvedAt,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(cliAuthChallenges.id, challenge.id))
|
||||
.returning()
|
||||
.then((rows) => rows[0] ?? challenge);
|
||||
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId: targetCompanyId,
|
||||
actorType: "user",
|
||||
actorId: userId,
|
||||
action: "agent_api_key.created",
|
||||
entityType: "agent",
|
||||
entityId: agent.id,
|
||||
details: {
|
||||
agentId: agent.id,
|
||||
agentName: agent.name,
|
||||
agentApiKeyId: createdAgentKey.id,
|
||||
name: createdAgentKey.name,
|
||||
challengeId: updated.id,
|
||||
},
|
||||
}, publications);
|
||||
|
||||
return { status: "approved" as const, challenge: updated, created: true };
|
||||
}
|
||||
|
||||
let boardKeyId = challenge.boardApiKeyId;
|
||||
if (!boardKeyId) {
|
||||
const createdKey = await tx
|
||||
|
||||
@@ -165,6 +165,8 @@ export const DELIVERY_QUEUES = {
|
||||
caseHandoffs: "case-handoffs",
|
||||
nativeHarnessBackupExpiration: "native-harness-backup-expiration",
|
||||
nativeCheckpointExpiration: "native-checkpoint-expiration",
|
||||
claimLeaseExpiry: "claim-lease-expiry",
|
||||
scheduledBoardPosts: "scheduled-board-posts",
|
||||
} as const;
|
||||
export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES];
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,587 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import type { Request } from "express";
|
||||
import { and, asc, eq, inArray, ne, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agentApiKeys, agents, boardApiKeys, companies } from "@paperclipai/db";
|
||||
import {
|
||||
AGENT_ROLES,
|
||||
deriveAgentUrlKey,
|
||||
isUuidLike,
|
||||
type AgentIdentityPolicy,
|
||||
type AgentRole,
|
||||
type CompanyResolutionView,
|
||||
type DeploymentMode,
|
||||
type WhoAmIView,
|
||||
} from "@paperclipai/shared";
|
||||
import { conflict, forbidden, notFound, unauthorized } from "../errors.js";
|
||||
import { assertCompanyAccess, boardAccessRequired, getActorInfo } from "../routes/authz.js";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
import { createHeadlessAgentInTransaction } from "./agent-lifecycle.js";
|
||||
import { authorizationService } from "./authorization.js";
|
||||
import {
|
||||
actionMatchesScopePattern,
|
||||
resolveHeadlessActor,
|
||||
resolveCompanyAgentIdentityPolicy,
|
||||
} from "./headless-common.js";
|
||||
import { pickAvailableIssuePrefix } from "./issue-prefix.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
function normalizeAgentRole(rawRole?: string | null): AgentRole {
|
||||
const candidate = rawRole?.trim().toLowerCase() ?? "";
|
||||
if ((AGENT_ROLES as readonly string[]).includes(candidate)) {
|
||||
return candidate as AgentRole;
|
||||
}
|
||||
return "general";
|
||||
}
|
||||
|
||||
function hashAgentToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
function createHeadlessAgentToken(): string {
|
||||
return `pcp_${randomBytes(24).toString("base64url")}`;
|
||||
}
|
||||
|
||||
function deriveRequestApiBase(req: Request): string {
|
||||
const forwardedProto = req.header("x-forwarded-proto")?.split(",")[0]?.trim();
|
||||
const proto = forwardedProto || req.protocol || "http";
|
||||
const forwardedHost = req.header("x-forwarded-host")?.split(",")[0]?.trim();
|
||||
const host = forwardedHost || req.get("host") || "127.0.0.1:3100";
|
||||
return `${proto}://${host}`;
|
||||
}
|
||||
|
||||
export function headlessIdentityService(
|
||||
db: Db,
|
||||
opts: { deploymentMode?: DeploymentMode } = {},
|
||||
) {
|
||||
function resolveDeploymentMode(req: Request): DeploymentMode {
|
||||
return (
|
||||
opts.deploymentMode ??
|
||||
(req.actor?.source === "local_implicit" ? "local_trusted" : "authenticated")
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveBoardKeyCompanyScope(req: Request): Promise<string | null> {
|
||||
if (req.actor?.type === "board" && req.actor.source === "board_key" && req.actor.keyId) {
|
||||
const [keyRow] = await db
|
||||
.select({ companyId: boardApiKeys.companyId })
|
||||
.from(boardApiKeys)
|
||||
.where(eq(boardApiKeys.id, req.actor.keyId));
|
||||
return keyRow?.companyId ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function resolveDefaultCompany(
|
||||
req: Request,
|
||||
companyQuery?: string | null,
|
||||
): Promise<CompanyResolutionView> {
|
||||
if (!req.actor || req.actor.type === "none") {
|
||||
throw unauthorized("Authentication required");
|
||||
}
|
||||
|
||||
const deploymentMode = resolveDeploymentMode(req);
|
||||
const trimmedQuery = companyQuery?.trim() || null;
|
||||
|
||||
type CompanyRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
issuePrefix: string;
|
||||
agentIdentityPolicy: AgentIdentityPolicy | null;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
let accessible: CompanyRow[] = [];
|
||||
let keyCompanyId: string | null = null;
|
||||
|
||||
if (req.actor.type === "agent") {
|
||||
if (req.actor.keyScope && req.actor.keyScope.kind !== "standard") {
|
||||
throw forbidden(
|
||||
`Scoped '${req.actor.keyScope.kind}' agent keys cannot access headless company resolution`,
|
||||
{ code: "scope_denied" },
|
||||
);
|
||||
}
|
||||
if (req.actor.companyId) {
|
||||
accessible = await db
|
||||
.select({
|
||||
id: companies.id,
|
||||
name: companies.name,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
createdAt: companies.createdAt,
|
||||
})
|
||||
.from(companies)
|
||||
.where(
|
||||
and(
|
||||
eq(companies.id, req.actor.companyId),
|
||||
eq(companies.status, "active"),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(companies.createdAt));
|
||||
}
|
||||
} else {
|
||||
keyCompanyId = await resolveBoardKeyCompanyScope(req);
|
||||
const isLocalImplicit = req.actor.source === "local_implicit";
|
||||
const isUnrestrictedAdmin = isLocalImplicit || Boolean(req.actor.isInstanceAdmin);
|
||||
|
||||
if (keyCompanyId) {
|
||||
if (isUnrestrictedAdmin || (req.actor.companyIds ?? []).includes(keyCompanyId)) {
|
||||
accessible = await db
|
||||
.select({
|
||||
id: companies.id,
|
||||
name: companies.name,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
createdAt: companies.createdAt,
|
||||
})
|
||||
.from(companies)
|
||||
.where(and(eq(companies.id, keyCompanyId), eq(companies.status, "active")))
|
||||
.orderBy(asc(companies.createdAt));
|
||||
}
|
||||
} else if (isUnrestrictedAdmin) {
|
||||
accessible = await db
|
||||
.select({
|
||||
id: companies.id,
|
||||
name: companies.name,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
createdAt: companies.createdAt,
|
||||
})
|
||||
.from(companies)
|
||||
.where(eq(companies.status, "active"))
|
||||
.orderBy(asc(companies.createdAt));
|
||||
} else {
|
||||
const companyIds = req.actor.companyIds ?? [];
|
||||
if (companyIds.length > 0) {
|
||||
accessible = await db
|
||||
.select({
|
||||
id: companies.id,
|
||||
name: companies.name,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
createdAt: companies.createdAt,
|
||||
})
|
||||
.from(companies)
|
||||
.where(
|
||||
and(inArray(companies.id, companyIds), eq(companies.status, "active")),
|
||||
)
|
||||
.orderBy(asc(companies.createdAt));
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
accessible.length === 0 &&
|
||||
!trimmedQuery &&
|
||||
!keyCompanyId &&
|
||||
(deploymentMode === "local_trusted" || req.actor.source === "local_implicit")
|
||||
) {
|
||||
const autoCreated = await db.transaction(async (tx) => {
|
||||
await tx.execute(
|
||||
sql`select pg_advisory_xact_lock(hashtext('paperclip:auto-default-company'))`,
|
||||
);
|
||||
const existing = await tx
|
||||
.select({
|
||||
id: companies.id,
|
||||
name: companies.name,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
createdAt: companies.createdAt,
|
||||
})
|
||||
.from(companies)
|
||||
.where(eq(companies.status, "active"))
|
||||
.orderBy(asc(companies.createdAt));
|
||||
if (existing.length > 0) {
|
||||
return existing[0]!;
|
||||
}
|
||||
const prefix = (await pickAvailableIssuePrefix(tx, "PC")) ?? "PC";
|
||||
const [inserted] = await tx
|
||||
.insert(companies)
|
||||
.values({
|
||||
name: "Workspace",
|
||||
issuePrefix: prefix,
|
||||
status: "active",
|
||||
defaultResponsibleUserId: "local-board",
|
||||
})
|
||||
.returning({
|
||||
id: companies.id,
|
||||
name: companies.name,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
createdAt: companies.createdAt,
|
||||
});
|
||||
return inserted!;
|
||||
});
|
||||
accessible = [autoCreated];
|
||||
}
|
||||
}
|
||||
|
||||
let selected: CompanyRow | undefined;
|
||||
if (trimmedQuery) {
|
||||
const lowerQuery = trimmedQuery.toLowerCase();
|
||||
selected = isUuidLike(trimmedQuery)
|
||||
? accessible.find((c) => c.id.toLowerCase() === lowerQuery)
|
||||
: accessible.find((c) => c.issuePrefix.toLowerCase() === lowerQuery) ??
|
||||
accessible.find((c) => c.name.trim().toLowerCase() === lowerQuery);
|
||||
if (!selected) {
|
||||
throw notFound(`Company '${trimmedQuery}' not found`, {
|
||||
code: "no_company_found",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
selected = accessible[0];
|
||||
if (!selected) {
|
||||
throw notFound("no_company_found", { code: "no_company_found" });
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: selected.id,
|
||||
name: selected.name,
|
||||
issuePrefix: selected.issuePrefix,
|
||||
agentIdentityPolicy: resolveCompanyAgentIdentityPolicy(
|
||||
selected.agentIdentityPolicy,
|
||||
deploymentMode,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
async function whoami(
|
||||
req: Request,
|
||||
companyIdQuery?: string | null,
|
||||
): Promise<WhoAmIView> {
|
||||
if (!req.actor || req.actor.type === "none") {
|
||||
throw unauthorized("Authentication required");
|
||||
}
|
||||
const deploymentMode = resolveDeploymentMode(req);
|
||||
const trimmed = companyIdQuery?.trim() || null;
|
||||
const companyId =
|
||||
trimmed && isUuidLike(trimmed)
|
||||
? trimmed
|
||||
: (await resolveDefaultCompany(req, trimmed)).id;
|
||||
|
||||
const actor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode,
|
||||
});
|
||||
|
||||
return {
|
||||
apiBase: deriveRequestApiBase(req),
|
||||
companyId: actor.companyId,
|
||||
companyPrefix: actor.companyPrefix,
|
||||
companyName: actor.companyName,
|
||||
principalType: actor.principalType,
|
||||
userId: actor.userId,
|
||||
agentId: actor.agentId,
|
||||
agentName: actor.agentName,
|
||||
actorProfile: actor.actorProfile,
|
||||
agentIdentityPolicy: actor.agentIdentityPolicy,
|
||||
scopes: actor.scopes,
|
||||
};
|
||||
}
|
||||
|
||||
async function connectAgent(
|
||||
req: Request,
|
||||
companyId: string,
|
||||
input: { name: string; role?: string; ttlSec?: number },
|
||||
) {
|
||||
if (!req.actor || req.actor.type === "none") {
|
||||
throw unauthorized("Authentication required");
|
||||
}
|
||||
if (req.actor.type !== "board") {
|
||||
throw boardAccessRequired(req);
|
||||
}
|
||||
if (!isUuidLike(companyId)) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
const headlessActor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode: resolveDeploymentMode(req),
|
||||
requiredAction: "agents.connect",
|
||||
});
|
||||
if (headlessActor.actorProfile && req.actor.source === "board_key") {
|
||||
throw forbidden("Profile-locked credentials cannot mint registered agent API keys", {
|
||||
code: "profile_locked",
|
||||
});
|
||||
}
|
||||
if (headlessActor.scopes?.channels && headlessActor.scopes.channels.length >= 0) {
|
||||
throw forbidden("Channel-scoped credentials cannot mint unrestricted agent API keys", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
if (
|
||||
headlessActor.scopes?.actions &&
|
||||
!headlessActor.scopes.actions.some((pattern) =>
|
||||
actionMatchesScopePattern("agents.connect", pattern),
|
||||
)
|
||||
) {
|
||||
throw forbidden("Caller scopes do not allow connecting agents", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
assertCompanyAccess(req, companyId);
|
||||
|
||||
const trimmedName = input.name.trim();
|
||||
if (!trimmedName) {
|
||||
throw conflict("Agent name cannot be empty");
|
||||
}
|
||||
|
||||
const publications: ActivityPublication[] = [];
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const [company] = await tx
|
||||
.select({
|
||||
id: companies.id,
|
||||
defaultResponsibleUserId: companies.defaultResponsibleUserId,
|
||||
requireBoardApprovalForNewAgents: companies.requireBoardApprovalForNewAgents,
|
||||
})
|
||||
.from(companies)
|
||||
.where(eq(companies.id, companyId));
|
||||
|
||||
if (!company) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
|
||||
const authz = authorizationService(tx as unknown as Db);
|
||||
const createDecision = await authz.decide({
|
||||
actor: req.actor,
|
||||
action: "agents:create",
|
||||
resource: { type: "company", companyId },
|
||||
});
|
||||
if (!createDecision.allowed) {
|
||||
throw forbidden(
|
||||
createDecision.explanation ?? "Missing permission: agents:create",
|
||||
{ code: "forbidden", reason: createDecision.reason },
|
||||
);
|
||||
}
|
||||
|
||||
const targetLower = trimmedName.toLowerCase();
|
||||
const existingAgents = await tx
|
||||
.select()
|
||||
.from(agents)
|
||||
.where(and(eq(agents.companyId, companyId), ne(agents.status, "terminated")));
|
||||
|
||||
let agent = existingAgents.find(
|
||||
(a) =>
|
||||
a.name.trim().toLowerCase() === targetLower ||
|
||||
deriveAgentUrlKey(a.name, a.id).toLowerCase() === targetLower,
|
||||
);
|
||||
|
||||
if (agent) {
|
||||
if (agent.status === "pending_approval") {
|
||||
throw conflict(
|
||||
"Agent is pending board approval and cannot receive an API key until approved.",
|
||||
{ code: "board_approval_required" },
|
||||
);
|
||||
}
|
||||
const configureDecision = await authz.decide({
|
||||
actor: req.actor,
|
||||
action: "agent_config:update",
|
||||
resource: { type: "agent", companyId, agentId: agent.id },
|
||||
});
|
||||
if (!configureDecision.allowed) {
|
||||
throw forbidden(
|
||||
configureDecision.explanation ??
|
||||
"Missing permission to manage the target agent",
|
||||
{ code: "forbidden", reason: configureDecision.reason },
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (company.requireBoardApprovalForNewAgents) {
|
||||
throw conflict(
|
||||
"Direct agent creation requires board approval. Use POST /api/companies/:companyId/agent-hires to create a pending hire approval.",
|
||||
{ code: "board_approval_required" },
|
||||
);
|
||||
}
|
||||
agent = await createHeadlessAgentInTransaction(tx as unknown as Db, {
|
||||
companyId,
|
||||
name: trimmedName,
|
||||
role: normalizeAgentRole(input.role),
|
||||
createdByUserId: req.actor.userId ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
const rawToken = createHeadlessAgentToken();
|
||||
const keyHash = hashAgentToken(rawToken);
|
||||
const responsibleUserId =
|
||||
req.actor.userId && req.actor.userId !== "local-board"
|
||||
? req.actor.userId
|
||||
: company.defaultResponsibleUserId ?? "local-board";
|
||||
const keyName = `cli-${trimmedName}-${new Date().toISOString().replaceAll(":", "-")}`;
|
||||
const expiresAt =
|
||||
input.ttlSec !== undefined ? new Date(Date.now() + input.ttlSec * 1000) : null;
|
||||
|
||||
const [keyRow] = await tx
|
||||
.insert(agentApiKeys)
|
||||
.values({
|
||||
agentId: agent.id,
|
||||
companyId,
|
||||
name: keyName,
|
||||
keyHash,
|
||||
responsibleUserId,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
|
||||
const actorInfo = getActorInfo(req);
|
||||
await logActivity(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
companyId,
|
||||
actorType: actorInfo.actorType,
|
||||
actorId: actorInfo.actorId,
|
||||
agentId: actorInfo.agentId,
|
||||
runId: actorInfo.runId,
|
||||
action: "agent_api_key.created",
|
||||
entityType: "agent",
|
||||
entityId: agent.id,
|
||||
details: {
|
||||
agentId: agent.id,
|
||||
agentName: agent.name,
|
||||
agentApiKeyId: keyRow!.id,
|
||||
name: keyRow!.name,
|
||||
},
|
||||
},
|
||||
publications,
|
||||
);
|
||||
|
||||
return {
|
||||
agent,
|
||||
agentId: agent.id,
|
||||
agentName: agent.name,
|
||||
companyId,
|
||||
apiKey: rawToken,
|
||||
token: rawToken,
|
||||
key: {
|
||||
id: keyRow!.id,
|
||||
name: keyRow!.name,
|
||||
token: rawToken,
|
||||
createdAt: keyRow!.createdAt.toISOString(),
|
||||
expiresAt: keyRow!.expiresAt ? keyRow!.expiresAt.toISOString() : null,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
for (const publication of publications) {
|
||||
try {
|
||||
publishActivity(publication);
|
||||
} catch (err) {
|
||||
logger.warn({ err }, "Failed to publish agent_api_key.created activity");
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function updateAgentIdentityPolicy(
|
||||
req: Request,
|
||||
companyId: string,
|
||||
agentIdentityPolicy: AgentIdentityPolicy,
|
||||
) {
|
||||
if (!req.actor || req.actor.type === "none") {
|
||||
throw unauthorized("Authentication required");
|
||||
}
|
||||
if (req.actor.type !== "board") {
|
||||
throw boardAccessRequired(req);
|
||||
}
|
||||
if (!isUuidLike(companyId)) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
const headlessActor = await resolveHeadlessActor(db, req, companyId, {
|
||||
deploymentMode: resolveDeploymentMode(req),
|
||||
requiredAction: "company.policy.update",
|
||||
});
|
||||
if (headlessActor.actorProfile && req.actor.source === "board_key") {
|
||||
throw forbidden("Profile-locked credentials cannot update company identity policy", {
|
||||
code: "profile_locked",
|
||||
});
|
||||
}
|
||||
if (headlessActor.scopes?.channels) {
|
||||
throw forbidden("Channel-scoped credentials cannot update company identity policy", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
if (
|
||||
headlessActor.scopes?.actions &&
|
||||
!headlessActor.scopes.actions.some((pattern) =>
|
||||
actionMatchesScopePattern("company.policy.update", pattern),
|
||||
)
|
||||
) {
|
||||
throw forbidden("Caller scopes do not allow updating company identity policy", {
|
||||
code: "scope_denied",
|
||||
});
|
||||
}
|
||||
if (
|
||||
req.actor.source !== "local_implicit" &&
|
||||
!req.actor.isInstanceAdmin &&
|
||||
Array.isArray(req.actor.memberships)
|
||||
) {
|
||||
const membership = req.actor.memberships.find((item) => item.companyId === companyId);
|
||||
if (
|
||||
!membership ||
|
||||
membership.status !== "active" ||
|
||||
(membership.membershipRole !== "owner" && membership.membershipRole !== "admin")
|
||||
) {
|
||||
throw forbidden("Owner or admin membership required to update identity policy");
|
||||
}
|
||||
}
|
||||
assertCompanyAccess(req, companyId);
|
||||
|
||||
const publications: ActivityPublication[] = [];
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.update(companies)
|
||||
.set({
|
||||
agentIdentityPolicy,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(companies.id, companyId))
|
||||
.returning({
|
||||
id: companies.id,
|
||||
agentIdentityPolicy: companies.agentIdentityPolicy,
|
||||
});
|
||||
|
||||
if (!row) {
|
||||
throw notFound("Company not found");
|
||||
}
|
||||
|
||||
const actorInfo = getActorInfo(req);
|
||||
await logActivity(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
companyId,
|
||||
actorType: actorInfo.actorType,
|
||||
actorId: actorInfo.actorId,
|
||||
agentId: actorInfo.agentId,
|
||||
runId: actorInfo.runId,
|
||||
action: "company.agent_identity_policy_updated",
|
||||
entityType: "company",
|
||||
entityId: companyId,
|
||||
details: { agentIdentityPolicy },
|
||||
},
|
||||
publications,
|
||||
);
|
||||
|
||||
return row;
|
||||
});
|
||||
|
||||
for (const publication of publications) {
|
||||
try {
|
||||
publishActivity(publication);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err },
|
||||
"Failed to publish company.agent_identity_policy_updated activity",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: updated.id,
|
||||
agentIdentityPolicy: updated.agentIdentityPolicy,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
resolveDefaultCompany,
|
||||
whoami,
|
||||
connectAgent,
|
||||
updateAgentIdentityPolicy,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,663 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
channels,
|
||||
companies,
|
||||
issueBatchIdempotencyKeys,
|
||||
issueRelations,
|
||||
issues,
|
||||
projects,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
applyKvLabelMutation,
|
||||
KvLabelMutationSchema,
|
||||
validateAndSortBatchPlan,
|
||||
type BatchCreatedTaskItem,
|
||||
type BatchCreateIssuesResult,
|
||||
type BoardEventView,
|
||||
type IssueScope,
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, conflict, unprocessable } from "../errors.js";
|
||||
import {
|
||||
logActivity,
|
||||
publishActivity,
|
||||
type ActivityPublication,
|
||||
} from "./activity-log.js";
|
||||
import {
|
||||
attachTagLabels,
|
||||
ensureChannel,
|
||||
resolveAssigneeAgent,
|
||||
} from "./headless-channels.js";
|
||||
import {
|
||||
appendBoardEvent,
|
||||
assertIssueChannelScopeAccess,
|
||||
assertProjectReadAccess,
|
||||
enforceHeadlessScopes,
|
||||
loadHeadlessIssueView,
|
||||
loadHeadlessIssueViews,
|
||||
publishCommittedBoardEvent,
|
||||
resolveIssueByIdOrIdentifier,
|
||||
resolveProjectReference,
|
||||
type HeadlessActorContext,
|
||||
} from "./headless-common.js";
|
||||
import {
|
||||
assertSchemaExists,
|
||||
formatBlocksAsFencedJson,
|
||||
validateSchemaBlocks,
|
||||
} from "./headless-schemas.js";
|
||||
|
||||
function canonicalizeValue(value: unknown): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(canonicalizeValue);
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
const obj = value as Record<string, unknown>;
|
||||
const sorted: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(obj).sort()) {
|
||||
const v = obj[key];
|
||||
if (v !== undefined) {
|
||||
sorted[key] = canonicalizeValue(v);
|
||||
}
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function hashCanonicalRequest(rawInput: unknown): string {
|
||||
const canonical = JSON.stringify(canonicalizeValue(rawInput));
|
||||
return createHash("sha256").update(canonical).digest("hex");
|
||||
}
|
||||
|
||||
function assertNoReservedLabelKeys(rawMutation: unknown): void {
|
||||
if (!rawMutation || typeof rawMutation !== "object") return;
|
||||
const mut = rawMutation as Record<string, unknown>;
|
||||
if (mut.set && typeof mut.set === "object" && !Array.isArray(mut.set)) {
|
||||
for (const key of Object.keys(mut.set)) {
|
||||
if (key.startsWith("paperclip.")) {
|
||||
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
|
||||
error: "reserved_label",
|
||||
code: "reserved_label",
|
||||
key,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(mut.unset)) {
|
||||
for (const key of mut.unset) {
|
||||
if (typeof key === "string" && key.startsWith("paperclip.")) {
|
||||
throw badRequest("Label keys starting with 'paperclip.' are reserved", {
|
||||
error: "reserved_label",
|
||||
code: "reserved_label",
|
||||
key,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function mutateIssueKvLabels(
|
||||
db: Db,
|
||||
issueRef: string,
|
||||
actor: HeadlessActorContext,
|
||||
rawMutation: unknown,
|
||||
): Promise<{ id: string; kvLabels: Record<string, string>; cursor: string }> {
|
||||
enforceHeadlessScopes(actor, { action: "label" });
|
||||
assertNoReservedLabelKeys(rawMutation);
|
||||
|
||||
const parsed = KvLabelMutationSchema.safeParse(rawMutation);
|
||||
if (!parsed.success) {
|
||||
throw badRequest(
|
||||
parsed.error.issues
|
||||
.map((i) => `${i.path.join(".") || "$"}: ${i.message}`)
|
||||
.join("; "),
|
||||
{
|
||||
error: "validation_error",
|
||||
code: "validation_error",
|
||||
issues: parsed.error.issues,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const target = await resolveIssueByIdOrIdentifier(db, issueRef, actor.companyId);
|
||||
|
||||
const publications: ActivityPublication[] = [];
|
||||
let committedEvent!: BoardEventView;
|
||||
|
||||
const result = await db.transaction(async (tx) => {
|
||||
const [locked] = await tx
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, target.id), eq(issues.companyId, actor.companyId)))
|
||||
.for("update");
|
||||
|
||||
if (!locked) {
|
||||
throw conflict("Issue disappeared during transaction");
|
||||
}
|
||||
|
||||
const { channelPath } = await assertIssueChannelScopeAccess(tx, locked, actor);
|
||||
if (!locked.channelId) {
|
||||
enforceHeadlessScopes(actor, { action: "label" });
|
||||
}
|
||||
|
||||
const currentKvLabels = (locked.kvLabels ?? {}) as Record<string, string>;
|
||||
const applied = applyKvLabelMutation(currentKvLabels, parsed.data);
|
||||
if (!applied.ok) {
|
||||
throw conflict("Label Compare-And-Swap precondition failed", {
|
||||
error: "label_conflict",
|
||||
code: "label_conflict",
|
||||
conflictingKeys: applied.conflictingKeys,
|
||||
currentLabels: currentKvLabels,
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await tx
|
||||
.update(issues)
|
||||
.set({
|
||||
kvLabels: applied.labels,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(issues.id, locked.id));
|
||||
|
||||
if (locked.channelId) {
|
||||
await tx
|
||||
.update(channels)
|
||||
.set({ lastActivityAt: now, updatedAt: now })
|
||||
.where(eq(channels.id, locked.channelId));
|
||||
}
|
||||
|
||||
await logActivity(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
companyId: actor.companyId,
|
||||
actorType: actor.principalType === "agent" ? "agent" : "user",
|
||||
actorId:
|
||||
actor.principalType === "agent"
|
||||
? actor.agentId!
|
||||
: (actor.userId ?? "local-board"),
|
||||
agentId: actor.agentId,
|
||||
issueId: locked.id,
|
||||
responsibleUserIdOverride: actor.responsibleUserId,
|
||||
action: "issue.kv_labels_updated",
|
||||
entityType: "issue",
|
||||
entityId: locked.id,
|
||||
details: {
|
||||
previous: currentKvLabels,
|
||||
current: applied.labels,
|
||||
},
|
||||
},
|
||||
publications,
|
||||
);
|
||||
|
||||
committedEvent = await appendBoardEvent(tx, {
|
||||
companyId: actor.companyId,
|
||||
type: "labels.changed",
|
||||
channelId: locked.channelId,
|
||||
channelPath,
|
||||
issueId: locked.id,
|
||||
identifier: locked.identifier ?? locked.id,
|
||||
actor,
|
||||
payload: {
|
||||
previous: currentKvLabels,
|
||||
current: applied.labels,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
id: locked.id,
|
||||
kvLabels: applied.labels,
|
||||
cursor: committedEvent.cursor,
|
||||
};
|
||||
});
|
||||
|
||||
for (const pub of publications) {
|
||||
publishActivity(pub);
|
||||
}
|
||||
publishCommittedBoardEvent(committedEvent);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function createBatchIssuesPlan(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
actor: HeadlessActorContext,
|
||||
rawInput: unknown,
|
||||
): Promise<BatchCreateIssuesResult> {
|
||||
const plan = validateAndSortBatchPlan(rawInput);
|
||||
if (!plan.ok) {
|
||||
const { ok: _ok, message: _msg, ...planDetails } = plan;
|
||||
throw unprocessable(plan.message, {
|
||||
error: plan.code,
|
||||
...planDetails,
|
||||
});
|
||||
}
|
||||
|
||||
enforceHeadlessScopes(actor, {
|
||||
action: "tasks.create",
|
||||
channelPath: plan.channel,
|
||||
});
|
||||
|
||||
const requestHash = hashCanonicalRequest(rawInput);
|
||||
const publications: ActivityPublication[] = [];
|
||||
const committedEvents: BoardEventView[] = [];
|
||||
|
||||
const result = await db.transaction(async (tx) => {
|
||||
if (plan.idempotencyKey) {
|
||||
// Serialize concurrent requests sharing the same (companyId, idempotencyKey)
|
||||
// before reading or writing any tasks so losers never commit duplicates.
|
||||
await tx.execute(
|
||||
sql`SELECT pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${plan.idempotencyKey}))`,
|
||||
);
|
||||
const [existingIdemp] = await tx
|
||||
.select()
|
||||
.from(issueBatchIdempotencyKeys)
|
||||
.where(
|
||||
and(
|
||||
eq(issueBatchIdempotencyKeys.companyId, companyId),
|
||||
eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (existingIdemp) {
|
||||
if (existingIdemp.requestHash === requestHash) {
|
||||
return {
|
||||
...(existingIdemp.responsePayload as unknown as BatchCreateIssuesResult),
|
||||
idempotentReplay: true,
|
||||
};
|
||||
}
|
||||
throw conflict("Idempotency key already used with a different plan payload", {
|
||||
error: "idempotency_conflict",
|
||||
code: "idempotency_conflict",
|
||||
idempotencyKey: plan.idempotencyKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const channel = plan.channel
|
||||
? await ensureChannel(tx, companyId, actor, { path: plan.channel })
|
||||
: null;
|
||||
|
||||
let planDefaultProjectId: string | null = channel?.defaultProjectId ?? null;
|
||||
if (plan.projectId !== undefined) {
|
||||
planDefaultProjectId =
|
||||
plan.projectId === null
|
||||
? null
|
||||
: await resolveProjectReference(tx, companyId, plan.projectId, actor);
|
||||
} else if (planDefaultProjectId) {
|
||||
await assertProjectReadAccess(tx, companyId, planDefaultProjectId, actor);
|
||||
}
|
||||
|
||||
// Pre-resolve external dependencies
|
||||
const externalIssueByRef = new Map<string, typeof issues.$inferSelect>();
|
||||
for (const task of plan.tasks) {
|
||||
for (const extRef of task.externalNeeds) {
|
||||
if (!externalIssueByRef.has(extRef)) {
|
||||
const extIssue = await resolveIssueByIdOrIdentifier(
|
||||
tx,
|
||||
extRef,
|
||||
companyId,
|
||||
);
|
||||
await assertIssueChannelScopeAccess(tx, extIssue, actor);
|
||||
externalIssueByRef.set(extRef, extIssue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate blocks, resultSchema, projectId, and assignees for all tasks before writing
|
||||
const resolvedTaskConfigs: Array<{
|
||||
projectId: string | null;
|
||||
assigneeAgentId: string | null;
|
||||
resultSchemaRef: string | null;
|
||||
}> = [];
|
||||
|
||||
for (const task of plan.tasks) {
|
||||
await validateSchemaBlocks(tx, companyId, task.blocks);
|
||||
const resultSchemaRef = task.resultSchema
|
||||
? await assertSchemaExists(tx, companyId, task.resultSchema)
|
||||
: null;
|
||||
|
||||
let taskProjectId = planDefaultProjectId;
|
||||
if (task.projectId === null) {
|
||||
taskProjectId = null;
|
||||
} else if (task.projectId !== undefined) {
|
||||
taskProjectId = await resolveProjectReference(
|
||||
tx,
|
||||
companyId,
|
||||
task.projectId,
|
||||
actor,
|
||||
);
|
||||
}
|
||||
|
||||
const assigneeAgentId = await resolveAssigneeAgent(tx, companyId, {
|
||||
assigneeAgentId: task.assigneeAgentId,
|
||||
for: task.for,
|
||||
});
|
||||
|
||||
resolvedTaskConfigs.push({
|
||||
projectId: taskProjectId,
|
||||
assigneeAgentId,
|
||||
resultSchemaRef,
|
||||
});
|
||||
}
|
||||
|
||||
// Atomically allocate issue numbers for the batch
|
||||
const now = new Date();
|
||||
const [maxRow] = await tx
|
||||
.select({
|
||||
maxNum: sql<number>`coalesce(max(${issues.issueNumber}), 0)`,
|
||||
})
|
||||
.from(issues)
|
||||
.where(eq(issues.companyId, companyId));
|
||||
const currentMax = Number(maxRow?.maxNum ?? 0);
|
||||
|
||||
const [companyRow] = await tx
|
||||
.update(companies)
|
||||
.set({
|
||||
issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + ${plan.tasks.length}`,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(companies.id, companyId))
|
||||
.returning({
|
||||
issueCounter: companies.issueCounter,
|
||||
issuePrefix: companies.issuePrefix,
|
||||
});
|
||||
|
||||
const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1;
|
||||
|
||||
const createdByKey = new Map<string, typeof issues.$inferSelect>();
|
||||
const createdRows: Array<typeof issues.$inferSelect> = [];
|
||||
const pendingEvents: Array<{
|
||||
issueId: string;
|
||||
identifier: string;
|
||||
key: string | null;
|
||||
type: "task.created" | "task.ready";
|
||||
payload: Record<string, unknown>;
|
||||
isTaskCreated?: boolean;
|
||||
}> = [];
|
||||
const cursorByIssueId = new Map<string, string>();
|
||||
const keyByIssueId = new Map<string, string | null>();
|
||||
|
||||
// Pre-fetch private project visibility for all referenced projects
|
||||
const referencedProjectIds = Array.from(
|
||||
new Set(
|
||||
resolvedTaskConfigs
|
||||
.map((c) => c.projectId)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
),
|
||||
);
|
||||
const privateProjectIds = new Set<string>();
|
||||
if (referencedProjectIds.length > 0) {
|
||||
const projRows = await tx
|
||||
.select({ id: projects.id, visibility: projects.visibility })
|
||||
.from(projects)
|
||||
.where(
|
||||
and(
|
||||
eq(projects.companyId, companyId),
|
||||
inArray(projects.id, referencedProjectIds),
|
||||
),
|
||||
);
|
||||
for (const p of projRows) {
|
||||
if (p.visibility === "private") privateProjectIds.add(p.id);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < plan.tasks.length; i += 1) {
|
||||
const task = plan.tasks[i]!;
|
||||
const cfg = resolvedTaskConfigs[i]!;
|
||||
const issueNumber = firstIssueNumber + i;
|
||||
const identifier = `${companyRow!.issuePrefix}-${issueNumber}`;
|
||||
const scope: IssueScope =
|
||||
(task.board ?? plan.board) ? "board" : channel ? "channel" : "board";
|
||||
const description =
|
||||
task.description !== null
|
||||
? task.description
|
||||
: task.blocks.length > 0
|
||||
? formatBlocksAsFencedJson(task.blocks)
|
||||
: null;
|
||||
const taskVisibility: "open" | "private" =
|
||||
channel?.visibility === "private" ||
|
||||
(cfg.projectId !== null && privateProjectIds.has(cfg.projectId))
|
||||
? "private"
|
||||
: "open";
|
||||
const taskIssueId = randomUUID();
|
||||
const privacyRootIssueId = taskVisibility === "private" ? taskIssueId : null;
|
||||
|
||||
const [inserted] = await tx
|
||||
.insert(issues)
|
||||
.values({
|
||||
id: taskIssueId,
|
||||
companyId,
|
||||
projectId: cfg.projectId,
|
||||
channelId: channel?.id ?? null,
|
||||
visibility: taskVisibility,
|
||||
privacyRootIssueId,
|
||||
title: task.title,
|
||||
description,
|
||||
status: "todo",
|
||||
scope,
|
||||
priority: task.priority,
|
||||
assigneeAgentId: cfg.assigneeAgentId,
|
||||
createdByAgentId: actor.agentId,
|
||||
createdByUserId: actor.agentId ? null : actor.userId,
|
||||
createdByProfile: actor.actorProfile,
|
||||
responsibleUserId: actor.responsibleUserId,
|
||||
kvLabels: task.labels,
|
||||
schemaBlocks: task.blocks,
|
||||
resultSchemaRef: cfg.resultSchemaRef,
|
||||
issueNumber,
|
||||
identifier,
|
||||
originKind: "manual",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning();
|
||||
|
||||
createdRows.push(inserted!);
|
||||
keyByIssueId.set(inserted!.id, task.key);
|
||||
if (task.key) {
|
||||
createdByKey.set(task.key, inserted!);
|
||||
}
|
||||
|
||||
if (task.tagLabels.length > 0) {
|
||||
await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels);
|
||||
}
|
||||
|
||||
const blockerIds: string[] = [];
|
||||
let hasOpenBlocker = false;
|
||||
|
||||
for (const localKey of task.localNeeds) {
|
||||
const blocker = createdByKey.get(localKey)!;
|
||||
blockerIds.push(blocker.id);
|
||||
hasOpenBlocker = true;
|
||||
}
|
||||
for (const extRef of task.externalNeeds) {
|
||||
const ext = externalIssueByRef.get(extRef)!;
|
||||
if (!blockerIds.includes(ext.id)) {
|
||||
blockerIds.push(ext.id);
|
||||
}
|
||||
if (ext.status !== "done" && ext.status !== "cancelled") {
|
||||
hasOpenBlocker = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (blockerIds.length > 0) {
|
||||
await tx
|
||||
.insert(issueRelations)
|
||||
.values(
|
||||
blockerIds.map((blockerId) => ({
|
||||
companyId,
|
||||
issueId: blockerId,
|
||||
relatedIssueId: inserted!.id,
|
||||
type: "blocks" as const,
|
||||
createdByAgentId: actor.agentId,
|
||||
createdByUserId: actor.agentId ? null : actor.userId,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing({
|
||||
target: [
|
||||
issueRelations.companyId,
|
||||
issueRelations.issueId,
|
||||
issueRelations.relatedIssueId,
|
||||
issueRelations.type,
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
await logActivity(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
companyId,
|
||||
actorType: actor.principalType === "agent" ? "agent" : "user",
|
||||
actorId:
|
||||
actor.principalType === "agent"
|
||||
? actor.agentId!
|
||||
: (actor.userId ?? "local-board"),
|
||||
agentId: actor.agentId,
|
||||
issueId: inserted!.id,
|
||||
responsibleUserIdOverride: actor.responsibleUserId,
|
||||
action: "issue.created",
|
||||
entityType: "issue",
|
||||
entityId: inserted!.id,
|
||||
details: {
|
||||
identifier,
|
||||
channel: channel?.path ?? null,
|
||||
batchKey: task.key,
|
||||
blockedByIssueIds: blockerIds,
|
||||
},
|
||||
},
|
||||
publications,
|
||||
);
|
||||
|
||||
pendingEvents.push({
|
||||
issueId: inserted!.id,
|
||||
identifier,
|
||||
key: task.key ?? null,
|
||||
type: "task.created",
|
||||
isTaskCreated: true,
|
||||
payload: {
|
||||
key: task.key,
|
||||
title: task.title,
|
||||
...(description ? { description: description.slice(0, 4000) } : {}),
|
||||
blockedByIssueIds: blockerIds,
|
||||
},
|
||||
});
|
||||
|
||||
if (!hasOpenBlocker && cfg.assigneeAgentId === null) {
|
||||
pendingEvents.push({
|
||||
issueId: inserted!.id,
|
||||
identifier,
|
||||
key: task.key ?? null,
|
||||
type: "task.ready",
|
||||
payload: { key: task.key },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (channel) {
|
||||
await tx
|
||||
.update(channels)
|
||||
.set({ lastActivityAt: now, updatedAt: now })
|
||||
.where(eq(channels.id, channel.id));
|
||||
}
|
||||
|
||||
for (const evInput of pendingEvents) {
|
||||
const evt = await appendBoardEvent(tx, {
|
||||
companyId,
|
||||
type: evInput.type,
|
||||
channelId: channel?.id ?? null,
|
||||
channelPath: channel?.path ?? null,
|
||||
issueId: evInput.issueId,
|
||||
identifier: evInput.identifier,
|
||||
actor,
|
||||
payload: evInput.payload,
|
||||
});
|
||||
committedEvents.push(evt);
|
||||
cursorByIssueId.set(evInput.issueId, evt.cursor);
|
||||
}
|
||||
|
||||
const issueViews = await loadHeadlessIssueViews(tx, createdRows);
|
||||
const items: BatchCreatedTaskItem[] = issueViews.map((issueView) => {
|
||||
const cursor = cursorByIssueId.get(issueView.id) ?? issueView.cursor;
|
||||
return {
|
||||
key: keyByIssueId.get(issueView.id) ?? null,
|
||||
id: issueView.id,
|
||||
identifier: issueView.identifier,
|
||||
cursor,
|
||||
issue: {
|
||||
...issueView,
|
||||
cursor,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const latestCursor =
|
||||
committedEvents[committedEvents.length - 1]?.cursor ?? "evt_0";
|
||||
const batchResult: BatchCreateIssuesResult = {
|
||||
tasks: items,
|
||||
cursor: latestCursor,
|
||||
idempotentReplay: false,
|
||||
};
|
||||
|
||||
if (plan.idempotencyKey) {
|
||||
const [insertedKey] = await tx
|
||||
.insert(issueBatchIdempotencyKeys)
|
||||
.values({
|
||||
companyId,
|
||||
idempotencyKey: plan.idempotencyKey,
|
||||
requestHash,
|
||||
responsePayload: batchResult as unknown as Record<string, unknown>,
|
||||
})
|
||||
.onConflictDoNothing({
|
||||
target: [
|
||||
issueBatchIdempotencyKeys.companyId,
|
||||
issueBatchIdempotencyKeys.idempotencyKey,
|
||||
],
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (!insertedKey) {
|
||||
const [raced] = await tx
|
||||
.select()
|
||||
.from(issueBatchIdempotencyKeys)
|
||||
.where(
|
||||
and(
|
||||
eq(issueBatchIdempotencyKeys.companyId, companyId),
|
||||
eq(issueBatchIdempotencyKeys.idempotencyKey, plan.idempotencyKey),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (raced && raced.requestHash === requestHash) {
|
||||
return {
|
||||
...(raced.responsePayload as unknown as BatchCreateIssuesResult),
|
||||
idempotentReplay: true,
|
||||
};
|
||||
}
|
||||
throw conflict(
|
||||
"Idempotency key already used with a different plan payload",
|
||||
{
|
||||
error: "idempotency_conflict",
|
||||
code: "idempotency_conflict",
|
||||
idempotencyKey: plan.idempotencyKey,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return batchResult;
|
||||
});
|
||||
|
||||
if (!result.idempotentReplay) {
|
||||
for (const pub of publications) {
|
||||
publishActivity(pub);
|
||||
}
|
||||
for (const evt of committedEvents) {
|
||||
publishCommittedBoardEvent(evt);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { companySchemas } from "@paperclipai/db";
|
||||
import {
|
||||
assertSafeRegexPattern,
|
||||
BUILT_IN_COMPANY_SCHEMAS,
|
||||
canonicalizeJsonSchema,
|
||||
createCompanySchemaInputSchema,
|
||||
parseSchemaRef,
|
||||
schemaBlockSchema,
|
||||
validateAgainstJsonSchema,
|
||||
type CompanySchemaView,
|
||||
type JsonSchemaObject,
|
||||
type SchemaBlock,
|
||||
} from "@paperclipai/shared";
|
||||
import { badRequest, conflict, notFound, unprocessable } from "../errors.js";
|
||||
import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
|
||||
import { enforceHeadlessScopes, type DbOrTx, type HeadlessActorContext } from "./headless-common.js";
|
||||
|
||||
const BUILT_IN_CREATED_AT = "1970-01-01T00:00:00.000Z";
|
||||
|
||||
function builtInSchemaToView(
|
||||
entry: (typeof BUILT_IN_COMPANY_SCHEMAS)[number],
|
||||
): CompanySchemaView {
|
||||
return {
|
||||
id: `builtin:${entry.ref}`,
|
||||
companyId: null,
|
||||
name: entry.name,
|
||||
version: entry.version,
|
||||
ref: entry.ref,
|
||||
description: entry.description,
|
||||
jsonSchema: entry.jsonSchema,
|
||||
builtIn: true,
|
||||
createdAt: BUILT_IN_CREATED_AT,
|
||||
};
|
||||
}
|
||||
|
||||
function customSchemaRowToView(
|
||||
row: typeof companySchemas.$inferSelect,
|
||||
): CompanySchemaView {
|
||||
return {
|
||||
id: row.id,
|
||||
companyId: row.companyId,
|
||||
name: row.name,
|
||||
version: row.version,
|
||||
ref: `${row.name}@${row.version}`,
|
||||
description: row.description ?? null,
|
||||
jsonSchema: row.jsonSchema as JsonSchemaObject,
|
||||
builtIn: false,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function findBuiltInSchema(name: string, version: number): CompanySchemaView | null {
|
||||
const match = BUILT_IN_COMPANY_SCHEMAS.find(
|
||||
(b) => b.name === name && b.version === version,
|
||||
);
|
||||
return match ? builtInSchemaToView(match) : null;
|
||||
}
|
||||
|
||||
async function findCustomSchema(
|
||||
dbOrTx: DbOrTx,
|
||||
companyId: string,
|
||||
name: string,
|
||||
version: number,
|
||||
): Promise<CompanySchemaView | null> {
|
||||
const [row] = await dbOrTx
|
||||
.select()
|
||||
.from(companySchemas)
|
||||
.where(
|
||||
and(
|
||||
eq(companySchemas.companyId, companyId),
|
||||
eq(companySchemas.name, name),
|
||||
eq(companySchemas.version, version),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return row ? customSchemaRowToView(row) : null;
|
||||
}
|
||||
|
||||
async function resolveSchemaView(
|
||||
dbOrTx: DbOrTx,
|
||||
companyId: string,
|
||||
name: string,
|
||||
version: number,
|
||||
): Promise<CompanySchemaView | null> {
|
||||
const custom = await findCustomSchema(dbOrTx, companyId, name, version);
|
||||
if (custom) return custom;
|
||||
return findBuiltInSchema(name, version);
|
||||
}
|
||||
|
||||
export function formatBlocksAsFencedJson(blocks: SchemaBlock[]): string {
|
||||
return blocks
|
||||
.map(
|
||||
(b) =>
|
||||
`\`\`\`json\n${JSON.stringify(
|
||||
{ schema: `${b.schema}@${b.version}`, data: b.data },
|
||||
null,
|
||||
2,
|
||||
)}\n\`\`\``,
|
||||
)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
export async function listCompanySchemas(
|
||||
dbOrTx: DbOrTx,
|
||||
companyId: string,
|
||||
actor?: HeadlessActorContext,
|
||||
): Promise<CompanySchemaView[]> {
|
||||
if (actor) {
|
||||
enforceHeadlessScopes(actor, { action: "read" });
|
||||
}
|
||||
const rows = await dbOrTx
|
||||
.select()
|
||||
.from(companySchemas)
|
||||
.where(eq(companySchemas.companyId, companyId))
|
||||
.orderBy(asc(companySchemas.name), asc(companySchemas.version));
|
||||
|
||||
const customViews = rows.map(customSchemaRowToView);
|
||||
const customRefs = new Set(customViews.map((s) => s.ref));
|
||||
const combined: CompanySchemaView[] = [
|
||||
...customViews,
|
||||
...BUILT_IN_COMPANY_SCHEMAS.filter((b) => !customRefs.has(b.ref)).map(
|
||||
builtInSchemaToView,
|
||||
),
|
||||
];
|
||||
|
||||
combined.sort((a, b) => {
|
||||
const nameCmp = a.name.localeCompare(b.name);
|
||||
if (nameCmp !== 0) return nameCmp;
|
||||
return a.version - b.version;
|
||||
});
|
||||
|
||||
return combined;
|
||||
}
|
||||
|
||||
export async function getCompanySchema(
|
||||
dbOrTx: DbOrTx,
|
||||
companyId: string,
|
||||
ref: string,
|
||||
actor?: HeadlessActorContext,
|
||||
): Promise<CompanySchemaView> {
|
||||
if (actor) {
|
||||
enforceHeadlessScopes(actor, { action: "read" });
|
||||
}
|
||||
let parsed: ReturnType<typeof parseSchemaRef>;
|
||||
try {
|
||||
parsed = parseSchemaRef(ref);
|
||||
} catch (err) {
|
||||
throw badRequest(
|
||||
err instanceof Error ? err.message : `Invalid schema ref "${ref}"`,
|
||||
{ error: "invalid_schema_ref", code: "invalid_schema_ref", ref },
|
||||
);
|
||||
}
|
||||
|
||||
const found = await resolveSchemaView(
|
||||
dbOrTx,
|
||||
companyId,
|
||||
parsed.name,
|
||||
parsed.version,
|
||||
);
|
||||
if (!found) {
|
||||
throw notFound(`Schema '${parsed.ref}' not found`, {
|
||||
error: "schema_not_found",
|
||||
code: "schema_not_found",
|
||||
ref: parsed.ref,
|
||||
});
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function assertSafeJsonSchemaPatterns(node: unknown, path = "$"): void {
|
||||
if (Array.isArray(node)) {
|
||||
for (let i = 0; i < node.length; i += 1) {
|
||||
assertSafeJsonSchemaPatterns(node[i], `${path}[${i}]`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!node || typeof node !== "object") return;
|
||||
const rec = node as Record<string, unknown>;
|
||||
if (typeof rec.pattern === "string") {
|
||||
try {
|
||||
assertSafeRegexPattern(rec.pattern);
|
||||
} catch (err) {
|
||||
throw badRequest(
|
||||
`${path}.pattern: ${err instanceof Error ? err.message : "Invalid or unsafe regex pattern"}`,
|
||||
{
|
||||
error: "validation_error",
|
||||
code: "validation_error",
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
if (rec.properties && typeof rec.properties === "object" && !Array.isArray(rec.properties)) {
|
||||
for (const [k, v] of Object.entries(rec.properties as Record<string, unknown>)) {
|
||||
assertSafeJsonSchemaPatterns(v, `${path}.properties.${k}`);
|
||||
}
|
||||
}
|
||||
if (rec.items !== undefined) {
|
||||
assertSafeJsonSchemaPatterns(rec.items, `${path}.items`);
|
||||
}
|
||||
if (rec.additionalProperties && typeof rec.additionalProperties === "object") {
|
||||
assertSafeJsonSchemaPatterns(rec.additionalProperties, `${path}.additionalProperties`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createCompanySchema(
|
||||
db: Db,
|
||||
companyId: string,
|
||||
actor: HeadlessActorContext,
|
||||
rawInput: unknown,
|
||||
): Promise<{ schema: CompanySchemaView; created: boolean }> {
|
||||
enforceHeadlessScopes(actor, { action: "post" });
|
||||
const parsedInput = createCompanySchemaInputSchema.safeParse(rawInput);
|
||||
if (!parsedInput.success) {
|
||||
throw badRequest(
|
||||
parsedInput.error.issues
|
||||
.map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`)
|
||||
.join("; "),
|
||||
{
|
||||
error: "validation_error",
|
||||
code: "validation_error",
|
||||
issues: parsedInput.error.issues,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const input = parsedInput.data;
|
||||
assertSafeJsonSchemaPatterns(input.jsonSchema);
|
||||
const parsedRef = input.ref
|
||||
? parseSchemaRef(input.ref)
|
||||
: parseSchemaRef(`${input.name!}@${input.version!}`);
|
||||
|
||||
if (
|
||||
input.ref &&
|
||||
((input.name && input.name !== parsedRef.name) ||
|
||||
(input.version !== undefined && input.version !== parsedRef.version))
|
||||
) {
|
||||
throw badRequest("Schema 'ref' disagrees with 'name' or 'version'", {
|
||||
error: "validation_error",
|
||||
code: "validation_error",
|
||||
});
|
||||
}
|
||||
|
||||
const incomingCanonical = canonicalizeJsonSchema(input.jsonSchema);
|
||||
const builtIn = findBuiltInSchema(parsedRef.name, parsedRef.version);
|
||||
if (builtIn) {
|
||||
if (canonicalizeJsonSchema(builtIn.jsonSchema) === incomingCanonical) {
|
||||
return { schema: builtIn, created: false };
|
||||
}
|
||||
throw conflict(
|
||||
`Built-in schema '${parsedRef.ref}' is immutable; register ${parsedRef.name}@${parsedRef.version + 1} instead`,
|
||||
{
|
||||
error: "schema_version_immutable",
|
||||
code: "schema_version_immutable",
|
||||
ref: parsedRef.ref,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const publications: ActivityPublication[] = [];
|
||||
const outcome = await db.transaction(async (tx) => {
|
||||
const existing = await findCustomSchema(
|
||||
tx,
|
||||
companyId,
|
||||
parsedRef.name,
|
||||
parsedRef.version,
|
||||
);
|
||||
if (existing) {
|
||||
if (canonicalizeJsonSchema(existing.jsonSchema) === incomingCanonical) {
|
||||
return { schema: existing, created: false };
|
||||
}
|
||||
throw conflict(
|
||||
`Schema '${parsedRef.ref}' already exists with a different definition; register ${parsedRef.name}@${parsedRef.version + 1} instead`,
|
||||
{
|
||||
error: "schema_version_immutable",
|
||||
code: "schema_version_immutable",
|
||||
ref: parsedRef.ref,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const [inserted] = await tx
|
||||
.insert(companySchemas)
|
||||
.values({
|
||||
companyId,
|
||||
name: parsedRef.name,
|
||||
version: parsedRef.version,
|
||||
description: input.description ?? null,
|
||||
jsonSchema: input.jsonSchema,
|
||||
createdByAgentId: actor.agentId,
|
||||
createdByUserId: actor.agentId ? null : actor.userId,
|
||||
createdByProfile: actor.actorProfile,
|
||||
})
|
||||
.onConflictDoNothing({
|
||||
target: [
|
||||
companySchemas.companyId,
|
||||
companySchemas.name,
|
||||
companySchemas.version,
|
||||
],
|
||||
})
|
||||
.returning();
|
||||
|
||||
if (!inserted) {
|
||||
const raced = await findCustomSchema(
|
||||
tx,
|
||||
companyId,
|
||||
parsedRef.name,
|
||||
parsedRef.version,
|
||||
);
|
||||
if (raced && canonicalizeJsonSchema(raced.jsonSchema) === incomingCanonical) {
|
||||
return { schema: raced, created: false };
|
||||
}
|
||||
throw conflict(
|
||||
`Schema '${parsedRef.ref}' already exists with a different definition; register ${parsedRef.name}@${parsedRef.version + 1} instead`,
|
||||
{
|
||||
error: "schema_version_immutable",
|
||||
code: "schema_version_immutable",
|
||||
ref: parsedRef.ref,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
await logActivity(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
companyId,
|
||||
actorType: actor.principalType === "agent" ? "agent" : "user",
|
||||
actorId:
|
||||
actor.principalType === "agent"
|
||||
? actor.agentId!
|
||||
: (actor.userId ?? "local-board"),
|
||||
agentId: actor.agentId,
|
||||
responsibleUserIdOverride: actor.responsibleUserId,
|
||||
action: "schema.created",
|
||||
entityType: "company_schema",
|
||||
entityId: inserted.id,
|
||||
details: {
|
||||
ref: parsedRef.ref,
|
||||
name: parsedRef.name,
|
||||
version: parsedRef.version,
|
||||
},
|
||||
},
|
||||
publications,
|
||||
);
|
||||
|
||||
return { schema: customSchemaRowToView(inserted), created: true };
|
||||
});
|
||||
|
||||
for (const pub of publications) {
|
||||
publishActivity(pub);
|
||||
}
|
||||
|
||||
return outcome;
|
||||
}
|
||||
|
||||
const schemaBlockArraySchema = z.array(schemaBlockSchema);
|
||||
|
||||
export async function validateSchemaBlocks(
|
||||
dbOrTx: DbOrTx,
|
||||
companyId: string,
|
||||
blocks?: SchemaBlock[],
|
||||
): Promise<SchemaBlock[]> {
|
||||
if (!blocks || blocks.length === 0) return [];
|
||||
|
||||
const parsedBlocks = schemaBlockArraySchema.safeParse(blocks);
|
||||
if (!parsedBlocks.success) {
|
||||
throw unprocessable(
|
||||
parsedBlocks.error.issues
|
||||
.map((issue) => `${issue.path.join(".") || "$"}: ${issue.message}`)
|
||||
.join("; "),
|
||||
{
|
||||
error: "schema_validation_failed",
|
||||
code: "schema_validation_failed",
|
||||
details: parsedBlocks.error.issues.map((i) => i.message),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const cache = new Map<string, CompanySchemaView>();
|
||||
for (const block of parsedBlocks.data) {
|
||||
const ref = `${block.schema}@${block.version}`;
|
||||
let schemaView = cache.get(ref);
|
||||
if (!schemaView) {
|
||||
const resolved = await resolveSchemaView(
|
||||
dbOrTx,
|
||||
companyId,
|
||||
block.schema,
|
||||
block.version,
|
||||
);
|
||||
if (!resolved) {
|
||||
throw unprocessable(`Unknown schema '${ref}'`, {
|
||||
error: "schema_validation_failed",
|
||||
code: "schema_validation_failed",
|
||||
schema: ref,
|
||||
details: [`Unknown schema '${ref}'`],
|
||||
});
|
||||
}
|
||||
schemaView = resolved;
|
||||
cache.set(ref, schemaView);
|
||||
}
|
||||
|
||||
const check = validateAgainstJsonSchema(schemaView.jsonSchema, block.data);
|
||||
if (!check.valid) {
|
||||
throw unprocessable(
|
||||
`Block '${ref}' failed schema validation: ${check.errors.join("; ")}`,
|
||||
{
|
||||
error: "schema_validation_failed",
|
||||
code: "schema_validation_failed",
|
||||
schema: ref,
|
||||
details: check.errors,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return parsedBlocks.data;
|
||||
}
|
||||
|
||||
export async function assertSchemaExists(
|
||||
dbOrTx: DbOrTx,
|
||||
companyId: string,
|
||||
ref: string,
|
||||
): Promise<string> {
|
||||
let parsed: ReturnType<typeof parseSchemaRef>;
|
||||
try {
|
||||
parsed = parseSchemaRef(ref);
|
||||
} catch (err) {
|
||||
throw unprocessable(
|
||||
err instanceof Error ? err.message : `Invalid schema ref '${ref}'`,
|
||||
{
|
||||
error: "invalid_schema_ref",
|
||||
code: "invalid_schema_ref",
|
||||
ref,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const found = await resolveSchemaView(
|
||||
dbOrTx,
|
||||
companyId,
|
||||
parsed.name,
|
||||
parsed.version,
|
||||
);
|
||||
if (!found) {
|
||||
throw unprocessable(`Unknown schema '${parsed.ref}'`, {
|
||||
error: "schema_not_found",
|
||||
code: "schema_not_found",
|
||||
ref: parsed.ref,
|
||||
});
|
||||
}
|
||||
return parsed.ref;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,10 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio
|
||||
|
||||
type WriteDb = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
|
||||
export function insertIssueComment(db: WriteDb, input: PgInsertValue<typeof issueComments> & { companyId: string }) {
|
||||
export function insertIssueComment(
|
||||
db: WriteDb,
|
||||
input: PgInsertValue<typeof issueComments> & { companyId: string },
|
||||
): Promise<Array<typeof issueComments.$inferSelect>> {
|
||||
return db.transaction(async tx => {
|
||||
await notifyStatusCardIssueChange(tx, input.companyId);
|
||||
await notifyIssueRecovery(tx, { companyId: input.companyId,
|
||||
|
||||
@@ -43,6 +43,7 @@ import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
agents,
|
||||
assets,
|
||||
channels,
|
||||
chatVoiceSessions,
|
||||
authUsers,
|
||||
companySecretProposals,
|
||||
@@ -150,6 +151,11 @@ import { logger } from "../middleware/logger.js";
|
||||
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
import { withTelemetryCompany } from "../telemetry-company-scope.js";
|
||||
import {
|
||||
appendBoardEvent,
|
||||
publishCommittedBoardEvent,
|
||||
} from "./headless-common.js";
|
||||
import type { BoardEventView } from "@paperclipai/shared";
|
||||
import { emitPlanApprovedAfterCommit } from "./product-telemetry.js";
|
||||
import { authorizationService } from "./authorization.js";
|
||||
import { isCloudManagedInstance } from "./cloud-instance.js";
|
||||
@@ -167,6 +173,7 @@ import {
|
||||
} from "./issue-review-policy.js";
|
||||
import {
|
||||
issueService,
|
||||
listIssueDependencyReadinessMap,
|
||||
executeIssuePostCommitActions,
|
||||
type IssuePostCommitAction,
|
||||
ensureAssignmentIssueAccessGrant,
|
||||
@@ -555,6 +562,8 @@ function assertInteractionResolutionAllowed(
|
||||
type IssueResolutionContext = {
|
||||
id: string;
|
||||
companyId: string;
|
||||
identifier?: string | null;
|
||||
channelId?: string | null;
|
||||
status: string;
|
||||
executionRunId: string | null;
|
||||
hiddenAt?: Date | null;
|
||||
@@ -2688,6 +2697,171 @@ export function issueThreadInteractionService(
|
||||
}
|
||||
}
|
||||
|
||||
function toInteractionBoardEventActor(actor: InteractionActor) {
|
||||
return actor.agentId
|
||||
? {
|
||||
principalType: "agent" as const,
|
||||
userId: null,
|
||||
agentId: actor.agentId,
|
||||
agentName: null,
|
||||
actorProfile: null,
|
||||
}
|
||||
: {
|
||||
principalType: "user" as const,
|
||||
userId: actor.userId ?? null,
|
||||
agentId: null,
|
||||
agentName: null,
|
||||
actorProfile: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveChannelPathForIssue(
|
||||
tx: Db,
|
||||
channelId: string | null | undefined,
|
||||
): Promise<string | null> {
|
||||
if (!channelId) return null;
|
||||
const [ch] = await tx
|
||||
.select({ path: channels.path })
|
||||
.from(channels)
|
||||
.where(eq(channels.id, channelId))
|
||||
.limit(1);
|
||||
return ch?.path ?? null;
|
||||
}
|
||||
|
||||
const hasRelationalBoardEventStore = Boolean(
|
||||
(db as unknown as { $client?: unknown; _?: unknown })?.$client ||
|
||||
(db as unknown as { _?: unknown })?._,
|
||||
);
|
||||
|
||||
async function appendInteractionResolvedBoardEvent(
|
||||
tx: Db,
|
||||
args: {
|
||||
issue: {
|
||||
id: string;
|
||||
companyId: string;
|
||||
channelId?: string | null;
|
||||
identifier?: string | null;
|
||||
};
|
||||
interaction: Pick<IssueThreadInteractionRow, "id" | "kind" | "status">;
|
||||
decision: "approve" | "reject";
|
||||
actor: InteractionActor;
|
||||
note?: string | null;
|
||||
},
|
||||
): Promise<BoardEventView | null> {
|
||||
if (!hasRelationalBoardEventStore) return null;
|
||||
const channelPath = await resolveChannelPathForIssue(tx, args.issue.channelId);
|
||||
const trimmedNote = args.note?.trim();
|
||||
return appendBoardEvent(tx, {
|
||||
companyId: args.issue.companyId,
|
||||
type: "interaction.resolved",
|
||||
channelId: args.issue.channelId ?? null,
|
||||
channelPath,
|
||||
issueId: args.issue.id,
|
||||
identifier: args.issue.identifier ?? args.issue.id,
|
||||
actor: toInteractionBoardEventActor(args.actor),
|
||||
payload: {
|
||||
interactionId: args.interaction.id,
|
||||
kind: args.interaction.kind,
|
||||
status: args.interaction.status,
|
||||
decision: args.decision,
|
||||
...(trimmedNote ? { note: trimmedNote } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function requeuePoolTaskOnResolve(
|
||||
tx: Db,
|
||||
args: {
|
||||
issueId: string;
|
||||
companyId: string;
|
||||
interaction: Pick<IssueThreadInteractionRow, "id" | "continuationPolicy">;
|
||||
actor: InteractionActor;
|
||||
publications: ActivityPublication[];
|
||||
boardEventsOut: BoardEventView[];
|
||||
},
|
||||
): Promise<void> {
|
||||
if (args.interaction.continuationPolicy !== "requeue_on_resolve") return;
|
||||
const [freshIssue] = await tx
|
||||
.select({
|
||||
id: issues.id,
|
||||
companyId: issues.companyId,
|
||||
status: issues.status,
|
||||
channelId: issues.channelId,
|
||||
identifier: issues.identifier,
|
||||
kvLabels: issues.kvLabels,
|
||||
})
|
||||
.from(issues)
|
||||
.where(and(eq(issues.id, args.issueId), eq(issues.companyId, args.companyId)))
|
||||
.limit(1);
|
||||
if (!freshIssue || freshIssue.status !== "blocked") return;
|
||||
|
||||
const [otherPending] = await tx
|
||||
.select({ id: issueThreadInteractions.id })
|
||||
.from(issueThreadInteractions)
|
||||
.where(
|
||||
and(
|
||||
eq(issueThreadInteractions.companyId, args.companyId),
|
||||
eq(issueThreadInteractions.issueId, args.issueId),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (otherPending) return;
|
||||
|
||||
const readiness = (
|
||||
await listIssueDependencyReadinessMap(
|
||||
tx as unknown as Db,
|
||||
args.companyId,
|
||||
[args.issueId],
|
||||
false,
|
||||
)
|
||||
).get(args.issueId);
|
||||
if (readiness && !readiness.isDependencyReady) return;
|
||||
|
||||
await issueService(db).update(
|
||||
args.issueId,
|
||||
{
|
||||
status: "todo",
|
||||
actorAgentId: args.actor.agentId ?? null,
|
||||
actorUserId: args.actor.userId ?? null,
|
||||
},
|
||||
tx,
|
||||
args.publications,
|
||||
);
|
||||
|
||||
const channelPath = await resolveChannelPathForIssue(tx, freshIssue.channelId);
|
||||
const eventActor = toInteractionBoardEventActor(args.actor);
|
||||
const identifier = freshIssue.identifier ?? freshIssue.id;
|
||||
const payload = {
|
||||
interactionId: args.interaction.id,
|
||||
kvLabels: freshIssue.kvLabels ?? {},
|
||||
};
|
||||
args.boardEventsOut.push(
|
||||
await appendBoardEvent(tx, {
|
||||
companyId: args.companyId,
|
||||
type: "task.unblocked",
|
||||
channelId: freshIssue.channelId,
|
||||
channelPath,
|
||||
issueId: freshIssue.id,
|
||||
identifier,
|
||||
actor: eventActor,
|
||||
payload,
|
||||
}),
|
||||
);
|
||||
args.boardEventsOut.push(
|
||||
await appendBoardEvent(tx, {
|
||||
companyId: args.companyId,
|
||||
type: "task.ready",
|
||||
channelId: freshIssue.channelId,
|
||||
channelPath,
|
||||
issueId: freshIssue.id,
|
||||
identifier,
|
||||
actor: eventActor,
|
||||
payload,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function acceptRequestConfirmation(args: {
|
||||
issue: { id: string; companyId: string };
|
||||
current: IssueThreadInteractionRow;
|
||||
@@ -2712,6 +2886,7 @@ export function issueThreadInteractionService(
|
||||
|
||||
const now = new Date();
|
||||
const postCommitActivityPublications: ActivityPublication[] = [];
|
||||
const postCommitBoardEvents: BoardEventView[] = [];
|
||||
const result = await db.transaction(async (tx) => {
|
||||
await assertInteractionRunWriteAllowed(tx as unknown as Db, args.issue, args.actor, [JSON.stringify(args.input)]);
|
||||
await notifyChatConfirmationResolution(tx, args.current);
|
||||
@@ -2727,6 +2902,8 @@ export function issueThreadInteractionService(
|
||||
.select({
|
||||
id: issues.id,
|
||||
companyId: issues.companyId,
|
||||
identifier: issues.identifier,
|
||||
channelId: issues.channelId,
|
||||
status: issues.status,
|
||||
executionRunId: issues.executionRunId,
|
||||
hiddenAt: issues.hiddenAt,
|
||||
@@ -2835,6 +3012,18 @@ export function issueThreadInteractionService(
|
||||
tx,
|
||||
acceptedInteraction,
|
||||
);
|
||||
const acceptedBoardEvent = await appendInteractionResolvedBoardEvent(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
issue: issueContext,
|
||||
interaction: updated,
|
||||
decision: "approve",
|
||||
actor: args.actor,
|
||||
},
|
||||
);
|
||||
if (acceptedBoardEvent) {
|
||||
postCommitBoardEvents.push(acceptedBoardEvent);
|
||||
}
|
||||
|
||||
let continuationIssue: IssueWakeTarget | null = null;
|
||||
const acceptedPlanTarget = readAcceptedPlanConfirmationTarget(
|
||||
@@ -2952,6 +3141,22 @@ export function issueThreadInteractionService(
|
||||
workMode: executionIssue.workMode,
|
||||
};
|
||||
}
|
||||
} else if (
|
||||
lockedCurrent.continuationPolicy === "requeue_on_resolve" &&
|
||||
issueContext.status === "blocked"
|
||||
) {
|
||||
const eventsBeforeRequeue = postCommitBoardEvents.length;
|
||||
await requeuePoolTaskOnResolve(tx as unknown as Db, {
|
||||
issueId: args.issue.id,
|
||||
companyId: args.issue.companyId,
|
||||
interaction: lockedCurrent,
|
||||
actor: args.actor,
|
||||
publications: postCommitActivityPublications,
|
||||
boardEventsOut: postCommitBoardEvents,
|
||||
});
|
||||
if (postCommitBoardEvents.length === eventsBeforeRequeue) {
|
||||
await touchIssue(tx, args.issue.id, args.issue.companyId);
|
||||
}
|
||||
} else {
|
||||
await touchIssue(tx, args.issue.id, args.issue.companyId);
|
||||
}
|
||||
@@ -2995,6 +3200,7 @@ export function issueThreadInteractionService(
|
||||
});
|
||||
const publish = async (committedDb: Db) => {
|
||||
for (const publication of postCommitActivityPublications) publishActivity(publication);
|
||||
for (const event of postCommitBoardEvents) publishCommittedBoardEvent(event);
|
||||
await emitInteractionResolvedTelemetry(committedDb, result.interaction);
|
||||
};
|
||||
if (args.mutationOptions?.deferConfirmationCommitEffects) args.mutationOptions.deferConfirmationCommitEffects(publish);
|
||||
@@ -3031,6 +3237,8 @@ export function issueThreadInteractionService(
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const rejectPostCommitActivityPublications: ActivityPublication[] = [];
|
||||
const rejectPostCommitBoardEvents: BoardEventView[] = [];
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
await assertInteractionRunWriteAllowed(tx as unknown as Db, args.issue, args.actor, [JSON.stringify(args.input)]);
|
||||
await notifyChatConfirmationResolution(tx, args.current);
|
||||
@@ -3041,6 +3249,8 @@ export function issueThreadInteractionService(
|
||||
.select({
|
||||
id: issues.id,
|
||||
companyId: issues.companyId,
|
||||
identifier: issues.identifier,
|
||||
channelId: issues.channelId,
|
||||
status: issues.status,
|
||||
executionRunId: issues.executionRunId,
|
||||
workMode: issues.workMode,
|
||||
@@ -3144,6 +3354,19 @@ export function issueThreadInteractionService(
|
||||
tx,
|
||||
rejectedInteraction,
|
||||
);
|
||||
const rejectedBoardEvent = await appendInteractionResolvedBoardEvent(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
issue: issueContext,
|
||||
interaction: resolved,
|
||||
decision: "reject",
|
||||
actor: args.actor,
|
||||
note: reason || null,
|
||||
},
|
||||
);
|
||||
if (rejectedBoardEvent) {
|
||||
rejectPostCommitBoardEvents.push(rejectedBoardEvent);
|
||||
}
|
||||
const rejectedPlanNeedsRevision =
|
||||
lockedCurrent.kind === "request_confirmation" &&
|
||||
readAcceptedPlanConfirmationTarget(
|
||||
@@ -3178,7 +3401,24 @@ export function issueThreadInteractionService(
|
||||
actorUserId: args.actor.userId ?? null,
|
||||
},
|
||||
tx,
|
||||
rejectPostCommitActivityPublications,
|
||||
);
|
||||
} else if (
|
||||
lockedCurrent.continuationPolicy === "requeue_on_resolve" &&
|
||||
issueContext.status === "blocked"
|
||||
) {
|
||||
const eventsBeforeRequeue = rejectPostCommitBoardEvents.length;
|
||||
await requeuePoolTaskOnResolve(tx as unknown as Db, {
|
||||
issueId: args.issue.id,
|
||||
companyId: args.issue.companyId,
|
||||
interaction: lockedCurrent,
|
||||
actor: args.actor,
|
||||
publications: rejectPostCommitActivityPublications,
|
||||
boardEventsOut: rejectPostCommitBoardEvents,
|
||||
});
|
||||
if (rejectPostCommitBoardEvents.length === eventsBeforeRequeue) {
|
||||
await touchIssue(tx, args.issue.id, args.issue.companyId);
|
||||
}
|
||||
} else {
|
||||
await touchIssue(tx, args.issue.id, args.issue.companyId);
|
||||
}
|
||||
@@ -3190,7 +3430,11 @@ export function issueThreadInteractionService(
|
||||
});
|
||||
|
||||
const rejected = hydrateInteraction(updated);
|
||||
const publish = (committedDb: Db) => emitInteractionResolvedTelemetry(committedDb, rejected);
|
||||
const publish = async (committedDb: Db) => {
|
||||
for (const publication of rejectPostCommitActivityPublications) publishActivity(publication);
|
||||
for (const event of rejectPostCommitBoardEvents) publishCommittedBoardEvent(event);
|
||||
await emitInteractionResolvedTelemetry(committedDb, rejected);
|
||||
};
|
||||
if (args.mutationOptions?.deferConfirmationCommitEffects) args.mutationOptions.deferConfirmationCommitEffects(publish);
|
||||
else await publish(db);
|
||||
return rejected;
|
||||
@@ -6821,10 +7065,17 @@ export function issueThreadInteractionService(
|
||||
}
|
||||
}
|
||||
|
||||
const postCommitActivityPublications: ActivityPublication[] = [];
|
||||
const postCommitBoardEvents: BoardEventView[] = [];
|
||||
let shouldTouchIssueAfterCommit = false;
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
// Serialize against task completion/cancellation and use the persisted
|
||||
// status, including when the caller read the task before it closed.
|
||||
const [issueRow] = await tx.select({ status: issues.status }).from(issues)
|
||||
const [issueRow] = await tx.select({
|
||||
status: issues.status,
|
||||
identifier: issues.identifier,
|
||||
channelId: issues.channelId,
|
||||
}).from(issues)
|
||||
.where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId))).for("update");
|
||||
if (!issueRow) throw interactionNotFoundError();
|
||||
let historicalAnswer = false;
|
||||
@@ -6875,6 +7126,37 @@ export function issueThreadInteractionService(
|
||||
await tx
|
||||
.insert(issueQuestionResponseDeliveries)
|
||||
.values(questionResponseDeliveryValues(answered));
|
||||
const answeredBoardEvent = await appendInteractionResolvedBoardEvent(
|
||||
tx as unknown as Db,
|
||||
{
|
||||
issue: {
|
||||
id: issue.id,
|
||||
companyId: issue.companyId,
|
||||
channelId: issueRow.channelId,
|
||||
identifier: issueRow.identifier,
|
||||
},
|
||||
interaction: row,
|
||||
decision: "approve",
|
||||
actor,
|
||||
note: input.summaryMarkdown ?? null,
|
||||
},
|
||||
);
|
||||
if (answeredBoardEvent) {
|
||||
postCommitBoardEvents.push(answeredBoardEvent);
|
||||
}
|
||||
const eventsBeforeRequeue = postCommitBoardEvents.length;
|
||||
await requeuePoolTaskOnResolve(tx as unknown as Db, {
|
||||
issueId: issue.id,
|
||||
companyId: issue.companyId,
|
||||
interaction: current,
|
||||
actor,
|
||||
publications: postCommitActivityPublications,
|
||||
boardEventsOut: postCommitBoardEvents,
|
||||
});
|
||||
shouldTouchIssueAfterCommit =
|
||||
postCommitBoardEvents.length === eventsBeforeRequeue;
|
||||
} else {
|
||||
shouldTouchIssueAfterCommit = true;
|
||||
}
|
||||
// Provider callbacks use this hook to atomically claim and complete
|
||||
// the action that resolved the interaction. Settle all remaining
|
||||
@@ -6889,7 +7171,15 @@ export function issueThreadInteractionService(
|
||||
return row;
|
||||
});
|
||||
|
||||
await touchIssue(db, issue.id, issue.companyId);
|
||||
for (const publication of postCommitActivityPublications) {
|
||||
publishActivity(publication);
|
||||
}
|
||||
for (const event of postCommitBoardEvents) {
|
||||
publishCommittedBoardEvent(event);
|
||||
}
|
||||
if (shouldTouchIssueAfterCommit) {
|
||||
await touchIssue(db, issue.id, issue.companyId);
|
||||
}
|
||||
const answered = hydrateInteraction(updated);
|
||||
await emitInteractionResolvedTelemetry(db, answered);
|
||||
return answered;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { and, eq, inArray, isNull, isNotNull, ne, or, type SQL } from "drizzle-o
|
||||
import { issues } from "@paperclipai/db";
|
||||
import { ISSUE_SCOPES, type IssueScope } from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { pendingUserRequestCondition } from "./issue-participation.js";
|
||||
|
||||
export function visibleIssueCondition(): SQL {
|
||||
return and(isNull(issues.hiddenAt), isNull(issues.harnessKind))!;
|
||||
@@ -17,6 +18,29 @@ export function nonChatAndChannelIssueCondition(): SQL {
|
||||
return and(ne(issues.scope, "chat"), ne(issues.scope, "channel"), isNull(issues.conversationAgentId))!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exclude standing 1:1 chats and passive channel streams while keeping
|
||||
* channel issues that are explicitly assigned to `mineUserId` or have a
|
||||
* pending interaction addressed to `mineUserId`.
|
||||
*/
|
||||
export function nonChatAndPassiveChannelCondition(
|
||||
companyId?: string,
|
||||
mineUserId?: string,
|
||||
): SQL {
|
||||
if (companyId && mineUserId) {
|
||||
return and(
|
||||
ne(issues.scope, "chat"),
|
||||
isNull(issues.conversationAgentId),
|
||||
or(
|
||||
ne(issues.scope, "channel"),
|
||||
eq(issues.assigneeUserId, mineUserId),
|
||||
pendingUserRequestCondition(companyId, mineUserId),
|
||||
)!,
|
||||
)!;
|
||||
}
|
||||
return nonChatAndChannelIssueCondition();
|
||||
}
|
||||
|
||||
/** Parse and validate comma-separated or repeated issue scope filters. */
|
||||
export function parseScopeFilter(
|
||||
input: IssueScope | string | readonly string[] | undefined,
|
||||
@@ -45,9 +69,13 @@ export function parseScopeFilter(
|
||||
|
||||
/** Resolve the surface scope SQL condition for issue list, count, and inbox queries. */
|
||||
export function surfaceScopeCondition(filters?: {
|
||||
companyId?: string;
|
||||
scope?: IssueScope | string | readonly IssueScope[];
|
||||
q?: string;
|
||||
issueIds?: string[];
|
||||
assigneeUserId?: string;
|
||||
touchedByUserId?: string;
|
||||
unreadForUserId?: string;
|
||||
}): { scopes: IssueScope[]; condition: SQL | undefined } {
|
||||
const scopes = parseScopeFilter(filters?.scope);
|
||||
if (scopes.length > 0) {
|
||||
@@ -57,7 +85,15 @@ export function surfaceScopeCondition(filters?: {
|
||||
};
|
||||
}
|
||||
if (!filters?.q?.trim() && !filters?.issueIds) {
|
||||
return { scopes, condition: nonChatAndChannelIssueCondition() };
|
||||
const mineUserId =
|
||||
filters?.assigneeUserId?.trim() ||
|
||||
filters?.touchedByUserId?.trim() ||
|
||||
filters?.unreadForUserId?.trim() ||
|
||||
undefined;
|
||||
return {
|
||||
scopes,
|
||||
condition: nonChatAndPassiveChannelCondition(filters?.companyId, mineUserId),
|
||||
};
|
||||
}
|
||||
return { scopes, condition: undefined };
|
||||
}
|
||||
|
||||
@@ -270,6 +270,7 @@ import {
|
||||
} from "./recovery/issue-graph-liveness.js";
|
||||
import {
|
||||
nonChatAndChannelIssueCondition,
|
||||
nonChatAndPassiveChannelCondition,
|
||||
parseScopeFilter,
|
||||
surfaceScopeCondition,
|
||||
visibleIssueCondition,
|
||||
@@ -2781,7 +2782,7 @@ export async function runWorkspaceIsFinalized(
|
||||
return heartbeatRunIsTerminalOrMissing(dbOrTx, runId);
|
||||
}
|
||||
|
||||
async function listIssueDependencyReadinessMap(
|
||||
export async function listIssueDependencyReadinessMap(
|
||||
dbOrTx: Pick<Db, "select">,
|
||||
companyId: string,
|
||||
issueIds: string[],
|
||||
@@ -3435,6 +3436,7 @@ async function withIssueLabels(
|
||||
const issueLabels = labelsByIssueId.get(row.id) ?? [];
|
||||
return {
|
||||
...row,
|
||||
...("claimTokenHash" in row ? { claimTokenHash: null } : {}),
|
||||
labels: issueLabels,
|
||||
labelIds: issueLabels.map((label) => label.id),
|
||||
watchdog: watchdogByIssueId.get(row.id) ?? null,
|
||||
@@ -5319,6 +5321,7 @@ const issueListSelect = {
|
||||
id: issues.id,
|
||||
companyId: issues.companyId,
|
||||
projectId: issues.projectId,
|
||||
channelId: issues.channelId,
|
||||
projectWorkspaceId: issues.projectWorkspaceId,
|
||||
goalId: issues.goalId,
|
||||
parentId: issues.parentId,
|
||||
@@ -5362,7 +5365,19 @@ const issueListSelect = {
|
||||
executionLockedAt: issues.executionLockedAt,
|
||||
createdByAgentId: issues.createdByAgentId,
|
||||
createdByUserId: issues.createdByUserId,
|
||||
createdByProfile: issues.createdByProfile,
|
||||
responsibleUserId: issues.responsibleUserId,
|
||||
kvLabels: issues.kvLabels,
|
||||
schemaBlocks: issues.schemaBlocks,
|
||||
resultSchemaRef: issues.resultSchemaRef,
|
||||
claimEpoch: issues.claimEpoch,
|
||||
claimTokenHash: sql<null>`null`,
|
||||
claimHolderAgentId: issues.claimHolderAgentId,
|
||||
claimHolderUserId: issues.claimHolderUserId,
|
||||
claimHolderProfile: issues.claimHolderProfile,
|
||||
claimLeasedAt: issues.claimLeasedAt,
|
||||
claimLeaseExpiresAt: issues.claimLeaseExpiresAt,
|
||||
claimAttemptCount: issues.claimAttemptCount,
|
||||
issueNumber: issues.issueNumber,
|
||||
identifier: issues.identifier,
|
||||
originKind: issues.originKind,
|
||||
@@ -7242,7 +7257,7 @@ export function issueService(db: Db) {
|
||||
|
||||
async function getIssueByUuid(id: string) {
|
||||
const row = await retryIdempotentDatabaseOperation(() => db
|
||||
.select({ ...getTableColumns(issues), displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() })
|
||||
.select({ ...getTableColumns(issues), claimTokenHash: sql<null>`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, id))
|
||||
.then((rows) => rows[0] ?? null));
|
||||
@@ -7253,7 +7268,7 @@ export function issueService(db: Db) {
|
||||
|
||||
async function getIssueByIdentifier(identifier: string) {
|
||||
const row = await retryIdempotentDatabaseOperation(() => db
|
||||
.select({ ...getTableColumns(issues), displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() })
|
||||
.select({ ...getTableColumns(issues), claimTokenHash: sql<null>`null`, displayStatus: issueDisplayStatusSql(), externalConversationState: externalConversationStateSql() })
|
||||
.from(issues)
|
||||
.where(eq(issues.identifier, identifier.toUpperCase()))
|
||||
.then((rows) => rows[0] ?? null));
|
||||
@@ -8581,7 +8596,7 @@ export function issueService(db: Db) {
|
||||
.from(participated).innerJoin(issues, eq(issues.id, sql`"mine_participants"."id"`)).where(and(
|
||||
eq(issues.companyId, companyId),
|
||||
visibleIssueCondition(),
|
||||
nonChatAndChannelIssueCondition(),
|
||||
nonChatAndPassiveChannelCondition(companyId, userId),
|
||||
nonPluginOperationIssueCondition(),
|
||||
ne(issues.status, "cancelled"),
|
||||
inboxVisibleForUserCondition(companyId, userId),
|
||||
@@ -8639,7 +8654,7 @@ export function issueService(db: Db) {
|
||||
? sql<boolean>`NOT (${inboxVisibleForUserCondition(companyId, inboxArchive.userId)})`
|
||||
: undefined;
|
||||
if (inboxArchive?.mode === "archived" && archivedCondition) conditions.push(archivedCondition);
|
||||
const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||
const { scopes, condition: scopeCondition } = surfaceScopeCondition({ ...filters, companyId });
|
||||
if (scopeCondition) conditions.push(scopeCondition);
|
||||
// Explicit child navigation includes waiting chat tasks, just like
|
||||
// readable-child counts. Ambient lists still omit idle conversations.
|
||||
@@ -9047,7 +9062,7 @@ export function issueService(db: Db) {
|
||||
if (filters?.readCondition) conditions.push(filters.readCondition);
|
||||
const creationCondition = creationVisibilityCondition(companyId, filters);
|
||||
if (creationCondition) conditions.push(creationCondition);
|
||||
const { scopes, condition: scopeCondition } = surfaceScopeCondition(filters);
|
||||
const { scopes, condition: scopeCondition } = surfaceScopeCondition({ ...filters, companyId });
|
||||
if (scopeCondition) conditions.push(scopeCondition);
|
||||
if (!filters?.q?.trim() && !filters?.issueIds && !scopes.includes("channel") && !scopes.includes("chat") && !filters?.parentId && !filters?.parentIds && !filters?.touchedByUserId && !filters?.unreadForUserId && !filters?.inboxArchivedByUserId) {
|
||||
conditions.push(nonIdleSlackIssueCondition());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { wakeWaitersOfStalledIssues, type BlockerStallWakeup } from "./blocker-stall-wakeups.js";
|
||||
import { wakeReadyPoolDependentsForBlocker } from "../headless-task-queue.js";
|
||||
import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js";
|
||||
import { DEPENDENCY_WAKE_REPEATED_FAILURE_STREAK, readDependencyWakeCircuit } from "./dependency-wake-circuit-breaker.js";
|
||||
import { INTERACTION_DELIVERY_DENIED, isInteractionDeliveryDeniedRun } from "../agent-interaction-delivery.js";
|
||||
@@ -6573,6 +6574,16 @@ export function recoveryService(
|
||||
result.enqueueFailed += stalls.failed;
|
||||
if (stalls.retryAt !== null) opts?.onDeferredDeadline?.(stalls.retryAt);
|
||||
}
|
||||
if (opts?.blockerIssueId) {
|
||||
try {
|
||||
await wakeReadyPoolDependentsForBlocker(db, opts.blockerIssueId);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
{ err, blockerIssueId: opts.blockerIssueId, source },
|
||||
"failed to wake unassigned pool dependents after blocker finality",
|
||||
);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+5
-1
@@ -1,6 +1,6 @@
|
||||
export {};
|
||||
|
||||
import type { AgentApiKeyScope } from "@paperclipai/shared";
|
||||
import type { AgentApiKeyScope, ClientScopes } from "@paperclipai/shared";
|
||||
|
||||
declare global {
|
||||
namespace Express {
|
||||
@@ -25,9 +25,13 @@ declare global {
|
||||
status?: string;
|
||||
}>;
|
||||
isInstanceAdmin?: boolean;
|
||||
ignoreInstanceAdmin?: boolean;
|
||||
canManageExperimentalSettings?: boolean;
|
||||
keyId?: string;
|
||||
keyScope?: AgentApiKeyScope;
|
||||
keyCompanyId?: string | null;
|
||||
keyLockedProfile?: string | null;
|
||||
keyScopes?: ClientScopes | null;
|
||||
runId?: string;
|
||||
onBehalfOfUserId?: string | null;
|
||||
authorizingUserId?: string;
|
||||
|
||||
Reference in new issue
Block a user