mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 04:54:00 +01:00
feat(plugin-daytona): persistent session model with plain command dispatch (#10941)
## Thinking Path > - Paperclip is the control plane for autonomous AI companies > - One core subsystem runs agent work inside sandboxes > - The Daytona provider uses that path to run user commands > - The current one-shot model does not keep a shell alive across commands > - This pull request adds an opt-in persistent session model for Daytona > - The benefit is faster command dispatch with the same sandbox boundaries ## Linked Issues or Issue Description ### Subsystem affected Cross-cutting. This change touches `packages/adapters`, provider tests, span names, and sandbox command behavior. ### Problem or motivation The Daytona provider needs a persistent shell for repeated command dispatch. The old advisory wrapper path does not reach that goal. It also adds cost and removes the session speed gain. ### Proposed solution Add a `useSessions` driver flag. Keep it off by default. Open one Daytona session per lease when the flag is on. Send each user command into that session. Read stdout and stderr from the session logs endpoint. Run each command in a subshell so `exit` does not stop the shell. Remove the advisory `bwrap` wrapper path and its lease metadata. Add session setup and teardown spans. Keep a hard delete on teardown. ### Alternatives considered Keep the advisory `bwrap` wrapper. That path does not give a real persistent session. It also keeps extra command overhead. Keep a one-shot fallback for user commands. That would weaken the session model and hide a missing session case. ### Roadmap alignment This work fits the `Cloud / Sandbox agents` milestone in `ROADMAP.md`. It also supports the control plane goal of safe remote sandbox execution. ### Additional context The handoff verification reported `tsc --noEmit` clean and 119 Daytona unit tests passing. The handoff also reported a clean host span allowlist test and five expected commits on the branch. The security review gate remains required before merge. ## What Changed - Added an opt-in persistent session model for the Daytona sandbox provider. - Routed user commands through `executeSessionCommand` when sessions are enabled. - Removed the advisory `bwrap` command wrapper path and the lease metadata it used. - Added session lifecycle spans and span allowlist coverage. - Documented the leak bound in `DIRECTORY-CONSTRAINT-FINDINGS.md`. ## Verification - `tsc --noEmit` clean for the Daytona plugin, per handoff verification. - Daytona unit suite passes, with 119 tests, per handoff verification. - Host span allowlist test passes, per handoff verification. ## Risks - Persistent sessions can leak if teardown fails. - Session logs must keep stdout and stderr separate. - The flag stays off by default to limit rollout risk. ## Model Used OpenAI GPT-5, Codex, tool use enabled. ## 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
d84c5eae7a
commit
cfed36ea6b
10 files changed
+1295
-705
No files matched your search
@@ -32,6 +32,13 @@ import { environmentRuntimeService, findReusableSandboxLeaseId } from "../servic
|
||||
import { environmentService } from "../services/environments.ts";
|
||||
import { secretService } from "../services/secrets.ts";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.ts";
|
||||
import {
|
||||
getActiveStepContext,
|
||||
runWithRuntimeParent,
|
||||
type StartupSpanContext,
|
||||
} from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
|
||||
import { traceparentFromContextToken } from "../instrumentation.ts";
|
||||
import { ROOT_CONTEXT, trace } from "@opentelemetry/api";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
@@ -699,6 +706,321 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
|
||||
expect(workerManager.call).toHaveBeenCalledWith(pluginId, "environmentReleaseLease", expect.anything(), 31234);
|
||||
});
|
||||
|
||||
// Build the fake plugin fixture for the run-parent release tests below. A
|
||||
// plugin sandbox provider can open a persistent session on the first command
|
||||
// and delete it on lease release; the delete emits a provider
|
||||
// `session.teardown` span. The host mints that span's parent from the active
|
||||
// step context at the release RPC. So the release must run under the run
|
||||
// parent, or the span loses its traceparent and the backend drops it.
|
||||
async function seedFakePluginSandbox() {
|
||||
const pluginId = randomUUID();
|
||||
const { companyId, environment: baseEnvironment, runId } = await seedEnvironment();
|
||||
const fakePluginConfig = {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:test",
|
||||
timeoutMs: 1234,
|
||||
reuseLease: false,
|
||||
};
|
||||
const environment = {
|
||||
...baseEnvironment,
|
||||
name: "Fake Plugin Sandbox",
|
||||
driver: "sandbox",
|
||||
config: fakePluginConfig,
|
||||
};
|
||||
await environmentService(db).update(environment.id, {
|
||||
driver: "sandbox",
|
||||
name: environment.name,
|
||||
config: fakePluginConfig,
|
||||
});
|
||||
await db.insert(plugins).values({
|
||||
id: pluginId,
|
||||
pluginKey: "paperclip.fake-plugin-sandbox-provider",
|
||||
packageName: "@paperclipai/plugin-fake-sandbox",
|
||||
version: "1.0.0",
|
||||
apiVersion: 1,
|
||||
categories: ["automation"],
|
||||
manifestJson: {
|
||||
id: "paperclip.fake-plugin-sandbox-provider",
|
||||
apiVersion: 1,
|
||||
version: "1.0.0",
|
||||
displayName: "Fake Plugin Sandbox Provider",
|
||||
description: "Test fake plugin provider",
|
||||
author: "Paperclip",
|
||||
categories: ["automation"],
|
||||
capabilities: ["environment.drivers.register"],
|
||||
entrypoints: { worker: "dist/worker.js" },
|
||||
environmentDrivers: [
|
||||
{
|
||||
driverKey: "fake-plugin",
|
||||
kind: "sandbox_provider",
|
||||
displayName: "Fake Plugin",
|
||||
configSchema: { type: "object" },
|
||||
},
|
||||
],
|
||||
},
|
||||
status: "ready",
|
||||
installOrder: 1,
|
||||
updatedAt: new Date(),
|
||||
} as any);
|
||||
return { companyId, environment, runId, pluginId };
|
||||
}
|
||||
|
||||
it("runs a plugin-backed lease release under the run-time exec parent, so the teardown span keeps a valid traceparent", async () => {
|
||||
const { companyId, environment, runId, pluginId } = await seedFakePluginSandbox();
|
||||
|
||||
// The active step context observed at the moment the host issues the release
|
||||
// RPC. The real worker manager mints the provider-span traceparent from
|
||||
// exactly this value, so a non-null context with a valid parent proves the
|
||||
// teardown span keeps a host-minted parent.
|
||||
let releaseStepContext: ReturnType<typeof getActiveStepContext> = null;
|
||||
const workerManager = {
|
||||
isRunning: vi.fn((id: string) => id === pluginId),
|
||||
call: vi.fn(async (_pluginId: string, method: string) => {
|
||||
if (method === "environmentAcquireLease") {
|
||||
return {
|
||||
providerLeaseId: "sandbox-1",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:test",
|
||||
timeoutMs: 1234,
|
||||
reuseLease: false,
|
||||
remoteCwd: "/workspace",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "environmentExecute") {
|
||||
return { exitCode: 0, signal: null, timedOut: false, stdout: "ok\n", stderr: "" };
|
||||
}
|
||||
if (method === "environmentReleaseLease") {
|
||||
releaseStepContext = getActiveStepContext();
|
||||
return undefined;
|
||||
}
|
||||
throw new Error(`Unexpected plugin method: ${method}`);
|
||||
}),
|
||||
} as unknown as PluginWorkerManager;
|
||||
const runtimeWithPlugin = environmentRuntimeService(db, { pluginWorkerManager: workerManager });
|
||||
|
||||
const acquired = await runtimeWithPlugin.acquireRunLease({
|
||||
companyId,
|
||||
environment,
|
||||
issueId: null,
|
||||
heartbeatRunId: runId,
|
||||
persistedExecutionWorkspace: null,
|
||||
});
|
||||
|
||||
// Build a real host run-parent context and run the first command under it,
|
||||
// exactly as the run drives an exec. The driver records this context for the
|
||||
// lease and replays it around the later release RPC.
|
||||
const runParent: StartupSpanContext = trace.setSpanContext(ROOT_CONTEXT, {
|
||||
traceId: "0af7651916cd43dd8448eb211c80319c",
|
||||
spanId: "b7ad6b7169203331",
|
||||
traceFlags: 1,
|
||||
isRemote: false,
|
||||
});
|
||||
await runWithRuntimeParent(runParent, () =>
|
||||
runtimeWithPlugin.execute({
|
||||
environment,
|
||||
lease: acquired.lease,
|
||||
command: "printf",
|
||||
args: ["ok"],
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
timeoutMs: 1000,
|
||||
}),
|
||||
);
|
||||
|
||||
await environmentService(db).update(environment.id, { driver: "local", config: {} });
|
||||
const released = await runtimeWithPlugin.releaseRunLeases(runId);
|
||||
|
||||
expect(released).toHaveLength(1);
|
||||
// The release RPC ran under the recorded run parent, so the host mints a
|
||||
// valid W3C traceparent from it. A dropped span would show a null context.
|
||||
expect(releaseStepContext).not.toBeNull();
|
||||
expect(releaseStepContext?.parentContext).toBe(runParent);
|
||||
expect(traceparentFromContextToken(releaseStepContext?.parentContext)).toBe(
|
||||
"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
|
||||
);
|
||||
});
|
||||
|
||||
it("releases a plugin-backed lease with no active step context when the run drove no exec", async () => {
|
||||
const { companyId, environment, runId, pluginId } = await seedFakePluginSandbox();
|
||||
|
||||
let releaseStepContext: ReturnType<typeof getActiveStepContext> = null;
|
||||
let releaseCalled = false;
|
||||
const workerManager = {
|
||||
isRunning: vi.fn((id: string) => id === pluginId),
|
||||
call: vi.fn(async (_pluginId: string, method: string) => {
|
||||
if (method === "environmentAcquireLease") {
|
||||
return {
|
||||
providerLeaseId: "sandbox-1",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:test",
|
||||
timeoutMs: 1234,
|
||||
reuseLease: false,
|
||||
remoteCwd: "/workspace",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "environmentReleaseLease") {
|
||||
releaseCalled = true;
|
||||
releaseStepContext = getActiveStepContext();
|
||||
return undefined;
|
||||
}
|
||||
throw new Error(`Unexpected plugin method: ${method}`);
|
||||
}),
|
||||
} as unknown as PluginWorkerManager;
|
||||
const runtimeWithPlugin = environmentRuntimeService(db, { pluginWorkerManager: workerManager });
|
||||
|
||||
await runtimeWithPlugin.acquireRunLease({
|
||||
companyId,
|
||||
environment,
|
||||
issueId: null,
|
||||
heartbeatRunId: runId,
|
||||
persistedExecutionWorkspace: null,
|
||||
});
|
||||
await environmentService(db).update(environment.id, { driver: "local", config: {} });
|
||||
const released = await runtimeWithPlugin.releaseRunLeases(runId);
|
||||
|
||||
expect(released).toHaveLength(1);
|
||||
// No command ran, so no session opened and no teardown span is emitted. The
|
||||
// release must not invent a parent from an unrelated ambient context; it
|
||||
// runs unwrapped, exactly as before the fix.
|
||||
expect(releaseCalled).toBe(true);
|
||||
expect(releaseStepContext).toBeNull();
|
||||
});
|
||||
|
||||
it("forwards the bypassSession flag to the plugin execute RPC so a pre-run command skips the session", async () => {
|
||||
const { companyId, environment, runId, pluginId } = await seedFakePluginSandbox();
|
||||
|
||||
// Capture the params of each environmentExecute RPC, so the test can assert
|
||||
// the host forwards `bypassSession` to the provider unchanged.
|
||||
const executeParams: Array<Record<string, unknown>> = [];
|
||||
const workerManager = {
|
||||
isRunning: vi.fn((id: string) => id === pluginId),
|
||||
call: vi.fn(async (_pluginId: string, method: string, params: Record<string, unknown>) => {
|
||||
if (method === "environmentAcquireLease") {
|
||||
return {
|
||||
providerLeaseId: "sandbox-1",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:test",
|
||||
timeoutMs: 1234,
|
||||
reuseLease: false,
|
||||
remoteCwd: "/workspace",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "environmentExecute") {
|
||||
executeParams.push(params);
|
||||
return { exitCode: 0, signal: null, timedOut: false, stdout: "ok\n", stderr: "" };
|
||||
}
|
||||
throw new Error(`Unexpected plugin method: ${method}`);
|
||||
}),
|
||||
} as unknown as PluginWorkerManager;
|
||||
const runtimeWithPlugin = environmentRuntimeService(db, { pluginWorkerManager: workerManager });
|
||||
|
||||
const acquired = await runtimeWithPlugin.acquireRunLease({
|
||||
companyId,
|
||||
environment,
|
||||
issueId: null,
|
||||
heartbeatRunId: runId,
|
||||
persistedExecutionWorkspace: null,
|
||||
});
|
||||
|
||||
// A pre-run command (the provision command) sets bypassSession explicitly.
|
||||
await runtimeWithPlugin.execute({
|
||||
environment,
|
||||
lease: acquired.lease,
|
||||
command: "bash",
|
||||
args: ["-lc", "true"],
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
timeoutMs: 1000,
|
||||
bypassSession: true,
|
||||
});
|
||||
// An in-run command runs under the run-parent context, so the host does not
|
||||
// bypass the session and the provider opens/uses the session.
|
||||
const runParent: StartupSpanContext = trace.setSpanContext(ROOT_CONTEXT, {
|
||||
traceId: "0af7651916cd43dd8448eb211c80319c",
|
||||
spanId: "b7ad6b7169203331",
|
||||
traceFlags: 1,
|
||||
isRemote: false,
|
||||
});
|
||||
await runWithRuntimeParent(runParent, () =>
|
||||
runtimeWithPlugin.execute({
|
||||
environment,
|
||||
lease: acquired.lease,
|
||||
command: "printf",
|
||||
args: ["ok"],
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
timeoutMs: 1000,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(executeParams).toHaveLength(2);
|
||||
expect(executeParams[0]?.bypassSession).toBe(true);
|
||||
// An in-run command carries a run parent, so it does not bypass the session.
|
||||
expect(executeParams[1]?.bypassSession).toBe(false);
|
||||
});
|
||||
|
||||
it("bypasses the session for a context-less command so the setup span keeps a run parent", async () => {
|
||||
const { companyId, environment, runId, pluginId } = await seedFakePluginSandbox();
|
||||
|
||||
// Capture the params of each environmentExecute RPC, so the test can assert
|
||||
// the host derives `bypassSession` from the active run-parent context.
|
||||
const executeParams: Array<Record<string, unknown>> = [];
|
||||
const workerManager = {
|
||||
isRunning: vi.fn((id: string) => id === pluginId),
|
||||
call: vi.fn(async (_pluginId: string, method: string, params: Record<string, unknown>) => {
|
||||
if (method === "environmentAcquireLease") {
|
||||
return {
|
||||
providerLeaseId: "sandbox-1",
|
||||
metadata: {
|
||||
provider: "fake-plugin",
|
||||
image: "fake:test",
|
||||
timeoutMs: 1234,
|
||||
reuseLease: false,
|
||||
remoteCwd: "/workspace",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (method === "environmentExecute") {
|
||||
executeParams.push(params);
|
||||
return { exitCode: 0, signal: null, timedOut: false, stdout: "ok\n", stderr: "" };
|
||||
}
|
||||
throw new Error(`Unexpected plugin method: ${method}`);
|
||||
}),
|
||||
} as unknown as PluginWorkerManager;
|
||||
const runtimeWithPlugin = environmentRuntimeService(db, { pluginWorkerManager: workerManager });
|
||||
|
||||
const acquired = await runtimeWithPlugin.acquireRunLease({
|
||||
companyId,
|
||||
environment,
|
||||
issueId: null,
|
||||
heartbeatRunId: runId,
|
||||
persistedExecutionWorkspace: null,
|
||||
});
|
||||
|
||||
// A command with no active run-parent context (a pre-run install/probe or
|
||||
// the agent process launch) runs before the run trace is active. The host
|
||||
// mints no plugin RPC traceparent for it, so a session opened here would drop
|
||||
// its setup span. The host bypasses the session for such a command.
|
||||
await runtimeWithPlugin.execute({
|
||||
environment,
|
||||
lease: acquired.lease,
|
||||
command: "sh",
|
||||
args: ["-c", "command -v claude"],
|
||||
cwd: "/workspace",
|
||||
env: {},
|
||||
timeoutMs: 1000,
|
||||
});
|
||||
|
||||
expect(executeParams).toHaveLength(1);
|
||||
expect(executeParams[0]?.bypassSession).toBe(true);
|
||||
});
|
||||
|
||||
it("builds the workspace-realization record with referenced sources for a plugin-backed sandbox realize", async () => {
|
||||
// A provider plugin realize handler returns only its realized cwd and provider metadata; it does
|
||||
// not build the workspace-realization record. The server must build that record from the run
|
||||
|
||||
@@ -143,6 +143,21 @@ describe("plugin provider span host handler", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("admits the session setup and teardown span names", async () => {
|
||||
const services = servicesFor();
|
||||
for (const name of ["session.setup", "session.teardown"]) {
|
||||
await services.tracer.record(
|
||||
{ name },
|
||||
{ traceparent: VALID_TRACEPARENT } as WorkerHostCallContext,
|
||||
);
|
||||
}
|
||||
const recorded = mockRecordSpan.mock.calls.map((c) => (c[0] as { name: string }).name);
|
||||
expect(recorded).toEqual([
|
||||
"sandbox.provider.session.setup",
|
||||
"sandbox.provider.session.teardown",
|
||||
]);
|
||||
});
|
||||
|
||||
it("forwards a valid start-time and end-time pair to the recorder", async () => {
|
||||
const services = servicesFor();
|
||||
const startTimeMs = Date.now() - 4500;
|
||||
|
||||
@@ -432,6 +432,13 @@ export function environmentRunOrchestrator(
|
||||
SHELL: "/bin/bash",
|
||||
},
|
||||
timeoutMs: 300_000,
|
||||
// The provision command runs before the run opens its trace root, so it
|
||||
// carries no run parent. A sandbox provider that opens a persistent
|
||||
// session on the first command must not open the session here, or the
|
||||
// session-setup span loses its parent and the span backend drops it.
|
||||
// Bypass the session for this command; the session opens on the first
|
||||
// in-run command instead, whose setup span parents to the run trace.
|
||||
bypassSession: true,
|
||||
});
|
||||
if (provisionResult.exitCode !== 0 || provisionResult.timedOut) {
|
||||
throw new Error(formatProvisionFailureDetail(provisionResult));
|
||||
|
||||
@@ -20,6 +20,11 @@ import type {
|
||||
PluginSyncOperation,
|
||||
} from "@paperclipai/plugin-sdk";
|
||||
import { ensureSshWorkspaceReady } from "@paperclipai/adapter-utils/ssh";
|
||||
import {
|
||||
getActiveStepContext,
|
||||
runWithRuntimeParent,
|
||||
type StartupSpanContext,
|
||||
} from "@paperclipai/adapter-utils/acpx-engine/startup-timing";
|
||||
import { environmentService } from "./environments.js";
|
||||
import {
|
||||
collectEnvironmentSecretRefs,
|
||||
@@ -188,6 +193,15 @@ export interface EnvironmentDriverExecuteInput extends EnvironmentDriverLeaseInp
|
||||
env?: Record<string, string>;
|
||||
stdin?: string;
|
||||
timeoutMs?: number;
|
||||
/**
|
||||
* Run this command outside the lease's persistent session. The run
|
||||
* orchestrator sets this on the workspace provision command, which runs before
|
||||
* the run opens its trace root. A sandbox provider that opens a persistent
|
||||
* session on the first command must run this command one-shot and keep the
|
||||
* session closed, so the session first opens on an in-run command whose setup
|
||||
* span parents to the run trace. The default keeps the session path.
|
||||
*/
|
||||
bypassSession?: boolean;
|
||||
}
|
||||
|
||||
export interface EnvironmentDriverSyncInput extends EnvironmentDriverLeaseInput {
|
||||
@@ -639,6 +653,31 @@ function createSandboxEnvironmentDriver(
|
||||
const pluginWorkerReadyPollMs = options.pluginWorkerReadyPollMs ?? DEFAULT_PLUGIN_SANDBOX_WORKER_READY_POLL_MS;
|
||||
const environmentsSvc = environmentService(db);
|
||||
|
||||
// The run-time exec parent context, held per lease id. A plugin sandbox
|
||||
// provider can open a persistent session on the first command and delete it
|
||||
// on lease release. The session open runs inside `execute`, under the run
|
||||
// parent (the same context the `sandbox.exec` span reads). The session delete
|
||||
// runs inside the lease-release RPC, which the run orchestrator calls after
|
||||
// the run, outside that scope. Without a parent the host mints no
|
||||
// `traceparent` and drops the provider `session.teardown` span. So `execute`
|
||||
// records the exec parent here, and the release paths replay it around the
|
||||
// release RPC. The host still mints and validates the `traceparent` itself;
|
||||
// the value only widens which host calls carry a run parent. An entry is
|
||||
// removed on release, so the map holds at most one context per live lease.
|
||||
const runExecParentByLeaseId = new Map<string, StartupSpanContext>();
|
||||
|
||||
// Run a lease-release RPC under the lease's recorded exec parent context, and
|
||||
// then drop the entry — the lease is gone. Under the parent the host mints a
|
||||
// `traceparent`, so a provider `session.teardown` span reaches the span
|
||||
// backend in the run trace. With no recorded context (no command ran, or a
|
||||
// local target with no trace context) the call runs unwrapped, exactly as
|
||||
// before, so the change never fails a release.
|
||||
function runLeaseReleaseWithRunParent<T>(leaseId: string, call: () => Promise<T>): Promise<T> {
|
||||
const runParent = runExecParentByLeaseId.get(leaseId);
|
||||
runExecParentByLeaseId.delete(leaseId);
|
||||
return runParent !== undefined ? runWithRuntimeParent(runParent, call) : call();
|
||||
}
|
||||
|
||||
async function resolveSandboxProviderPlugin(input: { provider: string }) {
|
||||
const running = await resolvePluginSandboxProviderDriverByKey({
|
||||
db,
|
||||
@@ -1274,6 +1313,31 @@ function createSandboxEnvironmentDriver(
|
||||
async execute(input) {
|
||||
// Plugin-backed sandbox providers: delegate command execution.
|
||||
if (input.lease.metadata?.sandboxProviderPlugin && pluginWorkerManager) {
|
||||
// Read the active run-parent context once. The host mints the plugin
|
||||
// RPC `traceparent` from this same context, so a provider `session.setup`
|
||||
// span parents to the run trace only when this context is present.
|
||||
const activeStep = getActiveStepContext();
|
||||
// Record the run-time exec parent context for this lease, so a later
|
||||
// lease-release RPC that emits the provider `session.teardown` span can
|
||||
// parent to the same run trace. This is the same context the
|
||||
// `sandbox.exec` span reads. Keep only a defined context; a local or SSH
|
||||
// target with no host trace context yields undefined and stores nothing.
|
||||
const execParentContext = activeStep?.parentContext;
|
||||
if (execParentContext !== undefined) {
|
||||
runExecParentByLeaseId.set(input.lease.id, execParentContext);
|
||||
}
|
||||
// Bypass the persistent session for any command that runs with no active
|
||||
// run-parent context. Such a command runs before the run trace is active:
|
||||
// the workspace provision command, the CLI install command, the
|
||||
// resolvability probe, and the agent process launch all run at the top of
|
||||
// the adapter execute, outside a measured step and outside the run
|
||||
// trace. A session opened on such a command emits a `session.setup` span
|
||||
// with no host-minted parent, and the span backend drops it. So run the
|
||||
// command one-shot and keep the session closed; the session then opens on
|
||||
// the first in-run command that carries a run parent (an agent tool
|
||||
// command runs under the run trace), whose setup span parents to the run
|
||||
// trace. A command that sets `bypassSession` explicitly always bypasses.
|
||||
const bypassSession = input.bypassSession === true || activeStep === null;
|
||||
const pluginId = readString(input.lease.metadata?.pluginId);
|
||||
const providerKey = readString(input.lease.metadata?.provider);
|
||||
if (pluginId && providerKey) {
|
||||
@@ -1300,6 +1364,13 @@ function createSandboxEnvironmentDriver(
|
||||
env: input.env,
|
||||
stdin: input.stdin,
|
||||
timeoutMs: input.timeoutMs,
|
||||
// Forward the effective session-bypass flag so a provider that opens
|
||||
// a persistent session skips it for a pre-run or context-less command
|
||||
// (the workspace provision command, the CLI install command, the
|
||||
// resolvability probe, the agent process launch). The session then
|
||||
// opens on the first in-run command that carries a run parent, whose
|
||||
// setup span parents to the run trace.
|
||||
bypassSession,
|
||||
}, resolvePluginExecuteRpcTimeoutMs({
|
||||
requestedTimeoutMs: input.timeoutMs,
|
||||
config: sanitizedConfig,
|
||||
@@ -1368,15 +1439,17 @@ function createSandboxEnvironmentDriver(
|
||||
lease: input.lease,
|
||||
provider: providerKey,
|
||||
});
|
||||
await pluginWorkerManager.call(pluginId, "environmentReleaseLease", {
|
||||
driverKey: providerKey,
|
||||
companyId: input.lease.companyId,
|
||||
environmentId: input.environment.id,
|
||||
issueId: input.lease.issueId,
|
||||
config: stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig),
|
||||
providerLeaseId: input.lease.providerLeaseId,
|
||||
leaseMetadata: metadata,
|
||||
}, resolvePluginSandboxRpcTimeoutMs(stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig)));
|
||||
await runLeaseReleaseWithRunParent(input.lease.id, () =>
|
||||
pluginWorkerManager.call(pluginId, "environmentReleaseLease", {
|
||||
driverKey: providerKey,
|
||||
companyId: input.lease.companyId,
|
||||
environmentId: input.environment.id,
|
||||
issueId: input.lease.issueId,
|
||||
config: stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig),
|
||||
providerLeaseId: input.lease.providerLeaseId,
|
||||
leaseMetadata: metadata,
|
||||
}, resolvePluginSandboxRpcTimeoutMs(stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig))),
|
||||
);
|
||||
} catch {
|
||||
cleanupStatus = "failed";
|
||||
}
|
||||
@@ -1414,15 +1487,17 @@ function createSandboxEnvironmentDriver(
|
||||
lease: input.lease,
|
||||
provider: providerKey,
|
||||
});
|
||||
await pluginWorkerManager.call(pluginId, "environmentDestroyLease", {
|
||||
driverKey: providerKey,
|
||||
companyId: input.lease.companyId,
|
||||
environmentId: input.environment.id,
|
||||
issueId: input.lease.issueId,
|
||||
config: stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig),
|
||||
providerLeaseId: input.lease.providerLeaseId,
|
||||
leaseMetadata: metadata,
|
||||
}, resolvePluginSandboxRpcTimeoutMs(stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig)));
|
||||
await runLeaseReleaseWithRunParent(input.lease.id, () =>
|
||||
pluginWorkerManager.call(pluginId, "environmentDestroyLease", {
|
||||
driverKey: providerKey,
|
||||
companyId: input.lease.companyId,
|
||||
environmentId: input.environment.id,
|
||||
issueId: input.lease.issueId,
|
||||
config: stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig),
|
||||
providerLeaseId: input.lease.providerLeaseId,
|
||||
leaseMetadata: metadata,
|
||||
}, resolvePluginSandboxRpcTimeoutMs(stripSandboxProviderEnvelope(config as SandboxEnvironmentConfig))),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const metadataConfig = sandboxConfigFromLeaseMetadata(input.lease);
|
||||
|
||||
@@ -510,7 +510,8 @@ const SPAN_ATTRS = SANDBOX_STARTUP_SPAN_ATTRS;
|
||||
/** The closed set of provider span names a plugin may emit. `pack` and
|
||||
* `transfer` are the host-local build and the byte upload. `mkdir`, `guard`,
|
||||
* `rename`, `extract`, and `provision` are the per-round-trip command spans in
|
||||
* the inbound sync path. */
|
||||
* the inbound sync path. `session.setup` and `session.teardown` are the short
|
||||
* spans that wrap a persistent-session create and delete. */
|
||||
const KNOWN_PROVIDER_SPAN_NAMES: ReadonlySet<string> = new Set([
|
||||
"pack",
|
||||
"transfer",
|
||||
@@ -519,6 +520,8 @@ const KNOWN_PROVIDER_SPAN_NAMES: ReadonlySet<string> = new Set([
|
||||
"rename",
|
||||
"extract",
|
||||
"provision",
|
||||
"session.setup",
|
||||
"session.teardown",
|
||||
]);
|
||||
|
||||
/** Clamp the span name to a closed, namespaced set. A known name maps to
|
||||
|
||||
Reference in new issue
Block a user