import { and, desc, eq, inArray, isNotNull } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import { parseObject } from "../adapters/utils.js"; import { resolveProviderApiPlacement } from "./native-runtime/provider-api-placement.js"; import { hasNativeLocalProcessStop } from "./native-local-process-stop.js"; import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { validatePrpEvent } from "../vendor/paperclip-runner/index.js"; import { nativeSha256 } from "./native-runtime/canonical.js"; import { isConfirmedCursorCloudTerminalObservation } from "./native-runtime/cursor-cloud-runtime.js"; export function hasAcknowledgedNativeRunStopRequest(run: { id: string; companyId: string; status: string; nativeIssueId: string | null; resultJson: Record | null; }): boolean { const result = run.resultJson; const intent = result?.nativeCancellation as Record | undefined; return intent?.schema === "paperclip.native-cancellation.v1" && intent.runId === run.id && intent.companyId === run.companyId && intent.issueId === run.nativeIssueId && intent.scope === "run" && intent.reasonCode === "cancellation_run_only" && intent.dispatchState === "acknowledged" && typeof intent.dispatched === "boolean" && typeof intent.intentAuditId === "string" && Boolean(intent.intentAuditId) && typeof intent.acknowledgementAuditId === "string" && Boolean(intent.acknowledgementAuditId); } export function hasAcknowledgedNativeRunStopReceipt(run: Parameters[0]): boolean { return hasAcknowledgedNativeRunStopRequest(run) && (run.resultJson?.nativeCancellation as Record).dispatched === true; } export function hasAcknowledgedNativeStopIntent(run: Parameters[0]): boolean { return run.resultJson?.cancelledByActorType === "user" && typeof run.resultJson.cancelledByUserId === "string" && Boolean(run.resultJson.cancelledByUserId) && hasAcknowledgedNativeRunStopReceipt(run); } /** An intentional handoff retains task state and deferred work for its successor. */ export function hasAcknowledgedNativeReassignmentStopIntent(run: Parameters[0]): boolean { return run.resultJson?.reassignmentStopRequested === true && hasAcknowledgedNativeRunStopReceipt(run); } export function isAcknowledgedNativeReassignmentStop(run: Parameters[0]): boolean { return run.status === "cancelled" && hasAcknowledgedNativeReassignmentStopIntent(run); } export function isAcknowledgedNativeStop(run: Parameters[0]): boolean { return run.status === "cancelled" && hasAcknowledgedNativeStopIntent(run); } /** API-owned execution has no Computer lease. Its provider terminal and retired * local controller must both be recorded before publishing shared Stop proof. */ export async function acknowledgedNativeApiStopExecutionHasStopped(db: Db, run: Pick): Promise { if (run.runtimeMode !== "native" || run.driverKind !== "cursor_cloud_api" || !isAcknowledgedNativeStop(run) || run.processPid !== null || run.processGroupId !== null || !run.nativeIssueId || !run.nativeSessionId || !run.runnerInstanceId) return false; const intent = parseObject(run.resultJson?.nativeCancellation); const requestedAt = typeof intent.recordedAt === "string" ? Date.parse(intent.recordedAt) : NaN; if (!Number.isFinite(requestedAt) || !Array.isArray(intent.effects) || intent.effects.length !== 1 || intent.effects[0] !== "release_run_resources" || !String(intent.intentAuditId ?? "").trim() || !String(intent.acknowledgementAuditId ?? "").trim()) return false; const profile = parseObject(run.runnerProfileJson); const execution = parseObject(profile.nativeExecutionInput); const binding = parseObject(execution.binding), session = parseObject(execution.session); if (profile.executionPlacement === undefined || profile.backend !== "cursor_cloud_api" || binding.companyId !== run.companyId || binding.runId !== run.id || binding.issueId !== run.nativeIssueId || binding.agentId !== run.agentId || session.normalizedSessionId !== run.nativeSessionId || session.driverKind !== "cursor_cloud_api") return false; try { if (!resolveProviderApiPlacement({ run, agent: { adapterType: "process", adapterConfig: {} } })) return false; } catch { return false; } const [lease] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), )).limit(1); if (lease || !await hasNativeLocalProcessStop(db, run.companyId, run.id)) return false; const [terminal] = await db.select().from(heartbeatRunEvents).where(and( eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), isNotNull(heartbeatRunEvents.sourceEventId), inArray(heartbeatRunEvents.eventType, ["turn.started", "turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]), )).orderBy(desc(heartbeatRunEvents.seq)).limit(1); const validated = validatePrpEvent(parseObject(terminal?.payload).prpEvent); if (!terminal || !validated.ok || terminal.sourcePayloadSha256 !== nativeSha256(validated.event)) return false; const event = validated.event; return isConfirmedCursorCloudTerminalObservation({ eventType: terminal.eventType, payload: event.payload }) && terminal.agentId === run.agentId && event.schema === "paperclip.prp.event.v1" && [1, 2].includes(Number(event.schemaVersion)) && terminal.protocolSchemaVersion === event.schemaVersion && event.eventType === terminal.eventType && event.sourceKind === "runner" && event.runId === run.id && event.normalizedSessionId === run.nativeSessionId && event.sourceInstanceId === run.runnerInstanceId && terminal.sourceInstanceId === event.sourceInstanceId && terminal.sourceEventId === event.sourceEventId && terminal.sourceSeq === event.sourceSeq && Number.isSafeInteger(event.sourceSeq) && Number(event.sourceSeq) > 0 && typeof event.turnId === "string" && Boolean(event.turnId); } /** A Stop acknowledgement alone does not prove provider cleanup completed. */ export async function acknowledgedNativeStopExecutionHasStopped(db: Db, run: Pick) { if (!isAcknowledgedNativeStop(run)) return false; const leases = await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), )); // Provider PIDs are meaningful only on their own host. A recovered sandbox // queued for destroy keeps its verified stop; the destroy is only cleanup. if (leases.some(lease => lease.provider !== "local")) return leases.every(lease => hasRemoteTerminationReceipt(lease) || hasRecoveredCleanupStopReceipt(lease)); if (leases.some(lease => !lease.releasedAt || lease.cleanupStatus === "failed")) return false; if (!run.processPid && !run.processGroupId) return hasNativeLocalProcessStop(db, run.companyId, run.id); const absent = (pid: number) => { try { process.kill(pid, 0); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; } }; return (!run.processPid || absent(run.processPid)) && (!run.processGroupId || absent(-run.processGroupId)); }