The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(acpx): per-step round-trip + provider-latency attribution for sandbox startup (#10222)
Nicky Leach197718bc00b0
diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.tsindex 3b064cadb0..f08288b3d0 100644--- a/packages/adapter-utils/src/acpx-engine/execute.test.ts+++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts@@ -46,7 +46,18 @@ async function makeTempRoot() {}afterEach(async () => {- await Promise.all(tempRoots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));+ // A remote run stages a process-session bridge whose detached event writer can+ // still be flushing a trailing event file into `.../process-sessions/<id>/events`+ // when the run's own best-effort `client.remove(sessionDir)` (which production+ // catch-wraps) has already returned. Under CI load that trailing write can land+ // between this recursive delete's directory snapshot and its `rmdir`, surfacing as+ // `ENOTEMPTY`. `maxRetries`/`retryDelay` make the cleanup ride out that window the+ // same way production tolerates it, instead of failing the just-passed test.+ await Promise.all(+ tempRoots.splice(0).map((root) =>+ fs.rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }),+ ),+ );});async function pathExists(candidate: string): Promise<boolean> {@@ -80,7 +91,16 @@ function createLocalSandboxRunner(}) => void,) {let counter = 0;+ // Synthetic provider-duration accumulators so per-step payload assertions can+ // verify the `providerExecMs`/`providerGetMs` threading end-to-end (the real+ // sandbox runner sources these from the Daytona plugin's result metadata; this+ // double stands in for that with a fixed per-exec cost).+ let providerExecMs = 0;+ let providerGetMs = 0;return {+ execCount: () => counter,+ providerExecMs: () => providerExecMs,+ providerGetMs: () => providerGetMs,execute: async (input: {command: string;args?: string[];@@ -92,6 +112,8 @@ function createLocalSandboxRunner(onSpawn?: (meta: { pid: number; startedAt: string }) => Promise<void>;}) => {counter += 1;+ providerExecMs += 600;+ providerGetMs += 15;onExecute?.(input);const command = input.command === "bash" ? "/bin/bash" : input.command;return await runChildProcess(`acpx-sandbox-run-${counter}`, command, input.args ?? [], {@@ -2773,6 +2795,125 @@ describe("ACPX engine per-step startup timing (run.startup.step events)", () =>}});+ it("carries per-step roundTrips + provider durations sourced from the sandbox runner counter", async () => {+ const root = await makeTempRoot();+ const stateDir = path.join(root, "state");+ const localCwd = path.join(root, "worktree");+ const remoteCwd = path.join(root, "remote-workspace");+ await fs.mkdir(localCwd, { recursive: true });+ await fs.mkdir(remoteCwd, { recursive: true });+ const executionTarget = {+ kind: "remote",+ transport: "sandbox",+ providerKey: "fake-plugin",+ remoteCwd,+ runner: createLocalSandboxRunner(),+ };++ const { events } = await runExecutor(+ { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir, cwd: localCwd },+ { authToken: "real-run-jwt", executionTarget },+ );++ const steps = stepEvents(events);+ const seen = new Map(steps.map((event) => [String(event.payload?.step), event]));++ // Every timed boundary carries a numeric roundTrips (the runner exposes+ // execCount), even the ones that never exec.+ for (const event of steps) {+ expect(typeof event.payload?.roundTrips).toBe("number");+ }+ // workspace.resolve is host-only → zero host→sandbox execs.+ expect(seen.get("workspace.resolve")?.payload?.roundTrips).toBe(0);+ // stage.sync ships the workspace over the exec seam → at least one round-trip,+ // and the accumulated provider durations scale with it.+ const stageSync = seen.get("stage.sync");+ expect(stageSync?.payload?.roundTrips as number).toBeGreaterThan(0);+ expect(stageSync?.payload?.providerExecMs).toBe(+ (stageSync?.payload?.roundTrips as number) * 600,+ );+ expect(stageSync?.payload?.providerGetMs).toBe(+ (stageSync?.payload?.roundTrips as number) * 15,+ );+ // The external ACP client crosses no host exec seam.+ expect(seen.get("acp.handshake")?.payload?.roundTrips).toBe(0);+ });++ it("splits acp.handshake into createRuntimeMs and ensureSessionMs sub-phases", async () => {+ const root = await makeTempRoot();+ const stateDir = path.join(root, "state");+ const localCwd = path.join(root, "worktree");+ const remoteCwd = path.join(root, "remote-workspace");+ await fs.mkdir(localCwd, { recursive: true });+ await fs.mkdir(remoteCwd, { recursive: true });+ const executionTarget = {+ kind: "remote",+ transport: "sandbox",+ providerKey: "fake-plugin",+ remoteCwd,+ runner: createLocalSandboxRunner(),+ };++ const { events } = await runExecutor(+ { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir, cwd: localCwd },+ { authToken: "real-run-jwt", executionTarget },+ );++ const handshake = stepEvents(events).find((event) => event.payload?.step === "acp.handshake");+ expect(handshake).toBeTruthy();+ expect(typeof handshake!.payload?.createRuntimeMs).toBe("number");+ expect(handshake!.payload?.createRuntimeMs as number).toBeGreaterThanOrEqual(0);+ expect(typeof handshake!.payload?.ensureSessionMs).toBe("number");+ expect(handshake!.payload?.ensureSessionMs as number).toBeGreaterThanOrEqual(0);+ });++ it("emits no acp.handshake event when a warm-handle hit skips the handshake", async () => {+ const root = await makeTempRoot();+ const stateDir = path.join(root, "state");+ const warmHandles = new Map();+ const secondEvents: Array<{ eventType: string; payload?: Record<string, unknown> }> = [];+ const execute = createAcpxEngineExecutor({+ warmHandles,+ createRuntime: () => buildRuntime() as never,+ });+ const config = {+ agent: "custom",+ agentCommand: "node ./fake-acp.js",+ stateDir,+ mode: "persistent",+ warmHandleIdleMs: 60_000,+ };+ const first = await execute({+ runId: "run-warm-1",+ agent: { id: "agent-1", companyId: "company-1" },+ runtime: {},+ config,+ context: {},+ onLog: async () => {},+ onMeta: async () => {},+ onEvent: async () => {},+ } as never);+ // The second run reuses the warm handle, so the whole handshake block is+ // skipped — it must emit NO acp.handshake event (not a zero-duration one).+ await execute({+ runId: "run-warm-2",+ agent: { id: "agent-1", companyId: "company-1" },+ runtime: { sessionParams: (first as { sessionParams?: unknown }).sessionParams },+ config,+ context: {},+ onLog: async () => {},+ onMeta: async () => {},+ onEvent: async (event: { eventType: string; payload?: Record<string, unknown> }) => {+ secondEvents.push(event);+ },+ } as never);++ const handshakeEmitted = secondEvents.some(+ (event) => event.eventType === "run.startup.step" && event.payload?.step === "acp.handshake",+ );+ expect(handshakeEmitted).toBe(false);+ });+it("does not emit startup-step events on a local (non-sandbox) run except workspace.resolve", async () => {const root = await makeTempRoot();const localCwd = path.join(root, "worktree");diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.tsindex 00661dde9f..5c1ec5937e 100644--- a/packages/adapter-utils/src/acpx-engine/execute.ts+++ b/packages/adapter-utils/src/acpx-engine/execute.ts@@ -82,7 +82,8 @@ import {DEFAULT_ACP_ENGINE_TIMEOUT_SEC,DEFAULT_ACP_ENGINE_WARM_HANDLE_IDLE_MS,} from "./constants.js";-import { measureStartupStep } from "./startup-timing.js";+import { measureStartupStep, type StartupStepMeasureOptions } from "./startup-timing.js";+import type { CommandManagedRuntimeRunner } from "../command-managed-runtime.js";const defaultModuleDir = path.dirname(fileURLToPath(import.meta.url));const PAPERCLIP_MANAGED_CODEX_SKILLS_MANIFEST = ".paperclip-managed-skills.json";@@ -381,6 +382,12 @@ interface AcpxPreparedRuntime {paperclipClaudeSettings: PaperclipClaudeSettingsResult | null;mcpServers: NonNullable<AcpRuntimeOptions["mcpServers"]>;mcpIdentity: Array<{ name: string; url: string; connectionId: string }>;+ // Per-step round-trip / provider-duration readers sourced from the sandbox+ // runner's counters (Open Q1). Empty for local runs and the runner-less+ // fallback, where no host→sandbox exec seam exists. Threaded into the+ // `acp.handshake` `measureStartupStep` call in the executor (the other six+ // boundaries live inside `buildRuntime` and read it directly).+ stepMetrics: StartupStepMeasureOptions;}const defaultWarmHandles = new Map<string, RuntimeCacheEntry>();@@ -838,6 +845,11 @@ async function prepareCodexSkillRuntime(input: {// `onEvent`), so the codex skill prep behaves identically when unmeasured.onEvent?: AdapterExecutionContext["onEvent"];now?: () => number;+ // Round-trip / provider-duration readers for the nested `skills.reconcile`+ // boundary (Open Q1). Threaded from `buildRuntime` so the step reports the+ // same host→sandbox counters as its siblings (0 here — skill prep is+ // host-only — which is itself the answer to "does this step exec?").+ stepMetrics?: StartupStepMeasureOptions;}): Promise<{ identity: Record<string, unknown>; commandNotes: string[] }> {const now = input.now ?? (() => Date.now());const envConfig = parseObject(input.config.env);@@ -870,6 +882,7 @@ async function prepareCodexSkillRuntime(input: {selectedSkills,onLog: input.onLog,}),+ input.stepMetrics ?? {},);for (const entry of selectedSkills) {@@ -1216,6 +1229,22 @@ async function stageAcpRemoteRuntime(input: {});}+// Bind a startup-step round-trip/provider-duration reader set to a runner's+// cumulative counters (Open Q1). Only the sandbox runner instruments the exec+// seam, so a runner without `execCount` (SSH, or none) yields an empty option+// set and the affected steps omit the fields entirely. Reader closures are+// passed — not the runner — so `measureStartupStep` stays runner-agnostic.+function buildStartupStepMetrics(+ runner: CommandManagedRuntimeRunner | undefined,+): StartupStepMeasureOptions {+ if (!runner) return {};+ return {+ ...(runner.execCount ? { roundTrips: () => runner.execCount!() } : {}),+ ...(runner.providerExecMs ? { providerExecMs: () => runner.providerExecMs!() } : {}),+ ...(runner.providerGetMs ? { providerGetMs: () => runner.providerGetMs!() } : {}),+ };+}+async function buildRuntime(input: {ctx: AdapterExecutionContext;engine: AcpxEngineSettings;@@ -1252,6 +1281,17 @@ async function buildRuntime(input: {? remoteExecutionIdentity.remoteCwd: cwd;const executionTargetIsRemote = remoteExecutionIdentity !== null;+ // Round-trip / provider-duration readers for per-step attribution (Open Q1),+ // sourced from the sandbox runner's cumulative counters. `measureStartupStep`+ // reads each as a `() => number` closure (never the runner itself, Risk R1)+ // and emits the per-step delta. Empty when there is no runner (local runs,+ // the runner-less ACP→CLI fallback, or an SSH runner that does not+ // instrument the seam), so those steps simply omit the fields.+ const stepMetrics = buildStartupStepMetrics(+ executionTarget?.kind === "remote" && executionTarget.transport === "sandbox"+ ? executionTarget.runner+ : undefined,+ );const shapedWorkspaceEnv = shapePaperclipWorkspaceEnvForExecution({workspaceCwd: effectiveWorkspaceCwd,workspaceWorktreePath,@@ -1262,6 +1302,7 @@ async function buildRuntime(input: {// here on the awaited directory materialization.await measureStartupStep(input.ctx, nowMs, "workspace.resolve", () =>ensureAbsoluteDirectory(cwd, { createIfMissing: true }),+ stepMetrics,);const acpxAgent = normalizeAgent(config);@@ -1422,7 +1463,9 @@ async function buildRuntime(input: {onLog: input.ctx.onLog,onEvent: input.ctx.onEvent,now: nowMs,+ stepMetrics,}),+ stepMetrics,);skillsIdentity = preparedSkills.identity;skillCommandNotes.push(...preparedSkills.commandNotes);@@ -1675,7 +1718,7 @@ async function buildRuntime(input: {};}return { stagedRuntime: await stage([]), teardown: null, dispose: null };- });+ }, stepMetrics);const delta: Record<string, string> = {};for (const [key, value] of Object.entries(env)) {if (envBeforeStage[key] !== value) delta[key] = value;@@ -1715,6 +1758,7 @@ async function buildRuntime(input: {hostApiToken: env.PAPERCLIP_API_KEY,onLog: input.ctx.onLog,}),+ stepMetrics,);if (paperclipBridge) {Object.assign(env, paperclipBridge.env);@@ -1741,6 +1785,7 @@ async function buildRuntime(input: {timeoutSec,onLog: input.ctx.onLog,}),+ stepMetrics,): null;} catch (err) {@@ -1813,6 +1858,7 @@ async function buildRuntime(input: {paperclipClaudeSettings,mcpServers,mcpIdentity,+ stepMetrics,};}@@ -2594,7 +2640,22 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {? (chunk) => routeChildStderr(childStderrState, chunk): undefined,};- const runtime = cached?.runtime ?? createRuntime(runtimeOptions);+ // Open Q2: split the ~7s `acp.handshake` into the two in-repo-observable+ // sub-phases — the ACP runtime construction (`createRuntime`) vs the session+ // establishment envelope (`ensureSession`). The finer spawn/`initialize`/+ // `session/new` split lives inside external `acpx` and is gated on an+ // upstream lifecycle hook (not bundled here). `createRuntime` runs once and+ // only on a cold start; a warm-handle hit reuses `cached.runtime`, so+ // `createRuntimeMs` stays undefined and the split reports nothing for it.+ let createRuntimeMs: number | undefined;+ let runtime: AcpRuntime;+ if (cached?.runtime) {+ runtime = cached.runtime;+ } else {+ const createRuntimeStart = now();+ runtime = createRuntime(runtimeOptions);+ createRuntimeMs = now() - createRuntimeStart;+ }if (cached) clearWarmHandleTimer(cached);if (!canResume && asString(previousParams.runtimeSessionName, "")) {await ctx.onLog(@@ -2612,17 +2673,29 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {try {// Step 7 — acp.handshake: ACP session establishment (session/new or// resume). A throwing handshake still reports its duration before the- // resume-retry path below runs.- handle = await measureStartupStep(ctx, now, "acp.handshake", () =>- runtime.ensureSession({+ // resume-retry path below runs. `roundTrips` is expected to be 0 (the+ // ACP client is external, not the host exec seam); the payload also+ // carries the createRuntime/ensureSession sub-split (Open Q2).+ let ensureSessionMs: number | undefined;+ handle = await measureStartupStep(ctx, now, "acp.handshake", async () => {+ const ensureSessionStart = now();+ const established = await runtime.ensureSession({sessionKey: prepared.sessionKey,agent: prepared.acpxAgent,mode: prepared.mode,cwd: prepared.cwd,resumeSessionId,sessionOptions: { env: prepared.env },+ });+ ensureSessionMs = now() - ensureSessionStart;+ return established;+ }, {+ ...prepared.stepMetrics,+ extra: () => ({+ ...(createRuntimeMs !== undefined ? { createRuntimeMs } : {}),+ ...(ensureSessionMs !== undefined ? { ensureSessionMs } : {}),}),- );+ });} catch (err) {if (!resumeSessionId || !isResumeFailure(err)) throw err;clearSession = true;@@ -2631,15 +2704,27 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {"stdout",`[paperclip] ACPX resume session "${resumeSessionId}" is unavailable; retrying with a fresh session.\n`,);- handle = await measureStartupStep(ctx, now, "acp.handshake", () =>- runtime.ensureSession({+ // Fresh-session retry: the runtime was already constructed on the+ // first attempt (never re-created), so this event reports only its+ // own `ensureSessionMs` — no `createRuntimeMs`.+ let retryEnsureSessionMs: number | undefined;+ handle = await measureStartupStep(ctx, now, "acp.handshake", async () => {+ const ensureSessionStart = now();+ const established = await runtime.ensureSession({sessionKey: prepared.sessionKey,agent: prepared.acpxAgent,mode: prepared.mode,cwd: prepared.cwd,sessionOptions: { env: prepared.env },+ });+ retryEnsureSessionMs = now() - ensureSessionStart;+ return established;+ }, {+ ...prepared.stepMetrics,+ extra: () => ({+ ...(retryEnsureSessionMs !== undefined ? { ensureSessionMs: retryEnsureSessionMs } : {}),}),- );+ });}}} catch (err) {diff --git a/packages/adapter-utils/src/acpx-engine/startup-timing.test.ts b/packages/adapter-utils/src/acpx-engine/startup-timing.test.tsindex 6db874f730..70a51899a7 100644--- a/packages/adapter-utils/src/acpx-engine/startup-timing.test.ts+++ b/packages/adapter-utils/src/acpx-engine/startup-timing.test.ts@@ -28,6 +28,86 @@ describe("measureStartupStep", () => {expect(events[0]!.message).toBe("startup step: stage.sync (150ms)");});+ it("includes the roundTrips delta in the payload when a round-trip reader is supplied", async () => {+ let t = 0;+ const now = () => t;+ // Cumulative host→sandbox exec counter; the step performs 3 execs.+ let execCount = 5;+ const events: AdapterRuntimeEvent[] = [];+ const onEvent = vi.fn(async (event: AdapterRuntimeEvent) => {+ events.push(event);+ });++ await measureStartupStep({ onEvent }, now, "stage.sync", async () => {+ t = 90;+ execCount += 3;+ return "ok";+ }, { roundTrips: () => execCount });++ expect(events[0]!.payload).toMatchObject({+ step: "stage.sync",+ durationMs: 90,+ roundTrips: 3,+ });+ });++ it("reports roundTrips: 0 for a step that performs no execs (reader supplied)", async () => {+ const now = () => 0;+ const events: AdapterRuntimeEvent[] = [];+ const onEvent = vi.fn(async (event: AdapterRuntimeEvent) => {+ events.push(event);+ });++ await measureStartupStep({ onEvent }, now, "workspace.resolve", async () => "ok", {+ roundTrips: () => 7,+ });++ expect(events[0]!.payload).toMatchObject({ step: "workspace.resolve", roundTrips: 0 });+ });++ it("omits roundTrips from the payload when no reader is supplied", async () => {+ const now = () => 0;+ const events: AdapterRuntimeEvent[] = [];+ const onEvent = vi.fn(async (event: AdapterRuntimeEvent) => {+ events.push(event);+ });++ await measureStartupStep({ onEvent }, now, "workspace.resolve", async () => "ok");++ expect(events[0]!.payload).not.toHaveProperty("roundTrips");+ });++ it("accumulates provider exec/get durations and merges extra fields into the payload", async () => {+ let t = 0;+ const now = () => t;+ let execMs = 100;+ let getMs = 40;+ const events: AdapterRuntimeEvent[] = [];+ const onEvent = vi.fn(async (event: AdapterRuntimeEvent) => {+ events.push(event);+ });++ await measureStartupStep({ onEvent }, now, "acp.handshake", async () => {+ t = 7000;+ execMs += 600; // one provider executeCommand round-trip+ getMs += 15; // one client.get re-fetch+ return "handle";+ }, {+ providerExecMs: () => execMs,+ providerGetMs: () => getMs,+ extra: () => ({ createRuntimeMs: 12, ensureSessionMs: 6988 }),+ });++ expect(events[0]!.payload).toMatchObject({+ step: "acp.handshake",+ durationMs: 7000,+ providerExecMs: 600,+ providerGetMs: 15,+ createRuntimeMs: 12,+ ensureSessionMs: 6988,+ });+ });+it("returns the wrapped fn result unchanged", async () => {const now = () => 0;const onEvent = vi.fn(async () => {});diff --git a/packages/adapter-utils/src/acpx-engine/startup-timing.ts b/packages/adapter-utils/src/acpx-engine/startup-timing.tsindex 06e46f1313..7e3f55941d 100644--- a/packages/adapter-utils/src/acpx-engine/startup-timing.ts+++ b/packages/adapter-utils/src/acpx-engine/startup-timing.ts@@ -9,37 +9,83 @@ import type { AdapterExecutionContext, AdapterRuntimeEvent } from "../types.js";*/export const RUN_STARTUP_STEP_EVENT_TYPE = "run.startup.step";-function buildStepEvent(step: string, durationMs: number): AdapterRuntimeEvent {+/**+ * Optional per-step attribution attached to a `run.startup.step` event, all+ * additive to the free-form jsonb payload (no schema change). Each reader is a+ * plain `() => number` closure so the timing helper stays decoupled from the+ * runner/provider it reads (Risk R1): `measureStartupStep` snapshots the reader+ * before `fn` and again in `finally`, emitting the delta.+ *+ * - `roundTrips` — cumulative host→sandbox `runner.execute` count; the delta is+ * how many round-trips the step performed (Open Q1, host boundary).+ * - `providerExecMs` / `providerGetMs` — cumulative provider-reported wall-time+ * (ms) for the `executeCommand` REST call vs the `client.get` sandbox+ * re-fetch; the delta attributes the step's round-trip time to its parts+ * (Open Q1, finer provider attribution).+ * - `extra` — a reader (called once in `finally`, after `fn` settles) returning+ * any additional numeric fields to merge into the payload; used by+ * `acp.handshake` to carry its `createRuntimeMs` / `ensureSessionMs` sub-split+ * (Open Q2), which are measured by the caller rather than read from a counter.+ */+export interface StartupStepMeasureOptions {+ roundTrips?: () => number;+ providerExecMs?: () => number;+ providerGetMs?: () => number;+ extra?: () => Record<string, number>;+}++function buildStepEvent(payload: Record<string, unknown>): AdapterRuntimeEvent {+ const step = String(payload.step);+ const durationMs = payload.durationMs as number;return {eventType: RUN_STARTUP_STEP_EVENT_TYPE,stream: "system",level: "info",message: `startup step: ${step} (${durationMs}ms)`,- payload: { step, durationMs },+ payload,};}/*** Time `fn` with the injected `now` clock and emit exactly one- * `run.startup.step` event carrying `{ step, durationMs }`. The event fires in a- * `finally`, so a throwing step still reports its duration before the error is- * re-thrown. `now` is injected (never `Date.now()` here) so callers/tests stay- * deterministic, and `ctx.onEvent` is optional — a missing sink is a no-op that- * neither throws nor swallows `fn`'s return value or error.+ * `run.startup.step` event carrying `{ step, durationMs }` plus any counters+ * supplied via `options`. The event fires in a `finally`, so a throwing step+ * still reports its duration before the error is re-thrown. `now` is injected+ * (never `Date.now()` here) so callers/tests stay deterministic, and+ * `ctx.onEvent` is optional — a missing sink is a no-op that neither throws nor+ * swallows `fn`'s return value or error. A step skipped by a warm cache never+ * calls this helper, so it emits no event (never a zero).*/export async function measureStartupStep<T>(ctx: Pick<AdapterExecutionContext, "onEvent">,now: () => number,step: string,fn: () => Promise<T>,+ options: StartupStepMeasureOptions = {},): Promise<T> {const start = now();+ const roundTripsStart = options.roundTrips?.();+ const providerExecStart = options.providerExecMs?.();+ const providerGetStart = options.providerGetMs?.();try {return await fn();} finally {const durationMs = now() - start;+ const payload: Record<string, unknown> = { step, durationMs };+ if (options.roundTrips) {+ payload.roundTrips = options.roundTrips() - (roundTripsStart ?? 0);+ }+ if (options.providerExecMs) {+ payload.providerExecMs = options.providerExecMs() - (providerExecStart ?? 0);+ }+ if (options.providerGetMs) {+ payload.providerGetMs = options.providerGetMs() - (providerGetStart ?? 0);+ }+ if (options.extra) {+ Object.assign(payload, options.extra());+ }try {- await ctx.onEvent?.(buildStepEvent(step, durationMs));+ await ctx.onEvent?.(buildStepEvent(payload));} catch {// Observability must not change startup control flow.}diff --git a/packages/adapter-utils/src/command-managed-runtime.ts b/packages/adapter-utils/src/command-managed-runtime.tsindex 0e93ebb175..399eca9479 100644--- a/packages/adapter-utils/src/command-managed-runtime.ts+++ b/packages/adapter-utils/src/command-managed-runtime.ts@@ -20,6 +20,25 @@ export interface CommandManagedRuntimeRunner {* and let the caller choose a chunked upload path when progress is requested.*/supportsSingleStreamStdinProgress?: boolean;+ /**+ * Cumulative count of host→sandbox `execute` round-trips this runner has+ * performed (Open Q1). Present only on runners that instrument the single+ * exec seam (the sandbox runner); the per-step delta is emitted as+ * `run.startup.step` `payload.roundTrips`. A `() => number` reader, never the+ * runner itself, is threaded into `measureStartupStep` so the timing helper+ * stays runner-agnostic.+ */+ execCount?(): number;+ /**+ * Cumulative provider-reported wall-time (ms) for the `executeCommand` REST+ * call ({@link providerExecMs}) vs the `client.get` sandbox re-fetch that+ * precedes it ({@link providerGetMs}), accumulated across every `execute`+ * round-trip (Open Q1, finer attribution). Present only when the provider+ * surfaces these durations on its result metadata; the per-step deltas are+ * emitted as `payload.providerExecMs` / `payload.providerGetMs`.+ */+ providerExecMs?(): number;+ providerGetMs?(): number;execute(input: {command: string;args?: string[];diff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.test.tsindex 999ca869a7..4fb9a13a2f 100644--- a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts+++ b/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts@@ -28,7 +28,7 @@ vi.mock("@daytonaio/sdk", () => ({DaytonaTimeoutError: MockDaytonaTimeoutError,}));-import plugin from "./plugin.js";+import plugin, { setDaytonaTimingClockForTest } from "./plugin.js";import manifest from "./manifest.js";function createMockSandbox(overrides: {@@ -1098,12 +1098,49 @@ describe("Daytona sandbox provider plugin", () => {expect(cwdArg).toBeUndefined();expect(envArg).toBeUndefined();expect(timeoutArg).toBe(1);- expect(result).toEqual({+ expect(result).toMatchObject({exitCode: 7,timedOut: false,stdout: "stdout\nstderr\n",stderr: "",});+ // Provider-boundary timings ride the free-form result metadata (Open Q1).+ expect(typeof (result!.metadata as Record<string, unknown>)?.durationMs).toBe("number");+ expect(typeof (result!.metadata as Record<string, unknown>)?.getDurationMs).toBe("number");+ });++ it("reports provider executeCommand and client.get durations via result metadata (injected clock)", async () => {+ process.env.DAYTONA_API_KEY = "host-key";+ const sandbox = createMockSandbox();+ sandbox.process.executeCommand.mockResolvedValue({+ exitCode: 0,+ result: "ok",+ artifacts: { stdout: "ok" },+ });+ mockGet.mockResolvedValue(sandbox);++ // Deterministic clock: getSandbox spans 40ms, executeCommand spans 600ms.+ // Call order across the execute path is: getStart, getEnd, execStart, execEnd.+ const ticks = [1000, 1040, 1040, 1640];+ let i = 0;+ const restoreClock = setDaytonaTimingClockForTest(() => ticks[Math.min(i++, ticks.length - 1)]!);+ try {+ const result = await plugin.definition.onEnvironmentExecute?.({+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ lease: { providerLeaseId: "sandbox-123", metadata: {} },+ command: "printf",+ args: ["hello"],+ cwd: "/workspace",+ timeoutMs: 1000,+ });++ expect(result!.metadata).toMatchObject({ durationMs: 600, getDurationMs: 40 });+ } finally {+ restoreClock();+ }});it("stages stdin in the sandbox filesystem when execution needs redirected input", async () => {@@ -1172,27 +1209,43 @@ describe("Daytona sandbox provider plugin", () => {sandbox.process.executeCommand.mockRejectedValue(new MockDaytonaTimeoutError("command timed out"));mockGet.mockResolvedValue(sandbox);- const result = await plugin.definition.onEnvironmentExecute?.({- driverKey: "daytona",- companyId: "company-1",- environmentId: "env-1",- config: {- timeoutMs: 300000,- reuseLease: false,- },- lease: { providerLeaseId: "sandbox-123", metadata: {} },- command: "sleep",- args: ["60"],- cwd: "/workspace",- timeoutMs: 1000,- });+ // Injected clock: getStart=0, getEnd=10 (getDurationMs=10), execStart=20,+ // execEnd/timeout=1520 (durationMs=1500). Deterministic so the timeout path's+ // provider-exec attribution is asserted exactly.+ const ticks = [0, 10, 20, 1520];+ let i = 0;+ const restoreClock = setDaytonaTimingClockForTest(() => ticks[Math.min(i++, ticks.length - 1)]!);- expect(result).toEqual({+ let result;+ try {+ result = await plugin.definition.onEnvironmentExecute?.({+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: {+ timeoutMs: 300000,+ reuseLease: false,+ },+ lease: { providerLeaseId: "sandbox-123", metadata: {} },+ command: "sleep",+ args: ["60"],+ cwd: "/workspace",+ timeoutMs: 1000,+ });+ } finally {+ restoreClock();+ }++ expect(result).toMatchObject({exitCode: null,timedOut: true,stdout: "",stderr: "command timed out\n",});+ // The exec reached executeCommand before timing out, so its wall-time is+ // preserved as durationMs (provider-exec attribution is not dropped on the+ // timeout path); the getSandbox re-fetch duration is also reported.+ expect(result!.metadata).toMatchObject({ durationMs: 1500, getDurationMs: 10 });});it("injects noninteractive git credential defaults for every one-shot command", async () => {diff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.tsindex 83e7696a2e..a2a0edd7b5 100644--- a/packages/plugins/sandbox-providers/daytona/src/plugin.ts+++ b/packages/plugins/sandbox-providers/daytona/src/plugin.ts@@ -39,6 +39,24 @@ import type {} from "@paperclipai/plugin-sdk";import { performSyncIn, performSyncOut } from "./file-sync.js";+// Injectable monotonic clock for provider-boundary timing (Open Q1). Defaults+// to the real wall clock; `plugin.test.ts` overrides it via+// `setDaytonaTimingClockForTest` so the measured `durationMs`/`getDurationMs`+// are deterministic. The timing path never calls `Date.now()` directly.+let timingNow: () => number = () => Date.now();++/**+ * Test seam: override the provider-timing clock and return a restore function.+ * Not used in production, where the default wall clock always applies.+ */+export function setDaytonaTimingClockForTest(now: () => number): () => void {+ const previous = timingNow;+ timingNow = now;+ return () => {+ timingNow = previous;+ };+}+interface DaytonaDriverConfig {apiKey: string | null;apiUrl: string | null;@@ -743,6 +761,13 @@ async function executeOneShot(const timeoutSeconds = toTimeoutSeconds(effectiveTimeoutMs);const stdinPath = params.stdin != null ? `/tmp/paperclip-stdin-${randomUUID()}` : null;+ // Marks the start of the `executeCommand` REST round-trip. Hoisted out of the+ // try so the timeout path below can still attribute the exec wall-time it spent+ // before the SDK aborted — a slow failed exec is exactly what we want to+ // measure. Stays null until we are about to call `executeCommand`, so a timeout+ // during the earlier `uploadFile` step honestly reports no `durationMs`.+ let execStart: number | null = null;+try {if (stdinPath) {await sandbox.fs.uploadFile(Buffer.from(params.stdin ?? "", "utf8"), stdinPath, timeoutSeconds);@@ -760,24 +785,36 @@ async function executeOneShot(// profile sourcing when params.cwd is set, and the Daytona executor's own// cwd argument runs before our login-shell init, which is the wrong order// (env from .bashrc would override caller env).+ // Time only the `executeCommand` REST round-trip (Open Q1) — the ~600ms+ // login-shell wrapper — so the caller can attribute a step's exec time to+ // the provider boundary via the free-form `metadata.durationMs`.+ execStart = timingNow();const result = await sandbox.process.executeCommand(command, undefined, undefined, timeoutSeconds);+ const durationMs = timingNow() - execStart;return {exitCode: typeof result.exitCode === "number" ? result.exitCode : 1,timedOut: false,stdout: result.result ?? result.artifacts?.stdout ?? "",stderr: "",+ metadata: { durationMs },};} catch (error) {if (error instanceof DaytonaTimeoutError) {const timeoutMessage = gitNet? `Git network operation timed out after ${Math.round(effectiveTimeoutMs / 1000)} s — the remote may be unreachable or noninteractive credentials are not configured.`: error.message.trim();+ // Preserve provider-boundary exec attribution on the timeout path: if the+ // SDK aborted the `executeCommand` call itself, report how long it ran+ // before timing out so slow failed startup exec is attributed to the+ // provider, not silently dropped.+ const durationMs = execStart != null ? timingNow() - execStart : undefined;return {exitCode: null,timedOut: true,stdout: "",stderr: `${timeoutMessage}\n`,+ ...(durationMs != null ? { metadata: { durationMs } } : {}),};}throw error;@@ -1256,9 +1293,19 @@ const plugin = definePlugin({}const config = parseDriverConfig(params.config);+ // Time the `client.get` sandbox re-fetch (Open Q1) separately from the+ // `executeCommand` round-trip so telemetry can split the per-call REST-get+ // cost from the exec cost. `ensureSandboxStarted` is a no-op for an+ // already-started sandbox, so it is excluded from the get measurement.+ const getStart = timingNow();const sandbox = await getSandbox(config, params.lease.providerLeaseId);+ const getDurationMs = timingNow() - getStart;await ensureSandboxStarted(sandbox, toTimeoutSeconds(resolveTimeoutMs(params.timeoutMs, config)));- return await executeOneShot(sandbox, params, config);+ const result = await executeOneShot(sandbox, params, config);+ return {+ ...result,+ metadata: { ...(result.metadata ?? {}), getDurationMs },+ };},// Opt-in native inbound transfer. Defining this hook (with onEnvironmentSyncOut)diff --git a/server/src/__tests__/environment-execution-target.test.ts b/server/src/__tests__/environment-execution-target.test.tsindex a627f105ca..dadcea97d9 100644--- a/server/src/__tests__/environment-execution-target.test.ts+++ b/server/src/__tests__/environment-execution-target.test.ts@@ -221,4 +221,99 @@ describe("resolveEnvironmentExecutionTarget", () => {});expect(target).not.toHaveProperty("paperclipApiUrl");});++ it("exposes a sandbox runner that counts round-trips and accumulates provider durations", async () => {+ mockResolveEnvironmentDriverConfigForRuntime.mockResolvedValue({+ driver: "sandbox",+ config: {+ provider: "fake-plugin",+ reuseLease: false,+ timeoutMs: 30_000,+ },+ });++ // Each exec reports its provider-boundary durations on the free-form result+ // metadata (the Daytona plugin does this); the runner accumulates them.+ const environmentRuntime = {+ execute: vi.fn().mockResolvedValue({+ exitCode: 0,+ signal: null,+ timedOut: false,+ stdout: "ok",+ stderr: "",+ metadata: { durationMs: 600, getDurationMs: 15 },+ }),+ supportsSync: vi.fn().mockReturnValue(false),+ };++ const target = await resolveEnvironmentExecutionTarget({+ db: {} as never,+ companyId: "company-1",+ adapterType: "codex_local",+ environment: { id: "env-1", driver: "sandbox", config: { provider: "fake-plugin" } },+ leaseId: "lease-1",+ leaseMetadata: { remoteCwd: "/workspace" },+ lease: { id: "lease-1" } as never,+ environmentRuntime: environmentRuntime as never,+ });++ const runner = (target as { runner?: {+ execCount(): number;+ providerExecMs(): number;+ providerGetMs(): number;+ execute(input: { command: string; args?: string[] }): Promise<unknown>;+ } }).runner;+ expect(runner).toBeTruthy();+ expect(runner!.execCount()).toBe(0);+ expect(runner!.providerExecMs()).toBe(0);+ expect(runner!.providerGetMs()).toBe(0);++ await runner!.execute({ command: "echo", args: ["a"] });+ await runner!.execute({ command: "echo", args: ["b"] });++ expect(runner!.execCount()).toBe(2);+ expect(runner!.providerExecMs()).toBe(1200);+ expect(runner!.providerGetMs()).toBe(30);+ });++ it("tolerates a provider result with no timing metadata (counts the round-trip, accumulates nothing)", async () => {+ mockResolveEnvironmentDriverConfigForRuntime.mockResolvedValue({+ driver: "sandbox",+ config: { provider: "fake-plugin", reuseLease: false, timeoutMs: 30_000 },+ });++ const environmentRuntime = {+ execute: vi.fn().mockResolvedValue({+ exitCode: 0,+ signal: null,+ timedOut: false,+ stdout: "",+ stderr: "",+ }),+ supportsSync: vi.fn().mockReturnValue(false),+ };++ const target = await resolveEnvironmentExecutionTarget({+ db: {} as never,+ companyId: "company-1",+ adapterType: "codex_local",+ environment: { id: "env-1", driver: "sandbox", config: { provider: "fake-plugin" } },+ leaseId: "lease-1",+ leaseMetadata: { remoteCwd: "/workspace" },+ lease: { id: "lease-1" } as never,+ environmentRuntime: environmentRuntime as never,+ });++ const runner = (target as { runner?: {+ execCount(): number;+ providerExecMs(): number;+ providerGetMs(): number;+ execute(input: { command: string }): Promise<unknown>;+ } }).runner;+ await runner!.execute({ command: "echo" });++ expect(runner!.execCount()).toBe(1);+ expect(runner!.providerExecMs()).toBe(0);+ expect(runner!.providerGetMs()).toBe(0);+ });});diff --git a/server/src/services/environment-execution-target.ts b/server/src/services/environment-execution-target.tsindex bbd86d8ce5..e609646ef4 100644--- a/server/src/services/environment-execution-target.ts+++ b/server/src/services/environment-execution-target.ts@@ -63,6 +63,20 @@ export async function resolveEnvironmentExecutionTarget(input: {? input.leaseMetadata.shellCommand: null;+ // Per-lease-runner cumulative counters for startup-step attribution (Open+ // Q1). Closed over by the `runner.execute` seam below and read back as+ // deltas by `measureStartupStep`.+ let execCount = 0;+ let providerExecMs = 0;+ let providerGetMs = 0;+ const accumulateProviderDurations = (metadata: Record<string, unknown> | undefined): void => {+ if (!metadata) return;+ const exec = metadata.durationMs;+ const get = metadata.getDurationMs;+ if (typeof exec === "number" && Number.isFinite(exec)) providerExecMs += exec;+ if (typeof get === "number" && Number.isFinite(get)) providerGetMs += get;+ };+return {kind: "remote",transport: "sandbox",@@ -79,7 +93,17 @@ export async function resolveEnvironmentExecutionTarget(input: {runner: input.environmentRuntime && input.lease? {supportsSingleStreamStdinProgress: false,+ // Round-trip counter + provider-duration accumulators on the single+ // host→sandbox exec seam (Open Q1). `measureStartupStep` reads the+ // per-step delta of each via the `() => number` closures below. The+ // provider durations ride the exec result's free-form `metadata`+ // (set by the Daytona plugin), so no protocol/schema change is+ // needed and providers that omit them simply accumulate nothing.+ execCount: () => execCount,+ providerExecMs: () => providerExecMs,+ providerGetMs: () => providerGetMs,execute: async (commandInput) => {+ execCount += 1;const startedAt = new Date().toISOString();const result = await input.environmentRuntime!.execute({environment: input.environment as Environment,@@ -91,6 +115,7 @@ export async function resolveEnvironmentExecutionTarget(input: {stdin: commandInput.stdin,timeoutMs: commandInput.timeoutMs,});+ accumulateProviderDurations(result.metadata);if (result.stdout) await commandInput.onLog?.("stdout", result.stdout);if (result.stderr) await commandInput.onLog?.("stderr", result.stderr);return {