mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip schedules work for agents. > - Each agent has a limit on simultaneous runs. > - A task driver can provide an execution environment with its own capacity. > - Previously the creation form sent the same limit for every driver. > - A driver can now declare the value Core saves when a new agent has no explicit limit. ## Linked Issues or Issue Description **Subsystem affected** Agent hiring and plugin environment drivers. **Current behavior** The create form, API, and import flow supply the global concurrency default before the task driver can provide one. **Proposed behavior** Let each task driver declare an optional per-agent concurrency default. Apply it once during hire and honor explicit agent limits. ## What Changed - Refreshed the three SDK source pins for the changed files. - Added the optional driver field `defaultMaxConcurrentRuns` with integer bounds from 1 through 50. - Applied it during hire using the resolved task environment. Saved the resolved runtime configuration in hire approvals. - Removed early defaults from the creation form, routes and new-agent imports. Preserved saved limits on export, including explicit values equal to the global default. Kept the current limit when importing an update with an omitted limit. ## Verification - [Full PR CI](https://github.com/paperclipai/paperclip/actions/runs/47000023360) passed on `83cce42b9a`. Server shard 16 passed on retry after a PostgreSQL connection reset on the first attempt. - `pnpm -r typecheck` passed. The SDK source pin check passed. `pnpm verify` selected broad CI coverage because the SDK input registry changed. - On rebased commit `83cce42b9a`, all 441 tests in six focused Vitest suites passed, including the MCP rollback test corrected in #23560. The SDK source pin check passed. ## Risks This affects new hires on drivers that opt in. Existing agents retain their saved configuration. Single-run provider limits still apply. An older client that explicitly sends the global default will keep that value. ## Model Used OpenAI GPT-6 via Codex. Used local source inspection, code editing, TypeScript and 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 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
174 lines
10 KiB
TypeScript
174 lines
10 KiB
TypeScript
import { assertAgentInteraction } from "./agent-interaction-policy.js";
|
|
import { assertNoInitialAgentInteractionPermissions, preserveAgentInteractionPermissions } from "../lib/agent-interaction-permissions.js";
|
|
import { assertEphemeralAgentInstructions } from "./agent-instructions.js";
|
|
import { initializeDurableAgentFiles } from "./agent-file-durability.js";
|
|
import { notifyAttentionRetentionWork } from "./retention-work-notifications.js";
|
|
import { notifySkillVersionRetention, notifySkillVersionPinChange } from "./skill-version-retention-notifications.js";
|
|
import { agentAppearanceSchema, randomAgentAppearance } from "@paperclipai/shared";
|
|
import { normalizePaperclipRunnerAdapterConfig } from "@paperclipai/adapter-utils/server-utils";
|
|
import { agents, toolConnectionInstalls, principalPermissionGrants, type Db } from "@paperclipai/db";
|
|
import { eq } from "drizzle-orm";
|
|
import { unprocessable } from "../errors.js";
|
|
import { agentRecordQueries, isPlainRecord, configPatchFromApprovalPayload, normalizeRuntimeConfigForNewAgent,
|
|
deduplicateAgentName, type CreateAgentData, type CreateAgentOptions, type AgentConfigurationPatch, type AgentHireRecord } from "../lib/agent-records.js";
|
|
import { CEO_HIRING_DENIAL_KEY, normalizeAgentPermissions, permissionsImplyLowTrust, NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS,
|
|
newStandardAgentGrantScope } from "../lib/agent-permissions.js";
|
|
import { readBuiltInAgentMarker } from "../lib/built-in-agent-metadata.js";
|
|
import { secretService, assertClaudeOAuthBindingInvariant } from "./secrets.js";
|
|
import { agentCredentialService } from "./agent-credentials.js";
|
|
import { agentIdentityService } from "./agent-identity.js";
|
|
import { initializePrimaryAgent } from "./primary-agent.js";
|
|
import { resolveAgentRunnerTaskDriverForCompany, resolveNewAgentRunnerForCompany } from "./agent-runner-selection.js";
|
|
import { instanceSettingsService } from "./instance-settings.js";
|
|
import { assertProviderApiPlacementPolicy, isProviderApiSetupDraft, resolveProviderApiPlacement } from "./native-runtime/provider-api-placement.js";
|
|
|
|
export async function prepareAgentHire(db: Db, companyId: string, input: CreateAgentData, options?: CreateAgentOptions): Promise<CreateAgentData> {
|
|
assertNoInitialAgentInteractionPermissions(input.permissions);
|
|
await assertAgentInteraction(db, { companyId, actorAgentId: options?.createdByAgentId, actorCompanyId: options?.createdByAgentCompanyId,
|
|
operation: "mention", texts: [JSON.stringify(input), ...(options?.interactionTexts ?? [])], lock: "update" });
|
|
await notifyAttentionRetentionWork(db, { companyId });
|
|
const { runner, ...data } = input;
|
|
const selection = options?.runnerResolved
|
|
? { adapterType: data.adapterType ?? "process", adapterConfig: isPlainRecord(data.adapterConfig) ? data.adapterConfig : {} }
|
|
: await resolveNewAgentRunnerForCompany(db, companyId, {
|
|
...data, adapterConfig: isPlainRecord(data.adapterConfig) ? data.adapterConfig : {}, runner,
|
|
});
|
|
data.adapterType = selection.adapterType;
|
|
data.adapterConfig = selection.adapterConfig;
|
|
const { ensureManager, assertBuiltInAgentMetadataMutationAllowed } = agentRecordQueries(db);
|
|
if (data.appearance?.customAvatarAssetId) throw unprocessable("Create the agent before uploading its avatar");
|
|
assertBuiltInAgentMetadataMutationAllowed(null, data.metadata, options);
|
|
if (data.reportsTo) {
|
|
await ensureManager(companyId, data.reportsTo);
|
|
}
|
|
|
|
const existingAgents = await db
|
|
.select({ id: agents.id, name: agents.name, status: agents.status })
|
|
.from(agents)
|
|
.where(eq(agents.companyId, companyId));
|
|
const uniqueName = deduplicateAgentName(data.name, existingAgents.filter(agent => agent.id !== options?.setupAgentId));
|
|
|
|
const role = data.role ?? "general";
|
|
// Only the permissions control records a CEO hiring restriction.
|
|
const requestedPermissions = data.permissions && typeof data.permissions === "object" && !Array.isArray(data.permissions)
|
|
? Object.fromEntries(Object.entries(data.permissions).filter(([key]) => key !== CEO_HIRING_DENIAL_KEY)) : data.permissions;
|
|
const normalizedPermissions = normalizeAgentPermissions(requestedPermissions, { context: "create" });
|
|
const adapterType = data.adapterType ?? "process";
|
|
const rawAdapterConfig = isPlainRecord(data.adapterConfig)
|
|
? await secretService(db).normalizeAdapterConfigForPersistence(companyId, data.adapterConfig, { adapterType })
|
|
: {};
|
|
const adapterConfig = normalizePaperclipRunnerAdapterConfig(adapterType, rawAdapterConfig);
|
|
const profile = { adapterType, adapterConfig };
|
|
const providerApiDraft = options?.setupOnly === true && isProviderApiSetupDraft(profile);
|
|
const providerApi = providerApiDraft ? null : resolveProviderApiPlacement({ agent: profile });
|
|
if (providerApi) assertProviderApiPlacementPolicy(await instanceSettingsService(db).getGeneral());
|
|
const taskDriver = !providerApiDraft && !providerApi && adapterType === "paperclip_runner" && !["openai_dot", "grok_bot", "muse"].includes(String(adapterConfig.provider))
|
|
? await resolveAgentRunnerTaskDriverForCompany(db, companyId, data.defaultEnvironmentId) : undefined;
|
|
const runtimeConfig = normalizeRuntimeConfigForNewAgent(data.runtimeConfig, taskDriver?.defaultMaxConcurrentRuns);
|
|
if (taskDriver?.warmTaskVersion === 1) {
|
|
adapterConfig.lifecycleMode = "warm";
|
|
}
|
|
await agentCredentialService(db).enforceClaudeOAuthBindingClaim(db, {
|
|
companyId, consume: true, environmentId: data.defaultEnvironmentId ?? null,
|
|
childAdapterConfig: adapterConfig, claudeLogin: options?.claudeLogin,
|
|
decision: assertClaudeOAuthBindingInvariant({ adapterType, nextConfig: adapterConfig }),
|
|
});
|
|
if (options?.setupAgentId) await notifySkillVersionRetention(db, companyId);
|
|
return { ...data, name: uniqueName,
|
|
appearance: data.appearance == null ? randomAgentAppearance() : agentAppearanceSchema.parse(data.appearance),
|
|
role, adapterType, adapterConfig, permissions: normalizedPermissions, runtimeConfig };
|
|
}
|
|
|
|
export async function initializeAgentHire(txDb: Db, created: AgentHireRecord, options?: CreateAgentOptions) {
|
|
const tx = txDb;
|
|
const companyId = created.companyId;
|
|
assertEphemeralAgentInstructions({ ...created, name: "" });
|
|
await initializeDurableAgentFiles(txDb, created);
|
|
await agentIdentityService(txDb).ensureAgentIdentity(companyId, created.id);
|
|
// New standard agents receive the standard direct grants at activation.
|
|
// Low-trust and bundled agents keep their explicit, narrower grants.
|
|
if (!options?.setupOnly && created.status !== "pending_approval" && !permissionsImplyLowTrust(created.permissions) &&
|
|
!readBuiltInAgentMarker(created.metadata)) {
|
|
await tx.insert(principalPermissionGrants).values(
|
|
NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({
|
|
companyId,
|
|
principalType: "agent" as const,
|
|
principalId: created.id,
|
|
permissionKey,
|
|
scope: newStandardAgentGrantScope(permissionKey, created.id),
|
|
})),
|
|
).onConflictDoNothing();
|
|
}
|
|
if (options?.aiConnectionInstall) {
|
|
const install = options.aiConnectionInstall;
|
|
const connectionIds = [...new Set([install.connectionId, ...(install.memberConnectionIds ?? [])])];
|
|
await tx.insert(toolConnectionInstalls).values(connectionIds.map(connectionId => ({
|
|
companyId, connectionId,
|
|
targetType: "agent" as const, targetId: created.id,
|
|
createdByUserId: install.createdByUserId,
|
|
}))).onConflictDoNothing();
|
|
}
|
|
await agentCredentialService(txDb).syncAgentSecretBindings(created, txDb);
|
|
if (!options?.setupOnly && options?.createdByUserId && !readBuiltInAgentMarker(created.metadata)) {
|
|
await initializePrimaryAgent(txDb, companyId, options.createdByUserId, created.id);
|
|
}
|
|
}
|
|
|
|
export async function prepareAgentHireApproval(txDb: Db, existing: AgentHireRecord, approvedPayload?: Record<string, unknown> | null): Promise<AgentConfigurationPatch> {
|
|
const approvedPatch = approvedPayload ? configPatchFromApprovalPayload(approvedPayload) : {};
|
|
const patch = { ...approvedPatch } as AgentConfigurationPatch;
|
|
const hasApprovedAdapterConfig = Object.prototype.hasOwnProperty.call(patch, "adapterConfig") && isPlainRecord(patch.adapterConfig);
|
|
if (
|
|
Object.prototype.hasOwnProperty.call(patch, "adapterConfig") &&
|
|
isPlainRecord(patch.adapterConfig)
|
|
) {
|
|
const normalizedAdapterConfig = await secretService(txDb).normalizeAdapterConfigForPersistence(
|
|
existing.companyId, patch.adapterConfig, { adapterType: (patch.adapterType ?? existing.adapterType) as string },
|
|
);
|
|
patch.adapterConfig = normalizePaperclipRunnerAdapterConfig(
|
|
(patch.adapterType ?? existing.adapterType) as string,
|
|
normalizedAdapterConfig,
|
|
);
|
|
} else if (
|
|
Object.prototype.hasOwnProperty.call(patch, "adapterType")
|
|
&& isPlainRecord(existing.adapterConfig)
|
|
) {
|
|
patch.adapterConfig = normalizePaperclipRunnerAdapterConfig(
|
|
patch.adapterType as string,
|
|
existing.adapterConfig,
|
|
);
|
|
}
|
|
if (patch.permissions !== undefined) {
|
|
// The pending-approval activation replays the original hire
|
|
// request, so the new-agent creation default applies.
|
|
patch.permissions = normalizeAgentPermissions(preserveAgentInteractionPermissions(existing.permissions, patch.permissions), { context: "create" });
|
|
}
|
|
if (hasApprovedAdapterConfig) {
|
|
await agentCredentialService(txDb).enforceClaudeOAuthBindingClaim(txDb, {
|
|
companyId: existing.companyId, consume: false, environmentId: null,
|
|
childAdapterConfig: patch.adapterConfig,
|
|
decision: assertClaudeOAuthBindingInvariant({ adapterType: patch.adapterType ?? existing.adapterType,
|
|
nextConfig: patch.adapterConfig, priorConfig: existing.adapterConfig }),
|
|
});
|
|
}
|
|
if (patch.adapterConfig !== undefined) await notifySkillVersionPinChange(txDb, existing.companyId, existing.adapterConfig ?? {}, patch.adapterConfig);
|
|
assertEphemeralAgentInstructions({ ...existing, ...patch, name: "" });
|
|
return patch;
|
|
}
|
|
|
|
export async function completeAgentHireApproval(txDb: Db, updated: AgentHireRecord, existing: AgentHireRecord) {
|
|
const tx = txDb;
|
|
await agentCredentialService(txDb).syncAgentSecretBindings(updated, txDb, existing.adapterConfig);
|
|
if (!permissionsImplyLowTrust(updated.permissions) && !readBuiltInAgentMarker(updated.metadata)) {
|
|
await tx.insert(principalPermissionGrants).values(
|
|
NEW_STANDARD_AGENT_DEFAULT_GRANT_KEYS.map((permissionKey) => ({
|
|
companyId: updated.companyId,
|
|
principalType: "agent" as const,
|
|
principalId: updated.id,
|
|
permissionKey,
|
|
scope: newStandardAgentGrantScope(permissionKey, updated.id),
|
|
})),
|
|
).onConflictDoNothing();
|
|
}
|
|
}
|