mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
<!-- 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>
588 lines
19 KiB
TypeScript
588 lines
19 KiB
TypeScript
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,
|
|
};
|
|
}
|