Skip to content

The open-source app everyone uses to manage agents at work

refactor(heartbeat): extract execution configuration (#15973)

Dotta914b70572c9a
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index da1bc58a96..90b2760794 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -1293,6 +1293,14 @@ cleanup. Public-path characterization tests are in
browser fixture also checks the persisted prompt variants and description revision
from a real process adapter before completing its task.
+Execution configuration is assembled in
+`server/src/services/heartbeat/execution-configuration.ts`: workspace and issue
+overrides, scoped credentials, managed AI identity, and runtime skill delivery.
+The executor receives credential ownership and failure-redaction updates as soon
+as they are available, so later setup failures still clean up acquired resources.
+Busy-account deferral returns explicitly before session/workspace preparation.
+Public-path tests are in `server/src/__tests__/heartbeat-execution-configuration.test.ts`.
+
Session preparation is in `server/src/services/heartbeat/session-preparation.ts`.
It selects fresh or resumable sessions from effective config and managed-account
identity, then resolves adapter session identity and compaction after workspace
diff --git a/server/src/__tests__/heartbeat-execution-configuration.test.ts b/server/src/__tests__/heartbeat-execution-configuration.test.ts
new file mode 100644
index 0000000000..ee1dbd6629
--- /dev/null
+++ b/server/src/__tests__/heartbeat-execution-configuration.test.ts
@@ -0,0 +1,160 @@
+import { randomUUID } from "node:crypto";
+import { access, readFile } from "node:fs/promises";
+import path from "node:path";
+import { eq } from "drizzle-orm";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { agents, companies, companyMemberships, createDb, heartbeatRunEvents, heartbeatRuns, issues, projects } from "@paperclipai/db";
+import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js";
+import { HttpError } from "../errors.js";
+import { heartbeatService } from "../services/heartbeat.js";
+import { aiConnectionService } from "../services/ai-connections.js";
+import * as aiRuntime from "../services/ai-connection-runtime.js";
+import * as sentry from "../sentry.js";
+import { waitForPendingRunFailureReports } from "../services/run-failure-report.js";
+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+
+const skillFailures = vi.hoisted(() => new Map<string, string>());
+vi.mock("../services/company-skills.js", async importOriginal => {
+ const actual = await importOriginal<typeof import("../services/company-skills.js")>();
+ return { ...actual, companySkillService: (...args: Parameters<typeof actual.companySkillService>) => {
+ const service = actual.companySkillService(...args);
+ return { ...service, listRuntimeSkillEntries: async (...input: Parameters<typeof service.listRuntimeSkillEntries>) => {
+ const failure = skillFailures.get(input[0]);
+ if (failure) throw new Error(failure);
+ return service.listRuntimeSkillEntries(...input);
+ } };
+ } };
+});
+
+const support = await getEmbeddedPostgresTestSupport();
+const describePostgres = support.supported ? describe : describe.skip;
+if (!support.supported) console.warn(`Skipping execution configuration tests: ${support.reason}`);
+
+describePostgres("heartbeat execution configuration through adapter dispatch", () => {
+ let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
+ let db: ReturnType<typeof createDb>;
+ let heartbeat: ReturnType<typeof heartbeatService>;
+ const captured = new Map<string, AdapterExecutionContext>();
+ const inspect = new Map<string, (input: AdapterExecutionContext) => Promise<void>>();
+ const adapterType = "codex_local";
+
+ beforeAll(async () => {
+ temporary = await startEmbeddedPostgresTestDatabase("heartbeat-execution-config-");
+ db = createDb(temporary.connectionString);
+ heartbeat = heartbeatService(db);
+ // Exercise real preparation for a managed-capable adapter without calling a provider.
+ registerServerAdapter({
+ type: adapterType, supportsLocalAgentJwt: false,
+ execute: async input => {
+ captured.set(input.runId, input);
+ await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, String(input.context.issueId)));
+ await inspect.get(input.agent.id)?.(input);
+ return { exitCode: 0, signal: null, timedOut: false, resultJson: {} };
+ },
+ testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }),
+ });
+ }, 30_000);
+ afterEach(() => { vi.restoreAllMocks(); skillFailures.clear(); });
+ afterAll(async () => {
+ await heartbeat?.drainActiveRunExecutions();
+ unregisterServerAdapter(adapterType);
+ await db?.$client.end({ timeout: 0 });
+ await temporary?.cleanup();
+ });
+
+ async function seed(managed = false) {
+ const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), projectId = randomUUID();
+ const userId = `configuration-user-${companyId}`;
+ const credential = `fixture-api-key-${companyId}`;
+ await db.insert(companies).values({ id: companyId, name: "Execution configuration fixture", issuePrefix: `C${companyId.slice(0, 6)}` });
+ await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "member" });
+ const account = managed ? await aiConnectionService(db).save(companyId, userId, {
+ provider: "openai", method: "api_key", ownership: "personal", name: "Fixture account", apiKey: credential, agentIds: [], allAgents: true,
+ }, credential) : null;
+ await db.insert(projects).values({ id: projectId, companyId, name: "Config project", env: { SHARED_VALUE: "project", PROJECT_ONLY: "project-only" } });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Configuration reader", adapterType, status: "idle",
+ adapterConfig: { model: "agent-model", env: { SHARED_VALUE: "agent", AGENT_ONLY: "agent-only", ...(managed ? { OPENAI_API_KEY: "stale-agent-key" } : {}) } },
+ runtimeConfig: account ? { aiConnection: { provider: "openai", method: "api_key", mode: "delegated", connectionId: account.connectionId, grantId: account.grantId } } : {},
+ });
+ await db.insert(issues).values({ id: issueId, companyId, projectId, title: "Configuration fixture", status: "todo", assigneeAgentId: agentId, responsibleUserId: userId, issueNumber: 1, assigneeAdapterOverrides: { adapterConfig: { model: "issue-model" } } });
+ return { companyId, agentId, issueId, credential };
+ }
+
+ async function execute(f: Awaited<ReturnType<typeof seed>>) {
+ const run = await heartbeat.wakeup(f.agentId, { source: "on_demand", triggerDetail: "manual", reason: "manual", payload: { issueId: f.issueId }, contextSnapshot: {
+ issueId: f.issueId, paperclipSecrets: { manifest: [{ secretKey: "untrusted-wake-value" }] },
+ paperclipWake: { connectorSkillInstructions: "untrusted wake instructions" },
+ } });
+ expect(run).not.toBeNull();
+ await heartbeat.drainActiveRunExecutions();
+ const [finished] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id));
+ expect(finished).toBeDefined();
+ return { finished, input: captured.get(run!.id) };
+ }
+
+ it("applies project environment and issue overrides and replaces caller-supplied runtime fields", async () => {
+ const f = await seed();
+ const { finished, input } = await execute(f);
+ expect(finished.status, finished.error ?? undefined).toBe("succeeded");
+ expect(input?.config).toMatchObject({ model: "issue-model", env: { SHARED_VALUE: "project", AGENT_ONLY: "agent-only", PROJECT_ONLY: "project-only" } });
+ expect(input?.context.paperclipSecrets).toBeUndefined();
+ expect(JSON.stringify(input?.context.paperclipWake)).not.toContain("untrusted wake instructions");
+ });
+
+ it("delivers the selected credential in an isolated home and removes it after completion", async () => {
+ const f = await seed(true);
+ let providerHome: string | undefined;
+ inspect.set(f.agentId, async input => {
+ const env = input.config.env as Record<string, string>;
+ providerHome = env.CODEX_HOME;
+ expect(env.OPENAI_API_KEY).toBe(f.credential);
+ expect(env.CODEX_API_KEY).toBe(f.credential);
+ expect(JSON.parse(await readFile(path.join(providerHome, "auth.json"), "utf8"))).toEqual({ OPENAI_API_KEY: f.credential });
+ await input.onMeta?.({ adapterType, command: "fixture", env, prompt: "fixture" });
+ });
+ const { finished, input } = await execute(f);
+ expect(finished.status, finished.error ?? undefined).toBe("succeeded");
+ expect(input?.context.aiConnection).toMatchObject({ accountName: "Fixture account", provider: "openai" });
+ expect(providerHome).toEqual(expect.any(String));
+ await expect(access(providerHome!)).rejects.toMatchObject({ code: "ENOENT" });
+ const events = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, finished.id));
+ expect(events.some(event => event.eventType === "adapter.invoke")).toBe(true);
+ expect(JSON.stringify(events)).not.toContain(f.credential);
+ });
+
+ it("cleans acquired credentials and redacts diagnostics when later skill preparation fails", async () => {
+ const f = await seed(true);
+ skillFailures.set(f.companyId, `Invalid fixture skill configuration: ${f.credential}`);
+ const capturedFailure = vi.spyOn(sentry, "captureRunFailure").mockImplementation(() => undefined);
+ const prepare = aiRuntime.prepareManagedAiRuntime;
+ let acquiredHome: string | undefined;
+ vi.spyOn(aiRuntime, "prepareManagedAiRuntime").mockImplementation(async (...args) => {
+ const runtime = await prepare(...args);
+ acquiredHome = runtime.home;
+ await access(acquiredHome!);
+ return runtime;
+ });
+ const { finished, input } = await execute(f);
+ expect(finished.status).toBe("failed");
+ expect(input).toBeUndefined();
+ expect(acquiredHome).toEqual(expect.any(String));
+ await expect(access(acquiredHome!)).rejects.toMatchObject({ code: "ENOENT" });
+ expect(finished.error).toContain("Invalid fixture skill configuration");
+ // The diagnostic reporter redacts runtime values before the external sink.
+ // The legacy local run.error field does not apply this value-based redaction.
+ await waitForPendingRunFailureReports();
+ expect(capturedFailure).toHaveBeenCalled();
+ expect(JSON.stringify(capturedFailure.mock.calls)).toContain("Invalid fixture skill configuration");
+ expect(JSON.stringify(capturedFailure.mock.calls)).not.toContain(f.credential);
+ });
+
+ it("defers a busy account without dispatch and preserves its scheduled retry", async () => {
+ const f = await seed(true);
+ vi.spyOn(aiRuntime, "prepareManagedAiRuntime").mockRejectedValueOnce(new HttpError(422, "AI credentials are being updated. Retry shortly.", { code: "ai_connection_busy" }));
+ const { finished, input } = await execute(f);
+ expect(input).toBeUndefined();
+ expect(finished).toMatchObject({ status: "cancelled", errorCode: "ai_connection_busy", resultJson: { executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: false } }, contextSnapshot: { aiConnectionBusyDeferredWhileAssignee: true } });
+ const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agentId));
+ expect(runs.filter(run => run.id !== finished.id)).toEqual([expect.objectContaining({ status: "scheduled_retry", scheduledRetryReason: "ai_connection_busy" })]);
+ });
+});
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 54006b8b7e..8f562fb862 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -1,3 +1,4 @@
+import { prepareHeartbeatExecutionConfiguration } from "./heartbeat/execution-configuration.js";
import { createHeartbeatRunOutput } from "./heartbeat/run-output.js";
import { prepareHeartbeatSession, resolveHeartbeatAdapterSession } from "./heartbeat/session-preparation.js";
import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js";
@@ -113,9 +114,6 @@ import {
resolveAcceptedPlanWakeRoutingDecision,
clearInteractionContinuationWakeContext,
PAPERCLIP_WAKE_PAYLOAD_KEY,
- resolveRunScopedMentionedSkillKeys,
- resolveExecutionRunAdapterConfig,
- applyRunScopedMentionedSkillKeys,
MANAGED_GITHUB_TOKEN_KEYS,
configuredPaperclipApiBaseUrl,
createHeartbeatRunPreparation,
@@ -134,8 +132,6 @@ export {
buildPaperclipWakePayload,
} from "./heartbeat/run-preparation.js";
import {
- buildExecutionWorkspaceConfigSnapshot,
- stripWorkspaceRuntimeFromExecutionRunConfig,
resolveRuntimeSessionParamsForWorkspace,
buildRunWorkspaceHints,
buildReferencedProjectRunObservability,
@@ -211,10 +207,7 @@ export { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js";
import { decisionModelService } from "./decision-models.js";
import { TASK_QUESTION_GUIDANCE } from "./issue-question-context.js";
import { createAgentIdentityRedactor } from "./agent-identity-redaction.js";
-import { agentIdentityService, supportsManagedAgentIdentity } from "./agent-identity.js";
-import { prepareConnectionInstructionDelivery } from "./connection-instructions.js";
-import { resolveAssignedConnectionInstructionsForRun } from "./native-runtime/assigned-mcp-tools.js";
import {
startupCancellationFence,
@@ -250,19 +243,13 @@ import {
watchLegacyControllerLease,
} from "./legacy-controller-lease.js";
-import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "./connector-runtime.js";
-import { connectionIntentService } from "./connection-intents.js";
import {
prepareManagedAiRuntime,
assertManagedAiProjectAuth,
- stripAiAuthBindings,
- isAiConnectionBusy,
- AI_AUTH_ENV_KEYS,
} from "./ai-connection-runtime.js";
import { aiConnectionBindingSchema, aiRuntimeConnectionBindingSchema, type AiConnectionRouterSelection } from "@paperclipai/shared";
import { aiConnectionRouterService, AiConnectionPoolExhausted, applyAiConnectionRouterTaskSettings } from "./ai-connection-router.js";
-import { managedAiSessionIdentityCompatible } from "./ai-connection-session.js";
import {
getExecutionBlocker,
} from "./execution-blocker.js";
@@ -336,7 +323,6 @@ import { HttpError, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import {
- resolveManagedGitHubIdentitySelection,
scrubGitCredentialText,
} from "./git-credentials.js";
// Re-exported because heartbeat's workspace surface exposed the scrubber before the
@@ -360,10 +346,6 @@ import {
resolveHeartbeatNativeRuntimeMode,
} from "./native-runtime/index.js";
-import {
- recordFailedSkillPreparation,
- type NativeRunHistoricalSpan,
-} from "./native-runtime/native-run-trace.js";
import {
parseNativeExecutionInput,
type NativeExecutionInput,
@@ -396,7 +378,6 @@ import {
emitAgentTaskRun,
emitAgentTaskRunById,
} from "./agent-task-run-telemetry.js";
-import { readAiConnectionConfigurationFailure, readAiCredentialAccessFailure } from "./ai-connection-configuration-failure.js";
import { reportRunFailure } from "./run-failure-report.js";
import { collectRunFailureSecretValues, type RunFailureReportOptions } from "./run-failure-diagnostics.js";
@@ -463,7 +444,6 @@ import {
} from "./run-scratch.js";
import {
applyDefaultIsolatedExecutionWorkspacePolicy,
- buildExecutionWorkspaceAdapterConfig,
gateProjectExecutionWorkspacePolicy,
parseIssueExecutionWorkspaceSettings,
parseProjectExecutionWorkspacePolicy,
@@ -489,7 +469,6 @@ import {
type PostCommitEffect,
MAX_TURN_CONTINUATION_RETRY_REASON,
WORKSPACE_BUSY_RETRY_REASON,
- AI_CONNECTION_BUSY_RETRY_REASON,
AI_CONNECTION_POOL_WAIT_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_RETRY_REASON,
INTERACTION_CONTINUATION_INFRA_WAKE_REASON,
@@ -516,9 +495,6 @@ import {
import { createRunSecretRedactionRegistry } from "./run-secret-redaction.js";
-import {
- readPaperclipSkillSyncPreference,
-} from "@paperclipai/adapter-utils/server-utils";
import { environmentService } from "./environments.js";
@@ -526,7 +502,6 @@ import {
environmentRuntimeService,
type ProviderResourceDisposition,
} from "./environment-runtime.js";
-import { skillVersionSelectionMap } from "./runtime-skill-selections.js";
import { environmentRunOrchestrator } from "./environment-run-orchestrator.js";
import {
@@ -544,9 +519,6 @@ import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { computeTaskDrain, applyTaskDrain, startTaskDrain, stopTaskDrain, readTaskDrain } from "./task-admission.js";
-const ACCEPTED_PLAN_CONVERSION_SKILL_KEY =
- "paperclipai/paperclip/paperclip-converting-plans-to-tasks";
-
const execFile = promisify(execFileCallback);
const UNSUCCESSFUL_HEARTBEAT_RUN_TERMINAL_STATUSES = [
"failed",
@@ -2698,185 +2670,24 @@ export function heartbeatService(
config: { config, issueAssigneeOverrides },
services: { executionWorkspacesSvc, environmentsSvc, instanceSettings, findSharedWorkspaceHolder },
});
- const workspaceManagedConfig = buildExecutionWorkspaceAdapterConfig({
- agentConfig: config,
- projectPolicy: projectExecutionWorkspacePolicy,
- issueSettings: issueExecutionWorkspaceSettings,
- mode: requestedExecutionWorkspaceMode,
- legacyUseProjectWorkspace:
- issueAssigneeOverrides?.useProjectWorkspace ?? null,
- });
- const mergedConfig = {
- ...workspaceManagedConfig,
- ...Object.fromEntries(Object.entries(issueAssigneeOverrides?.adapterConfig ?? {}).filter(([key]) => requestedAiBinding?.mode !== "router" || !["provider", "acpxAgent", "model", "modelReasoningEffort", "reasoningEffort", "effort", "variant"].includes(key))),
- ...(requestedAiBinding?.mode === "router" ? parseObject(parseObject(context.aiRouterSelection).runtimeConfig) : {}),
- // The base below is already task-owned. Keep directory transport while
- // preserving isolated mode and the mandatory sandbox preflight.
- ...(useIsolatedTaskDirectory ? { workspaceStrategy: { type: "project_primary" } } : {}),
- };
- const configSnapshot = buildExecutionWorkspaceConfigSnapshot(
- mergedConfig,
- selectedEnvironmentId,
- );
- const executionRunConfig =
- stripWorkspaceRuntimeFromExecutionRunConfig(mergedConfig);
- const runScopedMentionedSkillKeys =
- await resolveRunScopedMentionedSkillKeys({
- db,
- companyId: agent.companyId,
- issueId,
- commentIds: extractWakeCommentIds(context),
- });
- const runScopedSkillKeys =
- acceptedPlanContinuationWake &&
- !acceptedPlanWakeRoutingDecision?.suppressAcceptedContinuation
- ? [...runScopedMentionedSkillKeys, ACCEPTED_PLAN_CONVERSION_SKILL_KEY]
- : runScopedMentionedSkillKeys;
- const githubSelection = await resolveManagedGitHubIdentitySelection(
- db,
- agent.companyId,
- {
- agentId: agent.id,
- responsibleUserId,
- allowStandingDelegation: false,
- },
- );
- const useHostGitHub =
- !githubSelection.configured &&
- trustPreset.kind === "standard" &&
- ["local", "ssh"].includes(
- selectedEnvironmentForConfig?.driver ?? "local",
- );
-
- const { resolvedConfig, configuredTaskEnvironment, secretKeys, secretManifest } =
- await resolveExecutionRunAdapterConfig({
- managedAiCredentials: Boolean(aiBinding),
- managedGitHubCredentials: !useHostGitHub,
- companyId: agent.companyId,
- agentId: agent.id,
- adapterType: agent.adapterType,
- issueId,
- heartbeatRunId: run.id,
- environmentId: selectedEnvironmentForConfig?.id ?? null,
- environmentEnv: aiBinding ? stripAiAuthBindings(selectedEnvironmentForConfig?.envVars) : selectedEnvironmentForConfig?.envVars ?? null,
- environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
- projectId: projectContext?.id ?? null,
- routineId: routineEnvContext.routineId,
- responsibleUserId,
- executionRunConfig: aiBinding ? { ...executionRunConfig, env: stripAiAuthBindings(executionRunConfig.env) } : executionRunConfig,
- projectEnv: aiBinding ? stripAiAuthBindings(projectContext?.env) : projectContext?.env ?? null,
- routineEnv: aiBinding ? stripAiAuthBindings(routineEnvContext.env) : routineEnvContext.env,
- secretsSvc,
- trustPreset,
- });
- readFailureReportSecrets = () => collectRunFailureSecretValues(resolvedConfig.env, secretKeys);
- if (aiBinding) {
- try {
- managedAiRuntime = await prepareManagedAiRuntime(db, { companyId: agent.companyId, agentId: agent.id, responsibleUserId, adapterType: agent.adapterType, binding: aiBinding, config: resolvedConfig });
- } catch (error) {
- // Only fresh executions can receive a pre-provider wait receipt. A
- // persisted native input may already have provider effects to recover.
- if (isAiConnectionBusy(error) && !persistedNativeExecutionInput) {
- // Use the authority recorded by the locked admission gate, never
- // the issue's mutable assignee observed during runtime preparation.
- const authorizedNonAssigneeWake =
- parseObject(run.runnerProfileJson).aiConnectionNonAssigneeCommentWake === true ||
- (run.scheduledRetryReason === AI_CONNECTION_BUSY_RETRY_REASON &&
- isNonAssigneeWorkspaceBusyRetry(run.scheduledRetryReason, parseObject(run.contextSnapshot)));
- await finalizeAiConnectionBusyDeferral(run, error, !authorizedNonAssigneeWake);
- return;
- }
- if (responsibleUserId && issueId) {
- await connectionIntentService(db).request({ sub: agent.id, company_id: agent.companyId, run_id: run.id, responsible_user_id: responsibleUserId }, aiBinding.provider, { purpose: "ai" }).catch(() => {
- logger.warn({ runId: run.id, agentId: agent.id }, "Could not attach AI connection request; runtime configuration action remains available");
- });
- }
- throw new ConfigurationIncompleteFailure(error instanceof Error ? error.message : "Configure this agent’s AI connection", {
- configurationIncomplete: { reason: "ai_connection_unavailable", companyId: agent.companyId, agentId: agent.id, responsibleUserId,
- ...(!persistedNativeExecutionInput && readAiConnectionConfigurationFailure(error)
- ? { selectionFailure: readAiConnectionConfigurationFailure(error) } : {}),
- ...(readAiCredentialAccessFailure(error)
- ? { credentialAccess: readAiCredentialAccessFailure(error) } : {}),
- provider: aiBinding.provider, method: aiBinding.method, actionUrl: `/agents/${agent.id}/runtime`,
- fingerprint: `ai:${agent.id}:${responsibleUserId}:${JSON.stringify(aiBinding)}` },
- });
- }
- const savedAiAccount = parseObject(run.contextSnapshot?.aiConnection);
- if (persistedNativeExecutionInput && !managedAiSessionIdentityCompatible(
- savedAiAccount.sessionIdentity ?? savedAiAccount.identity,
- managedAiRuntime.sessionIdentity,
- managedAiRuntime.identity,
- )) {
- throw new ConfigurationIncompleteFailure("The AI account changed while this native run was suspended. Start a new execution.", { configurationIncomplete: { reason: "ai_connection_changed", actionUrl: `/agents/${agent.id}/runtime` } });
- }
- Object.assign(resolvedConfig, managedAiRuntime.config);
- for (const key of AI_AUTH_ENV_KEYS) secretKeys.add(key);
- context.aiConnection = { ...managedAiRuntime.attribution, accountName: managedAiRuntime.accountName, identity: managedAiRuntime.identity, sessionIdentity: managedAiRuntime.sessionIdentity };
- await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiConnection: context.aiConnection, ...(context.aiRouterTaskKey ? { aiRouterTaskKey: context.aiRouterTaskKey } : {}), ...(context.aiRouterSelection ? { aiRouterSelection: context.aiRouterSelection } : {}) })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
- }
- if (secretManifest.length > 0) {
- context.paperclipSecrets = {
- manifest: secretManifest,
- };
- } else {
- delete context.paperclipSecrets;
- }
- const effectiveResolvedConfig = applyRunScopedMentionedSkillKeys(
- resolvedConfig,
- runScopedSkillKeys,
- );
- const runtimeSkillPreference = readPaperclipSkillSyncPreference(
- effectiveResolvedConfig,
- );
- const nativeRunnerPreparationSpans: NativeRunHistoricalSpan[] = [];
- const skillsPrepareStartedAtMs = Date.now();
- const runtimeSkillEntries = await (async () => {
- try {
- return await companySkills.listRuntimeSkillEntries(agent.companyId, {
- versionSelections: skillVersionSelectionMap(
- runtimeSkillPreference.desiredSkillEntries,
- {
- versionPinsEnabled:
- resolvedInstanceSettings.experimental.enableBetaSkills ===
- true,
- },
- ),
- });
- } catch (error) {
- if (agent.adapterType === "paperclip_runner") {
- await recordFailedSkillPreparation({
- runId: run.id,
- startedAtMs: skillsPrepareStartedAtMs,
- onEvent: async (event) => {
- await appendRunEvent(run, event);
- },
- });
- }
- throw error;
- }
- })();
- nativeRunnerPreparationSpans.push({
- name: "skills.prepare",
- parentName: "task.prepare",
- startedAtMs: skillsPrepareStartedAtMs,
- endedAtMs: Date.now(),
- });
- const connectorAssignments = await resolveConnectorAssignments(db, { companyId: agent.companyId, agentId: agent.id, runId: run.id, issueId: typeof context.issueId === "string" ? context.issueId : undefined });
- const connectorSkillConfig = await applyConnectorSkills(effectiveResolvedConfig, runtimeSkillEntries, connectorAssignments);
- // Both CLI adapters and native context materialization use the same resolved set.
- runtimeSkillEntries.splice(0, runtimeSkillEntries.length, ...connectorSkillConfig.paperclipRuntimeSkills);
- const connectorDelivery = await prepareConnectorSkillDelivery(connectorSkillConfig, agent.adapterType);
- // Always replace this runtime-only field; caller wake data cannot supply skills.
- context.paperclipWake = { ...parseObject(context.paperclipWake), connectorSkillInstructions: connectorDelivery.instructions };
- let runtimeConfig = await prepareConnectionInstructionDelivery({
- resolve: () => resolveAssignedConnectionInstructionsForRun(db, { companyId: agent.companyId, agentId: agent.id, runId: run.id }),
- context, config: connectorDelivery.config, native: agent.adapterType === "paperclip_runner",
+ const executionConfiguration = await prepareHeartbeatExecutionConfiguration(db, {
+ run, agent,
+ task: { issueId, context, responsibleUserId, acceptedPlanContinuationWake, acceptedPlanWakeRoutingDecision, projectContext, routineEnvContext },
+ config: { config, issueAssigneeOverrides, requestedAiBinding, aiBinding },
+ policy: { trustPreset, projectExecutionWorkspacePolicy, issueExecutionWorkspaceSettings, requestedExecutionWorkspaceMode, useIsolatedTaskDirectory },
+ environment: { selectedEnvironmentId, selectedEnvironmentForConfig, resolvedInstanceSettings, persistedNativeExecutionInput },
+ services: { secretsSvc, companySkills, appendRunEvent, finalizeAiConnectionBusyDeferral },
+ onFailureSecretsResolved: (readSecrets) => { readFailureReportSecrets = readSecrets; },
+ onManagedAiRuntimeAcquired: (runtime) => { managedAiRuntime = runtime; },
+ onIdentityRedactorPrepared: (redactor) => { identityRedactor = redactor; },
});
- const agentIdentity = supportsManagedAgentIdentity(agent.adapterType, agent.adapterConfig, run.runtimeMode === "native" ? run.driverKind : undefined)
- ? await agentIdentityService(db).ensureAgentIdentity(agent.companyId, agent.id)
- : undefined;
- identityRedactor = createAgentIdentityRedactor(agentIdentity?.privateKeyPem);
- if (agentIdentity) secretKeys.add("PAPERCLIP_AGENT_PRIVATE_KEY");
+ if (!executionConfiguration.prepared) return;
+ const {
+ mergedConfig, configSnapshot, runScopedMentionedSkillKeys, githubSelection, useHostGitHub,
+ resolvedConfig, configuredTaskEnvironment, secretKeys, secretManifest,
+ runtimeSkillEntries, nativeRunnerPreparationSpans, agentIdentity,
+ } = executionConfiguration;
+ let { runtimeConfig } = executionConfiguration;
const resolvedFailureSecrets = readFailureReportSecrets();
readFailureReportSecrets = () => [
...resolvedFailureSecrets,
diff --git a/server/src/services/heartbeat/execution-configuration.ts b/server/src/services/heartbeat/execution-configuration.ts
new file mode 100644
index 0000000000..859371de9a
--- /dev/null
+++ b/server/src/services/heartbeat/execution-configuration.ts
@@ -0,0 +1,269 @@
+import { eq, sql } from "drizzle-orm";
+import { heartbeatRuns, type Db, type agents, type projects } from "@paperclipai/db";
+import type { AiConnectionBinding, AiRuntimeConnectionBinding } from "@paperclipai/shared";
+import { readPaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
+import { parseObject } from "../../adapters/utils.js";
+import { logger } from "../../middleware/logger.js";
+import { AI_CONNECTION_BUSY_RETRY_REASON, extractWakeCommentIds, isNonAssigneeWorkspaceBusyRetry } from "../../modules/run-dispatch/index.js";
+import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
+import { agentIdentityService, supportsManagedAgentIdentity } from "../agent-identity.js";
+import { readAiConnectionConfigurationFailure, readAiCredentialAccessFailure } from "../ai-connection-configuration-failure.js";
+import { AI_AUTH_ENV_KEYS, isAiConnectionBusy, prepareManagedAiRuntime, stripAiAuthBindings } from "../ai-connection-runtime.js";
+import { managedAiSessionIdentityCompatible } from "../ai-connection-session.js";
+import type { companySkillService } from "../company-skills.js";
+import { connectionIntentService } from "../connection-intents.js";
+import { prepareConnectionInstructionDelivery } from "../connection-instructions.js";
+import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../connector-runtime.js";
+import { buildExecutionWorkspaceAdapterConfig } from "../execution-workspace-policy.js";
+import { resolveManagedGitHubIdentitySelection } from "../git-credentials.js";
+import { resolveAssignedConnectionInstructionsForRun } from "../native-runtime/assigned-mcp-tools.js";
+import { recordFailedSkillPreparation, type NativeRunHistoricalSpan } from "../native-runtime/native-run-trace.js";
+import { collectRunFailureSecretValues } from "../run-failure-diagnostics.js";
+import { skillVersionSelectionMap } from "../runtime-skill-selections.js";
+import type { selectHeartbeatEnvironment } from "./environment-selection.js";
+import type { createHeartbeatRetries } from "./retries.js";
+import type { createHeartbeatLifecycle } from "./run-lifecycle.js";
+import {
+ ConfigurationIncompleteFailure, applyRunScopedMentionedSkillKeys, resolveExecutionRunAdapterConfig,
+ resolveRunScopedMentionedSkillKeys, type createHeartbeatRunPreparation, type resolveAcceptedPlanWakeRoutingDecision,
+} from "./run-preparation.js";
+import { buildExecutionWorkspaceConfigSnapshot, stripWorkspaceRuntimeFromExecutionRunConfig } from "./workspaces.js";
+import type { HeartbeatWorkspacePreparationInput } from "./workspace-preparation.js";
+
+const ACCEPTED_PLAN_CONVERSION_SKILL_KEY =
+ "paperclipai/paperclip/paperclip-converting-plans-to-tasks";
+
+type ManagedAiRuntime = Awaited<ReturnType<typeof prepareManagedAiRuntime>>;
+type EnvironmentSelection = Awaited<ReturnType<typeof selectHeartbeatEnvironment>>;
+
+export interface HeartbeatExecutionConfigurationInput {
+ run: typeof heartbeatRuns.$inferSelect;
+ agent: typeof agents.$inferSelect;
+ task: {
+ issueId: string | null;
+ context: Record<string, unknown>;
+ responsibleUserId: string | null;
+ acceptedPlanContinuationWake: boolean;
+ acceptedPlanWakeRoutingDecision: Awaited<ReturnType<typeof resolveAcceptedPlanWakeRoutingDecision>> | null;
+ projectContext: Pick<typeof projects.$inferSelect, "id" | "env"> | null;
+ routineEnvContext: Awaited<ReturnType<ReturnType<typeof createHeartbeatRunPreparation>["getRoutineEnvForExecutionIssue"]>>;
+ };
+ config: {
+ config: Record<string, unknown>;
+ issueAssigneeOverrides: { adapterConfig: Record<string, unknown> | null; useProjectWorkspace: boolean | null } | null;
+ requestedAiBinding: AiRuntimeConnectionBinding | undefined;
+ aiBinding: AiConnectionBinding | undefined;
+ };
+ policy: Pick<HeartbeatWorkspacePreparationInput["policy"],
+ "trustPreset" | "projectExecutionWorkspacePolicy" | "issueExecutionWorkspaceSettings" | "requestedExecutionWorkspaceMode" | "useIsolatedTaskDirectory">;
+ environment: Pick<EnvironmentSelection,
+ "selectedEnvironmentId" | "selectedEnvironmentForConfig" | "resolvedInstanceSettings" | "persistedNativeExecutionInput">;
+ services: {
+ secretsSvc: Parameters<typeof resolveExecutionRunAdapterConfig>[0]["secretsSvc"];
+ companySkills: Pick<ReturnType<typeof companySkillService>, "listRuntimeSkillEntries">;
+ appendRunEvent: ReturnType<typeof createHeartbeatLifecycle>["appendRunEvent"];
+ finalizeAiConnectionBusyDeferral: ReturnType<typeof createHeartbeatRetries>["finalizeAiConnectionBusyDeferral"];
+ };
+ // The executor must observe these before a later preparation step can throw.
+ onFailureSecretsResolved: (readSecrets: () => string[]) => void;
+ onManagedAiRuntimeAcquired: (runtime: ManagedAiRuntime) => void;
+ onIdentityRedactorPrepared: (redactor: ReturnType<typeof createAgentIdentityRedactor>) => void;
+}
+
+/** Assembles effective run configuration; the executor retains cleanup ownership. */
+export async function prepareHeartbeatExecutionConfiguration(db: Db, input: HeartbeatExecutionConfigurationInput) {
+ const { run, agent, onFailureSecretsResolved, onManagedAiRuntimeAcquired, onIdentityRedactorPrepared } = input;
+ const { issueId, context, responsibleUserId, acceptedPlanContinuationWake, acceptedPlanWakeRoutingDecision, projectContext, routineEnvContext } = input.task;
+ const { config, issueAssigneeOverrides, requestedAiBinding, aiBinding } = input.config;
+ const { trustPreset, projectExecutionWorkspacePolicy, issueExecutionWorkspaceSettings, requestedExecutionWorkspaceMode, useIsolatedTaskDirectory } = input.policy;
+ const { selectedEnvironmentId, selectedEnvironmentForConfig, resolvedInstanceSettings, persistedNativeExecutionInput } = input.environment;
+ const { secretsSvc, companySkills, appendRunEvent, finalizeAiConnectionBusyDeferral } = input.services;
+ let managedAiRuntime: ManagedAiRuntime | undefined;
+ const workspaceManagedConfig = buildExecutionWorkspaceAdapterConfig({
+ agentConfig: config,
+ projectPolicy: projectExecutionWorkspacePolicy,
+ issueSettings: issueExecutionWorkspaceSettings,
+ mode: requestedExecutionWorkspaceMode,
+ legacyUseProjectWorkspace:
+ issueAssigneeOverrides?.useProjectWorkspace ?? null,
+ });
+ const mergedConfig = {
+ ...workspaceManagedConfig,
+ ...Object.fromEntries(Object.entries(issueAssigneeOverrides?.adapterConfig ?? {}).filter(([key]) => requestedAiBinding?.mode !== "router" || !["provider", "acpxAgent", "model", "modelReasoningEffort", "reasoningEffort", "effort", "variant"].includes(key))),
+ ...(requestedAiBinding?.mode === "router" ? parseObject(parseObject(context.aiRouterSelection).runtimeConfig) : {}),
+ // The base below is already task-owned. Keep directory transport while
+ // preserving isolated mode and the mandatory sandbox preflight.
+ ...(useIsolatedTaskDirectory ? { workspaceStrategy: { type: "project_primary" } } : {}),
+ };
+ const configSnapshot = buildExecutionWorkspaceConfigSnapshot(
+ mergedConfig,
+ selectedEnvironmentId,
+ );
+ const executionRunConfig =
+ stripWorkspaceRuntimeFromExecutionRunConfig(mergedConfig);
+ const runScopedMentionedSkillKeys =
+ await resolveRunScopedMentionedSkillKeys({
+ db,
+ companyId: agent.companyId,
+ issueId,
+ commentIds: extractWakeCommentIds(context),
+ });
+ const runScopedSkillKeys =
+ acceptedPlanContinuationWake &&
+ !acceptedPlanWakeRoutingDecision?.suppressAcceptedContinuation
+ ? [...runScopedMentionedSkillKeys, ACCEPTED_PLAN_CONVERSION_SKILL_KEY]
+ : runScopedMentionedSkillKeys;
+ const githubSelection = await resolveManagedGitHubIdentitySelection(
+ db,
+ agent.companyId,
+ {
+ agentId: agent.id,
+ responsibleUserId,
+ allowStandingDelegation: false,
+ },
+ );
+ const useHostGitHub =
+ !githubSelection.configured &&
+ trustPreset.kind === "standard" &&
+ ["local", "ssh"].includes(
+ selectedEnvironmentForConfig?.driver ?? "local",
+ );
+
+ const { resolvedConfig, configuredTaskEnvironment, secretKeys, secretManifest } =
+ await resolveExecutionRunAdapterConfig({
+ managedAiCredentials: Boolean(aiBinding),
+ managedGitHubCredentials: !useHostGitHub,
+ companyId: agent.companyId,
+ agentId: agent.id,
+ adapterType: agent.adapterType,
+ issueId,
+ heartbeatRunId: run.id,
+ environmentId: selectedEnvironmentForConfig?.id ?? null,
+ environmentEnv: aiBinding ? stripAiAuthBindings(selectedEnvironmentForConfig?.envVars) : selectedEnvironmentForConfig?.envVars ?? null,
+ environmentDriver: selectedEnvironmentForConfig?.driver ?? null,
+ projectId: projectContext?.id ?? null,
+ routineId: routineEnvContext.routineId,
+ responsibleUserId,
+ executionRunConfig: aiBinding ? { ...executionRunConfig, env: stripAiAuthBindings(executionRunConfig.env) } : executionRunConfig,
+ projectEnv: aiBinding ? stripAiAuthBindings(projectContext?.env) : projectContext?.env ?? null,
+ routineEnv: aiBinding ? stripAiAuthBindings(routineEnvContext.env) : routineEnvContext.env,
+ secretsSvc,
+ trustPreset,
+ });
+ onFailureSecretsResolved(() => collectRunFailureSecretValues(resolvedConfig.env, secretKeys));
+ if (aiBinding) {
+ try {
+ managedAiRuntime = await prepareManagedAiRuntime(db, { companyId: agent.companyId, agentId: agent.id, responsibleUserId, adapterType: agent.adapterType, binding: aiBinding, config: resolvedConfig });
+ onManagedAiRuntimeAcquired(managedAiRuntime);
+ } catch (error) {
+ // Only fresh executions can receive a pre-provider wait receipt. A
+ // persisted native input may already have provider effects to recover.
+ if (isAiConnectionBusy(error) && !persistedNativeExecutionInput) {
+ // Use the authority recorded by the locked admission gate, never
+ // the issue's mutable assignee observed during runtime preparation.
+ const authorizedNonAssigneeWake =
+ parseObject(run.runnerProfileJson).aiConnectionNonAssigneeCommentWake === true ||
+ (run.scheduledRetryReason === AI_CONNECTION_BUSY_RETRY_REASON &&
+ isNonAssigneeWorkspaceBusyRetry(run.scheduledRetryReason, parseObject(run.contextSnapshot)));
+ await finalizeAiConnectionBusyDeferral(run, error, !authorizedNonAssigneeWake);
+ return { prepared: false as const };
+ }
+ if (responsibleUserId && issueId) {
+ await connectionIntentService(db).request({ sub: agent.id, company_id: agent.companyId, run_id: run.id, responsible_user_id: responsibleUserId }, aiBinding.provider, { purpose: "ai" }).catch(() => {
+ logger.warn({ runId: run.id, agentId: agent.id }, "Could not attach AI connection request; runtime configuration action remains available");
+ });
+ }
+ throw new ConfigurationIncompleteFailure(error instanceof Error ? error.message : "Configure this agent’s AI connection", {
+ configurationIncomplete: { reason: "ai_connection_unavailable", companyId: agent.companyId, agentId: agent.id, responsibleUserId,
+ ...(!persistedNativeExecutionInput && readAiConnectionConfigurationFailure(error)
+ ? { selectionFailure: readAiConnectionConfigurationFailure(error) } : {}),
+ ...(readAiCredentialAccessFailure(error)
+ ? { credentialAccess: readAiCredentialAccessFailure(error) } : {}),
+ provider: aiBinding.provider, method: aiBinding.method, actionUrl: `/agents/${agent.id}/runtime`,
+ fingerprint: `ai:${agent.id}:${responsibleUserId}:${JSON.stringify(aiBinding)}` },
+ });
+ }
+ const savedAiAccount = parseObject(run.contextSnapshot?.aiConnection);
+ if (persistedNativeExecutionInput && !managedAiSessionIdentityCompatible(
+ savedAiAccount.sessionIdentity ?? savedAiAccount.identity,
+ managedAiRuntime.sessionIdentity,
+ managedAiRuntime.identity,
+ )) {
+ throw new ConfigurationIncompleteFailure("The AI account changed while this native run was suspended. Start a new execution.", { configurationIncomplete: { reason: "ai_connection_changed", actionUrl: `/agents/${agent.id}/runtime` } });
+ }
+ Object.assign(resolvedConfig, managedAiRuntime.config);
+ for (const key of AI_AUTH_ENV_KEYS) secretKeys.add(key);
+ context.aiConnection = { ...managedAiRuntime.attribution, accountName: managedAiRuntime.accountName, identity: managedAiRuntime.identity, sessionIdentity: managedAiRuntime.sessionIdentity };
+ await db.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ aiConnection: context.aiConnection, ...(context.aiRouterTaskKey ? { aiRouterTaskKey: context.aiRouterTaskKey } : {}), ...(context.aiRouterSelection ? { aiRouterSelection: context.aiRouterSelection } : {}) })}::jsonb` }).where(eq(heartbeatRuns.id, run.id));
+ }
+ if (secretManifest.length > 0) {
+ context.paperclipSecrets = {
+ manifest: secretManifest,
+ };
+ } else {
+ delete context.paperclipSecrets;
+ }
+ const effectiveResolvedConfig = applyRunScopedMentionedSkillKeys(
+ resolvedConfig,
+ runScopedSkillKeys,
+ );
+ const runtimeSkillPreference = readPaperclipSkillSyncPreference(
+ effectiveResolvedConfig,
+ );
+ const nativeRunnerPreparationSpans: NativeRunHistoricalSpan[] = [];
+ const skillsPrepareStartedAtMs = Date.now();
+ const runtimeSkillEntries = await (async () => {
+ try {
+ return await companySkills.listRuntimeSkillEntries(agent.companyId, {
+ versionSelections: skillVersionSelectionMap(
+ runtimeSkillPreference.desiredSkillEntries,
+ {
+ versionPinsEnabled:
+ resolvedInstanceSettings.experimental.enableBetaSkills ===
+ true,
+ },
+ ),
+ });
+ } catch (error) {
+ if (agent.adapterType === "paperclip_runner") {
+ await recordFailedSkillPreparation({
+ runId: run.id,
+ startedAtMs: skillsPrepareStartedAtMs,
+ onEvent: async (event) => {
+ await appendRunEvent(run, event);
+ },
+ });
+ }
+ throw error;
+ }
+ })();
+ nativeRunnerPreparationSpans.push({
+ name: "skills.prepare",
+ parentName: "task.prepare",
+ startedAtMs: skillsPrepareStartedAtMs,
+ endedAtMs: Date.now(),
+ });
+ const connectorAssignments = await resolveConnectorAssignments(db, { companyId: agent.companyId, agentId: agent.id, runId: run.id, issueId: typeof context.issueId === "string" ? context.issueId : undefined });
+ const connectorSkillConfig = await applyConnectorSkills(effectiveResolvedConfig, runtimeSkillEntries, connectorAssignments);
+ // Both CLI adapters and native context materialization use the same resolved set.
+ runtimeSkillEntries.splice(0, runtimeSkillEntries.length, ...connectorSkillConfig.paperclipRuntimeSkills);
+ const connectorDelivery = await prepareConnectorSkillDelivery(connectorSkillConfig, agent.adapterType);
+ // Always replace this runtime-only field; caller wake data cannot supply skills.
+ context.paperclipWake = { ...parseObject(context.paperclipWake), connectorSkillInstructions: connectorDelivery.instructions };
+ let runtimeConfig = await prepareConnectionInstructionDelivery({
+ resolve: () => resolveAssignedConnectionInstructionsForRun(db, { companyId: agent.companyId, agentId: agent.id, runId: run.id }),
+ context, config: connectorDelivery.config, native: agent.adapterType === "paperclip_runner",
+ });
+ const agentIdentity = supportsManagedAgentIdentity(agent.adapterType, agent.adapterConfig, run.runtimeMode === "native" ? run.driverKind : undefined)
+ ? await agentIdentityService(db).ensureAgentIdentity(agent.companyId, agent.id)
+ : undefined;
+ const identityRedactor = createAgentIdentityRedactor(agentIdentity?.privateKeyPem);
+ onIdentityRedactorPrepared(identityRedactor);
+ if (agentIdentity) secretKeys.add("PAPERCLIP_AGENT_PRIVATE_KEY");
+ return {
+ prepared: true as const,
+ mergedConfig, configSnapshot, runScopedMentionedSkillKeys, githubSelection, useHostGitHub,
+ resolvedConfig, configuredTaskEnvironment, secretKeys, secretManifest,
+ runtimeSkillEntries, nativeRunnerPreparationSpans, runtimeConfig, agentIdentity,
+ };
+}