diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 2fc0f508f02..fbab031df90 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -345,6 +345,27 @@ Allow additional private hostnames (for example custom Tailscale hostnames): npx paperclipai allowed-hostname dotta-macbook-pro ``` +## Wake payload process transport + +Process adapters keep `PAPERCLIP_WAKE_PAYLOAD_JSON` inline up to 64 KiB of +UTF-8 data (including shell quoting overhead for remote launches). Larger values are written without modification to a private file +on the execution host. The child receives `PAPERCLIP_WAKE_PAYLOAD_PATH` instead +of the JSON variable. Consumers must support both forms. Prompt rendering and +gateway request serialization remain unchanged. + +Local files use a unique temporary directory (0700) and file (0600). Confined +local processes receive a read-only mount of that file. SSH and sandbox launches +upload bounded chunks into an exclusively created directory, then verify the +byte count before starting the child. Failed uploads prevent launch. The process +or ACP turn owns cleanup, including startup failure and cancellation paths. ACP +prompts name the current turn's file so a resumed process cannot select an old +wake from its initial environment. Invocation logs record payload size only. + +The files are temporary run data, not durable context. An abrupt host or worker +crash can leave a private temporary directory for the host's normal temporary +file cleanup. This transport does not bound other environment variables or CLI +prompt arguments, and does not apply to hosted SDK or gateway request bodies. + ## Test Commands Use the cheap local default unless you are specifically working on browser flows: diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts index 0b52c22e171..8c105c8cd24 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.test.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts @@ -132,11 +132,11 @@ function createLocalSandboxRunner( function buildRuntime( onSetConfigOption?: (input: { key: string; value: string }) => void, - onEnsureSession?: (input: Record) => void, + onEnsureSession?: (input: Record) => unknown, ) { return { ensureSession: async (input: Record) => { - onEnsureSession?.(input); + await onEnsureSession?.(input); return ({ backendSessionId: "backend-session", agentSessionId: "agent-session", @@ -168,6 +168,7 @@ async function runExecutor( runtimeMcp?: AdapterRuntimeMcpAccess; prepareRemoteManagedHome?: AcpxEngineExecutorOptions["prepareRemoteManagedHome"]; startupTraceContext?: AdapterExecutionContext["startupTraceContext"]; + inspectSession?: (input: Record) => Promise; } = {}, ) { const runtimeOptions: Record[] = []; @@ -180,11 +181,11 @@ async function runExecutor( ...(options.prepareRemoteManagedHome ? { prepareRemoteManagedHome: options.prepareRemoteManagedHome } : {}), - createRuntime: (options) => { - runtimeOptions.push(options as unknown as Record); + createRuntime: (runtimeConfig) => { + runtimeOptions.push(runtimeConfig as unknown as Record); return buildRuntime( ({ key, value }) => configOptions.push({ key, value }), - (input) => sessionInputs.push(input), + async (input) => { sessionInputs.push(input); await options.inspectSession?.(input); }, ) as never; }, }); @@ -369,6 +370,54 @@ const ALLOWED_TURN_SPAN_ATTRIBUTE_KEYS = new Set([ ]); describe("shared ACPX engine runtime behavior", () => { + it("removes the oversized wake file when ACP initialization fails", async () => { + const root = await makeTempRoot(); + let filePath = ""; + const execute = createAcpxEngineExecutor({ createRuntime: () => ({ + ...buildRuntime(), + ensureSession: async (input: { sessionOptions: { env: Record } }) => { + filePath = input.sessionOptions.env.PAPERCLIP_WAKE_PAYLOAD_PATH!; + expect(await fs.readFile(filePath, "utf8")).toContain("complete description"); + throw new Error("synthetic initialization failure"); + }, + }) as never }); + const result = await execute({ + runId: "failed-wake-init", agent: { id: "agent-1", companyId: "company-1" }, runtime: {}, + config: { agent: "custom", agentCommand: "node ./fake-acp.js", cwd: root, stateDir: path.join(root, "state") }, + context: { paperclipWake: { issue: { id: "issue-1", description: "complete description ".repeat(40_000) } } }, + onLog: async () => {}, onMeta: async () => {}, + } as never); + expect(result.errorCode).toBe("acpx_session_init_failed"); + expect(filePath).not.toBe(""); + await expect(fs.stat(path.dirname(filePath))).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("delivers the full oversized wake during ACP initialization and cleans it up after each resumed turn", async () => { + const root = await makeTempRoot(); + const config = { agent: "custom", agentCommand: "node ./fake-acp.js", cwd: root, stateDir: path.join(root, "state") }; + let sessionParams: unknown; + const paths: string[] = []; + for (const marker of ["first", "resumed"]) { + const description = marker + "🙂 complete context ".repeat(40_000); + const run = await runExecutor(config, { + runtime: sessionParams ? { sessionParams } : {}, + context: { taskId: "issue-1", paperclipWake: { issue: { id: "issue-1", identifier: "TEST-1", description } } }, + inspectSession: async (input) => { + const env = (input.sessionOptions as { env: Record }).env; + expect(env.PAPERCLIP_WAKE_PAYLOAD_JSON).toBeUndefined(); + const filePath = env.PAPERCLIP_WAKE_PAYLOAD_PATH!; + paths.push(filePath); + expect(JSON.parse(await fs.readFile(filePath, "utf8")).issue.description).toBe(description); + }, + }); + sessionParams = run.result.sessionParams; + expect(String(run.meta[0]?.prompt)).toContain(JSON.stringify(paths.at(-1))); + expect(String(run.meta[0]?.prompt)).toContain("takes precedence over any older wake environment"); + await expect(fs.stat(paths.at(-1)!)).rejects.toMatchObject({ code: "ENOENT" }); + } + expect(new Set(paths).size).toBe(2); + }); + it.each(["claude", "codex", "gemini", "kimi", "custom"])("defaults the legacy %s engine to full auto on fresh and resumed runs", async (agent) => { const root = await makeTempRoot(); const config = { diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts index 509a8dfb16d..8a3137e9cd1 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.ts @@ -21,6 +21,7 @@ import { formatAdapterExecutionTimeoutErrorMessage, formatAdapterExecutionTimeoutStartLogLine, prepareAdapterExecutionTargetRuntime, + prepareAdapterWakePayloadEnv, readAdapterExecutionTarget, resolveAdapterExecutionTargetTimeout, resolveReferencedSourceIgnore, @@ -76,6 +77,7 @@ import { type PaperclipSkillEntry, } from "@paperclipai/adapter-utils/server-utils"; import { shellQuote } from "@paperclipai/adapter-utils/ssh"; +import { renderWakePayloadFileNote, type WakePayloadDelivery } from "../wake-payload-env.js"; import { createAcpRuntime, createAgentRegistry, @@ -429,6 +431,7 @@ export interface AcpxEngineExecutorOptions { } interface AcpxPreparedRuntime { + wakePayloadDelivery: WakePayloadDelivery; acpxAgent: string; coalescePlaceholderToolUpdates: boolean; mode: "persistent" | "oneshot"; @@ -2433,8 +2436,13 @@ async function buildRuntime(input: { let paperclipBridge: AdapterExecutionTargetPaperclipBridgeHandle | null = null; let processSessionBridge: AdapterExecutionTargetProcessSessionBridgeHandle | null = null; let runtimeEnv: Record = {}; + let wakePayloadDelivery: WakePayloadDelivery | null = null; const startTransportStart = nowMs(); try { + wakePayloadDelivery = await prepareAdapterWakePayloadEnv(useRemoteProcessSession ? executionTarget : null, env); + delete env.PAPERCLIP_WAKE_PAYLOAD_JSON; + delete env.PAPERCLIP_WAKE_PAYLOAD_PATH; + Object.assign(env, wakePayloadDelivery.env); if (useRemoteProcessSession && sandboxSite) { // The sandbox run site brings up both host-side bridges concurrently, keeps // the one paperclip-env → process-session-launch dependency at a single @@ -2464,6 +2472,7 @@ async function buildRuntime(input: { const startedControl = sandboxSite?.controlBridge ?? paperclipBridge; const startedAgent = sandboxSite?.agentBridge ?? processSessionBridge; await Promise.allSettled([startedControl?.stop(), startedAgent?.stop()]); + await wakePayloadDelivery?.cleanup().catch(() => {}); // The staged home / copy-back teardown must run even if a bridge fails to // start after the workspace + managed home were already staged into the // sandbox, so a refreshed credential is copied back on this error path too. @@ -2506,6 +2515,7 @@ async function buildRuntime(input: { }); return { + wakePayloadDelivery, acpxAgent, coalescePlaceholderToolUpdates, mode, @@ -3008,6 +3018,7 @@ async function buildPrompt(ctx: AdapterExecutionContext, resumedSession: boolean : renderTemplate(promptTemplate, templateData); const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim(); const paperclipEnvNote = externalChatTurn ? "" : renderPaperclipEnvNote(env); + const wakePayloadFileNote = externalChatTurn ? "" : renderWakePayloadFileNote(env); const apiAccessNote = externalChatTurn ? "" : renderApiAccessNote(env); const prompt = joinPromptSections([ promptInstructionsPrefix, @@ -3016,6 +3027,7 @@ async function buildPrompt(ctx: AdapterExecutionContext, resumedSession: boolean sessionHandoffNote, taskContextNote, paperclipEnvNote, + wakePayloadFileNote, apiAccessNote, renderedPrompt, ]); @@ -3030,7 +3042,7 @@ async function buildPrompt(ctx: AdapterExecutionContext, resumedSession: boolean wakePromptChars: wakePrompt.length, sessionHandoffChars: sessionHandoffNote.length, taskContextChars: taskContextNote.length, - runtimeNoteChars: paperclipEnvNote.length + apiAccessNote.length, + runtimeNoteChars: paperclipEnvNote.length + wakePayloadFileNote.length + apiAccessNote.length, heartbeatPromptChars: renderedPrompt.length, }, }; @@ -3927,6 +3939,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { // null on the host lane (no staging) and on a build failure (where // `buildRuntime` already released its own partial lease). let releaseStagingLease: (() => void) | null = null; + let wakePayloadDelivery: WakePayloadDelivery | null = null; let stopTimer: ReturnType | undefined; let removeStopListener: (() => void) | undefined; // Unregisters the sandbox duplex bridge's loss listener (below, in @@ -4155,6 +4168,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { // Capture acquired resources before the cancellation boundary so the // normal settlement path also releases a just-completed build. releaseStagingLease = prepared.sessionStagingLeaseRelease; + wakePayloadDelivery = prepared.wakePayloadDelivery; } finally { await startupCancellation.finish(); } @@ -5430,6 +5444,9 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) { return await runAttempt(plan); } finally { clearTimeout(stopTimer); + await (wakePayloadDelivery as WakePayloadDelivery | null)?.cleanup().catch(async () => { + await ctx.onLog("stderr", "[paperclip] Could not remove the wake payload file after the turn ended.\n").catch(() => {}); + }); removeStopListener?.(); removeLossListener?.(); clearTimeout(lossDeadlineTimer); diff --git a/packages/adapter-utils/src/execution-target-sandbox.test.ts b/packages/adapter-utils/src/execution-target-sandbox.test.ts index 36695e85c1b..6504ae8d077 100644 --- a/packages/adapter-utils/src/execution-target-sandbox.test.ts +++ b/packages/adapter-utils/src/execution-target-sandbox.test.ts @@ -574,6 +574,43 @@ describe("sandbox adapter execution targets", () => { } }); + it.each([false, true])("delivers an oversized wake file through the real session wrapper (streamed=%s)", async (streamOutputViaSession) => { + const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-wake-session-")); + cleanupDirs.push(rootDir); + const payload = JSON.stringify({ description: "full 🙂 wake history ".repeat(40_000) }); + const childPath = path.join(rootDir, "child.mjs"); + await writeFile(childPath, `import fs from 'node:fs'; + const p = process.env.PAPERCLIP_WAKE_PAYLOAD_PATH; + process.stdout.write(JSON.stringify({ path: p, payload: fs.readFileSync(p, 'utf8'), inline: process.env.PAPERCLIP_WAKE_PAYLOAD_JSON ?? null }));`); + const delegate = createLocalSandboxRunner(); + const bridge = await startAdapterExecutionTargetProcessSessionBridge({ + runId: "large-wake-session", adapterKey: "acpx", runtimeRootDir: rootDir, + target: { kind: "remote", transport: "sandbox", remoteCwd: rootDir, runner: { + execute: async (input) => { + for (const value of [...(input.args ?? []), ...Object.values(input.env ?? {})]) { + expect(Buffer.byteLength(value)).toBeLessThan(128 * 1024); + } + return delegate.execute(input); + }, + } }, + command: process.execPath, args: [childPath], cwd: rootDir, + env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, timeoutSec: 10, streamOutputViaSession, + }); + let filePath = ""; + try { + const result = await runProxyWithInput(bridge!.agentCommand, "", true); + expect(result.code).toBe(0); + const received = JSON.parse(result.stdout); + expect(received.payload).toBe(payload); + expect(received.inline).toBeNull(); + filePath = received.path; + expect(await readFile(filePath, "utf8")).toBe(payload); + } finally { + await bridge?.stop(); + } + await expect(stat(path.dirname(filePath))).rejects.toMatchObject({ code: "ENOENT" }); + }, 30_000); + it("logs a streamed wrapper launch failure before forwarding its exit", async () => { const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-wrapper-launch-error-")); cleanupDirs.push(rootDir); diff --git a/packages/adapter-utils/src/execution-target.ts b/packages/adapter-utils/src/execution-target.ts index f67d01aad42..6f790f39c26 100644 --- a/packages/adapter-utils/src/execution-target.ts +++ b/packages/adapter-utils/src/execution-target.ts @@ -80,6 +80,7 @@ import { type TerminalResultCleanupOptions, } from "./server-utils.js"; import { sanitizeRemoteExecutionEnv } from "./remote-execution-env.js"; +import { prepareWakePayloadEnv, type WakePayloadDelivery } from "./wake-payload-env.js"; import { preferredShellForSandbox, shellCommandArgs } from "./sandbox-shell.js"; import { runWithRuntimeParent, @@ -706,6 +707,11 @@ export async function ensureAdapterExecutionTargetCommandResolvable( env: NodeJS.ProcessEnv, options: { installCommand?: string | null; timeoutSec?: number | null } = {}, ) { + // A command lookup never consumes wake context. Do not forward a large + // payload (or a previous turn's file) through the provider's probe launch. + env = { ...env }; + delete env.PAPERCLIP_WAKE_PAYLOAD_JSON; + delete env.PAPERCLIP_WAKE_PAYLOAD_PATH; if (target?.kind === "remote" && target.transport === "sandbox") { await ensureSandboxCommandResolvable( command, @@ -857,6 +863,47 @@ export async function runAdapterExecutionTargetProcess( command: string, args: string[], options: AdapterExecutionTargetProcessOptions, +): Promise { + if (target?.kind !== "remote" || target.transport !== "sandbox") { + return runAdapterExecutionTargetProcessWithPreparedEnv(runId, target, command, args, options); + } + const delivery = await prepareAdapterWakePayloadEnv(target, options.env); + try { + return await runAdapterExecutionTargetProcessWithPreparedEnv(runId, target, command, args, { ...options, env: delivery.env }); + } finally { + await delivery.cleanup().catch(async () => { + await options.onLog("stderr", "[paperclip] Could not remove the wake payload file after the process ended.\n").catch(() => {}); + }); + } +} + +/** Prepare on the host where the provider process actually runs. */ +export async function prepareAdapterWakePayloadEnv( + target: AdapterExecutionTarget | null | undefined, + env: Record, +): Promise { + if (target?.kind !== "remote") return prepareWakePayloadEnv(env); + if (target.transport === "ssh") { + return prepareWakePayloadEnv(env, async (script) => + (await runSshCommand(target.spec, script, { timeoutMs: 30_000, maxBuffer: 64 * 1024 })).stdout); + } + const runner = requireSandboxRunner(target); + return prepareWakePayloadEnv(env, async (script) => { + const result = await runner.execute({ + command: "sh", args: ["-c", script], cwd: target.remoteCwd, + timeoutMs: 30_000, bypassSession: true, + }); + if (result.timedOut || result.exitCode !== 0) throw new Error("Wake payload file operation failed."); + return result.stdout; + }); +} + +async function runAdapterExecutionTargetProcessWithPreparedEnv( + runId: string, + target: AdapterExecutionTarget | null | undefined, + command: string, + args: string[], + options: AdapterExecutionTargetProcessOptions, ): Promise { if (target?.kind === "remote" && target.transport === "sandbox") { const runner = requireSandboxRunner(target); @@ -1932,7 +1979,35 @@ const AGENT_SESSION_SEND_INPUT_SPAN = "sandbox.agentSession.sendInput"; * file found (`1 + 2n` execs). */ const AGENT_SESSION_POLL_OUTPUT_SPAN = "sandbox.agentSession.pollOutput"; -export async function startAdapterExecutionTargetProcessSessionBridge(input: { +export async function startAdapterExecutionTargetProcessSessionBridge( + input: Parameters[0], +): Promise { + let delivery: WakePayloadDelivery | null = null; + const cleanup = async () => { + await delivery?.cleanup().catch(async () => { + await input.onLog?.("stderr", "[paperclip] Could not remove the wake payload file after the session ended.\n").catch(() => {}); + }); + }; + try { + const bridge = await startProcessSessionBridgeWithPreparedEnv({ + ...input, + env: async () => { + const env = typeof input.env === "function" ? await input.env() : input.env; + delivery = await prepareAdapterWakePayloadEnv(input.target, env); + return delivery.env; + }, + }); + if (!bridge) { await cleanup(); return null; } + return { ...bridge, stop: async () => { + try { await bridge.stop(); } finally { await cleanup(); } + } }; + } catch (error) { + await cleanup(); + throw error; + } +} + +async function startProcessSessionBridgeWithPreparedEnv(input: { runId: string; target: AdapterExecutionTarget | null | undefined; runtimeRootDir: string | null | undefined; diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.ts index e45d008f8fe..061027b5aa1 100644 --- a/packages/adapter-utils/src/server-utils.ts +++ b/packages/adapter-utils/src/server-utils.ts @@ -10,7 +10,8 @@ import { buildLocalProcessSandboxSpawnTarget, type LocalProcessSandboxOptions, } from "./local-process-sandbox.js"; -import { buildSshSpawnTarget, type SshRemoteExecutionSpec } from "./ssh.js"; +import { buildSshSpawnTarget, runSshCommand, type SshRemoteExecutionSpec } from "./ssh.js"; +import { prepareWakePayloadEnv } from "./wake-payload-env.js"; import { redactCommandText } from "./command-redaction.js"; import { paperclipChatFilePreparationDelivery } from "./chat-file-delivery.js"; import { @@ -165,7 +166,7 @@ export function isPaperclipRuntimeEnvKey(key: string): boolean { // Other PAPERCLIP_*-named config keys are allowed as long as Paperclip has // not assigned the same key for the run (runtime vars always win). export function isForbiddenConfigEnvKey(key: string): boolean { - return key === "PAPERCLIP_API_KEY"; + return key === "PAPERCLIP_API_KEY" || key === "PAPERCLIP_WAKE_PAYLOAD_PATH"; } const PAPERCLIP_SKILL_ROOT_RELATIVE_CANDIDATES = [ "../../skills", @@ -3069,6 +3070,10 @@ export function redactEnvForLogs( ): Record { const redacted: Record = {}; for (const [key, value] of Object.entries(env)) { + if (key === "PAPERCLIP_WAKE_PAYLOAD_JSON") { + redacted[key] = `[wake payload: ${Buffer.byteLength(value, "utf8")} bytes]`; + continue; + } redacted[key] = SENSITIVE_ENV_KEY.test(key) ? REDACTED_LOG_VALUE : value; } return redacted; @@ -4572,6 +4577,34 @@ export async function ensureCommandResolvable( } export async function runChildProcess( + runId: string, + command: string, + args: string[], + opts: Parameters[3], +): Promise { + const remote = opts.remoteExecution; + const delivery = await prepareWakePayloadEnv(opts.env, remote + ? async (script) => (await runSshCommand(remote, script, { timeoutMs: 30_000, maxBuffer: 64 * 1024 })).stdout + : undefined); + try { + return await runChildProcessWithPreparedEnv(runId, command, args, { + ...opts, + env: delivery.env, + localProcessSandbox: opts.localProcessSandbox && delivery.filePath && !remote + ? { ...opts.localProcessSandbox, managedPaths: [ + ...(opts.localProcessSandbox.managedPaths ?? []), + { path: delivery.filePath, access: "ro" }, + ] } + : opts.localProcessSandbox, + }); + } finally { + await delivery.cleanup().catch(async () => { + await opts.onLog("stderr", "[paperclip] Could not remove the wake payload file after the process ended.\n").catch(() => {}); + }); + } +} + +async function runChildProcessWithPreparedEnv( runId: string, command: string, args: string[], diff --git a/packages/adapter-utils/src/ssh-fixture.test.ts b/packages/adapter-utils/src/ssh-fixture.test.ts index c9c7657f564..2ba21f8b843 100644 --- a/packages/adapter-utils/src/ssh-fixture.test.ts +++ b/packages/adapter-utils/src/ssh-fixture.test.ts @@ -1,4 +1,5 @@ import { execFile, spawn } from "node:child_process"; +import { createHash } from "node:crypto"; import { mkdir, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises"; import net from "node:net"; import os from "node:os"; @@ -19,6 +20,7 @@ import { type SshEnvLabFixtureState, } from "./ssh.js"; import { prepareRemoteManagedRuntime } from "./remote-managed-runtime.js"; +import { runChildProcess } from "./server-utils.js"; const SSH_FIXTURE_TEST_TIMEOUT_MS = 30_000; let sshEnvLabUnsupportedReason: string | null = null; @@ -512,6 +514,27 @@ describe("ssh env-lab fixture", () => { ).rejects.toThrow("Invalid SSH environment variable key: BAD KEY"); }); + it("delivers and removes an oversized wake on the SSH host", async (context) => { + const rootDir = await createFixtureRootDir(); + const started = await startSshEnvLabFixtureOrSkip(path.join(rootDir, "state.json"), "SSH wake payload test"); + if (!started) { context.skip(); return; } + const config = await buildSshEnvLabFixtureConfig(started); + const payload = JSON.stringify({ description: "full 🙂 wake context ".repeat(10_000) }); + const result = await runChildProcess("ssh-wake", process.execPath, ["-e", ` + const fs = require('node:fs'); + const p = process.env.PAPERCLIP_WAKE_PAYLOAD_PATH; + console.log(JSON.stringify({ path: p, digest: require('node:crypto').createHash('sha256').update(fs.readFileSync(p)).digest('hex'), inline: process.env.PAPERCLIP_WAKE_PAYLOAD_JSON ?? null })); + `], { + cwd: rootDir, env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, timeoutSec: 10, graceSec: 1, onLog: async () => {}, + remoteExecution: { ...config, remoteCwd: started.workspaceDir }, + }); + expect(result.exitCode).toBe(0); + const received = JSON.parse(result.stdout); + expect(received.digest).toBe(createHash("sha256").update(payload).digest("hex")); + expect(received.inline).toBeNull(); + await expect(stat(path.dirname(received.path))).rejects.toMatchObject({ code: "ENOENT" }); + }, SSH_FIXTURE_TEST_TIMEOUT_MS); + it("syncs a local directory into the remote fixture workspace", async () => { const rootDir = await createFixtureRootDir(); const statePath = path.join(rootDir, "state.json"); diff --git a/packages/adapter-utils/src/wake-payload-env.test.ts b/packages/adapter-utils/src/wake-payload-env.test.ts new file mode 100644 index 00000000000..ca4e5bfa009 --- /dev/null +++ b/packages/adapter-utils/src/wake-payload-env.test.ts @@ -0,0 +1,160 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { prepareWakePayloadEnv, renderWakePayloadFileNote, WAKE_PAYLOAD_INLINE_MAX_BYTES } from "./wake-payload-env.js"; +import { isForbiddenConfigEnvKey, redactEnvForLogs, runChildProcess } from "./server-utils.js"; +import { runAdapterExecutionTargetProcess } from "./execution-target.js"; + +const exec = promisify(execFile); +const payload = JSON.stringify({ description: "🙂 café\n".repeat(60_000), messages: ["first", "last"] }); +const digest = (value: string) => createHash("sha256").update(value).digest("hex"); +const cleanup: Array<() => Promise> = []; +afterEach(async () => { vi.restoreAllMocks(); await Promise.all(cleanup.splice(0).map((fn) => fn())); }); +const childScript = ` + const fs = require('node:fs'); + const p = process.env.PAPERCLIP_WAKE_PAYLOAD_PATH; + const body = fs.readFileSync(p, 'utf8'); + let stdin = ''; + process.stdin.on('data', c => stdin += c); + process.stdin.on('end', () => console.log(JSON.stringify({ + digest: require('node:crypto').createHash('sha256').update(body).digest('hex'), + path: p, inline: process.env.PAPERCLIP_WAKE_PAYLOAD_JSON ?? null, stdin, + mode: fs.statSync(p).mode & 511, directoryMode: fs.statSync(require('node:path').dirname(p)).mode & 511 + }))); +`; + +describe("lossless wake payload transport", () => { + it("keeps small payload bytes unchanged and measures UTF-8 bytes at the boundary", async () => { + const inline = "é".repeat(WAKE_PAYLOAD_INLINE_MAX_BYTES / 2); + const small = await prepareWakePayloadEnv({ PAPERCLIP_WAKE_PAYLOAD_JSON: inline, PAPERCLIP_WAKE_PAYLOAD_PATH: "/stale" }); + expect(small.env).toEqual({ PAPERCLIP_WAKE_PAYLOAD_JSON: inline }); + expect(small.filePath).toBeNull(); + const large = await prepareWakePayloadEnv({ PAPERCLIP_WAKE_PAYLOAD_JSON: inline + "é" }); + cleanup.push(large.cleanup); + expect(await fs.readFile(large.filePath!, "utf8")).toBe(inline + "é"); + expect(large.env.PAPERCLIP_WAKE_PAYLOAD_JSON).toBeUndefined(); + }); + + it("uses separate private files for overlapping runs and never mutates the input", async () => { + const env = { PAPERCLIP_WAKE_PAYLOAD_JSON: payload, PAPERCLIP_RUN_ID: "same-run-retry" }; + const [first, second] = await Promise.all([prepareWakePayloadEnv(env), prepareWakePayloadEnv(env)]); + cleanup.push(first.cleanup, second.cleanup); + expect(first.filePath).not.toBe(second.filePath); + expect(env).toEqual({ PAPERCLIP_WAKE_PAYLOAD_JSON: payload, PAPERCLIP_RUN_ID: "same-run-retry" }); + await first.cleanup(); + expect(await fs.readFile(second.filePath!, "utf8")).toBe(payload); + expect(renderWakePayloadFileNote(second.env)).toContain(JSON.stringify(second.filePath)); + }); + + it("accounts for shell quoting expansion on remote launches", async () => { + const quoted = JSON.stringify({ description: "'".repeat(8_000) }); + expect(Buffer.byteLength(quoted)).toBeLessThan(WAKE_PAYLOAD_INLINE_MAX_BYTES); + const delivery = await prepareWakePayloadEnv({ PAPERCLIP_WAKE_PAYLOAD_JSON: quoted }, async (script) => + (await exec("sh", ["-c", script])).stdout); + cleanup.push(delivery.cleanup); + expect(await fs.readFile(delivery.filePath!, "utf8")).toBe(quoted); + expect(delivery.env.PAPERCLIP_WAKE_PAYLOAD_JSON).toBeUndefined(); + }); + + it("launches a real child with the complete large payload, preserves stdin, and removes the file", async () => { + const result = await runChildProcess("large-wake", process.execPath, ["-e", childScript], { + cwd: os.tmpdir(), env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, stdin: "original prompt", + timeoutSec: 10, graceSec: 1, onLog: async () => {}, + }); + expect(result.exitCode).toBe(0); + const received = JSON.parse(result.stdout); + expect(received).toMatchObject({ digest: digest(payload), inline: null, stdin: "original prompt" }); + if (process.platform !== "win32") expect(received).toMatchObject({ mode: 0o600, directoryMode: 0o700 }); + await expect(fs.stat(path.dirname(received.path))).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it.skipIf(process.platform !== "linux")("reproduces Linux E2BIG when the original payload is used as an env entry", async () => { + await expect(exec(process.execPath, ["-e", ""], { env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload } })) + .rejects.toMatchObject({ code: "E2BIG" }); + }); + + it("cleans up when the child cannot start", async () => { + const mkdtemp = vi.spyOn(fs, "mkdtemp"); + await expect(runChildProcess("failed-wake", "/paperclip-test-no-such-command", [], { + cwd: os.tmpdir(), env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, timeoutSec: 5, graceSec: 1, onLog: async () => {}, + })).rejects.toThrow("Failed to start command"); + const directory = await mkdtemp.mock.results[0]!.value; + await expect(fs.stat(directory)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it.skipIf(process.platform !== "linux")("binds only the owned payload file into a confined process", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-wake-mount-test-")); + cleanup.push(() => fs.rm(root, { recursive: true, force: true })); + const fakeBwrap = path.join(root, "fake-bwrap.cjs"); + await fs.writeFile(fakeBwrap, `#!${process.execPath}\nconsole.log(JSON.stringify({ args: process.argv.slice(2), path: process.env.PAPERCLIP_WAKE_PAYLOAD_PATH }));`, { mode: 0o700 }); + const result = await runChildProcess("confined-wake", process.execPath, ["-e", ""], { + cwd: root, env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, timeoutSec: 5, graceSec: 1, onLog: async () => {}, + localProcessSandbox: { workspaceDir: root, filesystemScope: "workspace", command: fakeBwrap }, + }); + expect(result.exitCode).toBe(0); + const received = JSON.parse(result.stdout); + const index = received.args.indexOf(received.path); + expect(received.args.slice(index - 1, index + 2)).toEqual(["--ro-bind", received.path, received.path]); + const mounts = received.args.flatMap((arg: string, index: number) => + arg === "--bind" || arg === "--ro-bind" ? [received.args[index + 1]] : []); + expect(mounts).not.toContain(path.dirname(received.path)); + await expect(fs.stat(received.path)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("cleans up after a timeout", async () => { + const result = await runChildProcess("timeout-wake", process.execPath, ["-e", "console.log(process.env.PAPERCLIP_WAKE_PAYLOAD_PATH); setInterval(() => {}, 1000)"], { + cwd: os.tmpdir(), env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, timeoutSec: 0.2, graceSec: 1, onLog: async () => {}, + }); + expect(result.timedOut).toBe(true); + await expect(fs.stat(path.dirname(result.stdout.trim()))).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("delivers exact bytes through bounded remote commands and cleans up after the remote child", async () => { + const commands: string[] = []; + const result = await runAdapterExecutionTargetProcess("remote-wake", { + kind: "remote", transport: "sandbox", remoteCwd: os.tmpdir(), + runner: { execute: async (input) => { + for (const value of [...(input.args ?? []), ...Object.values(input.env ?? {})]) { + expect(Buffer.byteLength(value)).toBeLessThan(32 * 1024); + } + commands.push((input.args ?? []).join(" ")); + return runChildProcess("remote-test-command", input.command, input.args ?? [], { + cwd: os.tmpdir(), env: input.env ?? {}, stdin: input.stdin, timeoutSec: 10, graceSec: 1, onLog: async () => {}, + }); + } }, + }, process.execPath, ["-e", childScript], { + cwd: os.tmpdir(), env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, stdin: "remote prompt", + timeoutSec: 10, graceSec: 1, onLog: async () => {}, + }); + expect(result.exitCode).toBe(0); + const received = JSON.parse(result.stdout); + expect(received).toMatchObject({ digest: digest(payload), inline: null, stdin: "remote prompt", mode: 0o600, directoryMode: 0o700 }); + await expect(fs.stat(path.dirname(received.path))).rejects.toMatchObject({ code: "ENOENT" }); + expect(commands.filter((s) => s.includes("base64 -d")).length).toBeGreaterThan(1); + }); + + it.each(["upload", "verification"])("fails closed on remote %s failure without leaking payload chunks", async (failure) => { + let directory = ""; + let appends = 0; + const promise = prepareWakePayloadEnv({ PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, async (script) => { + if (script.startsWith("umask 077 && mkdir")) directory = script.match(/'(\/tmp\/paperclip-wake-[^']+)'/)![1]!; + if (script.includes("base64 -d") && ++appends === 2 && failure === "upload") throw new Error(script); + if (script.startsWith("test ") && failure === "verification") throw new Error(script); + return (await exec("sh", ["-c", script])).stdout; + }); + await expect(promise).rejects.toThrow(/^Could not deliver the complete wake payload file\.$/); + expect(directory).not.toBe(""); + await expect(fs.stat(directory)).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("rejects configured file paths and keeps wake contents out of invocation logs", () => { + expect(isForbiddenConfigEnvKey("PAPERCLIP_WAKE_PAYLOAD_PATH")).toBe(true); + const logged = redactEnvForLogs({ PAPERCLIP_WAKE_PAYLOAD_JSON: payload }); + expect(logged.PAPERCLIP_WAKE_PAYLOAD_JSON).toBe(`[wake payload: ${Buffer.byteLength(payload)} bytes]`); + expect(JSON.stringify(logged)).not.toContain("café"); + }); +}); diff --git a/packages/adapter-utils/src/wake-payload-env.ts b/packages/adapter-utils/src/wake-payload-env.ts new file mode 100644 index 00000000000..029c06fc9a6 --- /dev/null +++ b/packages/adapter-utils/src/wake-payload-env.ts @@ -0,0 +1,94 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; + +// Leave headroom for other environment entries and shell/provider wrappers. +// This is a transport threshold, never a limit on the wake's contents. +export const WAKE_PAYLOAD_INLINE_MAX_BYTES = 64 * 1024; +const PAYLOAD_KEY = "PAPERCLIP_WAKE_PAYLOAD_JSON"; +const PATH_KEY = "PAPERCLIP_WAKE_PAYLOAD_PATH"; +const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; + +export interface WakePayloadDelivery { + env: Record; + filePath: string | null; + cleanup(): Promise; +} + +/** Execute a bounded shell command on the actual agent host, with no wake env. */ +export type WakePayloadRemoteCommand = (script: string) => Promise; + +/** + * The caller owns this delivery until the process/turn settles. Never accept a + * path supplied by a payload or config, overwrite a shared scratch file, or + * change the caller's env (which may be reused for probes/retries). + */ +export async function prepareWakePayloadEnv( + input: Record, + remoteCommand?: WakePayloadRemoteCommand, +): Promise { + const payload = input[PAYLOAD_KEY]; + const env = { ...input }; + // Inline contents take precedence over a stale file reference. + if (payload !== undefined) delete env[PATH_KEY]; + // SSH/provider launchers can quote the environment inside another shell + // command. Apostrophes expand at each layer, even for a small raw JSON value. + const transportBytes = payload + ? Buffer.byteLength(remoteCommand ? quote(quote(payload)) : payload, "utf8") + : 0; + if (!payload || transportBytes <= WAKE_PAYLOAD_INLINE_MAX_BYTES) { + return { env, filePath: null, cleanup: async () => {} }; + } + + let directory: string; + let filePath: string; + let cleanup: () => Promise; + if (remoteCommand) { + directory = `/tmp/paperclip-wake-${randomUUID()}`; + filePath = `${directory}/payload.json`; + // Do not remove a pre-existing path when exclusive creation fails. + try { + await remoteCommand(`umask 077 && mkdir -m 700 ${quote(directory)}`); + } catch { + throw new Error("Could not create the private wake payload directory."); + } + cleanup = async () => { await remoteCommand(`rm -rf -- ${quote(directory)}`); }; + try { + await remoteCommand(`umask 077 && set -C && : > ${quote(filePath)}`); + const encoded = Buffer.from(payload, "utf8").toString("base64"); + // Some providers turn stdin into a shell argument. Bound the transport + // ourselves instead of trusting that stdin remains a stream end to end. + for (let offset = 0; offset < encoded.length; offset += 16 * 1024) { + await remoteCommand( + `printf '%s' ${quote(encoded.slice(offset, offset + 16 * 1024))} | base64 -d >> ${quote(filePath)}`, + ); + } + await remoteCommand(`test "$(wc -c < ${quote(filePath)})" -eq ${Buffer.byteLength(payload, "utf8")}`); + } catch { + await cleanup().catch(() => {}); + // Provider errors can include the command (and thus a payload chunk). + throw new Error("Could not deliver the complete wake payload file."); + } + } else { + directory = await fs.mkdtemp(path.join(await fs.realpath(os.tmpdir()), "paperclip-wake-")); + filePath = path.join(directory, "payload.json"); + cleanup = () => fs.rm(directory, { recursive: true, force: true }); + try { + await fs.chmod(directory, 0o700); + await fs.writeFile(filePath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" }); + } catch { + await cleanup().catch(() => {}); + throw new Error("Could not deliver the complete wake payload file."); + } + } + delete env[PAYLOAD_KEY]; + env[PATH_KEY] = filePath; + return { env, filePath, cleanup }; +} + +export function renderWakePayloadFileNote(env: Record): string { + const filePath = env[PATH_KEY]; + if (!filePath) return ""; + return `The complete structured wake payload for this turn is in ${JSON.stringify(filePath)}. Read this JSON file if you need the structured wake context. This turn's path takes precedence over any older wake environment retained by a resumed session. The file is removed when this turn ends.`; +} diff --git a/skills/paperclip/SKILL.md b/skills/paperclip/SKILL.md index 0c7ceab69fa..5847b9348a0 100644 --- a/skills/paperclip/SKILL.md +++ b/skills/paperclip/SKILL.md @@ -19,7 +19,7 @@ In Paperclip, **task** and **issue** refer to the same work item. The UI may use Env vars auto-injected: `PAPERCLIP_AGENT_ID`, `PAPERCLIP_COMPANY_ID`, `PAPERCLIP_API_URL`, `PAPERCLIP_RUN_ID`. Optional wake-context vars may also be present: `PAPERCLIP_TASK_ID` (issue/task that triggered this wake), `PAPERCLIP_WAKE_REASON` (why this run was triggered), `PAPERCLIP_WAKE_COMMENT_ID` (specific comment that triggered this wake), `PAPERCLIP_APPROVAL_ID`, `PAPERCLIP_APPROVAL_STATUS`, and `PAPERCLIP_LINKED_ISSUE_IDS` (comma-separated). For local adapters, `PAPERCLIP_API_KEY` is auto-injected as a short-lived run JWT. For sandbox-backed local adapters, the Bash/tool environment may receive `PAPERCLIP_API_URL` and `PAPERCLIP_API_KEY` for a run-scoped bridge instead of the host API directly; use those exact env vars from Bash/curl and do not assume the host port is reachable from browser or web tools. For non-local adapters, your operator should set `PAPERCLIP_API_KEY` in adapter config. All requests use `Authorization: Bearer $PAPERCLIP_API_KEY`. All endpoints are under `/api`. Use JSON except for multipart attachment uploads and binary content downloads. Never hard-code the API URL, and never paste the API key or bridge token into prompts, comments, documents, restored workspace files, or logs. -Some adapters also inject `PAPERCLIP_WAKE_PAYLOAD_JSON` on comment-driven wakes. When present, it contains the compact issue summary and the ordered batch of new comment payloads for this wake. Use it first. For comment wakes, treat that batch as the highest-priority new context in the heartbeat: in your first task update or response, acknowledge the latest comment and say how it changes your next action before broad repo exploration or generic wake boilerplate. Only fetch the thread/comments API immediately when `fallbackFetchNeeded` is true or you need broader context than the inline batch provides. +Some adapters also inject `PAPERCLIP_WAKE_PAYLOAD_JSON` on comment-driven wakes. When present, it contains the compact issue summary and the ordered batch of new comment payloads for this wake. Use it first. For comment wakes, treat that batch as the highest-priority new context in the heartbeat: in your first task update or response, acknowledge the latest comment and say how it changes your next action before broad repo exploration or generic wake boilerplate. Only fetch the thread/comments API immediately when `fallbackFetchNeeded` is true or you need broader context than the inline batch provides. Large wake payloads are delivered as a private UTF-8 JSON file instead. Read the file named by `PAPERCLIP_WAKE_PAYLOAD_PATH`; it contains the complete payload, with no transport truncation. A file path supplied in the current turn's prompt takes precedence over wake variables retained by a resumed process. These files exist only for the active run; do not retain their paths for later turns or copy their contents into logs. Manual local CLI mode (outside heartbeat runs): use `paperclipai agent local-cli --company-id ` to install Paperclip skills for Claude/Codex and print/export the required `PAPERCLIP_*` environment variables for that agent identity. @@ -127,7 +127,7 @@ If already checked out by you, returns normally. If owned by another agent: `409 **Step 6 — Understand context.** Prefer `GET /api/issues/{issueId}/heartbeat-context` first. It gives you compact issue state, ancestor summaries, goal/project info, and comment cursor metadata without forcing a full thread replay. -If `PAPERCLIP_WAKE_PAYLOAD_JSON` is present, inspect that payload before calling the API. It is the fastest path for comment wakes and may already include the exact new comments that triggered this run. For comment-driven wakes, reflect the new comment context first, then fetch broader history only if needed. +If the current turn supplies a wake payload file path, or `PAPERCLIP_WAKE_PAYLOAD_PATH` or `PAPERCLIP_WAKE_PAYLOAD_JSON` is present, inspect that payload before calling the API. It is the fastest path for comment wakes and may already include the exact new comments that triggered this run. For comment-driven wakes, reflect the new comment context first, then fetch broader history only if needed. Use comments incrementally: