mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 02:30:43 +01:00
refactor(heartbeat): extract execution configuration (#15973)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Heartbeat turns task, agent, environment, and account settings into an executable run. > - The executor still assembles scoped credentials and skill configuration inline between environment selection and session preparation. > - That phase has a clear input/output boundary, but credential acquisition must remain visible to cleanup even when later setup fails. > - This pull request extracts configuration assembly and immediately notifies the executor of acquired resources and redaction state. > - The executor retains admission, dispatch, and cleanup, with the same statement ordering and explicit busy-account deferral. ## Linked Issues or Issue Description **What existing behavior does this improve?** Maintenance of heartbeat execution. This PR follows #15969 and #15966, both now merged. The branch is rebased onto `master`; `git range-diff` confirms that the extraction patch is unchanged. **Current behavior** `heartbeat.ts` has 4,561 lines and 188,950 bytes. Configuration assembly mixes workspace overrides, secrets, managed AI preparation, and skill delivery into the executor. **Proposed behavior** `execution-configuration.ts` owns this preparation phase in 269 lines and 16,204 bytes. The executor calls it between environment and session preparation and retains immediate cleanup ownership. `heartbeat.ts` becomes 4,372 lines and 178,459 bytes. **Reason and benefit** The execution path exposes another named phase, with tests that exercise its effective configuration, resource lifetime, failure diagnostics, and busy-account result through public heartbeat dispatch. Related work: #11827 changes pre-dispatch secret refresh and #15355 changes GitHub delegation; this extraction preserves current policies. **Breaking changes** None intended. Public exports remain available, and the original helpers keep their modules. ## What Changed - Move configuration merging, scoped secret resolution, managed AI acquisition, runtime skills, connector instructions, and managed identity preparation into one typed module. - Notify the executor immediately when failure-redaction values, managed credentials, and identity redaction become available. Returning resources only after all preparation succeeds would lose cleanup on partial failure. - Preserve the live failure-secret getter for later runtime environment changes. Return an explicit deferred result for busy accounts. - Add four real-database characterization tests through `heartbeat.wakeup`, using actual credential files and cleanup with a fixture adapter. - Update the developer module map. ## Verification - Before extraction: all 45 tests pass across the new public-path tests and existing project-environment tests. - After extraction: 47 tests pass across execution configuration, project environment, and runtime skills. No skips. - Two additional real-process managed identity tests pass; nine unrelated cases are deliberately filtered out. - `pnpm -r typecheck` and `pnpm build` pass. - Normalized syntax comparison confirms the moved body and reconstructed executor match after accounting for immediate ownership callbacks and the explicit prepared/deferred result. - Isolated browser acceptance: 2/2 pass (3.9 minutes). A real process worker completes after Git recovery, with persisted stdout and matching final output byte counts. Persistent failures stop after three attempts. Both outcomes survive reload. The disposable server was shut down after verification. - All eleven new public-path characterization cases across the three-PR stack pass together on the final commit. - All 140 named public exports from the batch baseline remain available. - CI initially failed the legacy-continuation message browser case: periodic recovery escalated the issue, then queue admission cancelled the run with `execution_reconciliation_required` before configuration preparation. The unchanged predecessor shard passes, and the exact case passes locally (5 seconds in the browser). The original failing case passed on its single rerun (8.2 seconds), but GitHub then shut down the runner during a different test (`The runner has received a shutdown signal`). The separate infrastructure restart completed: 24 browser cases passed, with two existing optional cases skipped. Assertions and timeouts are unchanged. - Greptile: 5/5 on `27ab7e3df64c157ba1f00c5757db812ff7a4e5aa`, with no actionable findings. Hosted full-suite CI passes on this exact commit: all 54 check runs and the additional commit status are successful. - Merge preparation: all eleven characterization tests pass after rebasing onto `master`. Fresh full CI passes for `1758673f87eaa76a8b2c520eac4b631ada5d9ba1`: 55 successful checks and two optional Storybook skips, including all eight browser shards, typecheck, tests, and build. Greptile is 5/5 on this exact commit with zero review threads. All heartbeat source, tests, documentation, and browser assertions are identical to the previously reviewed final stack. ## Risks - A failure after AI acquisition must still remove the disposable credential home. The new public-path failure test proves actual filesystem cleanup and diagnostic redaction before the external reporting sink. - The baseline exposed an existing gap: arbitrary exception text in the local `run.error` field can contain a credential even though the failure reporter redacts it. This behavior is unchanged and merits a separate fix; the test does not claim the local error field is sanitized. - Account-busy deferral must return without dispatch while retaining its scheduled retry. The new test checks the durable run states. - Browser acceptance uses a real process fixture and disposable data, without live provider calls. ## Model Used OpenAI Codex, based on GPT-6, assisted with reasoning, code edits, tool execution, and verification. The exact deployment model ID and context-window size are not exposed in this session. ## 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>
This commit is contained in:
1 parent
37913e4907
commit
914b70572c
4 files changed
+455
-207
No files matched your search
@@ -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
|
||||
|
||||
@@ -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" })]);
|
||||
});
|
||||
});
|
||||
@@ -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 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 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 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,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user