Skip to content

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

Preserve bounded workspace sync diagnostics across RPC (#15481)

Devin Foley465140596fcc
diff --git a/doc/observability.md b/doc/observability.md
index b9d19e6f21..c09b721929 100644
--- a/doc/observability.md
+++ b/doc/observability.md
@@ -576,6 +576,13 @@ integers from 1 through 255. These fields accompany a known restore failure code
only. They omit error messages, raw command lines, paths, process output, and arbitrary
cause data. Git error wrappers preserve only these safe codes and numbers for
diagnostics, without adding the original error as a cause.
+Native sandbox `environmentSyncOut` failures carry the same allowlisted codes
+and bounded HTTP/exit statuses across the plugin worker RPC boundary. The host
+revalidates that optional envelope and retains it only for restore diagnostics.
+The envelope excludes provider messages, response bodies, names, paths, and
+credentials. The existing RPC error message and code remain unchanged, as do
+restore classification, retries, and source retention. Older workers without the
+envelope still report `unknown` when no structured cause is available.
For `git_integration`, optional `workspaceRestoreGitCommand` identifies the fixed
command family: `rev_parse`, `symbolic_ref`, `merge_base`, `merge_tree`,
`commit_tree`, `update_ref`, or `log`. `workspaceRestoreGitFailureKind` is
diff --git a/doc/run-log-events.md b/doc/run-log-events.md
index 8941314f27..10557d8b6b 100644
--- a/doc/run-log-events.md
+++ b/doc/run-log-events.md
@@ -343,6 +343,12 @@ the enclosing workspace task. The original error and restore safety policy are
unchanged. These lines stay in the instance run log and its configured durable
storage, and are not new first-party telemetry events.
+Native sandbox `environmentSyncOut` errors preserve allowlisted error codes and
+bounded HTTP/exit statuses across worker RPC for this diagnostic line. The host
+revalidates the envelope and keeps the original failure and recovery policy.
+Provider messages, paths, response bodies, credentials, and arbitrary error data
+are not copied into the new envelope. Older workers can still report `unknown`.
+
The optional `step` identifies the failed restore operation. For
`phase=workspace` and `step=git_integration`, `gitCommand` identifies one fixed
command family (`rev_parse`, `symbolic_ref`, `merge_base`, `merge_tree`,
diff --git a/packages/plugins/sdk/src/environment-sync-error.ts b/packages/plugins/sdk/src/environment-sync-error.ts
new file mode 100644
index 0000000000..0450310a07
--- /dev/null
+++ b/packages/plugins/sdk/src/environment-sync-error.ts
@@ -0,0 +1,58 @@
+/** Diagnostic evidence only. Never use this envelope to authorize cleanup or retry. */
+export interface PluginEnvironmentSyncErrorDiagnostic {
+ errorCode: string;
+ httpStatus?: number;
+ exitCode?: number;
+}
+
+const SCHEMA = "paperclip/environment-sync-error/v1";
+// Match the host's workspace restore diagnostic allowlist. Both sides validate
+// independently: plugin-supplied data must never widen the host's log surface.
+const ERROR_CODES = new Set([
+ "ENOENT", "EACCES", "EPERM", "ENOSPC", "EIO", "EXDEV", "ENOTDIR", "EISDIR",
+ "ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE", "ENOTFOUND", "EAI_AGAIN",
+ "ABORT_ERR", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET",
+]);
+
+function field(value: unknown, key: string): unknown {
+ try { return value && typeof value === "object" ? (value as Record<string, unknown>)[key] : undefined; }
+ catch { return undefined; }
+}
+
+function integer(value: unknown, minimum: number, maximum: number): number | undefined {
+ return typeof value === "number" && Number.isInteger(value) && value >= minimum && value <= maximum
+ ? value : undefined;
+}
+
+function sanitize(value: unknown): PluginEnvironmentSyncErrorDiagnostic | undefined {
+ const code = field(value, "errorCode");
+ const errorCode = typeof code === "string" && ERROR_CODES.has(code) ? code : "unknown";
+ const httpStatus = integer(field(value, "httpStatus"), 400, 599);
+ const exitCode = integer(field(value, "exitCode"), 1, 255);
+ if (errorCode === "unknown" && httpStatus === undefined && exitCode === undefined) return undefined;
+ return { errorCode, ...(httpStatus !== undefined ? { httpStatus } : {}), ...(exitCode !== undefined ? { exitCode } : {}) };
+}
+
+/** Capture known codes and numbers, never arbitrary error data, text, or names. */
+export function environmentSyncErrorData(error: unknown): unknown {
+ const diagnostic: PluginEnvironmentSyncErrorDiagnostic = { errorCode: "unknown" };
+ let current = error;
+ // Bound nested SDK causes, including cyclic errors and throwing getters.
+ for (let depth = 0; depth < 4 && current && typeof current === "object"; depth++) {
+ const code = field(current, "code");
+ if (diagnostic.errorCode === "unknown" && typeof code === "string" && ERROR_CODES.has(code)) diagnostic.errorCode = code;
+ diagnostic.httpStatus ??= integer(field(current, "status"), 400, 599)
+ ?? integer(field(current, "statusCode"), 400, 599)
+ ?? integer(field(field(current, "response"), "status"), 400, 599);
+ diagnostic.exitCode ??= integer(field(current, "exitCode"), 1, 255) ?? integer(code, 1, 255);
+ current = field(current, "cause");
+ }
+ const safe = sanitize(diagnostic);
+ return safe ? { schema: SCHEMA, diagnostic: safe } : undefined;
+}
+
+/** Revalidate the worker envelope before adapting it into host-only diagnostics. */
+export function readEnvironmentSyncErrorDiagnostic(error: unknown): PluginEnvironmentSyncErrorDiagnostic | undefined {
+ const data = field(error, "data");
+ return field(data, "schema") === SCHEMA ? sanitize(field(data, "diagnostic")) : undefined;
+}
diff --git a/packages/plugins/sdk/src/index.ts b/packages/plugins/sdk/src/index.ts
index b834be1a60..7610aaa9a1 100644
--- a/packages/plugins/sdk/src/index.ts
+++ b/packages/plugins/sdk/src/index.ts
@@ -452,5 +452,7 @@ export {
export { PluginEnvironmentCreationCleanupError, environmentCreationCleanupErrorData, readEnvironmentCreationCleanupError } from "./environment-creation-cleanup.js";
export type { PluginEnvironmentCreationCleanup } from "./environment-creation-cleanup.js";
+export { readEnvironmentSyncErrorDiagnostic } from "./environment-sync-error.js";
+export type { PluginEnvironmentSyncErrorDiagnostic } from "./environment-sync-error.js";
export type { AiConnectionPool, AiConnectionPoolConfig, AiConnectionPoolMember, AiConnectionRouterRequest, AiConnectionRouterResult, AiConnectionRouterSelection } from "@paperclipai/shared";
diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts
index 6684f8fdd1..786e71954f 100644
--- a/packages/plugins/sdk/src/worker-rpc-host.ts
+++ b/packages/plugins/sdk/src/worker-rpc-host.ts
@@ -1,5 +1,6 @@
import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared";
import { environmentCreationCleanupErrorData } from "./environment-creation-cleanup.js";
+import { environmentSyncErrorData } from "./environment-sync-error.js";
/**
* Worker-side RPC host — runs inside the child process spawned by the host.
*
@@ -1581,7 +1582,8 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
sendMessage(createErrorResponse(id, errorCode, errorMessage,
method === "environmentAcquireLease" || method === "environmentDestroyLease"
- ? environmentCreationCleanupErrorData(err) : undefined));
+ ? environmentCreationCleanupErrorData(err)
+ : method === "environmentSyncOut" ? environmentSyncErrorData(err) : undefined));
}
}
diff --git a/packages/plugins/sdk/tests/environment-sync-error.test.ts b/packages/plugins/sdk/tests/environment-sync-error.test.ts
new file mode 100644
index 0000000000..26d9805493
--- /dev/null
+++ b/packages/plugins/sdk/tests/environment-sync-error.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from "vitest";
+import { environmentSyncErrorData, readEnvironmentSyncErrorDiagnostic } from "../src/environment-sync-error.js";
+
+const schema = "paperclip/environment-sync-error/v1";
+
+describe("environment sync diagnostic envelope", () => {
+ it("keeps only known codes and bounded numbers from nested provider errors", () => {
+ const error = Object.assign(new Error("private-message"), {
+ name: "private-name", code: "private-code", path: "/private-path",
+ response: { status: 503, data: { token: "private-token" } },
+ data: { credentials: "private-credentials" },
+ cause: { code: "ECONNRESET", exitCode: 7, stderr: "private-output" },
+ });
+ const data = environmentSyncErrorData(error);
+ expect(data).toEqual({ schema, diagnostic: { errorCode: "ECONNRESET", httpStatus: 503, exitCode: 7 } });
+ expect(JSON.stringify(data)).not.toContain("private-");
+ expect(readEnvironmentSyncErrorDiagnostic({ data })).toEqual({ errorCode: "ECONNRESET", httpStatus: 503, exitCode: 7 });
+ });
+
+ it.each([undefined, null, "private-error", { code: "PRIVATE_TOKEN" }, { status: 600 }, { status: 399 },
+ { statusCode: "503" }, { status: 500.5 }, { exitCode: 0 }, { exitCode: 256 }, { code: -32001 },
+ { exitCode: Infinity }, { data: { schema, diagnostic: { errorCode: "EACCES" } } },
+ ])("omits unrecognized or unbounded provider values: %j", (error) => {
+ expect(environmentSyncErrorData(error)).toBeUndefined();
+ });
+
+ it("bounds cyclic causes and ignores throwing getters without changing the error", () => {
+ const error = Object.defineProperties({ statusCode: 429 } as Record<string, unknown>, {
+ code: { get() { throw new Error("private-code"); } },
+ response: { get() { throw new Error("private-response"); } },
+ });
+ error.cause = error;
+ expect(environmentSyncErrorData(error)).toEqual({ schema, diagnostic: { errorCode: "unknown", httpStatus: 429 } });
+ const wrap = (cause: unknown) => ({ cause });
+ expect(environmentSyncErrorData(wrap(wrap(wrap({ code: "EIO" }))))).toEqual({ schema, diagnostic: { errorCode: "EIO" } });
+ expect(environmentSyncErrorData(wrap(wrap(wrap(wrap({ code: "EIO" })))))).toBeUndefined();
+ });
+
+ it("revalidates worker fields and ignores arbitrary payload and protocol versions", () => {
+ expect(readEnvironmentSyncErrorDiagnostic({ data: { schema, diagnostic: {
+ errorCode: "EACCES", httpStatus: 403, exitCode: 1.5,
+ message: "private-message", path: "/private-path", credentials: "private-token",
+ } } })).toEqual({ errorCode: "EACCES", httpStatus: 403 });
+ expect(readEnvironmentSyncErrorDiagnostic({ data: { schema: "other", diagnostic: { errorCode: "EACCES" } } })).toBeUndefined();
+ expect(readEnvironmentSyncErrorDiagnostic({ data: { schema, diagnostic: { errorCode: "private-token", httpStatus: 900 } } })).toBeUndefined();
+ expect(readEnvironmentSyncErrorDiagnostic(Object.defineProperty({}, "data", { get() { throw new Error("private"); } }))).toBeUndefined();
+ });
+});
diff --git a/server/src/__tests__/environment-sync-out-error.test.ts b/server/src/__tests__/environment-sync-out-error.test.ts
new file mode 100644
index 0000000000..36407d2453
--- /dev/null
+++ b/server/src/__tests__/environment-sync-out-error.test.ts
@@ -0,0 +1,78 @@
+import { createInterface } from "node:readline";
+import { PassThrough } from "node:stream";
+import { describe, expect, it } from "vitest";
+import {
+ createRequest, definePlugin, isJsonRpcResponse, JsonRpcCallError, parseMessage,
+ PLUGIN_RPC_ERROR_CODES, serializeMessage, startWorkerRpcHost, type JsonRpcResponse,
+} from "@paperclipai/plugin-sdk";
+import {
+ getWorkspaceRestoreDiagnostic, withWorkspaceRestoreDiagnostics, withWorkspaceRestoreStep,
+} from "@paperclipai/adapter-utils/workspace-restore-diagnostics";
+import { preserveEnvironmentSyncOutErrorDiagnostic } from "../services/environment-sync-out-error.js";
+
+async function roundTrip(method: string, error: unknown): Promise<{ error: JsonRpcCallError; wire: string }> {
+ const stdin = new PassThrough();
+ const stdout = new PassThrough();
+ const lines = createInterface({ input: stdout });
+ const worker = startWorkerRpcHost({ stdin, stdout, plugin: definePlugin({
+ async setup() {},
+ async onEnvironmentSyncOut() { throw error; },
+ async onEnvironmentSyncIn() { throw error; },
+ async onEnvironmentExecute() { throw error; },
+ }) });
+ try {
+ const response = new Promise<{ message: JsonRpcResponse; wire: string }>((resolve) => {
+ lines.on("line", (wire) => {
+ const message = parseMessage(wire);
+ if (isJsonRpcResponse(message)) resolve({ message, wire });
+ });
+ });
+ stdin.write(serializeMessage(createRequest(method, {}, "sync-out-test")));
+ const { message, wire } = await response;
+ if (!("error" in message) || !message.error) throw new Error("Expected RPC failure");
+ return { error: new JsonRpcCallError(message.error), wire };
+ } finally {
+ worker.stop(); lines.close(); stdin.destroy(); stdout.destroy();
+ }
+}
+
+describe("environment sync-out restore diagnostics", () => {
+ it("retains bounded evidence through the real worker RPC roundtrip and host restore classifier", async () => {
+ const failure = Object.assign(new Error("Workspace export failed"), {
+ name: "private-provider-class", code: "ETIMEDOUT", statusCode: 504,
+ response: { data: { apiKey: "private-token" } }, path: "/private-path",
+ cause: new Error("private-cause"), data: { credentials: "private-credentials" },
+ });
+ const { error, wire } = await roundTrip("environmentSyncOut", failure);
+ expect(wire).not.toContain("private-");
+ expect(wire.length).toBeLessThan(400);
+ expect(error.code).toBe(PLUGIN_RPC_ERROR_CODES.WORKER_ERROR);
+ expect(error.message).toBe(failure.message);
+ const before = structuredClone({ message: error.message, code: error.code, data: error.data });
+ const logs: string[] = [];
+ await expect(withWorkspaceRestoreDiagnostics("workspace", () => withWorkspaceRestoreStep("workspace_transfer", async () => {
+ throw preserveEnvironmentSyncOutErrorDiagnostic(error);
+ }), async (line) => { logs.push(line); })).rejects.toBe(error);
+ expect(getWorkspaceRestoreDiagnostic(error)).toEqual({ phase: "workspace", step: "workspace_transfer", errorCode: "ETIMEDOUT", httpStatus: 504 });
+ expect(logs).toEqual(['[paperclip] Workspace restore diagnostic: {"phase":"workspace","step":"workspace_transfer","errorCode":"ETIMEDOUT","httpStatus":504}\n']);
+ expect({ message: error.message, code: error.code, data: error.data }).toEqual(before);
+ expect(error).not.toHaveProperty("cause");
+ });
+
+ it.each(["environmentSyncIn", "environmentExecute"])("does not add the sync-out envelope to %s", async (method) => {
+ const { error } = await roundTrip(method, Object.assign(new Error("Provider failure"), { code: "EACCES", status: 503 }));
+ expect(error.data).toBeUndefined();
+ expect(preserveEnvironmentSyncOutErrorDiagnostic(error)).toBe(error);
+ expect(getWorkspaceRestoreDiagnostic(error)).toBeUndefined();
+ });
+
+ it("keeps old workers and unknown diagnostics compatible without changing policy fields", async () => {
+ const { error } = await roundTrip("environmentSyncOut", new Error("daytona_sandbox_not_found"));
+ expect(error.data).toBeUndefined();
+ expect(preserveEnvironmentSyncOutErrorDiagnostic(error)).toBe(error);
+ expect(error.message).toBe("daytona_sandbox_not_found");
+ const original = Object.freeze(new JsonRpcCallError({ code: -32001, message: "Existing worker failure" }));
+ expect(preserveEnvironmentSyncOutErrorDiagnostic(original)).toBe(original);
+ expect(preserveEnvironmentSyncOutErrorDiagnostic(null)).toBeNull();
+ });
+});
diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts
index 4105ec6642..07ba10ebe4 100644
--- a/server/src/services/environment-runtime.ts
+++ b/server/src/services/environment-runtime.ts
@@ -1,5 +1,6 @@
import { hasStopOnlyCleanup, prepareSandboxStopAndRetain, readStopOnlyCleanup, settleStopOnlyCleanup, stopOnlyCleanupKey } from "./sandbox-stop-and-retain.js";
import { readEnvironmentCreationCleanupError } from "@paperclipai/plugin-sdk";
+import { preserveEnvironmentSyncOutErrorDiagnostic } from "./environment-sync-out-error.js";
import { remoteTerminationReceipt } from "./remote-execution-termination.js";
import { hasNativeWorkspaceExportResume, releaseCompletedNativeWorkspaceExportRetention } from "./native-runtime/native-workspace-export-resume.js";
import { createHash, randomUUID } from "node:crypto";
@@ -1812,7 +1813,9 @@ function createSandboxEnvironmentDriver(
expiresAt: input.lease.expiresAt?.toISOString() ?? null,
},
operations: input.operations,
- }, resolvePluginSandboxRpcTimeoutMs(sanitizedConfig));
+ }, resolvePluginSandboxRpcTimeoutMs(sanitizedConfig)).catch((error: unknown) => {
+ throw method === "environmentSyncOut" ? preserveEnvironmentSyncOutErrorDiagnostic(error) : error;
+ });
}
return {
diff --git a/server/src/services/environment-sync-out-error.ts b/server/src/services/environment-sync-out-error.ts
new file mode 100644
index 0000000000..f9574f696a
--- /dev/null
+++ b/server/src/services/environment-sync-out-error.ts
@@ -0,0 +1,15 @@
+import { readEnvironmentSyncErrorDiagnostic } from "@paperclipai/plugin-sdk";
+import { preserveWorkspaceRestoreErrorDiagnostic } from "@paperclipai/adapter-utils/workspace-restore-diagnostics";
+
+/** Keep the original RPC failure and policy fields; add only private diagnostic evidence. */
+export function preserveEnvironmentSyncOutErrorDiagnostic(error: unknown): unknown {
+ const diagnostic = readEnvironmentSyncErrorDiagnostic(error);
+ if (diagnostic && error && typeof error === "object") {
+ preserveWorkspaceRestoreErrorDiagnostic(error, {
+ code: diagnostic.errorCode,
+ status: diagnostic.httpStatus,
+ exitCode: diagnostic.exitCode,
+ });
+ }
+ return error;
+}