Files
PaperClipAI/packages/plugins/sandbox-providers/daytona/src/duplex-command-stream.live.test.ts
Nicky LeachandPaperclip 445547c989 feat(duplex): run the Daytona sandbox callback bridge over Node HTTP/2 (#12120)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Sandbox providers carry agent work through controlled execution
channels
> - The Daytona callback bridge uses a bespoke line-framed protocol over
its duplex channel
> - The bespoke protocol adds framing work and does not use the Node
transport that already supports multiplexed streams
> - This pull request carries raw bytes across the channel, adds a Node
HTTP/2 bridge, and selects it for Daytona
> - The benefit is one authenticated, multiplexed callback session with
queue_v1 as the bounded fallback

## Linked Issues or Issue Description

**Subsystem affected**

The packages/plugins Daytona provider and the shared duplex execution
path.

**Problem or motivation**

The Daytona callback bridge uses a bespoke line-framed protocol over the
provider duplex channel. This adds protocol work and limits stream
handling.

**Proposed solution**

Carry raw bytes through the cross-layer channel. Add an authenticated
Node HTTP/2 host server and sandbox client gateway. Select http2_v1 for
Daytona and retain queue_v1 as the fallback.

**Alternatives considered**

Keep the current duplex_v1 protocol. This keeps the bespoke framing path
and does not provide one HTTP/2 session for callback streams.

**Roadmap alignment**

ROADMAP.md lists Daytona under cloud and sandbox agents. This change
improves the shipped Daytona provider path.

**Additional context**

The branch adds no dependency. Node 24 provides the http2 module. The
host token check and canonical path parser remain the single dispatch
path.

## What Changed

- Carry raw Uint8Array chunks through the adapter, plugin, worker,
runtime, and Daytona layers.
- Encode bytes as base64 only across the JSON-RPC hop, because JSON has
no binary type.
- Add the bounded host HTTP/2 server and the in-sandbox HTTP/2 client
gateway.
- Authenticate every stream with the per-run bridge token before route
work.
- Parse the path once and reuse the canonical result for route and
forwarding work.
- Select http2_v1 for Daytona and fall back once to queue_v1 when the
client preface is absent.
- Add transport, session, stream, and fallback telemetry.
- Mark HTTP/2 as the preferred transport and queue_v1 as the
soft-deprecated fallback.

## Verification

- `npx vitest run packages/adapter-utils/src` — 990 passed and 4
skipped.
- `npx vitest run
server/src/__tests__/plugin-worker-manager-duplex.test.ts` — 32 passed.
- `npx vitest run --config
packages/plugins/sandbox-providers/daytona/vitest.config.ts` — 220
passed and 6 skipped.
- `npx tsc --noEmit` in `packages/adapter-utils`, `packages/shared`,
`packages/plugins/sdk`, and `server` — clean.
- No `package.json` or `pnpm-lock.yaml` file changed.
- The live Daytona test skips when `DAYTONA_API_KEY` is absent.
- The root `npx tsc --noEmit` command has a pre-existing missing
`packages/adapters/droid-local` reference on this branch and on
`master`.

## Risks

- The transport change affects several duplex layers and could expose
byte-boundary errors.
- A missing HTTP/2 client preface falls back once to queue_v1 and
records `preface_missing`.
- The host token check and canonical path parser must remain on the
shared dispatch path.
- The live Daytona test needs `DAYTONA_API_KEY` and does not run in this
agent sandbox.

## Model Used

OpenAI GPT-5, tool-enabled coding agent with repository inspection,
GitHub CLI, and shell execution.

## 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>
2026-08-25 07:35:39 -07:00

414 lines
18 KiB
TypeScript

// Live characterization of the Daytona duplex channel against the real provider.
//
// The test is credential-gated by design. It runs only when the run shell holds a
// Daytona API key, and it skips cleanly when the key is absent. The key comes from
// `DAYTONA_API_KEY`, which the plugin also reads as the credential fallback
// (`plugin.ts`). A skip is acceptable: the merged live coverage re-runs at a later
// phase and at rollout.
//
// What it proves on one live sandbox:
// 1. The duplex channel and an ordinary command run at the same time.
// 2. Host input sent after the child starts arrives, with no terminal echo and
// no frame corruption.
// 3. Channel teardown leaves no leaked provider session.
//
// The channel runs `cat` as the child. `cat` copies its input to its output, so a
// host write returns one time as program output. The launch wrapper sets the
// pseudo-terminal to raw mode with echo off, so the terminal adds no second copy
// and no newline translation. A returned line that equals the sent line, one time,
// proves both the delivery and the clean stream.
//
// The Daytona SDK is a runtime dependency of this live test only. The module loads
// it with a dynamic import inside the gated block, so the file imports with no SDK
// present and the other Daytona tests still run without it.
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { randomUUID } from "node:crypto";
import http2 from "node:http2";
import { Duplex } from "node:stream";
import {
openDaytonaDuplexChannelSession,
type DaytonaPtyProcess,
type DuplexChannelSession,
} from "./duplex-command-stream.js";
const DAYTONA_API_KEY = process.env.DAYTONA_API_KEY?.trim() ?? "";
const HAS_DAYTONA_CREDENTIAL = DAYTONA_API_KEY.length > 0;
const describeLive = HAS_DAYTONA_CREDENTIAL ? describe : describe.skip;
if (!HAS_DAYTONA_CREDENTIAL) {
// eslint-disable-next-line no-console
console.warn(
"Skipping the Daytona duplex channel live test: DAYTONA_API_KEY is not set in the run shell.",
);
}
// A live sandbox create and destroy needs a generous timeout. The provider round
// trip dominates the wall-clock time.
const LIVE_TIMEOUT_MS = 180_000;
// The minimal shape of the live Daytona sandbox that the test uses. The dynamic
// import returns the real SDK types; this local shape keeps the file type-safe
// without a static SDK import.
interface LiveDaytonaSandbox {
process: DaytonaPtyProcess & {
executeCommand(command: string): Promise<{ exitCode?: number; result?: string }>;
listSessions?: () => Promise<Array<{ sessionId?: string }>>;
};
delete(): Promise<void>;
}
/**
* Wait until `predicate(text)` is true for the running output, or reject after
* `timeoutMs`. The poll interval is short, so the wait ends soon after the output
* arrives.
*/
async function waitFor(
readOutput: () => string,
predicate: (text: string) => boolean,
timeoutMs: number,
label: string,
): Promise<void> {
const deadline = Date.now() + timeoutMs;
for (;;) {
if (predicate(readOutput())) return;
if (Date.now() > deadline) {
throw new Error(`Timed out waiting for ${label}. Output so far: ${JSON.stringify(readOutput())}`);
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
/** Open a `cat` duplex channel and collect its output into a growing string. */
async function openCatChannel(
sandbox: LiveDaytonaSandbox,
): Promise<{ session: DuplexChannelSession; readOutput: () => string }> {
let output = "";
const session = await openDaytonaDuplexChannelSession(sandbox.process, ["cat"]);
session.onData((chunk) => {
output += chunk;
});
return { session, readOutput: () => output };
}
describeLive("Daytona duplex channel (live)", () => {
let sandbox: LiveDaytonaSandbox | null = null;
beforeAll(async () => {
const { Daytona } = await import("@daytonaio/sdk");
const client = new Daytona({ apiKey: DAYTONA_API_KEY });
sandbox = (await client.create()) as unknown as LiveDaytonaSandbox;
}, LIVE_TIMEOUT_MS);
afterAll(async () => {
await sandbox?.delete().catch(() => undefined);
}, LIVE_TIMEOUT_MS);
it(
"runs the duplex channel and an ordinary command on one live sandbox",
async () => {
const live = sandbox!;
const { session, readOutput } = await openCatChannel(live);
try {
// Run an ordinary command while the channel child stays alive. Both use the
// same live sandbox, so a success on both proves they coexist.
const token = `ordinary-${randomUUID()}`;
const ordinary = await live.process.executeCommand(`printf %s ${token}`);
expect(ordinary.exitCode ?? 0).toBe(0);
expect(ordinary.result ?? "").toContain(token);
// The channel child still answers. A write returns as program output.
const ping = `chan-${randomUUID()}`;
session.write(Buffer.from(`${ping}\n`));
await waitFor(readOutput, (text) => text.includes(ping), 30_000, "channel echo");
} finally {
await session.close();
}
},
LIVE_TIMEOUT_MS,
);
it(
"delivers host input sent after startup with no echo and no frame corruption",
async () => {
const live = sandbox!;
const { session, readOutput } = await openCatChannel(live);
try {
// Let the launch wrapper run `stty raw -echo` before the host input. The
// wrapper output echoes in cooked mode, so wait for the raw-mode switch
// before the measured write.
await new Promise((resolve) => setTimeout(resolve, 4_000));
const baseline = readOutput().length;
const line = `PING-${randomUUID()}`;
session.write(Buffer.from(`${line}\n`));
await waitFor(
readOutput,
(text) => text.slice(baseline).includes(line),
30_000,
"delayed host input",
);
// Only `cat` writes the line, one time. Raw mode with echo off adds no
// second copy, so the sent token appears exactly one time after the write.
const afterWrite = readOutput().slice(baseline);
const occurrences = afterWrite.split(line).length - 1;
expect(occurrences).toBe(1);
// The stream carries the frame bytes with no newline translation. The
// returned line keeps its single line-feed and gains no carriage return.
expect(afterWrite).toContain(`${line}\n`);
expect(afterWrite).not.toContain(`${line}\r`);
} finally {
await session.close();
}
},
LIVE_TIMEOUT_MS,
);
it(
"leaves no leaked provider session after channel close",
async () => {
const live = sandbox!;
const listSessions = live.process.listSessions?.bind(live.process);
const baseline = listSessions ? (await listSessions()).length : 0;
const { session } = await openCatChannel(live);
await session.close();
if (listSessions) {
// The channel uses a pseudo-terminal, not an ordinary session. So the
// session list stays at the baseline. A leaked session would raise the
// count.
const after = (await listSessions()).length;
expect(after).toBe(baseline);
}
// The child exits after close, so a fresh ordinary command still succeeds on
// the same sandbox. A leaked channel would block or corrupt the sandbox.
const token = `after-close-${randomUUID()}`;
const probe = await live.process.executeCommand(`printf %s ${token}`);
expect(probe.exitCode ?? 0).toBe(0);
expect(probe.result ?? "").toContain(token);
},
LIVE_TIMEOUT_MS,
);
it(
"serves repeated channel round trips with no idle polling and no per-request session growth",
async () => {
const live = sandbox!;
const listSessions = live.process.listSessions?.bind(live.process);
const { session, readOutput } = await openCatChannel(live);
try {
// Wait for the raw-mode switch, then take the open baseline. The channel
// uses a pseudo-terminal, not an ordinary session, so the session list
// stays flat through the whole exchange.
await new Promise((resolve) => setTimeout(resolve, 4_000));
const openSessions = listSessions ? (await listSessions()).length : 0;
// Send a batch of request-shaped lines over the one open channel and
// measure the round-trip latency of each. The transport writes no queue
// file and runs no exec per line, so the round trip is the stream latency.
const latenciesMs: number[] = [];
const rounds = 10;
for (let index = 0; index < rounds; index += 1) {
const line = `RTT-${index}-${randomUUID()}`;
const baseline = readOutput().length;
const start = Date.now();
session.write(Buffer.from(`${line}\n`));
await waitFor(
readOutput,
(text) => text.slice(baseline).includes(line),
30_000,
"channel round trip",
);
latenciesMs.push(Date.now() - start);
}
// Hold the channel idle. A polling transport would run a provider exec on
// each tick and raise the session count. The duplex channel polls nothing.
await new Promise((resolve) => setTimeout(resolve, 5_000));
if (listSessions) {
const afterSessions = (await listSessions()).length;
// Zero idle polls and zero per-request session growth: the session count
// never rose above the open baseline.
expect(afterSessions).toBe(openSessions);
}
const min = Math.min(...latenciesMs);
const max = Math.max(...latenciesMs);
const avg = Math.round(latenciesMs.reduce((sum, value) => sum + value, 0) / latenciesMs.length);
// eslint-disable-next-line no-console
console.log(
`[duplex-live] channel round-trip latency over ${rounds} requests: min=${min}ms avg=${avg}ms max=${max}ms; idle-poll session growth=0; per-request session growth=0`,
);
expect(latenciesMs.length).toBe(rounds);
} finally {
await session.close();
}
},
LIVE_TIMEOUT_MS,
);
it(
"leaves no leaked session and keeps the sandbox usable after a forced mid-flight disconnect",
async () => {
const live = sandbox!;
const listSessions = live.process.listSessions?.bind(live.process);
const baseline = listSessions ? (await listSessions()).length : 0;
const { session, readOutput } = await openCatChannel(live);
// Wait for the raw-mode switch, then start a write and force a disconnect
// before its echo returns. The abrupt close models a lost provider channel.
await new Promise((resolve) => setTimeout(resolve, 4_000));
const inFlight = `INFLIGHT-${randomUUID()}`;
session.write(Buffer.from(`${inFlight}\n`));
// Close at once, without waiting for the echo. The pending round trip never
// settles through the stream; the channel tears down instead.
await session.close();
if (listSessions) {
// The forced disconnect left no leaked provider session. The count is back
// at the baseline that preceded the channel.
const after = (await listSessions()).length;
expect(after).toBe(baseline);
}
// Do not read the in-flight echo; the disconnect settled the run. Reference
// the output length only to keep the reader wired.
expect(readOutput().length).toBeGreaterThanOrEqual(0);
// The sandbox stays usable: a fresh ordinary command still succeeds. A
// leaked channel would block or corrupt the sandbox.
const token = `post-disconnect-${randomUUID()}`;
const probe = await live.process.executeCommand(`printf %s ${token}`);
expect(probe.exitCode ?? 0).toBe(0);
expect(probe.result ?? "").toContain(token);
// eslint-disable-next-line no-console
console.log("[duplex-live] forced mid-flight disconnect: leaked sessions=0; sandbox usable after=yes");
},
LIVE_TIMEOUT_MS,
);
it(
"test_live_daytona_run_uses_http2_v1_end_to_end",
async () => {
// Phase 4 selects http2_v1 by running one Node HTTP/2 session directly
// on this same pseudo-terminal channel, right after the READY line.
// This package ships standalone (see the file header), so it cannot
// import the host readiness gate or the preface scan from
// `@paperclipai/adapter-utils`; this test reimplements the minimal,
// self-contained version of both, using only `node:http2`, so the
// proof runs against a real Daytona PTY end to end.
const live = sandbox!;
const nonce = randomUUID();
// The 24-octet HTTP/2 client connection preface (RFC 9113, Section 3.4).
const CLIENT_PREFACE = Buffer.from("505249202a20485454502f322e300d0a0d0a534d0d0a0d0a", "hex");
// The sandbox-side child: send the READY line, then hand stdin/stdout to
// a real HTTP/2 client session and dispatch one request — the same
// shape `runHttp2Gateway()` in `sandbox-callback-bridge.ts` runs.
const nodeScript = [
`process.stdout.write(JSON.stringify({version:2,type:"ready",nonce:${JSON.stringify(nonce)}})+"\\n");`,
`const http2=require("node:http2");`,
`const {Duplex}=require("node:stream");`,
`const stdio=new Duplex({read(){},write(chunk,enc,cb){const ok=process.stdout.write(chunk);if(ok)cb();else process.stdout.once("drain",cb);}});`,
`process.stdin.on("data",c=>stdio.push(c));`,
`process.stdin.on("end",()=>stdio.push(null));`,
`const session=http2.connect("http://bridge.internal",{createConnection:()=>stdio});`,
`session.on("error",()=>process.exit(1));`,
`const stream=session.request({":method":"GET",":path":"/ping"});`,
`let body="";`,
`stream.on("data",c=>{body+=c;});`,
`stream.on("error",()=>process.exit(3));`,
`stream.on("end",()=>{session.close(()=>process.exit(body==="pong"?0:2));});`,
`stream.end();`,
].join("");
const session = await openDaytonaDuplexChannelSession(live.process, ["node", "-e", nodeScript]);
try {
// Reads bytes from the channel until it finds one complete newline-
// terminated READY line, then hands every later byte — including any
// already-buffered suffix of the same chunk — to `onAfterReady`.
const readyAndAfter = await new Promise<{ nonce: string; afterReady: Buffer }>((resolve, reject) => {
let buffer = Buffer.alloc(0);
const timer = setTimeout(
() => reject(new Error(`Timed out waiting for the READY line. Bytes so far: ${buffer.length}`)),
30_000,
);
session.onData((chunk) => {
buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
const newlineIndex = buffer.indexOf(0x0a);
if (newlineIndex === -1) return;
clearTimeout(timer);
const line = buffer.subarray(0, newlineIndex).toString("utf8");
const decoded = JSON.parse(line) as { type?: string; nonce?: string };
resolve({ nonce: decoded.nonce ?? "", afterReady: Buffer.from(buffer.subarray(newlineIndex + 1)) });
});
});
expect(readyAndAfter.nonce).toBe(nonce);
// Scan the retained suffix for the client preface, the same rule
// `createHttp2PrefaceScanningChannel` in `execution-target.ts` applies:
// the scan window opens only on bytes after the accepted READY line.
let sawPreface = false;
let downstream: ((chunk: Buffer) => void) | null = null;
let pendingAfterPreface = Buffer.alloc(0);
let scanBuffer = readyAndAfter.afterReady;
function deliver(chunk: Buffer): void {
if (downstream) downstream(chunk);
else pendingAfterPreface = Buffer.concat([pendingAfterPreface, chunk]);
}
function handleChunk(chunk: Buffer): void {
if (sawPreface) {
deliver(chunk);
return;
}
scanBuffer = Buffer.concat([scanBuffer, chunk]);
const offset = scanBuffer.indexOf(CLIENT_PREFACE);
if (offset === -1) return;
sawPreface = true;
const fromPreface = Buffer.from(scanBuffer.subarray(offset));
scanBuffer = Buffer.alloc(0);
deliver(fromPreface);
}
// The already-retained suffix might already hold the preface.
handleChunk(Buffer.alloc(0));
session.onData((chunk) => handleChunk(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
// Wrap the channel as a Node `Duplex` starting at the preface offset,
// and bind one plaintext HTTP/2 server session on it.
const boundDuplex: Duplex = new Duplex({
read() {},
write(chunk: unknown, _encoding, callback) {
session.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as ArrayBufferLike));
callback();
},
});
downstream = (chunk) => boundDuplex.push(chunk);
if (pendingAfterPreface.length > 0) {
boundDuplex.push(pendingAfterPreface);
pendingAfterPreface = Buffer.alloc(0);
}
const server = http2.createServer();
server.on("stream", (stream) => {
stream.respond({ ":status": 200 });
stream.end("pong");
});
server.emit("connection", boundDuplex);
const exit = await session.wait();
expect(exit.exitCode).toBe(0);
// eslint-disable-next-line no-console
console.log("[duplex-live] http2_v1: READY, then the real client preface, then one full HTTP/2 round trip, all over one live Daytona PTY.");
} finally {
await session.close();
}
},
LIVE_TIMEOUT_MS,
);
});