mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 00:05:49 +02:00
## Thinking Path > - Paperclip manages AI agents and their work. > - Agent creation, approval, pause, and termination change whether an agent can work. > - These changes currently use separate service and database paths. > - Some agents need setup after their record exists and before their harness can run. > - This PR adds one module that owns those state changes and their transactions. > - The module records progress and retries incomplete work after a server restart. ## Linked Issues or Issue Description **Problem or motivation** A hire can become active before its execution environment is ready. Direct agent state writes also bypass one common lifecycle boundary. Termination does not have a durable step for resource cleanup. **Proposed solution** Use agent lifecycle commands for hiring, approval, pause, resume, and termination. Keep proposed hires pending until approval. Prepare each approved hire, test its saved harness configuration, and then permit work. Wait for required plugin work before completing a step. **Alternatives considered** A general database commit hook would expose transaction details to callers. A timer alone would delay each new hire. This module owns each command transaction and starts its worker after commit. A periodic scan recovers work after a process stops. **Roadmap alignment** This change adds the lifecycle boundary for the existing agent and plugin systems. It does not add a user interface or a provider implementation. It replaces the lifecycle delivery approach in #15391. Related proposals include #11475 and #13099; this change does not add their external executor protocols. ## What Changed - Add durable approval, preparation, verification, pause, resume, stop, and cleanup states. - Keep agent creation, lifecycle state, configuration writes, and agent record deletion behind `modules/agent-lifecycle`. Keep validation, credential rules, reads, onboarding, invitations, general approvals, and company data deletion in their services. - Commit a hire before the remaining onboarding or invitation work. Serialize requests with the existing dedicated database connection helper. Reuse the hire after a failed attempt. - Keep accepted work in the run queue during setup. Require execution and cleanup evidence before completing pause or termination. - Retain the original credential owner when approving migrated hires. - Start lifecycle work after each command commits. Use database leases and revision checks for retries and late results. - Add a generic required plugin method and capability. Store the required plugin IDs for each agent. Track host and plugin completion separately. - Keep harness verification and credential rules in services. Supply their results to lifecycle through explicit ports. Reject failed logins and incomplete probes. - Remove reverse imports from lifecycle adapters into services. Share record queries and validation below both layers. - Use one hire decision path for agent IDs and approval IDs. Resolve the approval and agent change in one transaction. Expose policy reconciliation on the command object. - Save configuration and verification invalidation through one module operation. Ordinary commands own their transaction. Restrict the shared transaction integration to its listed callers. Reject identity, company, accounting, timestamp, and unknown fields. - Require completed termination before deleting agent records. The company deletion service calls the module through a separate deletion interface. - Save an approved secret before applying its agent binding. A failed binding leaves the secret approved. A retry reuses it. - Remove old permission and metadata export files. Move hire configuration rules out of lifecycle persistence. - Report failed worker steps and scans with operation context and known error codes. Omit provider messages, stacks, and configuration values. Document ordinary application use and extension rules. - Recover expired native owners only after execution stops. Retry cleanup of failed retained leases. Wait for setup in the live smoke script. - Keep manual, budget, and company pause reasons separate. Guard execution status writes with the ready state. - Add a migration, boundary checks, regression tests, and a lifecycle guide. Keep the current UI. - Limit periodic policy checks to 100 eligible agents per minute. Continue from the last agent ID. Exclude pending hires and agents in termination or a final state. Keep explicit company and budget updates immediate. ## Verification - Latest head `ccc3c86b0` aligns the shared status update schema with the PATCH route. All 15 shared tests, 104 server route/OpenAPI tests, 2 CLI tests, and shared/server/CLI TypeScript checks pass. The Greptile comment is fixed. CI is running; no new Apex review was requested for this small fix. - Rebase `75708ac94` rebases onto master at `2eb5187e4`. The backup test uses the shared 90-second timeout from master; the older timeout commit was removed. The affected backup test passes. - Agent budget edits now pass the target agent ID through enforcement. All 50 affected tests, server TypeScript, and 11 boundary tests pass. Both configuration update paths have regression coverage. CI is running on the latest head. No new Apex review was requested for these small fixes. - Rebase `9b568666a` preserves the run-control extraction and delivery-work startup changes from master. All 559 affected tests, server TypeScript, and 11 boundary tests pass. CI and Apex review are running on the final head. - The policy scan fix passes 56 lifecycle and diagnostic tests, 24 policy and caller tests, and 11 boundary tests. A regression test checks the page limit, interval, excluded states, and cursor wraparound. - Rebase `fd4698750` passes all 611 tests in eight affected lifecycle, route, and heartbeat suites. Server TypeScript and all 11 module boundary tests pass. The company deletion rollback and concurrent hire tests are included. - Follow-up `00aac7646` fixes the failed decision deletion test and the public update schema. All 126 affected server tests, 8 shared tests, 2 CLI tests, and 11 boundary tests pass. Shared, server, CLI, and UI TypeScript checks pass. - Server TypeScript passes: `pnpm --filter @paperclipai/server exec tsc --noEmit`. - All 11 boundary tests pass: `node --test scripts/check-module-boundaries.test.mjs`. The repository boundary scan also passes. - All 68 lifecycle, failure diagnostic, and harness verification tests pass. Tests reject forbidden fields through the root command, combined transition command, and restricted transaction integration. They also check invalid fields returned by configuration preparation. - Failure tests cover host work, plugin work, claims, renewals, deferrals, and scans. Log tests check known error codes and exclusion of private error contents. - All 355 tests in 10 existing caller suites pass. These tests cover secret approval, pairing, pending hires, credentials, company import, built-in agents, managed agents, instructions, and skills. - The branch is rebased onto `origin/master` at `2eb5187e4`. The queue guards and cancellation lock fix use the extracted heartbeat queue. Agent cancellation uses the extracted run-control file. The source diff scan found no secrets or private URLs. - Earlier checks cover approval retries, rollback, late verification results, policy holds, deletion rollback, concurrent company deletion, and queue admission during setup. - Before the rebase, CI passed on `00aac7646` and Greptile Apex rated it 5/5 with no open comments. CI and a new Apex review are pending for the rebased commit. The branch has no merge conflicts. - The full local build and native Dot suite were not run. The host has no Cargo. No live provider test was run. ## Risks - Background policy recovery takes more than one minute when more than 100 agents are eligible. Explicit company and budget updates still reconcile immediately. - The restricted configuration integration keeps an agent reference and its dependent records in one transaction. It cannot change a budget or invoke a lifecycle transition. A periodic scan starts pending setup after that transaction commits. - Secret approval and binding use separate transactions. A failed binding can leave an approved secret with no agent binding. - New approved hires remain unavailable until setup and verification complete. Existing clients see `paused` during these steps. This PR does not change the UI. - Migration `0320_daily_onslaught.sql` maps existing statuses and pause reasons. It does not create external resources or claim that an existing harness passed verification. - Use a coordinated server update for this migration. Older server versions can write legacy status without the new lifecycle checks. - A failed onboarding or invitation request can leave a committed hire. A retry reuses that hire and completes the remaining records. - Deletion requires completed termination. Company deletion can require another request while cleanup is pending. - Required plugins must make repeated calls safe and reject older revisions. A disabled or removed required plugin blocks completion until it is restored. - A new hire can run a second harness test after the existing UI test. Some adapters can charge for this test. - No live provider test was run. Provider implementation and resource backfill remain separate work. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code tools, and local test 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 described the issue in this PR with the feature request field labels - [x] I have not referenced internal or instance-local issues or links - [x] My branch name describes the change - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] Targeted local tests pass - [x] All Paperclip CI gates are green on the new commit - [x] Greptile Apex is 5/5 with no open comments on the new commit - [x] I will address review comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
198 lines
9.0 KiB
TypeScript
198 lines
9.0 KiB
TypeScript
import { eq } from "drizzle-orm";
|
|
import { agents, type Db } from "@paperclipai/db";
|
|
import { collectSecretRefs, collectUserSecretRefs, syncAgentAdapterEnvBindings } from "./agent-secret-bindings.js";
|
|
import { logActivity } from "./activity-log.js";
|
|
import { claudeOAuthBindingsMatchExactly, claudeOAuthClaimRejectedError,
|
|
CLAUDE_LOCAL_ADAPTER_TYPE, readClaudeOAuthBinding, secretService, type ClaudeOAuthBindingInvariantDecision } from "./secrets.js";
|
|
import { createDbSetupTokenCleanupStore } from "./setup-token-session.js";
|
|
import type { ClaudeLoginContext, RevisionMetadata } from "../lib/agent-records.js";
|
|
|
|
export function agentCredentialService(db: Db) {
|
|
const secretsSvc = secretService(db);
|
|
async function syncAgentSecretBindings(
|
|
agent: { id: string; companyId: string; adapterConfig: unknown },
|
|
dbClient: Db = db,
|
|
previousAdapterConfig: unknown = null,
|
|
actor: RevisionMetadata = {},
|
|
) {
|
|
const scopedSecretsSvc = dbClient === db ? secretsSvc : secretService(dbClient);
|
|
await syncAgentAdapterEnvBindings({
|
|
secretsSvc: scopedSecretsSvc,
|
|
companyId: agent.companyId,
|
|
agentId: agent.id,
|
|
adapterConfig: agent.adapterConfig,
|
|
});
|
|
const previousRefs = new Set([
|
|
...collectSecretRefs(previousAdapterConfig).map((ref) => `secret:${ref.secretId}:${ref.configPath}`),
|
|
...collectUserSecretRefs(previousAdapterConfig).map((ref) => `user:${ref.definitionKey}:${ref.configPath}`),
|
|
]);
|
|
const createdRefs = [
|
|
...collectSecretRefs(agent.adapterConfig).map((ref) => ({
|
|
key: `secret:${ref.secretId}:${ref.configPath}`,
|
|
configPath: ref.configPath,
|
|
bindingType: "secret_ref",
|
|
secretId: ref.secretId,
|
|
definitionKey: null,
|
|
})),
|
|
...collectUserSecretRefs(agent.adapterConfig).map((ref) => ({
|
|
key: `user:${ref.definitionKey}:${ref.configPath}`,
|
|
configPath: ref.configPath,
|
|
bindingType: "user_secret_ref",
|
|
secretId: null,
|
|
definitionKey: ref.definitionKey,
|
|
})),
|
|
].filter((ref) => !previousRefs.has(ref.key));
|
|
const actorType = actor.createdByUserId ? "user" as const : actor.createdByAgentId ? "agent" as const : "system" as const;
|
|
const actorId = actor.createdByUserId ?? actor.createdByAgentId ?? "system";
|
|
for (const ref of createdRefs) {
|
|
await logActivity(dbClient, {
|
|
companyId: agent.companyId,
|
|
actorType,
|
|
actorId,
|
|
agentId: actor.createdByAgentId ?? null,
|
|
action: "secret.binding.created",
|
|
entityType: "agent",
|
|
entityId: agent.id,
|
|
details: {
|
|
targetType: "agent",
|
|
targetId: agent.id,
|
|
configPath: ref.configPath,
|
|
bindingType: ref.bindingType,
|
|
secretId: ref.secretId,
|
|
definitionKey: ref.definitionKey,
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Enforces the Claude OAuth binding claim inside a write transaction. It runs
|
|
* after {@link assertClaudeOAuthBindingInvariant} decided that the write
|
|
* introduces or keeps the fixed binding.
|
|
*
|
|
* When the write introduces the fixed binding:
|
|
* * A create or hire path (`consume: true`) consumes a stored-session claim
|
|
* with one conditional write. It builds the claim scope from the company,
|
|
* the owner user, the fixed adapter, the environment, and the
|
|
* `storedSessionId`. It inserts the binding only when the write returns one
|
|
* row; otherwise it raises the fixed claim error, which rolls back the
|
|
* whole transaction and inserts no binding.
|
|
* * An update, approval, or rollback path (`consume: false`) carries no
|
|
* claim, so it raises the same fixed claim error at once.
|
|
*
|
|
* The user-actor apply-existing path (`applyExistingWithoutClaim`) binds the
|
|
* fixed reference with no login round trip. The route sets the flag only for
|
|
* an authenticated user actor and derives the owner from that actor. The gate
|
|
* permits the no-claim bind only when the owner already has a stored value for
|
|
* the company. It reads the owner value status; it reads no token. A missing
|
|
* owner or a missing stored value raises the same fixed claim error, so the
|
|
* caller cannot tell the reasons apart.
|
|
*
|
|
* The hire-inheritance path (`inheritedFromAgentId`) binds the fixed
|
|
* reference with no login round trip and no stored owner value, because the
|
|
* owning user resolves per run, not from a value stored against this agent.
|
|
* The route copies the parent's reference onto the child before this
|
|
* transaction starts, so a concurrent version change on the parent can
|
|
* leave the child holding a stale version. The gate re-reads the named
|
|
* parent agent inside this transaction and permits the bind only when the
|
|
* parent exists, is in the same company, is a `claude_local` agent, and its
|
|
* current reference matches the child's copied reference exactly, including
|
|
* the version selector. The gate locks the parent row with `SELECT ...
|
|
* FOR UPDATE` before it reads the reference. The lock blocks a concurrent
|
|
* credential rotation on the same parent row until this transaction
|
|
* commits or rolls back, so the compare-and-bind check stays atomic with
|
|
* the parent's current state. The route derives the parent identifier
|
|
* from the authenticated agent actor, never from the request body, so the
|
|
* gate treats it as a claim to verify, not a trusted value.
|
|
*
|
|
* A controlled internal override skips the claim for a migration or an
|
|
* administrator repair. The function creates the fixed user-secret definition
|
|
* before the caller runs the declaration synchronization, so the synchronized
|
|
* declaration always references an existing definition.
|
|
*/
|
|
async function enforceClaudeOAuthBindingClaim(
|
|
txDb: Db,
|
|
input: {
|
|
companyId: string;
|
|
decision: ClaudeOAuthBindingInvariantDecision;
|
|
consume: boolean;
|
|
environmentId: string | null;
|
|
claudeLogin?: ClaudeLoginContext;
|
|
/**
|
|
* The adapter config the write is about to persist. The
|
|
* `inheritedFromAgentId` path reads the child's copied
|
|
* `CLAUDE_CODE_OAUTH_TOKEN` reference from it, to compare against the
|
|
* parent's current reference.
|
|
*/
|
|
childAdapterConfig?: unknown;
|
|
},
|
|
): Promise<void> {
|
|
const ownerUserId = input.claudeLogin?.ownerUserId ?? null;
|
|
if (input.decision.introducesBinding && !input.claudeLogin?.allowInternalBindingOverride) {
|
|
if (input.claudeLogin?.applyExistingWithoutClaim) {
|
|
// The user-actor apply-existing path. The route derived the owner from
|
|
// the authenticated user actor. The gate binds the fixed reference only
|
|
// when that owner already has a stored value. It reads no token.
|
|
if (!ownerUserId) {
|
|
throw claudeOAuthClaimRejectedError();
|
|
}
|
|
const stored = await secretService(txDb).readClaudeOAuthUserSecretStatus(
|
|
input.companyId,
|
|
ownerUserId,
|
|
);
|
|
if (!stored) {
|
|
throw claudeOAuthClaimRejectedError();
|
|
}
|
|
} else if (input.claudeLogin?.inheritedFromAgentId) {
|
|
// The hire-inheritance path. Re-read the named parent inside this
|
|
// transaction; a caller-supplied identifier never binds on its own.
|
|
// Compare the parent's current reference against the reference
|
|
// already copied onto the child, including the version selector, so
|
|
// a concurrent version change on the parent cannot leave the child
|
|
// bound to a stale version.
|
|
const parentId = input.claudeLogin.inheritedFromAgentId;
|
|
const parent = await txDb
|
|
.select({
|
|
companyId: agents.companyId,
|
|
adapterType: agents.adapterType,
|
|
adapterConfig: agents.adapterConfig,
|
|
})
|
|
.from(agents)
|
|
.where(eq(agents.id, parentId))
|
|
.for("update")
|
|
.then((rows) => rows[0] ?? null);
|
|
const parentBinding = readClaudeOAuthBinding(parent?.adapterConfig ?? null);
|
|
const childBinding = readClaudeOAuthBinding(input.childAdapterConfig ?? null);
|
|
if (
|
|
!parent ||
|
|
parent.companyId !== input.companyId ||
|
|
parent.adapterType !== CLAUDE_LOCAL_ADAPTER_TYPE ||
|
|
!claudeOAuthBindingsMatchExactly(parentBinding, childBinding)
|
|
) {
|
|
throw claudeOAuthClaimRejectedError();
|
|
}
|
|
} else if (!input.consume) {
|
|
throw claudeOAuthClaimRejectedError();
|
|
} else {
|
|
const consumed = await createDbSetupTokenCleanupStore(txDb).consumeStoredClaim({
|
|
sessionId: input.claudeLogin?.storedSessionId ?? "",
|
|
companyId: input.companyId,
|
|
ownerUserId: ownerUserId ?? "",
|
|
adapterType: CLAUDE_LOCAL_ADAPTER_TYPE,
|
|
});
|
|
if (!consumed) {
|
|
throw claudeOAuthClaimRejectedError();
|
|
}
|
|
}
|
|
}
|
|
if (input.decision.introducesBinding || input.decision.keepsBinding) {
|
|
// Create the fixed definition before declaration synchronization.
|
|
await secretService(txDb).ensureClaudeOAuthUserSecretDefinition(input.companyId, {
|
|
userId: ownerUserId,
|
|
});
|
|
}
|
|
}
|
|
|
|
return { syncAgentSecretBindings, enforceClaudeOAuthBindingClaim };
|
|
}
|