mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-21 19:02:37 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - An agent gets environment variables from its execution environment, its own configuration, its project, and its routine. Secrets are resolved for each run. > - A plugin environment can run the agent as a native Runner task on its own host, through the environment task contract. > - That contract has no field for the agent's variables. Runs on a plugin environment get only the variables that the plugin sets itself. > - This pull request adds a versioned contract field for the values, sends them on a session handoff, lets Codex commands inherit the variables in an external sandbox, and lets a plugin protect the variables that it sets itself. > - The benefit is that plain and secret variables work on plugin environments in the same way as on local environments. ## Linked Issues or Issue Description Refs #21233. That pull request by @lucktastic finds the same gap and proposes the same capability and field names (`configuredEnvironmentVersion: 1`, `configuredEnvironment`). This pull request uses the same names, so providers implement one contract. It differs in these places: - Codex commands get the variables through an external-sandbox denylist, not through key names sent at `prepare`. A retained Runner does not need a new preparation when a key is added or removed. - A session handoff `resume` gets the values, because it starts a new Runner on another computer. Value changes on the same computer need no new field: Core's process reuse key includes the values, so Core starts a new task. - A driver can declare `protectedEnvironmentKeys`. Paperclip rejects or warns when one is saved. - The run log names skipped variables only for an older provider. Thank you to @lucktastic for the diagnosis and the contract shape. **What happened?** An agent has environment variables, plain and secret. Its runs on a plugin task environment do not get them. `PAPERCLIP_CONFIGURED_ENV_KEYS` in the run lists only the variables that the plugin sets. **Expected behavior** Each run gets the agent's configured variables. **Steps to reproduce** 1. Set a plain and a secret environment variable on an agent. 2. Assign the agent to a plugin environment that provides Runner tasks. 3. Start a run. Read the names in `PAPERCLIP_CONFIGURED_ENV_KEYS` in a command that the agent runs. 4. The agent's names are not in the list. ## What Changed - **SDK contract** (`packages/plugins/sdk/src/environment-tasks.ts`): - A provider advertises `configuredEnvironmentVersion: 1` on `describe`. - `submit` gets `configuredEnvironment`. `resume` gets it only for a session handoff. - Names, count, and sizes have the same limits as the Runner projection. - **Server**: - `createRunnerdBackendWithinSessionClaim` gives the run's configured projection to the plugin task owner. The projection has no provider credentials and no generated runtime keys. - `createPluginRunnerTaskOwner` sends the fields only to a provider with the capability. An older provider gets no new field, and the run log names the variables that were not set. The log never prints values. - **Codex** (`codex-security-config.ts`): - An externally sandboxed launch uses `inherit="all"`, `ignore_default_excludes=true`, and an `exclude` list of Codex's own credentials, instead of an `include_only` list fixed at preparation time. - A test reads the Runner's Codex environment keys, and fails if a new key is not classified. - Host launches keep the bounded allowlist. - **runnerd** (`codex_provider.rs`): `runtime_notification_codex_args` still grants the notification files to read-only profiles when no allowlist is present. Plan mode in an external sandbox needs these grants. - **Protected keys**: - An environment driver can declare `protectedEnvironmentKeys` in its manifest. - Paperclip rejects a protected key on an agent or environment that uses the driver. The 422 has code `protected_environment_variable`. - On a project, a routine, or another agent, Paperclip saves the key. The response has a `configurationWarnings` notice that names the environments. The project and routine pages show the notice as a toast. The agent pages already show configuration warnings. - **Docs**: `doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md` describes the provider obligations. - `tests/runner-e2e/source-sdk-public-inputs.json`: refresh the reviewed SDK source pin. ## Verification - `packages/plugins/sdk`: `vitest run tests/environment-tasks.test.ts` (38 pass). Accepts bounded values. Rejects bad names, NUL bytes, too many variables, and oversized values. - `server`: `vitest run src/services/native-runtime/plugin-runner-task.test.ts` (95 pass). Values go only to a provider with the capability, never in `prepare`. `resume` sends values only for a handoff. - `server`: `vitest run src/services/protected-environment-keys.test.ts src/__tests__/project-routes-env.test.ts` (10 pass). Rejection, notices, and the project route response. - `server`: all route suites that import the project, routine, environment, or agent routes (45 files, 1689 pass). - `packages/shared`: `vitest run src/validators/plugin.test.ts` (64 pass). - `packages/paperclip-runner`: `vitest run src/drivers/codex src/configured-environment.test.ts src/live/runner-provider-launch.test.ts` (444 pass). - `packages/paperclip-runner/runner`: `cargo test -p paperclip-runner-core --lib runtime_notification` (9 pass, 2 ignored as before). - `pnpm typecheck` in `packages/shared`, `packages/plugins/sdk`, `packages/paperclip-runner`, `server`, and `ui`. - Not run locally: `pnpm verify --full` and browser suites. Required CI covers the final revision. ## Risks - **Existing providers:** low risk. Core sends no new field to a provider without the capability. Their runs behave as before, with one added log line when variables were skipped. - **Codex in an external sandbox:** commands now see every variable in the Runner environment except Codex's own credentials. The execution environment builds that environment from an allowlist. If the Runner gives Codex a new credential, the drift test fails until the key is classified. - **Saving env:** new rejections happen only when an installed driver declares `protectedEnvironmentKeys`. No driver declares them today. - **Providers:** they must keep the values transient and never save or log them. The doc lists these obligations. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
720 lines
27 KiB
TypeScript
720 lines
27 KiB
TypeScript
import { Router, type Request } from "express";
|
|
import { listProtectedEnvironmentKeyHolders, protectedEnvironmentKeyWarnings } from "../services/protected-environment-keys.js";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
createRoutineSchema,
|
|
createDocumentAnnotationCommentSchema,
|
|
createDocumentAnnotationThreadSchema,
|
|
createRoutineTriggerSchema,
|
|
rotateRoutineTriggerSecretSchema,
|
|
runRoutineSchema,
|
|
updateDocumentAnnotationThreadSchema,
|
|
updateRoutineSchema,
|
|
updateRoutineTriggerSchema,
|
|
} from "@paperclipai/shared";
|
|
import { trackRoutineCreated } from "@paperclipai/shared/telemetry";
|
|
import { validate, validateIssueMutationBody } from "../middleware/validate.js";
|
|
import { accessService, documentAnnotationService, logActivity, routineService } from "../services/index.js";
|
|
import { assertCompanyAccess, getAccessibleResource, getActorInfo, hasCompanyAccess } from "./authz.js";
|
|
import { badRequest, forbidden, unauthorized, unsupportedMediaType } from "../errors.js";
|
|
import { getTelemetryClient } from "../telemetry.js";
|
|
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
|
|
|
export function routineRoutes(
|
|
db: Db,
|
|
options: { pluginWorkerManager?: PluginWorkerManager } = {},
|
|
) {
|
|
const router = Router();
|
|
const svc = routineService(db, {
|
|
pluginWorkerManager: options.pluginWorkerManager,
|
|
});
|
|
const documentAnnotationsSvc = documentAnnotationService(db);
|
|
const access = accessService(db);
|
|
const routineDocumentKey = "description";
|
|
|
|
function parseBooleanQuery(value: unknown) {
|
|
return value === true || value === "true" || value === "1";
|
|
}
|
|
|
|
function annotationActorInput(req: Request) {
|
|
const actor = getActorInfo(req);
|
|
return {
|
|
actor,
|
|
annotationActor: {
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
userId: actor.actorType === "user" ? actor.actorId : null,
|
|
runId: actor.runId,
|
|
},
|
|
};
|
|
}
|
|
|
|
async function remapRoutineDescriptionAnnotations(req: Request, routineId: string) {
|
|
const doc = await svc.getDescriptionDocument(routineId);
|
|
if (!doc) return;
|
|
const remapped = await documentAnnotationsSvc.remapOpenThreadsForRoutineDocument({
|
|
routineId,
|
|
key: routineDocumentKey,
|
|
documentId: doc.id,
|
|
nextRevisionId: doc.latestRevisionId,
|
|
nextRevisionNumber: doc.latestRevisionNumber,
|
|
nextBody: doc.body,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
for (const remap of remapped) {
|
|
await logActivity(db, {
|
|
companyId: doc.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.document_annotation_remapped",
|
|
entityType: "routine",
|
|
entityId: routineId,
|
|
details: {
|
|
key: doc.key,
|
|
documentKey: doc.key,
|
|
documentId: doc.id,
|
|
threadId: remap.thread.id,
|
|
revisionNumber: doc.latestRevisionNumber,
|
|
anchorState: remap.thread.anchorState,
|
|
anchorConfidence: remap.thread.anchorConfidence,
|
|
snapshotId: remap.snapshot.id,
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
async function assertBoardCanAssignTasks(req: Request, companyId: string) {
|
|
assertCompanyAccess(req, companyId);
|
|
if (req.actor.type !== "board") return;
|
|
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return;
|
|
const allowed = await access.canUser(companyId, req.actor.userId, "tasks:assign");
|
|
if (!allowed) {
|
|
throw forbidden("Missing permission: tasks:assign");
|
|
}
|
|
}
|
|
|
|
async function canChangeResponsibleUser(req: Request, companyId: string) {
|
|
if (req.actor.type !== "board") return false;
|
|
if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) return true;
|
|
// Match assertCompanyAccess's write restrictions even on this GET route.
|
|
if (Array.isArray(req.actor.memberships)) {
|
|
const membership = req.actor.memberships.find((item) => item.companyId === companyId);
|
|
if (!membership || membership.status !== "active" || membership.membershipRole === "viewer") return false;
|
|
}
|
|
return access.canUser(companyId, req.actor.userId, "tasks:assign");
|
|
}
|
|
|
|
function assertCanManageCompanyRoutine(req: Request, companyId: string, assigneeAgentId?: string | null) {
|
|
assertCompanyAccess(req, companyId);
|
|
if (req.actor.type === "board") return;
|
|
if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized();
|
|
if (assigneeAgentId !== req.actor.agentId) {
|
|
throw forbidden("Agents can only manage routines assigned to themselves");
|
|
}
|
|
}
|
|
|
|
async function assertCanManageExistingRoutine(req: Request, routineId: string) {
|
|
const routine = await svc.get(routineId);
|
|
if (!routine || !hasCompanyAccess(req, routine.companyId)) return null;
|
|
assertCompanyAccess(req, routine.companyId);
|
|
if (req.actor.type === "board") return routine;
|
|
if (req.actor.type !== "agent" || !req.actor.agentId) throw unauthorized();
|
|
if (routine.assigneeAgentId !== req.actor.agentId) {
|
|
throw forbidden("Agents can only manage routines assigned to themselves");
|
|
}
|
|
return routine;
|
|
}
|
|
|
|
async function logRoutineRevisionCreated(req: Request, input: {
|
|
companyId: string;
|
|
routineId: string;
|
|
revisionId: string | null;
|
|
revisionNumber: number;
|
|
changeSummary?: string | null;
|
|
triggerCount?: number | null;
|
|
}) {
|
|
if (!input.revisionId) return;
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: input.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.revision_created",
|
|
entityType: "routine",
|
|
entityId: input.routineId,
|
|
details: {
|
|
revisionId: input.revisionId,
|
|
revisionNumber: input.revisionNumber,
|
|
changeSummary: input.changeSummary ?? null,
|
|
triggerCount: input.triggerCount ?? null,
|
|
},
|
|
});
|
|
}
|
|
|
|
router.get("/companies/:companyId/routines", async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
assertCompanyAccess(req, companyId);
|
|
const projectId = typeof req.query.projectId === "string" ? req.query.projectId : undefined;
|
|
const result = await svc.list(companyId, { projectId });
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/companies/:companyId/routines", validate(createRoutineSchema), async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
await assertBoardCanAssignTasks(req, companyId);
|
|
assertCanManageCompanyRoutine(req, companyId, req.body.assigneeAgentId);
|
|
const created = await svc.create(companyId, req.body, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
...(req.actor.type === "agent" ? { actorResponsibleUserId: req.actor.onBehalfOfUserId ?? null } : {}),
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.created",
|
|
entityType: "routine",
|
|
entityId: created.id,
|
|
details: { title: created.title, assigneeAgentId: created.assigneeAgentId },
|
|
});
|
|
const telemetryClient = getTelemetryClient();
|
|
if (telemetryClient) {
|
|
trackRoutineCreated(telemetryClient);
|
|
}
|
|
await logRoutineRevisionCreated(req, {
|
|
companyId,
|
|
routineId: created.id,
|
|
revisionId: created.latestRevisionId,
|
|
revisionNumber: created.latestRevisionNumber,
|
|
changeSummary: "Created routine",
|
|
triggerCount: 0,
|
|
});
|
|
const configurationWarnings = req.body.env !== undefined
|
|
? protectedEnvironmentKeyWarnings(await listProtectedEnvironmentKeyHolders(db), req.body.env, "env") : [];
|
|
res.status(201).json({ ...created, ...(configurationWarnings.length ? { configurationWarnings } : {}) });
|
|
});
|
|
|
|
router.get("/routines/:id", async (req, res) => {
|
|
const detail = await getAccessibleResource(req, res, svc.getDetail(req.params.id as string), "Routine not found");
|
|
if (!detail) return;
|
|
res.json({ ...detail, canChangeResponsibleUser: await canChangeResponsibleUser(req, detail.companyId) });
|
|
});
|
|
|
|
router.get("/routines/:id/revisions", async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const revisions = await svc.listRevisions(routine.id);
|
|
res.json(revisions);
|
|
});
|
|
|
|
router.get("/routines/:id/description/annotations", async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const status = req.query.status === "resolved" || req.query.status === "all" ? req.query.status : "open";
|
|
const threads = await documentAnnotationsSvc.listThreadsForRoutineDocument(routine.id, routineDocumentKey, {
|
|
status,
|
|
includeComments: parseBooleanQuery(req.query.includeComments),
|
|
});
|
|
res.json(threads);
|
|
});
|
|
|
|
router.get("/routines/:id/description/annotations/:threadId", async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const thread = await documentAnnotationsSvc.getThreadForRoutineDocument(
|
|
routine.id,
|
|
routineDocumentKey,
|
|
req.params.threadId as string,
|
|
);
|
|
if (!thread) {
|
|
res.status(404).json({ error: "Annotation thread not found" });
|
|
return;
|
|
}
|
|
res.json(thread);
|
|
});
|
|
|
|
router.post(
|
|
"/routines/:id/description/annotations",
|
|
validate(createDocumentAnnotationThreadSchema),
|
|
async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const { actor, annotationActor } = annotationActorInput(req);
|
|
const thread = await documentAnnotationsSvc.createRoutineThread(
|
|
routine.id,
|
|
routineDocumentKey,
|
|
req.body,
|
|
annotationActor,
|
|
);
|
|
const firstComment = thread.comments[0];
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.document_annotation_thread_created",
|
|
entityType: "routine",
|
|
entityId: routine.id,
|
|
details: {
|
|
key: thread.documentKey,
|
|
documentKey: thread.documentKey,
|
|
documentId: thread.documentId,
|
|
threadId: thread.id,
|
|
commentId: firstComment?.id ?? null,
|
|
revisionNumber: thread.currentRevisionNumber,
|
|
quote: thread.selectedText.slice(0, 240),
|
|
},
|
|
});
|
|
res.status(201).json(thread);
|
|
},
|
|
);
|
|
|
|
router.post(
|
|
"/routines/:id/description/annotations/:threadId/comments",
|
|
validate(createDocumentAnnotationCommentSchema),
|
|
async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const { actor, annotationActor } = annotationActorInput(req);
|
|
const comment = await documentAnnotationsSvc.addRoutineComment(
|
|
routine.id,
|
|
routineDocumentKey,
|
|
req.params.threadId as string,
|
|
req.body,
|
|
annotationActor,
|
|
);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.document_annotation_comment_added",
|
|
entityType: "routine",
|
|
entityId: routine.id,
|
|
details: {
|
|
key: routineDocumentKey,
|
|
documentKey: routineDocumentKey,
|
|
threadId: comment.threadId,
|
|
commentId: comment.id,
|
|
bodySnippet: comment.body.slice(0, 120),
|
|
},
|
|
});
|
|
res.status(201).json(comment);
|
|
},
|
|
);
|
|
|
|
router.patch(
|
|
"/routines/:id/description/annotations/:threadId",
|
|
validate(updateDocumentAnnotationThreadSchema),
|
|
async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const { actor, annotationActor } = annotationActorInput(req);
|
|
const thread = await documentAnnotationsSvc.updateRoutineThread(
|
|
routine.id,
|
|
routineDocumentKey,
|
|
req.params.threadId as string,
|
|
req.body,
|
|
annotationActor,
|
|
);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: thread.status === "resolved"
|
|
? "routine.document_annotation_thread_resolved"
|
|
: "routine.document_annotation_thread_reopened",
|
|
entityType: "routine",
|
|
entityId: routine.id,
|
|
details: {
|
|
key: thread.documentKey,
|
|
documentKey: thread.documentKey,
|
|
documentId: thread.documentId,
|
|
threadId: thread.id,
|
|
status: thread.status,
|
|
},
|
|
});
|
|
res.json(thread);
|
|
},
|
|
);
|
|
|
|
router.patch("/routines/:id", validate(updateRoutineSchema), async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
const assigneeWillChange =
|
|
req.body.assigneeAgentId !== undefined &&
|
|
req.body.assigneeAgentId !== routine.assigneeAgentId;
|
|
if (req.body.responsibleUserId !== undefined) {
|
|
if (req.actor.type !== "board") {
|
|
throw forbidden("Only people can change routine responsibility");
|
|
}
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
}
|
|
if (assigneeWillChange) {
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
}
|
|
const statusWillActivate =
|
|
req.body.status !== undefined &&
|
|
req.body.status === "active" &&
|
|
routine.status !== "active";
|
|
if (statusWillActivate) {
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
}
|
|
if (
|
|
req.actor.type === "agent" &&
|
|
req.body.assigneeAgentId !== undefined &&
|
|
req.body.assigneeAgentId !== req.actor.agentId
|
|
) {
|
|
throw forbidden("Agents can only assign routines to themselves");
|
|
}
|
|
const updated = await svc.update(routine.id, req.body, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.updated",
|
|
entityType: "routine",
|
|
entityId: routine.id,
|
|
details: {
|
|
title: updated?.title ?? routine.title,
|
|
...(req.body.responsibleUserId !== undefined ? {
|
|
previousResponsibleUserId: updated?.previousResponsibleUserId,
|
|
responsibleUserId: updated?.responsibleUserId,
|
|
} : {}),
|
|
},
|
|
});
|
|
if (updated && updated.latestRevisionId !== routine.latestRevisionId) {
|
|
await remapRoutineDescriptionAnnotations(req, routine.id);
|
|
await logRoutineRevisionCreated(req, {
|
|
companyId: routine.companyId,
|
|
routineId: routine.id,
|
|
revisionId: updated.latestRevisionId,
|
|
revisionNumber: updated.latestRevisionNumber,
|
|
changeSummary: "Updated routine",
|
|
triggerCount: null,
|
|
});
|
|
}
|
|
if (updated) {
|
|
const { previousResponsibleUserId: _previousResponsibleUserId, ...response } = updated;
|
|
const configurationWarnings = req.body.env !== undefined
|
|
? protectedEnvironmentKeyWarnings(await listProtectedEnvironmentKeyHolders(db), req.body.env, "env") : [];
|
|
res.json({ ...response, ...(configurationWarnings.length ? { configurationWarnings } : {}) });
|
|
} else {
|
|
res.json(null);
|
|
}
|
|
});
|
|
|
|
router.post("/routines/:id/revisions/:revisionId/restore", async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
const result = await svc.restoreRevision(routine.id, req.params.revisionId as string, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.revision_restored",
|
|
entityType: "routine",
|
|
entityId: routine.id,
|
|
details: {
|
|
revisionId: result.revision.id,
|
|
revisionNumber: result.revision.revisionNumber,
|
|
restoredFromRevisionId: result.restoredFromRevisionId,
|
|
restoredFromRevisionNumber: result.restoredFromRevisionNumber,
|
|
triggerCount: result.revision.snapshot.triggers.length,
|
|
},
|
|
});
|
|
await remapRoutineDescriptionAnnotations(req, routine.id);
|
|
res.json(result);
|
|
});
|
|
|
|
router.get("/routines/:id/runs", async (req, res) => {
|
|
const routine = await getAccessibleResource(req, res, svc.get(req.params.id as string), "Routine not found");
|
|
if (!routine) return;
|
|
const limit = Number(req.query.limit ?? 50);
|
|
const result = await svc.listRuns(routine.id, Number.isFinite(limit) ? limit : 50);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/routines/:id/triggers", validate(createRoutineTriggerSchema), async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
const created = await svc.createTrigger(routine.id, req.body, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.trigger_created",
|
|
entityType: "routine_trigger",
|
|
entityId: created.trigger.id,
|
|
details: { routineId: routine.id, kind: created.trigger.kind },
|
|
});
|
|
await logRoutineRevisionCreated(req, {
|
|
companyId: routine.companyId,
|
|
routineId: routine.id,
|
|
revisionId: created.revision.id,
|
|
revisionNumber: created.revision.revisionNumber,
|
|
changeSummary: created.revision.changeSummary,
|
|
triggerCount: created.revision.snapshot.triggers.length,
|
|
});
|
|
res.status(201).json(created);
|
|
});
|
|
|
|
router.patch("/routine-triggers/:id", validate(updateRoutineTriggerSchema), async (req, res) => {
|
|
const trigger = await svc.getTrigger(req.params.id as string);
|
|
if (!trigger) {
|
|
res.status(404).json({ error: "Routine trigger not found" });
|
|
return;
|
|
}
|
|
const routine = await assertCanManageExistingRoutine(req, trigger.routineId);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine trigger not found" });
|
|
return;
|
|
}
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
const updated = await svc.updateTrigger(trigger.id, req.body, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: req.body.archived === true ? "routine.trigger_removed" : req.body.archived === false ? "routine.trigger_restored" : req.body.setupPending === false ? "routine.trigger_setup_finished" : "routine.trigger_updated",
|
|
entityType: "routine",
|
|
entityId: routine.id,
|
|
details: { triggerId: trigger.id, kind: updated?.trigger.kind ?? trigger.kind },
|
|
});
|
|
if (updated) {
|
|
await logRoutineRevisionCreated(req, {
|
|
companyId: routine.companyId,
|
|
routineId: routine.id,
|
|
revisionId: updated.revision.id,
|
|
revisionNumber: updated.revision.revisionNumber,
|
|
changeSummary: updated.revision.changeSummary,
|
|
triggerCount: updated.revision.snapshot.triggers.length,
|
|
});
|
|
}
|
|
res.json(updated?.trigger ?? null);
|
|
});
|
|
|
|
router.delete("/routine-triggers/:id", async (req, res) => {
|
|
const trigger = await svc.getTrigger(req.params.id as string);
|
|
if (!trigger) {
|
|
res.status(404).json({ error: "Routine trigger not found" });
|
|
return;
|
|
}
|
|
const routine = await assertCanManageExistingRoutine(req, trigger.routineId);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine trigger not found" });
|
|
return;
|
|
}
|
|
const deleted = await svc.deleteTrigger(trigger.id, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.trigger_deleted",
|
|
entityType: "routine_trigger",
|
|
entityId: trigger.id,
|
|
details: { routineId: routine.id, kind: trigger.kind },
|
|
});
|
|
if (deleted.revision) {
|
|
await logRoutineRevisionCreated(req, {
|
|
companyId: routine.companyId,
|
|
routineId: routine.id,
|
|
revisionId: deleted.revision.id,
|
|
revisionNumber: deleted.revision.revisionNumber,
|
|
changeSummary: deleted.revision.changeSummary,
|
|
triggerCount: deleted.revision.snapshot.triggers.length,
|
|
});
|
|
}
|
|
res.status(204).end();
|
|
});
|
|
|
|
router.post(
|
|
"/routine-triggers/:id/rotate-secret",
|
|
validate(rotateRoutineTriggerSecretSchema),
|
|
async (req, res) => {
|
|
const trigger = await svc.getTrigger(req.params.id as string);
|
|
if (!trigger) {
|
|
res.status(404).json({ error: "Routine trigger not found" });
|
|
return;
|
|
}
|
|
const routine = await assertCanManageExistingRoutine(req, trigger.routineId);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine trigger not found" });
|
|
return;
|
|
}
|
|
const rotated = await svc.rotateTriggerSecret(trigger.id, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? "board" : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.trigger_secret_rotated",
|
|
entityType: "routine_trigger",
|
|
entityId: trigger.id,
|
|
details: { routineId: routine.id },
|
|
});
|
|
await logRoutineRevisionCreated(req, {
|
|
companyId: routine.companyId,
|
|
routineId: routine.id,
|
|
revisionId: rotated.revision.id,
|
|
revisionNumber: rotated.revision.revisionNumber,
|
|
changeSummary: rotated.revision.changeSummary,
|
|
triggerCount: rotated.revision.snapshot.triggers.length,
|
|
});
|
|
res.json(rotated);
|
|
},
|
|
);
|
|
|
|
router.post("/routines/:id/run", validateIssueMutationBody(runRoutineSchema), async (req, res) => {
|
|
const routine = await assertCanManageExistingRoutine(req, req.params.id as string);
|
|
if (!routine) {
|
|
res.status(404).json({ error: "Routine not found" });
|
|
return;
|
|
}
|
|
await assertBoardCanAssignTasks(req, routine.companyId);
|
|
const input = req.actor.type === "agent" ? { ...req.body, source: "manual" as const } : req.body;
|
|
const run = await svc.runRoutine(routine.id, input, {
|
|
agentId: req.actor.type === "agent" ? req.actor.agentId : null,
|
|
userId: req.actor.type === "board" ? req.actor.userId ?? null : null,
|
|
runId: req.actor.runId ?? null,
|
|
});
|
|
const actor = getActorInfo(req);
|
|
await logActivity(db, {
|
|
companyId: routine.companyId,
|
|
actorType: actor.actorType,
|
|
actorId: actor.actorId,
|
|
agentId: actor.agentId,
|
|
runId: actor.runId,
|
|
agentApiKeyId: actor.agentApiKeyId,
|
|
action: "routine.run_triggered",
|
|
entityType: "routine_run",
|
|
entityId: run.id,
|
|
details: { routineId: routine.id, source: run.source, status: run.status },
|
|
});
|
|
res.status(202).json(run);
|
|
});
|
|
|
|
router.post("/routine-triggers/public/:publicId/fire", async (req, res) => {
|
|
if (!req.is("application/json")) {
|
|
throw unsupportedMediaType("Send the webhook payload with Content-Type: application/json");
|
|
}
|
|
if (!req.body || typeof req.body !== "object" || Array.isArray(req.body)) {
|
|
throw badRequest("Webhook payload must be a JSON object");
|
|
}
|
|
const idempotencyScope = req.header("x-paperclip-idempotency-scope");
|
|
if (idempotencyScope != null && idempotencyScope !== "trigger" && idempotencyScope !== "routine") {
|
|
throw badRequest("X-Paperclip-Idempotency-Scope must be trigger or routine");
|
|
}
|
|
const result = await svc.firePublicTrigger(req.params.publicId as string, {
|
|
sourceRunToken: req.header("x-paperclip-source-run-token"),
|
|
idempotencyScope: idempotencyScope as "trigger" | "routine" | undefined,
|
|
authorizationHeader: req.header("authorization"),
|
|
signatureHeader: req.header("x-paperclip-signature"),
|
|
hubSignatureHeader: req.header("x-hub-signature-256"),
|
|
firefliesSignatureHeader: req.header("x-hub-signature"),
|
|
timestampHeader: req.header("x-paperclip-timestamp"),
|
|
idempotencyKey: req.header("idempotency-key") ?? req.header("x-github-delivery"),
|
|
rawBody: (req as { rawBody?: Buffer }).rawBody ?? null,
|
|
payload: typeof req.body === "object" && req.body !== null ? req.body as Record<string, unknown> : null,
|
|
});
|
|
res.status(202).json(result);
|
|
});
|
|
|
|
return router;
|
|
}
|