feat(login): use the login pseudo-terminal for Codex device login and de-Claude the shared channel (#12020)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agent adapters use provider-specific login flows
> - Codex device login needs a live pseudo-terminal (PTY), while the
shared channel still uses Claude-specific names
> - The old streamed-exec path does not provide the prompt transport
that Codex needs
> - This pull request moves Codex device login to the shared login PTY
and removes the dead streamed-exec path
> - The benefit is one controlled login transport with fail-closed
capability checks and safer credential reads

## Linked Issues or Issue Description

**Problem or motivation**

Codex device login used a streamed-exec path that did not provide the
required prompt transport. The shared login channel also exposed
Claude-specific names outside Claude code.

**Expected behavior**

The host selects a fixed login command from trusted adapter data. Codex
login uses the provider login PTY. Providers without that capability
fail closed.

**Proposed solution**

Use a server-controlled session home, create and validate it as a fresh
0700 directory, read credentials from one validated descriptor, and
rename shared channel names to the neutral login PTY family.

**Alternatives considered**

Keep the shared login PTY as the single transport. Do not keep the
removed streamed-exec path because it cannot provide the required prompt
transport.

**Roadmap alignment**

This change supports the planned login transport work. It does not add a
separate roadmap item.

## What Changed

- Route Codex device login through the shared login PTY transport.
- Select the login command from a closed internal command key.
- Carry a server-controlled session home through the launch contract.
- Create and validate the session home as a fresh 0700 directory owned
by the login user.
- Read the credential file with descriptor-relative, no-follow path
walking and final descriptor checks.
- Gate the login route and run lease on the provider login PTY
capability.
- Rename shared channel names to the neutral login PTY family.
- Remove the streamed-exec transport value, selector field, driver
branch, and related tests.
- Hide Codex login in the user interface when the provider lacks the
login PTY capability.

## Verification

- Server unit suites pass: 89/89.
- Adapter-utils suites pass: 262/262.
- Codex-local suites pass: 326/326.
- Credential-read reader suite passes: 20/20.
- Daytona login PTY suite passes: 30/30.
- Device-login suites pass: 56/56.
- TypeScript checks pass for server, adapter-utils, and UI.
- GitHub Actions must pass after pull request creation.
- Greptile review must reach 5/5 with no open P2 findings,
recommendations, or follow-ups.

## Risks

- Providers without a login PTY capability lose Codex login support by
design.
- The credential read rejects invalid ownership, mode, type, path, and
size.
- The launch-time sandbox directory race remains outside the threat
model because the login runs inside the sandbox and a hostile sandbox
already controls its credential.

## Model Used

OpenAI Codex, GPT-5, tool use and code review assistance. The exact
context window and reasoning mode are not exposed by the runtime.

## 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:
Nicky LeachandPaperclip authored and GitHub committed 2026-08-23 09:44:59 -07:00
1 parent 16b59c9315
commit 63df7ad2b3
52 files changed
+3500 -1033

No files matched your search

@@ -42,7 +42,7 @@
],
"scripts": {
"prebuild": "pnpm -C ../../../.. --filter @paperclipai/plugin-sdk ensure-build-deps",
"build": "rm -rf dist && tsc",
"build": "rm -rf dist && tsc && mkdir -p dist/scripts && cp -R src/scripts/. dist/scripts/",
"clean": "rm -rf dist",
"typecheck": "pnpm -C ../../../.. --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit",
"test": "vitest run --config vitest.config.ts",
@@ -27,7 +27,7 @@
// Dependency boundary: this provider plugin ships standalone (the workspace
// excludes `packages/plugins/sandbox-providers/**`). So the module imports no
// workspace package. It reuses the narrow Daytona PTY surface that
// `setup-token-pty.ts` declares (`DaytonaPtyProcess`, `DaytonaPtyHandle`,
// `login-pty.ts` declares (`DaytonaPtyProcess`, `DaytonaPtyHandle`,
// `DaytonaPtyCreateOptions`), so a caller passes `sandbox.process` with no
// adapter. The narrow surface keeps the module unit-testable with a fake PTY.
@@ -37,13 +37,13 @@ import type {
DaytonaPtyCreateOptions,
DaytonaPtyHandle,
DaytonaPtyProcess,
} from "./setup-token-pty.js";
} from "./login-pty.js";
export type {
DaytonaPtyCreateOptions,
DaytonaPtyHandle,
DaytonaPtyProcess,
} from "./setup-token-pty.js";
} from "./login-pty.js";
import { sendPtyInputInChunks } from "./pty-chunked-input.js";
@@ -0,0 +1,645 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
composeLaunchLine,
createDaytonaLoginHomeFs,
createDaytonaLoginPtySessionOpener,
encodePosixShellArg,
openDaytonaLoginPtySession,
type DaytonaExecResult,
type DaytonaLoginHomeFs,
type DaytonaPtyCreateOptions,
type DaytonaPtyHandle,
type DaytonaPtyProcess,
type DaytonaSandboxExec,
type LoginHomeInspection,
type LoginPtyLaunchDescriptor,
} from "./login-pty.js";
// The Enter byte the terminal login UI reads to submit the browser code.
const ENTER = "\r";
const HOME = "/tmp/paperclip-adapter-login/11111111-2222-4333-8444-555555555555";
const LOGIN_UID = 1000;
const CLAUDE: LoginPtyLaunchDescriptor = { loginCommandKey: "claude", sessionHome: HOME };
const CODEX: LoginPtyLaunchDescriptor = { loginCommandKey: "codex", sessionHome: HOME };
/** A directory entry in the virtual filesystem. */
type FakeEntry = Omit<LoginHomeInspection, "exists">;
const ABSENT: LoginHomeInspection = {
exists: false,
isSymlink: false,
isDirectory: false,
mode: "",
ownerUid: null,
};
/**
* A fake login-home filesystem. It models one virtual path. `createDirectory`
* fails when the path exists and otherwise stores `createAs` (a clean 0700
* directory owned by the login user by default). A test seeds a pre-existing
* entry, forces a bad created entry, or swaps the entry through `onCreatePty`, so
* a test drives each rejection and the pre-launch re-check.
*/
function createFakeHomeFs(config?: {
loginUid?: number;
seed?: FakeEntry;
createAs?: FakeEntry;
createShouldFail?: boolean;
}): DaytonaLoginHomeFs & {
created: Array<{ path: string; mode: string }>;
inspectCount: number;
setEntry: (entry: FakeEntry | null) => void;
} {
const loginUid = config?.loginUid ?? LOGIN_UID;
const cleanDir: FakeEntry = {
isSymlink: false,
isDirectory: true,
mode: "700",
ownerUid: loginUid,
};
let entry: FakeEntry | null = config?.seed ?? null;
const created: Array<{ path: string; mode: string }> = [];
const state = { inspectCount: 0 };
return {
created,
get inspectCount() {
return state.inspectCount;
},
setEntry(next: FakeEntry | null): void {
entry = next;
},
async loginUserId(): Promise<number> {
return loginUid;
},
async inspect(): Promise<LoginHomeInspection> {
state.inspectCount += 1;
return entry ? { exists: true, ...entry } : ABSENT;
},
async createDirectory(path: string, mode: string): Promise<void> {
if (config?.createShouldFail || entry) {
throw new Error("LOGIN_PTY_HOME_REJECTED");
}
created.push({ path, mode });
entry = config?.createAs ?? cleanDir;
},
};
}
/**
* A fake Daytona PTY handle. It records each input write, drives the output
* stream on demand, and records the kill and the disconnect. The tests use it in
* place of the real SDK `PtyHandle`, so the session runs with no sandbox.
*/
function createFakePtyHandle(
onData: (data: Uint8Array) => void | Promise<void>,
onWaitForConnection?: () => void,
): DaytonaPtyHandle & {
inputs: string[];
emitText: (text: string) => void;
emitBytes: (bytes: Uint8Array) => void;
finish: (exitCode: number | undefined) => void;
killed: number;
disconnected: number;
} {
const encoder = new TextEncoder();
const inputs: string[] = [];
let resolveWait: ((value: { exitCode?: number; error?: string }) => void) | null = null;
const waitPromise = new Promise<{ exitCode?: number; error?: string }>((resolve) => {
resolveWait = resolve;
});
let killed = 0;
let disconnected = 0;
return {
async waitForConnection(): Promise<void> {
onWaitForConnection?.();
},
async sendInput(data: string | Uint8Array): Promise<void> {
inputs.push(typeof data === "string" ? data : new TextDecoder().decode(data));
},
wait(): Promise<{ exitCode?: number; error?: string }> {
return waitPromise;
},
async kill(): Promise<void> {
killed += 1;
},
async disconnect(): Promise<void> {
disconnected += 1;
},
emitText(text: string): void {
onData(encoder.encode(text));
},
emitBytes(bytes: Uint8Array): void {
onData(bytes);
},
finish(exitCode: number | undefined): void {
resolveWait?.({ exitCode });
},
get inputs(): string[] {
return inputs;
},
get killed(): number {
return killed;
},
get disconnected(): number {
return disconnected;
},
};
}
/**
* A fake Daytona process. It opens one fake PTY handle and records the create
* options, so a test asserts the terminal size and the launch line. `onCreatePty`
* runs when the session opens the terminal, so a test swaps a symlink in after
* the directory creation but before the launch input.
*/
function createFakeProcess(onCreatePty?: () => void): DaytonaPtyProcess & {
handle: ReturnType<typeof createFakePtyHandle> | null;
createOptions: DaytonaPtyCreateOptions | null;
createCount: number;
} {
const state: {
handle: ReturnType<typeof createFakePtyHandle> | null;
createOptions: DaytonaPtyCreateOptions | null;
createCount: number;
} = { handle: null, createOptions: null, createCount: 0 };
return {
get handle() {
return state.handle;
},
get createOptions() {
return state.createOptions;
},
get createCount() {
return state.createCount;
},
async createPty(options: DaytonaPtyCreateOptions): Promise<DaytonaPtyHandle> {
state.createCount += 1;
state.createOptions = options;
onCreatePty?.();
const handle = createFakePtyHandle(options.onData);
state.handle = handle;
return handle;
},
};
}
describe("encodePosixShellArg", () => {
it("wraps a value in single quotes and neutralizes metacharacters", () => {
expect(encodePosixShellArg("/tmp/x")).toBe("'/tmp/x'");
// A metacharacter, a space, and a semicolon stay literal inside the quotes.
expect(encodePosixShellArg("; rm -rf / #")).toBe("'; rm -rf / #'");
// An embedded single quote closes, escapes, and reopens the quote.
expect(encodePosixShellArg("a'b")).toBe("'a'\\''b'");
expect(encodePosixShellArg("$(id)")).toBe("'$(id)'");
});
});
describe("composeLaunchLine", () => {
it("composes the Claude line with no CODEX_HOME", () => {
const line = composeLaunchLine(CLAUDE);
expect(line).toBe("exec claude setup-token");
expect(line).not.toContain("CODEX_HOME");
});
it("composes the Codex line with exactly one encoded CODEX_HOME", () => {
const line = composeLaunchLine(CODEX);
expect(line).toBe(`exec env CODEX_HOME='${HOME}' codex login --device-auth`);
// Exactly one CODEX_HOME assignment, and the exact approved Codex command.
expect(line.match(/CODEX_HOME=/g)).toHaveLength(1);
expect(line.endsWith("codex login --device-auth")).toBe(true);
});
});
describe("openDaytonaLoginPtySession — session home", () => {
it("creates the exact UUID directory as a new 0700 directory owned by the login user", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs();
await openDaytonaLoginPtySession(process, fs, CLAUDE);
// The provider created the exact directory as a new 0700 directory.
expect(fs.created).toEqual([{ path: HOME, mode: "700" }]);
// The terminal opened and the launch line ran.
expect(process.createCount).toBe(1);
expect(process.handle?.inputs[0]).toBe("exec claude setup-token" + ENTER);
});
it("sends the Codex launch line with the encoded CODEX_HOME", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs();
await openDaytonaLoginPtySession(process, fs, CODEX);
expect(process.handle?.inputs[0]).toBe(
`exec env CODEX_HOME='${HOME}' codex login --device-auth` + ENTER,
);
// The Claude line carries no CODEX_HOME; the Codex line carries exactly one.
expect((process.handle?.inputs[0]?.match(/CODEX_HOME=/g) ?? []).length).toBe(1);
});
it("rejects a pre-existing target before it creates the directory", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs({
seed: { isSymlink: false, isDirectory: true, mode: "700", ownerUid: LOGIN_UID },
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
// The provider never created the directory and never opened the terminal.
expect(fs.created).toEqual([]);
expect(process.createCount).toBe(0);
});
it("rejects a pre-existing symlink at the target", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs({
seed: { isSymlink: true, isDirectory: false, mode: "777", ownerUid: LOGIN_UID },
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
expect(process.createCount).toBe(0);
});
it("rejects a created target that is a symlink", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs({
createAs: { isSymlink: true, isDirectory: false, mode: "700", ownerUid: LOGIN_UID },
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
expect(process.createCount).toBe(0);
});
it("rejects a created target that is not a directory", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs({
createAs: { isSymlink: false, isDirectory: false, mode: "700", ownerUid: LOGIN_UID },
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
expect(process.createCount).toBe(0);
});
it("rejects a created directory with a wrong owner", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs({
createAs: { isSymlink: false, isDirectory: true, mode: "700", ownerUid: LOGIN_UID + 1 },
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
expect(process.createCount).toBe(0);
});
it("rejects a created directory with a wrong mode", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs({
createAs: { isSymlink: false, isDirectory: true, mode: "755", ownerUid: LOGIN_UID },
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
expect(process.createCount).toBe(0);
});
it("rejects a symlink swapped in after creation, before the launch input", async () => {
// The directory validates cleanly, then a symlink replaces it while the
// terminal opens. The no-symlink re-check before the launch input fails.
const fs = createFakeHomeFs();
const process = createFakeProcess(() => {
fs.setEntry({ isSymlink: true, isDirectory: false, mode: "777", ownerUid: LOGIN_UID });
});
await expect(openDaytonaLoginPtySession(process, fs, CLAUDE)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
// The terminal opened, but the launch input never ran.
expect(process.createCount).toBe(1);
expect(process.handle?.inputs).toEqual([]);
});
it("rejects a descriptor with a command key outside the closed set", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs();
await expect(
openDaytonaLoginPtySession(process, fs, {
loginCommandKey: "gemini" as unknown as "claude",
sessionHome: HOME,
}),
).rejects.toThrow("LOGIN_PTY_DESCRIPTOR_REJECTED");
// The provider never touched the filesystem or the terminal.
expect(fs.created).toEqual([]);
expect(process.createCount).toBe(0);
});
it("rejects a descriptor whose session home shape is wrong", async () => {
const process = createFakeProcess();
const fs = createFakeHomeFs();
await expect(
openDaytonaLoginPtySession(process, fs, {
loginCommandKey: "codex",
sessionHome: "/tmp/paperclip-adapter-login/../etc",
}),
).rejects.toThrow("LOGIN_PTY_DESCRIPTOR_REJECTED");
expect(process.createCount).toBe(0);
});
});
describe("openDaytonaLoginPtySession — session mechanics", () => {
it("starts the login command on a pseudo-terminal with a fixed size", async () => {
const process = createFakeProcess();
await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
expect(process.createOptions?.cols).toBe(120);
expect(process.createOptions?.rows).toBe(30);
expect(process.handle?.inputs[0]).toBe("exec claude setup-token" + ENTER);
});
it("returns incremental terminal output to the listener", async () => {
const process = createFakeProcess();
const received: string[] = [];
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
session.onData((chunk) => received.push(chunk));
process.handle?.emitText("the url below to sign in\n");
process.handle?.emitText("Paste code here if prompted\n");
expect(received).toEqual(["the url below to sign in\n", "Paste code here if prompted\n"]);
});
it("buffers early output until the listener registers", async () => {
const process = createFakeProcess();
const received: string[] = [];
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
process.handle?.emitText("early output ");
process.handle?.emitText("more output");
expect(received).toEqual([]);
session.onData((chunk) => received.push(chunk));
expect(received).toEqual(["early output more output"]);
});
it("delivers the browser code plus the Enter byte to the command", async () => {
const process = createFakeProcess();
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
session.write("BROWSERCODE" + ENTER);
// The write runs through the serialized chunk chain, so it lands on a later
// microtask. Flush the chain before the assertion.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(process.handle?.inputs[1]).toBe("BROWSERCODE" + ENTER);
expect(process.handle?.inputs[1]?.endsWith(ENTER)).toBe(true);
});
it("keeps a multibyte character whole across two output chunks", async () => {
const process = createFakeProcess();
const received: string[] = [];
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
session.onData((chunk) => received.push(chunk));
const euro = new TextEncoder().encode("€");
process.handle?.emitBytes(euro.subarray(0, 2));
process.handle?.emitBytes(euro.subarray(2));
expect(received.join("")).toBe("€");
});
it("resolves wait with the command exit code", async () => {
const process = createFakeProcess();
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
process.handle?.finish(9);
await expect(session.wait()).resolves.toEqual({ exitCode: 9 });
});
it("maps an absent exit code to null", async () => {
const process = createFakeProcess();
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
process.handle?.finish(undefined);
await expect(session.wait()).resolves.toEqual({ exitCode: null });
});
it("kills the child and closes the session", async () => {
const process = createFakeProcess();
const session = await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE);
session.kill();
expect(process.handle?.killed).toBe(1);
await session.close();
expect(process.handle?.disconnected).toBe(1);
});
it("passes the working directory to the pseudo-terminal", async () => {
const process = createFakeProcess();
await openDaytonaLoginPtySession(process, createFakeHomeFs(), CLAUDE, { cwd: "/workspace" });
expect(process.createOptions?.cwd).toBe("/workspace");
});
});
describe("openDaytonaLoginPtySession — ancestor symlink", () => {
it("starts no pseudo-terminal when the home filesystem check fails closed", async () => {
// A symlinked login-root ancestor makes the descriptor-relative inspection fail
// closed. The session opener must reject before it opens the terminal, so no
// pseudo-terminal starts and the login command never runs.
const process = createFakeProcess();
let created = false;
const fs: DaytonaLoginHomeFs = {
async loginUserId(): Promise<number> {
return LOGIN_UID;
},
async inspect(): Promise<LoginHomeInspection> {
throw new Error("LOGIN_PTY_HOME_REJECTED");
},
async createDirectory(): Promise<void> {
created = true;
},
};
await expect(openDaytonaLoginPtySession(process, fs, CODEX)).rejects.toThrow(
"LOGIN_PTY_HOME_REJECTED",
);
// The provider never created the directory and never opened the terminal.
expect(created).toBe(false);
expect(process.createCount).toBe(0);
});
});
describe("createDaytonaLoginHomeFs — login-profile preamble", () => {
// A capturing exec surface. It records each command and returns a fixed result,
// so a test reads the exact command string the helper runs.
function createCapturingExec(result: DaytonaExecResult): DaytonaSandboxExec & {
commands: string[];
} {
const commands: string[] = [];
return {
commands,
async executeCommand(command: string): Promise<DaytonaExecResult> {
commands.push(command);
// `id -u` resolves the login user id. Return a fixed uid so the caller
// continues to the node helper command under test.
if (command.startsWith("id -u")) {
return { exitCode: 0, result: "1000" };
}
return result;
},
};
}
// The command sources /etc/profile before it runs node. The Daytona image may
// expose node only through a login profile, so node must run after the profile
// source. This assertion proves the helper runtime and the login PTY capability
// stay consistent.
function expectProfileBeforeNode(command: string | undefined): void {
expect(command).toBeDefined();
const profileIndex = command!.indexOf("/etc/profile");
const nodeIndex = command!.indexOf("node -e");
expect(profileIndex).toBeGreaterThanOrEqual(0);
expect(nodeIndex).toBeGreaterThanOrEqual(0);
expect(profileIndex).toBeLessThan(nodeIndex);
}
it("sources the login profiles before it runs the node inspect helper", async () => {
const exec = createCapturingExec({ exitCode: 0, result: "ABSENT" });
const fs = createDaytonaLoginHomeFs(exec);
await fs.inspect(HOME);
expectProfileBeforeNode(exec.commands.find((command) => command.includes("node -e")));
});
it("sources the login profiles before it runs the node create helper", async () => {
const exec = createCapturingExec({ exitCode: 0, result: "" });
const fs = createDaytonaLoginHomeFs(exec);
await fs.createDirectory(HOME, "700");
expectProfileBeforeNode(exec.commands.find((command) => command.includes("node -e")));
});
});
// The real login-home filesystem runs a node helper on the sandbox. The helper
// walks the path with `/proc/self/fd`, which is Linux only. A non-Linux host skips
// these tests. The fake exec runs the helper locally, so the descriptor-relative
// walk is tested against a real filesystem. The login sandbox is Linux.
const describeLinux = process.platform === "linux" ? describe : describe.skip;
describeLinux("createDaytonaLoginHomeFs — descriptor-relative walk", () => {
let root: string;
beforeAll(() => {
root = mkdtempSync(path.join(tmpdir(), "daytona-login-home-"));
});
afterAll(() => {
rmSync(root, { recursive: true, force: true });
});
// A local exec surface. It runs the composed command with `/bin/sh -c`, so the
// real node helper runs against the local filesystem.
function createLocalExec(): DaytonaSandboxExec {
return {
async executeCommand(command: string): Promise<DaytonaExecResult> {
const result = spawnSync("/bin/sh", ["-c", command], { encoding: "utf8" });
return { exitCode: result.status ?? undefined, result: result.stdout ?? "" };
},
};
}
const UUID = "11111111-2222-4333-8444-555555555555";
it("reports a not-yet-created target as absent", async () => {
const fs = createDaytonaLoginHomeFs(createLocalExec());
const home = path.join(root, "absent-root", UUID);
const inspection = await fs.inspect(home);
expect(inspection.exists).toBe(false);
});
it("creates the login root and the session home relative to a trusted descriptor", async () => {
const fs = createDaytonaLoginHomeFs(createLocalExec());
const home = path.join(root, "clean-root", UUID);
await fs.createDirectory(home, "700");
const inspection = await fs.inspect(home);
expect(inspection.exists).toBe(true);
expect(inspection.isSymlink).toBe(false);
expect(inspection.isDirectory).toBe(true);
expect(inspection.mode).toBe("700");
expect(inspection.ownerUid).toBe(process.getuid ? process.getuid() : inspection.ownerUid);
});
it("rejects a pre-existing session home target", async () => {
const fs = createDaytonaLoginHomeFs(createLocalExec());
const home = path.join(root, "exists-root", UUID);
await fs.createDirectory(home, "700");
// A second create of the same target fails, because the target exists.
await expect(fs.createDirectory(home, "700")).rejects.toThrow("LOGIN_PTY_HOME_REJECTED");
});
it("fails the inspection closed when the login root is a symlink", async () => {
// Pre-place a symlink at the login-root ancestor. The descriptor-relative walk
// opens the root with a no-follow open, so the inspection fails closed.
const fs = createDaytonaLoginHomeFs(createLocalExec());
const attacker = path.join(root, "inspect-attacker");
mkdirSync(attacker, { mode: 0o700 });
const rootLink = path.join(root, "inspect-symlink-root");
symlinkSync(attacker, rootLink);
const home = path.join(rootLink, UUID);
await expect(fs.inspect(home)).rejects.toThrow("LOGIN_PTY_HOME_REJECTED");
});
it("fails the creation closed when the login root is a pre-placed symlink", async () => {
// Pre-place a symlink at the login-root ancestor that points at an attacker
// tree. The creation opens the root with a no-follow open after the tolerant
// `mkdir`, so it fails closed and creates no directory in the attacker tree.
const fs = createDaytonaLoginHomeFs(createLocalExec());
const attacker = path.join(root, "create-attacker");
mkdirSync(attacker, { mode: 0o700 });
const rootLink = path.join(root, "create-symlink-root");
symlinkSync(attacker, rootLink);
const home = path.join(rootLink, UUID);
await expect(fs.createDirectory(home, "700")).rejects.toThrow("LOGIN_PTY_HOME_REJECTED");
// The creation placed no session home inside the attacker tree.
expect(existsSync(path.join(attacker, UUID))).toBe(false);
});
});
describe("createDaytonaLoginPtySessionOpener", () => {
it("opens a session for the descriptor on each call", async () => {
const process = createFakeProcess();
const opener = createDaytonaLoginPtySessionOpener(process, createFakeHomeFs(), {
cwd: "/workspace",
});
const session = await opener(CLAUDE);
expect(process.createOptions?.cwd).toBe("/workspace");
expect(process.handle?.inputs[0]).toBe("exec claude setup-token" + ENTER);
expect(typeof session.onData).toBe("function");
expect(typeof session.write).toBe("function");
expect(typeof session.wait).toBe("function");
expect(typeof session.kill).toBe("function");
expect(typeof session.close).toBe("function");
});
});
@@ -0,0 +1,586 @@
// The Daytona pseudo-terminal (PTY) session for the shared login flow. The login
// command needs a real pseudo-terminal: pipe stdio emits no login prompt. The
// Daytona SDK opens a PTY through `process.createPty`. This module binds that PTY
// to a small session that the login PTY transport consumes, so the login runner
// runs the command on a real terminal, streams the terminal output, and delivers
// the delayed browser code plus the Enter byte.
//
// Command contract: the host resolves a closed login command key and a validated
// session home, and it carries them in a launch descriptor. The descriptor holds
// no command string. This module maps the key to a compile-time command, so a
// caller cannot select or override the command. For the Codex key the module
// composes `exec env CODEX_HOME=<encoded-home> <fixed-codex-command>`. For the
// Claude key it composes `exec <fixed-claude-command>` with no CODEX_HOME. The
// module encodes the dynamic home with a POSIX shell-argument encoder, so the
// home cannot add a second shell token or a second command.
//
// Session home: the module revalidates the descriptor and the home shape, then
// creates the exact UUID directory as a NEW directory with mode 0700, owned by the
// login user. The inspection and the creation open the filesystem root, then walk
// each path component with a no-follow, directory-only open, so a symlink at any
// ancestor (the login root or a directory above it) fails closed. A single
// composite `stat` or `mkdir` follows a symlink at an ancestor; the per-component
// walk does not. The creation creates the login root if the root is absent and the
// UUID directory as a NEW directory, both relative to an open trusted descriptor.
// The module rejects a pre-existing target, a symlink, a non-directory, a wrong
// owner, and a wrong mode. It uses no recursive delete. It re-checks the directory
// with a no-symlink walk before it opens the terminal and again before it sends the
// launch input, so a symlink swapped in after creation fails before the launch.
//
// Dependency boundary: this provider plugin ships standalone (the workspace
// excludes `packages/plugins/sandbox-providers/**`). So the module imports no
// workspace package. It declares the small session shape locally through
// {@link LoginPtySession}. The shape matches the `LoginPtySession` interface in
// `@paperclipai/adapter-utils`, so the transport factory `createLoginPtyTransport`
// accepts the session opener from this module with no adapter. The runner drives
// the transport; the transport drives this session.
//
// SDK boundary: the module holds no Daytona SDK type import. It declares the small
// subset of the SDK PTY and filesystem surfaces that it uses through
// {@link DaytonaPtyProcess}, {@link DaytonaPtyHandle}, and {@link DaytonaSandboxExec}.
// The SDK `Process` and `PtyHandle` satisfy those subsets, so a caller passes
// `sandbox.process` with no adapter. The narrow surface keeps the module
// unit-testable with a fake PTY and a fake filesystem.
//
// Security (secret handling): the login runner delivers the browser code and the
// Enter byte through {@link DaytonaPtyHandle.sendInput}. The SDK sends the input
// over the PTY socket, so the code never rides a command line and never reaches a
// process argument list. The session forwards the raw terminal bytes with no ANSI
// or OSC 8 handling; the login parser owns that handling.
import { randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { sendPtyInputInChunks } from "./pty-chunked-input.js";
/**
* The closed set of login command identities. The worker maps each key to a
* compile-time command. A value outside this set fails closed before the module
* touches the filesystem.
*/
export type LoginCommandKey = "claude" | "codex";
/**
* The host-resolved launch descriptor. It carries the closed command key and the
* server-controlled session home. It holds no command string.
*/
export interface LoginPtyLaunchDescriptor {
/** The host-resolved fixed command identity. */
loginCommandKey: LoginCommandKey;
/**
* The server-controlled session home. The shape is exact:
* `/tmp/paperclip-adapter-login/<uuid>`.
*/
sessionHome: string;
}
/**
* The compile-time command for each login command key. The Daytona plugin ships
* standalone, so it holds its own copy of the fixed commands. A future change to
* a command lands here and in the adapter constant together.
*/
const LOGIN_COMMAND_BY_KEY: Readonly<Record<LoginCommandKey, string>> = {
claude: "claude setup-token",
codex: "codex login --device-auth",
};
/** The octal mode string for a new session home directory. */
const LOGIN_HOME_MODE = "700";
/** The fixed root for a login session home. */
const LOGIN_SESSION_HOME_ROOT = "/tmp/paperclip-adapter-login";
/**
* The exact absolute path shape for a login session home. The path is the fixed
* root, one slash, and one UUID. The anchors reject a relative path, a traversal,
* whitespace, a control character, and a shell metacharacter, because none of
* those match the UUID or the fixed root.
*/
const SESSION_HOME_PATTERN =
/^\/tmp\/paperclip-adapter-login\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
/** The fixed non-secret error a rejected launch descriptor or session home returns. */
export const LOGIN_PTY_DESCRIPTOR_REJECTED = "LOGIN_PTY_DESCRIPTOR_REJECTED";
/** The fixed non-secret error a rejected session home directory returns. */
export const LOGIN_PTY_HOME_REJECTED = "LOGIN_PTY_HOME_REJECTED";
/**
* Encodes one value as a single POSIX shell argument. It wraps the value in
* single quotes and escapes each embedded single quote. The shell treats every
* other character inside single quotes as a literal, so an encoded value cannot
* add a second shell token or a second command.
*/
export function encodePosixShellArg(value: string): string {
return `'${value.split("'").join("'\\''")}'`;
}
/** Reports whether a value is a member of the closed login command key set. */
export function isLoginCommandKey(value: unknown): value is LoginCommandKey {
return value === "claude" || value === "codex";
}
/**
* Composes the launch line for the descriptor. For the Codex key it prefixes one
* safely encoded `CODEX_HOME` assignment with `env`. For the Claude key it adds no
* `CODEX_HOME`. It replaces the interactive shell with the command through `exec`,
* so the pseudo-terminal runs the command directly and its exit code becomes the
* PTY exit code.
*/
export function composeLaunchLine(descriptor: LoginPtyLaunchDescriptor): string {
const command = LOGIN_COMMAND_BY_KEY[descriptor.loginCommandKey];
if (descriptor.loginCommandKey === "codex") {
const encodedHome = encodePosixShellArg(descriptor.sessionHome);
return `exec env CODEX_HOME=${encodedHome} ${command}`;
}
return `exec ${command}`;
}
/**
* A live pseudo-terminal session for one login command. The session allocates a
* real pseudo-terminal, streams the raw terminal output, accepts delayed input,
* and stops the child. The shape matches the `LoginPtySession` interface in
* `@paperclipai/adapter-utils`, so the transport factory there accepts a session
* opener that returns this session.
*/
export interface LoginPtySession {
/** Registers the one output listener. The session streams each raw chunk in order. */
onData(listener: (chunk: string) => void): void;
/** Writes raw input bytes to the pseudo-terminal. */
write(data: string): void;
/** Resolves with the child exit code when the command ends. */
wait(): Promise<{ exitCode: number | null }>;
/** Stops the child process. Safe to call more than one time. */
kill(): void;
/** Releases the session resources. Safe to call more than one time. */
close(): Promise<void>;
}
/** Opens a {@link LoginPtySession} for `descriptor`. The transport calls it one time. */
export type LoginPtySessionOpener = (
descriptor: LoginPtyLaunchDescriptor,
) => Promise<LoginPtySession>;
/**
* The subset of the Daytona SDK `PtyHandle` that the session uses. The SDK
* `PtyHandle` satisfies this interface, so a caller passes the real handle with
* no adapter.
*/
export interface DaytonaPtyHandle {
/** Resolves when the PTY socket connection is ready for input and output. */
waitForConnection(): Promise<void>;
/** Sends raw input bytes to the pseudo-terminal. */
sendInput(data: string | Uint8Array): Promise<void>;
/** Resolves with the exit result when the pseudo-terminal process ends. */
wait(): Promise<{ exitCode?: number; error?: string }>;
/** Kills the pseudo-terminal process. */
kill(): Promise<void>;
/** Closes the PTY socket and releases the resources. */
disconnect(): Promise<void>;
}
/**
* The options the session passes to `createPty`. The session sets a fixed
* terminal size and one output callback. It sets the working directory when the
* caller provides one.
*/
export interface DaytonaPtyCreateOptions {
id: string;
cwd?: string;
cols: number;
rows: number;
onData: (data: Uint8Array) => void | Promise<void>;
}
/**
* The subset of the Daytona SDK `Process` that the session uses. The SDK
* `Process` satisfies this interface, so a caller passes `sandbox.process`.
*/
export interface DaytonaPtyProcess {
createPty(options: DaytonaPtyCreateOptions): Promise<DaytonaPtyHandle>;
}
/** The result of one command run on the sandbox. */
export interface DaytonaExecResult {
exitCode?: number;
result?: string;
}
/**
* The subset of the Daytona SDK `Process` that the filesystem helper uses. The
* SDK `Process` satisfies this interface through `executeCommand`, so a caller
* passes `sandbox.process`.
*/
export interface DaytonaSandboxExec {
executeCommand(
command: string,
cwd?: string,
env?: Record<string, string>,
timeout?: number,
): Promise<DaytonaExecResult>;
}
/** One no-follow inspection of a filesystem path. */
export interface LoginHomeInspection {
/** True when the path exists (as any type). */
exists: boolean;
/** True when the path itself is a symbolic link. */
isSymlink: boolean;
/** True when the path itself is a directory. */
isDirectory: boolean;
/** The octal permission string, for example `700`. Empty when the path is absent. */
mode: string;
/** The owner user id, or null when the path is absent. */
ownerUid: number | null;
}
/**
* The narrow filesystem surface the session home operations need. The production
* surface runs commands on the sandbox; a unit test injects a fake. The inspection
* and the creation walk each path component with a no-follow open, so a symlink at
* any ancestor fails closed and a symlink at the target reports the link.
*/
export interface DaytonaLoginHomeFs {
/** Resolves the user id of the login user that runs the pseudo-terminal. */
loginUserId(): Promise<number>;
/**
* Inspects `path` without following a symlink at the target or at any ancestor.
* It rejects (throws) when an ancestor is a symlink or a non-directory.
*/
inspect(path: string): Promise<LoginHomeInspection>;
/**
* Creates `path` as a NEW directory with the octal `mode`. It creates the login
* root ancestor if the root is absent. It fails when the target path exists or
* when an ancestor is a symlink. It follows no composite pathname.
*/
createDirectory(path: string, mode: string): Promise<void>;
}
/** The options for the Daytona login PTY session. */
export interface DaytonaLoginPtyOptions {
/** The working directory for the login PTY. Defaults to the sandbox default. */
cwd?: string;
}
// The terminal size for the login PTY. The login UI prints a short prompt, so a
// standard terminal size is enough. A fixed size keeps the output stable.
const LOGIN_PTY_COLS = 120;
const LOGIN_PTY_ROWS = 30;
/**
* The input terminator that replaces the interactive shell with the login
* command. The `exec` builtin replaces the shell process image with the command,
* so the PTY runs the command directly. When the command ends, the PTY ends with
* the command exit code, and the delayed input reaches the command, not a shell.
* The terminal reads the carriage return as the Enter key.
*/
const PTY_COMMAND_TERMINATOR = "\r";
/** Normalizes an octal permission string to its numeric value for comparison. */
function octalMode(value: string): number {
return Number.parseInt(value, 8);
}
/**
* Revalidates the launch descriptor. It fails closed when the command key is
* outside the closed set or the session home shape is wrong. A unit test that
* bypasses the host boundary hits this check, so the provider never trusts an
* unvalidated descriptor.
*/
function assertDescriptor(descriptor: LoginPtyLaunchDescriptor): void {
if (!isLoginCommandKey(descriptor.loginCommandKey)) {
throw new Error(LOGIN_PTY_DESCRIPTOR_REJECTED);
}
if (!SESSION_HOME_PATTERN.test(descriptor.sessionHome)) {
throw new Error(LOGIN_PTY_DESCRIPTOR_REJECTED);
}
}
/**
* Creates and validates the exact session home directory. It rejects a
* pre-existing target (including a symlink), creates the directory as a NEW
* directory with mode 0700, then verifies the directory type, the no-symlink
* state, the mode, and the login-user ownership. It uses no recursive delete.
*/
async function prepareSessionHome(fs: DaytonaLoginHomeFs, sessionHome: string): Promise<void> {
const loginUid = await fs.loginUserId();
// Reject a pre-existing target. A no-follow inspection reports a symlink, a
// file, or a directory as present, so any pre-existing target fails here.
const before = await fs.inspect(sessionHome);
if (before.exists) {
throw new Error(LOGIN_PTY_HOME_REJECTED);
}
// Create the exact directory as a NEW directory with mode 0700. The create
// fails when the path exists, so the create never follows a symlink.
await fs.createDirectory(sessionHome, LOGIN_HOME_MODE);
// Verify the created directory. Reject a symlink, a non-directory, a wrong
// owner, and a wrong mode. Do not delete on a rejection; the sandbox is
// ephemeral and the provider uses no recursive delete.
const after = await fs.inspect(sessionHome);
if (
!after.exists ||
after.isSymlink ||
!after.isDirectory ||
after.ownerUid !== loginUid ||
octalMode(after.mode) !== octalMode(LOGIN_HOME_MODE)
) {
throw new Error(LOGIN_PTY_HOME_REJECTED);
}
}
/**
* Re-checks the directory with a no-symlink check. It rejects a symlink and a
* non-directory, so a symlink swapped in after creation fails before the launch.
*/
async function assertHomeStillSafe(fs: DaytonaLoginHomeFs, sessionHome: string): Promise<void> {
const now = await fs.inspect(sessionHome);
if (!now.exists || now.isSymlink || !now.isDirectory) {
throw new Error(LOGIN_PTY_HOME_REJECTED);
}
}
/**
* Opens a Daytona PTY session for `descriptor` and returns it as a
* {@link LoginPtySession}. The function revalidates the descriptor and the home
* shape, creates and validates the session home, opens a real pseudo-terminal,
* re-checks the directory before the launch, composes the safe launch line, and
* sends it. The session streams the raw terminal output, delivers delayed input,
* and stops the child.
*
* The function decodes the terminal bytes as a UTF-8 stream, so a multibyte
* character that splits across two output chunks stays whole. It buffers the
* output until the transport registers the listener, so no early chunk is lost.
*/
export async function openDaytonaLoginPtySession(
process: DaytonaPtyProcess,
fs: DaytonaLoginHomeFs,
descriptor: LoginPtyLaunchDescriptor,
options?: DaytonaLoginPtyOptions,
): Promise<LoginPtySession> {
assertDescriptor(descriptor);
// Create and validate the session home before the terminal opens.
await prepareSessionHome(fs, descriptor.sessionHome);
// Re-check the directory with a no-symlink check before `createPty`.
await assertHomeStillSafe(fs, descriptor.sessionHome);
const decoder = new TextDecoder("utf-8");
let listener: ((chunk: string) => void) | null = null;
let buffered = "";
const handle = await process.createPty({
id: `paperclip-login-pty-${randomUUID()}`,
...(options?.cwd ? { cwd: options.cwd } : {}),
cols: LOGIN_PTY_COLS,
rows: LOGIN_PTY_ROWS,
onData: (data: Uint8Array): void => {
// Decode the terminal bytes as a stream, so a split multibyte character
// stays whole across two chunks. Forward the raw text; the parser owns the
// ANSI and OSC 8 handling.
const text = decoder.decode(data, { stream: true });
if (text.length === 0) return;
if (listener) listener(text);
else buffered += text;
},
});
await handle.waitForConnection();
// Re-check the directory with a no-symlink check immediately before the launch
// input, so a symlink swapped in after creation fails before `sendInput`.
await assertHomeStillSafe(fs, descriptor.sessionHome);
// Replace the interactive shell with the login command, so the pseudo-terminal
// runs the command directly. The runner then writes the delayed browser code
// to the command, not to a shell.
await handle.sendInput(composeLaunchLine(descriptor) + PTY_COMMAND_TERMINATOR);
// The tail of the write chain. The chunker awaits each chunk, so one write can
// suspend between its chunks. The chain runs each write after the previous
// write ends, so the chunks of two writes never interleave on the wire.
let writeChain: Promise<void> = Promise.resolve();
return {
onData(next: (chunk: string) => void): void {
listener = next;
if (buffered.length > 0) {
const pending = buffered;
buffered = "";
next(pending);
}
},
write(data: string): void {
// Send the input as byte-bounded chunks under the provider message cap. The
// login input is short today, so the latent defect never fires, but the same
// unbounded write goes through the one chunker. The chain runs this write
// after the previous write ends, so two writes keep their order and never
// interleave their chunks. A write error must not throw into the runner, so
// the runner's fixed status stays the single result path.
writeChain = writeChain.then(() =>
sendPtyInputInChunks((chunk) => handle.sendInput(chunk), data),
);
},
async wait(): Promise<{ exitCode: number | null }> {
const result = await handle.wait();
return { exitCode: typeof result.exitCode === "number" ? result.exitCode : null };
},
kill(): void {
void handle.kill().catch(() => undefined);
},
async close(): Promise<void> {
await handle.disconnect().catch(() => undefined);
},
};
}
/**
* The inspection helper source. The provider reads it from its own script file and
* runs it on the sandbox as `<login-profile-preamble> && node -e <script> <path>`.
* The preamble sources the login profiles first, so `node` resolves on an image
* that exposes node only through a login profile. The sandbox already runs node
* for the Paperclip bridge, so the helper needs no extra runtime. The helper
* source lives in `scripts/login-home-inspect.cjs`, so no large script stays as a
* string literal in this module. The helper opens the filesystem root, then walks
* each ancestor of the final path component with a no-follow, directory-only open,
* and reads the final component with `lstat`.
*
* The helper prints one line and sets one exit code:
* - a missing ancestor or a missing final component prints `ABSENT` and exits 0;
* - an existing final component prints `<type>|<octal-mode>|<uid>` and exits 0,
* where `<type>` is `symlink`, `directory`, or `other`;
* - a symlink or a non-directory at any ancestor prints nothing and exits 3, so
* the caller fails closed on an ancestor symlink.
*/
const LOGIN_HOME_INSPECT_SCRIPT = readFileSync(
fileURLToPath(new URL("./scripts/login-home-inspect.cjs", import.meta.url)),
"utf8",
);
/**
* The creation helper source. The provider reads it from its own script file and
* runs it on the sandbox as
* `<login-profile-preamble> && node -e <script> <path> <octal-mode>`. The preamble
* sources the login profiles first, so `node` resolves on an image that exposes
* node only through a login profile. The helper source lives in
* `scripts/login-home-create.cjs`. The helper opens the filesystem
* root, then walks each ancestor above the login root with a no-follow,
* directory-only open. It creates the login root (the second-to-last component) if
* the root is absent, then opens the root with a no-follow open, so a symlink at
* the root fails closed. It creates the final component as a NEW directory relative
* to the root descriptor, so a pre-existing target fails and the create never
* follows a symlink. It exits 0 on success and non-zero on every failure.
*
* The no-follow open of the root after the create closes the swap window: an
* attacker that replaces the root with a symlink between the create and the open
* fails the open.
*/
const LOGIN_HOME_CREATE_SCRIPT = readFileSync(
fileURLToPath(new URL("./scripts/login-home-create.cjs", import.meta.url)),
"utf8",
);
/**
* The login-profile preamble for a node helper command. Daytona's
* `executeCommand` runs the command in a non-login shell, so the shell does not
* source `/etc/profile` on its own. The Daytona reference image puts `node` on
* the PATH through `/etc/profile.d`, which only a login profile sources. The
* login pseudo-terminal resolves the login command through the same profiles, so
* the helper sources the login profiles first and a non-login shell then resolves
* `node`. This keeps the helper runtime and the login PTY capability consistent:
* an image that exposes `node` only through a login profile runs the helper. The
* main exec path uses the same profile chain (see `buildLoginShellScript` in
* `plugin.ts`). Each source line fails open (`|| true`), so a missing profile
* does not fail the helper.
*/
const LOGIN_PROFILE_PREAMBLE = [
"if [ -f /etc/profile ]; then . /etc/profile >/dev/null 2>&1 || true; fi",
'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile" >/dev/null 2>&1 || true; elif [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc" >/dev/null 2>&1 || true; fi',
'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile" >/dev/null 2>&1 || true; fi',
].join(" && ");
/**
* Composes a `node` helper command that runs after the login-profile preamble.
* The preamble puts `node` on the PATH, then the `&&` chain runs `node -e` with
* the already shell-encoded argument list. The `node` exit code becomes the
* command exit code, and `2>/dev/null` suppresses only the node stderr. The
* caller passes an argument string that is already shell-encoded.
*/
function composeNodeHelperCommand(encodedArgs: string): string {
return `${LOGIN_PROFILE_PREAMBLE} && node -e ${encodedArgs} 2>/dev/null`;
}
/**
* Creates a {@link DaytonaLoginHomeFs} bound to a Daytona `process`. It runs a
* fixed node helper on the sandbox to inspect and create the session home. Each
* helper opens the filesystem root, then walks each path component with a
* no-follow, directory-only open, so a symlink at any ancestor fails closed. The
* inspection reads the final component with `lstat`, so a symlink at the target
* reports the link. The creation creates the login root if absent and the session
* home as a NEW directory, both relative to an open trusted descriptor, so no
* operation follows a composite pathname. The real filesystem operations land
* against a live sandbox; a unit test injects a fake surface instead.
*/
export function createDaytonaLoginHomeFs(exec: DaytonaSandboxExec): DaytonaLoginHomeFs {
return {
async loginUserId(): Promise<number> {
const out = await exec.executeCommand("id -u");
const uid = Number.parseInt((out.result ?? "").trim(), 10);
if (!Number.isInteger(uid)) {
throw new Error(LOGIN_PTY_HOME_REJECTED);
}
return uid;
},
async inspect(path: string): Promise<LoginHomeInspection> {
// Read the file type, the octal mode, and the owner uid with a descriptor
// relative no-follow walk. A non-zero exit means a symlink or a non-directory
// at an ancestor, so the read fails closed. An `ABSENT` line means the target
// does not exist yet, which is the safe precondition for a create.
const script = encodePosixShellArg(LOGIN_HOME_INSPECT_SCRIPT);
const encodedPath = encodePosixShellArg(path);
const out = await exec.executeCommand(composeNodeHelperCommand(`${script} ${encodedPath}`));
if ((out.exitCode ?? 0) !== 0) {
throw new Error(LOGIN_PTY_HOME_REJECTED);
}
const text = (out.result ?? "").trim();
if (text.length === 0 || text === "ABSENT") {
return { exists: false, isSymlink: false, isDirectory: false, mode: "", ownerUid: null };
}
const [fileType = "", mode = "", ownerText = ""] = text.split("|");
const ownerUid = Number.parseInt(ownerText, 10);
return {
exists: true,
isSymlink: fileType === "symlink",
isDirectory: fileType === "directory",
mode,
ownerUid: Number.isInteger(ownerUid) ? ownerUid : null,
};
},
async createDirectory(path: string, mode: string): Promise<void> {
const script = encodePosixShellArg(LOGIN_HOME_CREATE_SCRIPT);
const encodedPath = encodePosixShellArg(path);
const encodedMode = encodePosixShellArg(mode);
const out = await exec.executeCommand(
composeNodeHelperCommand(`${script} ${encodedPath} ${encodedMode}`),
);
if ((out.exitCode ?? 0) !== 0) {
throw new Error(LOGIN_PTY_HOME_REJECTED);
}
},
};
}
/**
* Creates a {@link LoginPtySessionOpener} bound to a Daytona `process` and a
* {@link DaytonaLoginHomeFs}. The opener runs the login command on a real
* pseudo-terminal, streams the terminal output, delivers the delayed browser code
* plus the Enter byte, and stops the child for a terminal state.
*/
export function createDaytonaLoginPtySessionOpener(
process: DaytonaPtyProcess,
fs: DaytonaLoginHomeFs,
options?: DaytonaLoginPtyOptions,
): LoginPtySessionOpener {
return (descriptor: LoginPtyLaunchDescriptor) =>
openDaytonaLoginPtySession(process, fs, descriptor, options);
}
@@ -67,7 +67,11 @@ const manifest: PaperclipPluginManifestV1 = {
supportsTemplateDelete: true,
// Daytona hosts an interactive login on a real pseudo-terminal. It is the
// only bundled provider that implements the login pseudo-terminal methods,
// so it advertises the capability.
// so it advertises the capability. The session home helpers and the
// credential reader run on node, and the sandbox already runs node for the
// Paperclip bridge. So the login has no extra runtime prerequisite, and the
// advertised capability matches the runtime contract for every configured
// image or snapshot.
supportsLoginPty: true,
configSchema: {
type: "object",
@@ -46,25 +46,32 @@ import { performSyncIn, performSyncOut, withProviderSpan } from "./file-sync.js"
// The session runs the login command on a real pseudo-terminal, streams the
// terminal output, and delivers the delayed browser code plus the Enter byte. A
// later phase binds the opener to `sandbox.process` and wraps it with the
// `createSetupTokenPtyTransport` factory from `@paperclipai/adapter-utils` to
// `createLoginPtyTransport` factory from `@paperclipai/adapter-utils` to
// build the transport the login runner drives.
export {
createDaytonaSetupTokenPtySessionOpener,
openDaytonaSetupTokenPtySession,
} from "./setup-token-pty.js";
createDaytonaLoginPtySessionOpener,
openDaytonaLoginPtySession,
createDaytonaLoginHomeFs,
} from "./login-pty.js";
export type {
SetupTokenPtySession,
SetupTokenPtySessionOpener,
LoginPtySession,
LoginPtySessionOpener,
LoginPtyLaunchDescriptor,
DaytonaPtyHandle,
DaytonaPtyProcess,
DaytonaPtyCreateOptions,
DaytonaSetupTokenPtyOptions,
} from "./setup-token-pty.js";
import { openDaytonaSetupTokenPtySession as openSetupTokenPtySession } from "./setup-token-pty.js";
DaytonaLoginPtyOptions,
DaytonaLoginHomeFs,
} from "./login-pty.js";
import {
openDaytonaLoginPtySession as openLoginPtySession,
createDaytonaLoginHomeFs,
} from "./login-pty.js";
import type {
SetupTokenPtySession as SetupTokenPtyWorkerSession,
LoginPtySession as LoginPtyWorkerSession,
DaytonaPtyProcess,
} from "./setup-token-pty.js";
DaytonaSandboxExec,
} from "./login-pty.js";
// The Daytona duplex command stream for the sandbox callback bridge. The channel
// runs the gateway command on a raw pseudo-terminal, streams the frames, and
@@ -1904,17 +1911,17 @@ async function executeInSession(
// create time, so the host closes the exact terminal by that identifier even
// when the open reply was lost. It also indexes by the worker session identifier
// for input and stop. The `onShutdown` hook closes every open session here.
interface DaytonaSetupTokenPtyEntry {
interface DaytonaLoginPtyEntry {
hostRouteId: string;
workerSessionId: string;
session: SetupTokenPtyWorkerSession;
session: LoginPtyWorkerSession;
}
const daytonaSetupTokenPtyByRoute = new Map<string, DaytonaSetupTokenPtyEntry>();
const daytonaSetupTokenPtyBySession = new Map<string, DaytonaSetupTokenPtyEntry>();
const daytonaLoginPtyByRoute = new Map<string, DaytonaLoginPtyEntry>();
const daytonaLoginPtyBySession = new Map<string, DaytonaLoginPtyEntry>();
function forgetDaytonaSetupTokenPty(entry: DaytonaSetupTokenPtyEntry): void {
daytonaSetupTokenPtyByRoute.delete(entry.hostRouteId);
daytonaSetupTokenPtyBySession.delete(entry.workerSessionId);
function forgetDaytonaLoginPty(entry: DaytonaLoginPtyEntry): void {
daytonaLoginPtyByRoute.delete(entry.hostRouteId);
daytonaLoginPtyBySession.delete(entry.workerSessionId);
}
// The worker-side registry of live duplex channels. The worker registers each
@@ -2731,55 +2738,60 @@ const plugin = definePlugin({
});
},
// Open one live Claude `setup-token` login pseudo-terminal. Resolve
// the cached sandbox by the provider lease id, run the fixed login command on a
// Open one live login pseudo-terminal. Resolve the cached sandbox by the
// provider lease id, revalidate the host launch descriptor and the session
// home, create and validate the session home, run the fixed login command on a
// real pseudo-terminal, and register the session under the host route id. Stream
// the raw output and the exit through `ctx.setupTokenPty`, bound to the returned
// the raw output and the exit through `ctx.loginPty`, bound to the returned
// worker session id. Fail closed when no cached sandbox matches the lease.
async onSetupTokenPtyOpen(params) {
async onLoginPtyOpen(params) {
const sandbox = await sandboxHandleCache.findByProviderLeaseId(params.providerLeaseId);
if (!sandbox) {
throw new Error(
"Daytona setup-token login: no cached sandbox resolves the provider lease.",
"Daytona login pseudo-terminal: no cached sandbox resolves the provider lease.",
);
}
const session = await openSetupTokenPtySession(
const homeFs = createDaytonaLoginHomeFs(
sandbox.process as unknown as DaytonaSandboxExec,
);
const session = await openLoginPtySession(
sandbox.process as unknown as DaytonaPtyProcess,
params.command,
homeFs,
{ loginCommandKey: params.loginCommandKey, sessionHome: params.sessionHome },
);
const workerSessionId = `pty-${randomUUID()}`;
const entry: DaytonaSetupTokenPtyEntry = {
const entry: DaytonaLoginPtyEntry = {
hostRouteId: params.hostRouteId,
workerSessionId,
session,
};
daytonaSetupTokenPtyByRoute.set(params.hostRouteId, entry);
daytonaSetupTokenPtyBySession.set(workerSessionId, entry);
daytonaLoginPtyByRoute.set(params.hostRouteId, entry);
daytonaLoginPtyBySession.set(workerSessionId, entry);
// Register the output listener before the first input, so no early output
// chunk is lost. The client stamps the worker session id, so the host binds
// the output to the open route.
session.onData((chunk) => {
pluginContext?.setupTokenPty.output(workerSessionId, chunk);
pluginContext?.loginPty.output(workerSessionId, chunk);
});
// Forward the child exit one time. The host resolves the login run on it.
void session.wait().then(
(result) => pluginContext?.setupTokenPty.exit(workerSessionId, result.exitCode),
() => pluginContext?.setupTokenPty.exit(workerSessionId, null),
(result) => pluginContext?.loginPty.exit(workerSessionId, result.exitCode),
() => pluginContext?.loginPty.exit(workerSessionId, null),
);
return { workerSessionId };
},
// Write delayed input to an open login pseudo-terminal, keyed by the worker
// session id. Drop the input for an unknown session.
async onSetupTokenPtyInput(params) {
const entry = daytonaSetupTokenPtyBySession.get(params.workerSessionId);
async onLoginPtyInput(params) {
const entry = daytonaLoginPtyBySession.get(params.workerSessionId);
if (!entry) return;
entry.session.write(params.data);
},
// Stop an open login pseudo-terminal child, keyed by the worker session id.
async onSetupTokenPtyStop(params) {
const entry = daytonaSetupTokenPtyBySession.get(params.workerSessionId);
async onLoginPtyStop(params) {
const entry = daytonaLoginPtyBySession.get(params.workerSessionId);
if (!entry) return;
entry.session.kill();
},
@@ -2788,10 +2800,10 @@ const plugin = definePlugin({
// close with the same identifier. The close is idempotent: it returns the
// acknowledgement even when the entry is already gone, so the host confirms the
// terminal is closed. The worker never keys the close on the worker session id.
async onSetupTokenPtyClose(params) {
const entry = daytonaSetupTokenPtyByRoute.get(params.hostRouteId);
async onLoginPtyClose(params) {
const entry = daytonaLoginPtyByRoute.get(params.hostRouteId);
if (entry) {
forgetDaytonaSetupTokenPty(entry);
forgetDaytonaLoginPty(entry);
await entry.session.close().catch(() => undefined);
}
return { hostRouteId: params.hostRouteId };
@@ -2884,9 +2896,9 @@ const plugin = definePlugin({
// orderly shutdown, then drain the sandbox handle cache, so a graceful shutdown
// holds no live terminal and no live channel.
async onShutdown() {
const openSessions = [...daytonaSetupTokenPtyByRoute.values()];
daytonaSetupTokenPtyByRoute.clear();
daytonaSetupTokenPtyBySession.clear();
const openSessions = [...daytonaLoginPtyByRoute.values()];
daytonaLoginPtyByRoute.clear();
daytonaLoginPtyBySession.clear();
for (const entry of openSessions) {
await entry.session.close().catch(() => undefined);
}
@@ -0,0 +1,69 @@
// The session-home creation helper. The provider runs it in the sandbox as
// `node -e <this file> <path> <octal-mode>`. The sandbox already runs node for the
// Paperclip bridge, so the helper needs no extra runtime.
//
// The helper opens the filesystem root, then walks each ancestor above the login
// root with a no-follow, directory-only open. Node has no `openat`, so the helper
// opens each next component through `/proc/self/fd/<dfd>/<component>`: the kernel
// resolves the magic descriptor link, then applies `O_NOFOLLOW` to the final
// component. It creates the login root (the second-to-last component) if the root
// is absent, then opens the root with a no-follow open, so a symlink at the root
// fails closed. It creates the final component as a NEW directory relative to the
// root descriptor, so a pre-existing target fails and the create never follows a
// symlink. It exits 0 on success and non-zero on every failure.
//
// The no-follow open of the root after the create closes the swap window: an
// attacker that replaces the root with a symlink between the create and the open
// fails the open.
"use strict";
const fs = require("node:fs");
const path = process.argv[1];
const mode = Number.parseInt(process.argv[2], 8);
if (typeof path !== "string" || !path.startsWith("/")) process.exit(1);
if (!Number.isInteger(mode)) process.exit(1);
const parts = path.split("/").filter((component) => component.length > 0);
if (parts.length < 2) process.exit(1);
let dfd;
try {
dfd = fs.openSync("/", fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
} catch {
process.exit(1);
}
for (const part of parts.slice(0, -2)) {
try {
dfd = fs.openSync(
`/proc/self/fd/${dfd}/${part}`,
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
);
} catch {
process.exit(1);
}
}
const root = parts[parts.length - 2];
try {
fs.mkdirSync(`/proc/self/fd/${dfd}/${root}`, { mode: 0o700 });
} catch (error) {
if (!error || error.code !== "EEXIST") process.exit(1);
}
let rfd;
try {
rfd = fs.openSync(
`/proc/self/fd/${dfd}/${root}`,
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
);
} catch {
process.exit(1);
}
try {
fs.mkdirSync(`/proc/self/fd/${rfd}/${parts[parts.length - 1]}`, { mode });
} catch {
process.exit(1);
}
process.exit(0);
@@ -0,0 +1,66 @@
// The session-home inspection helper. The provider runs it in the sandbox as
// `node -e <this file> <path>`. The sandbox already runs node for the Paperclip
// bridge, so the helper needs no extra runtime.
//
// The helper opens the filesystem root, then walks each ancestor of the final
// path component with a no-follow, directory-only open. Node has no `openat`, so
// the helper opens each next component through `/proc/self/fd/<dfd>/<component>`:
// the kernel resolves the magic descriptor link, then applies `O_NOFOLLOW` to the
// final component. This binds each open to the descriptor inode, so a symlink at
// any ancestor fails closed. The helper reads the final component with `lstat`, so
// a symlink at the target reports the link, not the target.
//
// The helper prints one line and sets one exit code:
// - a missing ancestor or a missing final component prints `ABSENT` and exits 0;
// - an existing final component prints `<type>|<octal-mode>|<uid>` and exits 0,
// where `<type>` is `symlink`, `directory`, or `other`;
// - a symlink or a non-directory at any ancestor prints nothing and exits 3, so
// the caller fails closed on an ancestor symlink.
"use strict";
const fs = require("node:fs");
const path = process.argv[1];
if (typeof path !== "string" || !path.startsWith("/")) process.exit(3);
const parts = path.split("/").filter((component) => component.length > 0);
if (parts.length === 0) process.exit(3);
function absent() {
process.stdout.write("ABSENT");
process.exit(0);
}
let dfd;
try {
dfd = fs.openSync("/", fs.constants.O_RDONLY | fs.constants.O_DIRECTORY);
} catch {
process.exit(3);
}
for (const part of parts.slice(0, -1)) {
try {
dfd = fs.openSync(
`/proc/self/fd/${dfd}/${part}`,
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
);
} catch (error) {
if (error && error.code === "ENOENT") absent();
process.exit(3);
}
}
const last = parts[parts.length - 1];
let st;
try {
st = fs.lstatSync(`/proc/self/fd/${dfd}/${last}`);
} catch (error) {
if (error && error.code === "ENOENT") absent();
process.exit(3);
}
let fileType;
if (st.isSymbolicLink()) fileType = "symlink";
else if (st.isDirectory()) fileType = "directory";
else fileType = "other";
process.stdout.write(`${fileType}|${(st.mode & 0o7777).toString(8)}|${st.uid}`);
process.exit(0);
@@ -1,222 +0,0 @@
import { describe, expect, it } from "vitest";
import {
createDaytonaSetupTokenPtySessionOpener,
openDaytonaSetupTokenPtySession,
type DaytonaPtyCreateOptions,
type DaytonaPtyHandle,
type DaytonaPtyProcess,
} from "./setup-token-pty.js";
// The Enter byte the terminal login UI reads to submit the browser code.
const ENTER = "\r";
/**
* A fake Daytona PTY handle. It records each input write, drives the output
* stream on demand, and records the kill and the disconnect. The tests use it in
* place of the real SDK `PtyHandle`, so the session runs with no sandbox.
*/
function createFakePtyHandle(onData: (data: Uint8Array) => void | Promise<void>): DaytonaPtyHandle & {
inputs: string[];
emitText: (text: string) => void;
emitBytes: (bytes: Uint8Array) => void;
finish: (exitCode: number | undefined) => void;
killed: number;
disconnected: number;
} {
const encoder = new TextEncoder();
const inputs: string[] = [];
let resolveWait: ((value: { exitCode?: number; error?: string }) => void) | null = null;
const waitPromise = new Promise<{ exitCode?: number; error?: string }>((resolve) => {
resolveWait = resolve;
});
let killed = 0;
let disconnected = 0;
return {
async waitForConnection(): Promise<void> {},
async sendInput(data: string | Uint8Array): Promise<void> {
inputs.push(typeof data === "string" ? data : new TextDecoder().decode(data));
},
wait(): Promise<{ exitCode?: number; error?: string }> {
return waitPromise;
},
async kill(): Promise<void> {
killed += 1;
},
async disconnect(): Promise<void> {
disconnected += 1;
},
// Test control below. The session never reads these fields.
emitText(text: string): void {
onData(encoder.encode(text));
},
emitBytes(bytes: Uint8Array): void {
onData(bytes);
},
finish(exitCode: number | undefined): void {
resolveWait?.({ exitCode });
},
get inputs(): string[] {
return inputs;
},
get killed(): number {
return killed;
},
get disconnected(): number {
return disconnected;
},
};
}
/**
* A fake Daytona process. It opens one fake PTY handle and records the create
* options, so a test asserts the terminal size and the command start.
*/
function createFakeProcess(): DaytonaPtyProcess & {
handle: ReturnType<typeof createFakePtyHandle> | null;
createOptions: DaytonaPtyCreateOptions | null;
} {
const state: {
handle: ReturnType<typeof createFakePtyHandle> | null;
createOptions: DaytonaPtyCreateOptions | null;
} = { handle: null, createOptions: null };
return {
get handle() {
return state.handle;
},
get createOptions() {
return state.createOptions;
},
async createPty(options: DaytonaPtyCreateOptions): Promise<DaytonaPtyHandle> {
state.createOptions = options;
const handle = createFakePtyHandle(options.onData);
state.handle = handle;
return handle;
},
};
}
describe("openDaytonaSetupTokenPtySession", () => {
it("starts the login command on a pseudo-terminal with a fixed size", async () => {
const process = createFakeProcess();
await openDaytonaSetupTokenPtySession(process, "claude setup-token");
expect(process.createOptions?.cols).toBe(120);
expect(process.createOptions?.rows).toBe(30);
// The session replaces the shell with the command through `exec`, so the
// pseudo-terminal runs the command directly and its exit code is the PTY
// exit code.
expect(process.handle?.inputs[0]).toBe("exec claude setup-token" + ENTER);
});
it("returns incremental terminal output to the listener", async () => {
const process = createFakeProcess();
const received: string[] = [];
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
session.onData((chunk) => received.push(chunk));
process.handle?.emitText("the url below to sign in\n");
process.handle?.emitText("Paste code here if prompted\n");
expect(received).toEqual(["the url below to sign in\n", "Paste code here if prompted\n"]);
});
it("buffers early output until the listener registers", async () => {
const process = createFakeProcess();
const received: string[] = [];
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
// Output arrives before the transport registers the listener.
process.handle?.emitText("early output ");
process.handle?.emitText("more output");
expect(received).toEqual([]);
session.onData((chunk) => received.push(chunk));
// The session flushes the buffered output in order on registration.
expect(received).toEqual(["early output more output"]);
});
it("delivers the browser code plus the Enter byte to the command", async () => {
const process = createFakeProcess();
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
session.write("BROWSERCODE" + ENTER);
// The first input is the command start; the second input is the delayed
// browser code plus the Enter byte.
expect(process.handle?.inputs[1]).toBe("BROWSERCODE" + ENTER);
expect(process.handle?.inputs[1]?.endsWith(ENTER)).toBe(true);
});
it("keeps a multibyte character whole across two output chunks", async () => {
const process = createFakeProcess();
const received: string[] = [];
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
session.onData((chunk) => received.push(chunk));
// The euro sign is three UTF-8 bytes. Split it across two chunks, so the
// stream decoder must join the bytes.
const euro = new TextEncoder().encode("€");
process.handle?.emitBytes(euro.subarray(0, 2));
process.handle?.emitBytes(euro.subarray(2));
expect(received.join("")).toBe("€");
});
it("resolves wait with the command exit code", async () => {
const process = createFakeProcess();
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
process.handle?.finish(9);
await expect(session.wait()).resolves.toEqual({ exitCode: 9 });
});
it("maps an absent exit code to null", async () => {
const process = createFakeProcess();
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
process.handle?.finish(undefined);
await expect(session.wait()).resolves.toEqual({ exitCode: null });
});
it("kills the child and closes the session", async () => {
const process = createFakeProcess();
const session = await openDaytonaSetupTokenPtySession(process, "claude setup-token");
session.kill();
expect(process.handle?.killed).toBe(1);
await session.close();
expect(process.handle?.disconnected).toBe(1);
});
it("passes the working directory to the pseudo-terminal", async () => {
const process = createFakeProcess();
await openDaytonaSetupTokenPtySession(process, "claude setup-token", { cwd: "/workspace" });
expect(process.createOptions?.cwd).toBe("/workspace");
});
});
describe("createDaytonaSetupTokenPtySessionOpener", () => {
it("opens a session for the command on each call", async () => {
const process = createFakeProcess();
const opener = createDaytonaSetupTokenPtySessionOpener(process, { cwd: "/workspace" });
const session = await opener("claude setup-token");
expect(process.createOptions?.cwd).toBe("/workspace");
expect(process.handle?.inputs[0]).toBe("exec claude setup-token" + ENTER);
// The opener returns a session the transport can drive.
expect(typeof session.onData).toBe("function");
expect(typeof session.write).toBe("function");
expect(typeof session.wait).toBe("function");
expect(typeof session.kill).toBe("function");
expect(typeof session.close).toBe("function");
});
});
@@ -1,207 +0,0 @@
// The Daytona pseudo-terminal (PTY) session for the Claude `setup-token` login.
// The login command needs a real pseudo-terminal: pipe stdio emits no login
// prompt. The Daytona SDK opens a PTY through `process.createPty`. This module
// binds that PTY to a small session that the setup-token transport consumes, so
// the login runner runs the command on a real terminal, streams the terminal
// output, and delivers the delayed browser code plus the Enter byte.
//
// Dependency boundary: this provider plugin ships standalone (the workspace
// excludes `packages/plugins/sandbox-providers/**`). So the module imports no
// workspace package. It declares the small session shape locally through
// {@link SetupTokenPtySession}. The shape matches the `SetupTokenPtySession`
// interface in `@paperclipai/adapter-utils`, so the transport factory
// `createSetupTokenPtyTransport` accepts the session opener from this module with
// no adapter. The runner drives the transport; the transport drives this session.
//
// SDK boundary: the module holds no Daytona SDK type import. It declares the
// small subset of the SDK PTY surface that it uses through
// {@link DaytonaPtyProcess} and {@link DaytonaPtyHandle}. The SDK `Process` and
// `PtyHandle` satisfy that subset, so a caller passes `sandbox.process` with no
// adapter. The narrow surface keeps the module unit-testable with a fake PTY.
//
// Security (secret handling): the login runner delivers the browser code and the
// Enter byte through {@link DaytonaPtyHandle.sendInput}. The SDK sends the input
// over the PTY socket, so the code never rides a command line and never reaches a
// process argument list. The session forwards the raw terminal bytes with no
// ANSI or OSC 8 handling; the setup-token parser owns that handling.
import { randomUUID } from "node:crypto";
import { sendPtyInputInChunks } from "./pty-chunked-input.js";
/**
* A live pseudo-terminal session for one setup-token login command. The session
* allocates a real pseudo-terminal, streams the raw terminal output, accepts
* delayed input, and stops the child. The shape matches the
* `SetupTokenPtySession` interface in `@paperclipai/adapter-utils`, so the
* transport factory there accepts a session opener that returns this session.
*/
export interface SetupTokenPtySession {
/** Registers the one output listener. The session streams each raw chunk in order. */
onData(listener: (chunk: string) => void): void;
/** Writes raw input bytes to the pseudo-terminal. */
write(data: string): void;
/** Resolves with the child exit code when the command ends. */
wait(): Promise<{ exitCode: number | null }>;
/** Stops the child process. Safe to call more than one time. */
kill(): void;
/** Releases the session resources. Safe to call more than one time. */
close(): Promise<void>;
}
/** Opens a {@link SetupTokenPtySession} for `command`. The transport calls it one time. */
export type SetupTokenPtySessionOpener = (command: string) => Promise<SetupTokenPtySession>;
/**
* The subset of the Daytona SDK `PtyHandle` that the session uses. The SDK
* `PtyHandle` satisfies this interface, so a caller passes the real handle with
* no adapter.
*/
export interface DaytonaPtyHandle {
/** Resolves when the PTY socket connection is ready for input and output. */
waitForConnection(): Promise<void>;
/** Sends raw input bytes to the pseudo-terminal. */
sendInput(data: string | Uint8Array): Promise<void>;
/** Resolves with the exit result when the pseudo-terminal process ends. */
wait(): Promise<{ exitCode?: number; error?: string }>;
/** Kills the pseudo-terminal process. */
kill(): Promise<void>;
/** Closes the PTY socket and releases the resources. */
disconnect(): Promise<void>;
}
/**
* The options the session passes to `createPty`. The session sets a fixed
* terminal size and one output callback. It sets the working directory when the
* caller provides one.
*/
export interface DaytonaPtyCreateOptions {
id: string;
cwd?: string;
cols: number;
rows: number;
onData: (data: Uint8Array) => void | Promise<void>;
}
/**
* The subset of the Daytona SDK `Process` that the session uses. The SDK
* `Process` satisfies this interface, so a caller passes `sandbox.process`.
*/
export interface DaytonaPtyProcess {
createPty(options: DaytonaPtyCreateOptions): Promise<DaytonaPtyHandle>;
}
/** The options for the Daytona setup-token PTY session. */
export interface DaytonaSetupTokenPtyOptions {
/** The working directory for the login PTY. Defaults to the sandbox default. */
cwd?: string;
}
// The terminal size for the login PTY. The login UI prints a short prompt, so a
// standard terminal size is enough. A fixed size keeps the output stable.
const SETUP_TOKEN_PTY_COLS = 120;
const SETUP_TOKEN_PTY_ROWS = 30;
/**
* The input terminator that replaces the interactive shell with the login
* command. The `exec` builtin replaces the shell process image with the command,
* so the PTY runs the command directly. When the command ends, the PTY ends with
* the command exit code, and the delayed input reaches the command, not a shell.
* The terminal reads the carriage return as the Enter key.
*/
const PTY_COMMAND_TERMINATOR = "\r";
/**
* Opens a Daytona PTY session for `command` and returns it as a
* {@link SetupTokenPtySession}. The session allocates a real pseudo-terminal,
* streams the raw terminal output, delivers delayed input, and stops the child.
*
* The function starts the login command with `exec`, so the pseudo-terminal runs
* the command directly and the command exit code becomes the PTY exit code. The
* function decodes the terminal bytes as a UTF-8 stream, so a multibyte
* character that splits across two output chunks stays whole. It buffers the
* output until the transport registers the listener, so no early chunk is lost.
*/
export async function openDaytonaSetupTokenPtySession(
process: DaytonaPtyProcess,
command: string,
options?: DaytonaSetupTokenPtyOptions,
): Promise<SetupTokenPtySession> {
const decoder = new TextDecoder("utf-8");
let listener: ((chunk: string) => void) | null = null;
let buffered = "";
const handle = await process.createPty({
id: `paperclip-setup-token-${randomUUID()}`,
...(options?.cwd ? { cwd: options.cwd } : {}),
cols: SETUP_TOKEN_PTY_COLS,
rows: SETUP_TOKEN_PTY_ROWS,
onData: (data: Uint8Array): void => {
// Decode the terminal bytes as a stream, so a split multibyte character
// stays whole across two chunks. Forward the raw text; the parser owns the
// ANSI and OSC 8 handling.
const text = decoder.decode(data, { stream: true });
if (text.length === 0) return;
if (listener) listener(text);
else buffered += text;
},
});
await handle.waitForConnection();
// Replace the interactive shell with the login command, so the pseudo-terminal
// runs the command directly. The runner then writes the delayed browser code
// to the command, not to a shell.
await handle.sendInput(`exec ${command}${PTY_COMMAND_TERMINATOR}`);
// The tail of the write chain. The chunker awaits each chunk, so one write can
// suspend between its chunks. The chain runs each write after the previous
// write ends, so the chunks of two writes never interleave on the wire.
let writeChain: Promise<void> = Promise.resolve();
return {
onData(next: (chunk: string) => void): void {
listener = next;
if (buffered.length > 0) {
const pending = buffered;
buffered = "";
next(pending);
}
},
write(data: string): void {
// Send the input as byte-bounded chunks under the provider message cap. The
// login input is short today, so the latent defect never fires, but the same
// unbounded write goes through the one chunker. The chain runs this write
// after the previous write ends, so two writes keep their order and never
// interleave their chunks. A write error must not throw into the runner, so
// the runner's fixed status stays the single result path.
writeChain = writeChain.then(() =>
sendPtyInputInChunks((chunk) => handle.sendInput(chunk), data),
);
},
async wait(): Promise<{ exitCode: number | null }> {
const result = await handle.wait();
return { exitCode: typeof result.exitCode === "number" ? result.exitCode : null };
},
kill(): void {
void handle.kill().catch(() => undefined);
},
async close(): Promise<void> {
await handle.disconnect().catch(() => undefined);
},
};
}
/**
* Creates a {@link SetupTokenPtySessionOpener} bound to a Daytona `process`. Pass
* `sandbox.process` from the Daytona SDK. A later phase wraps the opener with the
* `createSetupTokenPtyTransport` factory from `@paperclipai/adapter-utils` and
* hands the transport to the login runner. The opener runs the login command on
* a real pseudo-terminal, streams the terminal output, delivers the delayed
* browser code plus the Enter byte, and stops the child for a terminal state.
*/
export function createDaytonaSetupTokenPtySessionOpener(
process: DaytonaPtyProcess,
options?: DaytonaSetupTokenPtyOptions,
): SetupTokenPtySessionOpener {
return (command: string) => openDaytonaSetupTokenPtySession(process, command, options);
}
+16 -16
View File
@@ -82,12 +82,12 @@ import type {
PluginExternalObjectResolveResult,
RefreshExternalObjectsParams,
RefreshExternalObjectsResult,
PluginSetupTokenPtyOpenParams,
PluginSetupTokenPtyOpenResult,
PluginSetupTokenPtyInputParams,
PluginSetupTokenPtyStopParams,
PluginSetupTokenPtyCloseParams,
PluginSetupTokenPtyCloseResult,
PluginLoginPtyOpenParams,
PluginLoginPtyOpenResult,
PluginLoginPtyInputParams,
PluginLoginPtyStopParams,
PluginLoginPtyCloseParams,
PluginLoginPtyCloseResult,
PluginDuplexChannelOpenParams,
PluginDuplexChannelOpenResult,
PluginDuplexChannelWriteParams,
@@ -449,27 +449,27 @@ export interface PluginDefinition {
* Called to open one live Claude `setup-token` login pseudo-terminal.
* The worker registers the terminal under the host route identifier and returns a
* worker session identifier for the output notification binding only. The worker
* streams output and the exit through `ctx.setupTokenPty`, never as a reply.
* Defining the four `onSetupTokenPty*` hooks advertises the four methods.
* streams output and the exit through `ctx.loginPty`, never as a reply.
* Defining the four `onLoginPty*` hooks advertises the four methods.
*/
onSetupTokenPtyOpen?(
params: PluginSetupTokenPtyOpenParams,
): Promise<PluginSetupTokenPtyOpenResult>;
onLoginPtyOpen?(
params: PluginLoginPtyOpenParams,
): Promise<PluginLoginPtyOpenResult>;
/** Called to write delayed input to an open login pseudo-terminal, keyed by the worker session identifier. */
onSetupTokenPtyInput?(params: PluginSetupTokenPtyInputParams): Promise<void>;
onLoginPtyInput?(params: PluginLoginPtyInputParams): Promise<void>;
/** Called to stop an open login pseudo-terminal child, keyed by the worker session identifier. */
onSetupTokenPtyStop?(params: PluginSetupTokenPtyStopParams): Promise<void>;
onLoginPtyStop?(params: PluginLoginPtyStopParams): Promise<void>;
/**
* Called to close an open login pseudo-terminal by the host route identifier. The
* worker closes the exact terminal registered under that identifier and returns a
* close acknowledgement that carries the same identifier.
*/
onSetupTokenPtyClose?(
params: PluginSetupTokenPtyCloseParams,
): Promise<PluginSetupTokenPtyCloseResult>;
onLoginPtyClose?(
params: PluginLoginPtyCloseParams,
): Promise<PluginLoginPtyCloseResult>;
/**
* Called to open one persistent duplex channel. The worker registers the
+2 -2
View File
@@ -82,8 +82,8 @@ export {
parseMessage,
JsonRpcParseError,
JsonRpcCallError,
SETUP_TOKEN_PTY_OUTPUT_NOTIFICATION,
SETUP_TOKEN_PTY_EXIT_NOTIFICATION,
LOGIN_PTY_OUTPUT_NOTIFICATION,
LOGIN_PTY_EXIT_NOTIFICATION,
DUPLEX_CHANNEL_DATA_NOTIFICATION,
DUPLEX_CHANNEL_EXIT_NOTIFICATION,
_resetIdCounter,
+46 -29
View File
@@ -972,7 +972,7 @@ export interface PluginRenderCloseEvent {
}
// ---------------------------------------------------------------------------
// Setup-token login pseudo-terminal (PTY) worker methods.
// Login pseudo-terminal (PTY) worker methods.
// ---------------------------------------------------------------------------
// The host drives one live Claude `setup-token` login pseudo-terminal inside a
// sandbox provider worker. The host owns the route. It mints an opaque host
@@ -985,11 +985,19 @@ export interface PluginRenderCloseEvent {
// output and exit as notifications, never as a reply, so the host binds them by
// the worker session identifier while the route is open.
/**
* The closed set of login command identities. The host resolves the key from the
* trusted adapter type and carries it in the open request. The worker maps the
* key to a compile-time command. The open request carries no command string, so a
* caller cannot select or override the command.
*/
export type PluginLoginCommandKey = "claude" | "codex";
/** The open request for one live login pseudo-terminal. The worker registers the terminal by `hostRouteId`. */
export interface PluginSetupTokenPtyOpenParams {
export interface PluginLoginPtyOpenParams {
/** The host-owned opaque route identifier. The worker registers the terminal by it. */
hostRouteId: string;
/** The environment driver key, for the worker sandbox scope. */
/** The environment driver key, for the worker sandbox scope. It routes the worker; it confers no command authority. */
driverKey: string;
/** The company that owns the login session. */
companyId: string;
@@ -997,18 +1005,27 @@ export interface PluginSetupTokenPtyOpenParams {
environmentId: string;
/** The provider lease the sandbox is cached under. The worker resolves the sandbox by it. */
providerLeaseId: string;
/** The fixed login command. The worker runs only this command on the terminal. */
command: string;
/**
* The host-resolved fixed command identity. The worker maps it to a
* compile-time command. The open request carries no command string.
*/
loginCommandKey: PluginLoginCommandKey;
/**
* The server-controlled, validated session home. The shape is exact:
* `/tmp/paperclip-adapter-login/<uuid>`. The worker revalidates the shape
* before it touches the filesystem.
*/
sessionHome: string;
}
/** The open reply. It returns the worker session identifier for output binding only. */
export interface PluginSetupTokenPtyOpenResult {
export interface PluginLoginPtyOpenResult {
/** The worker session identifier. It binds the output and the exit notification only. */
workerSessionId: string;
}
/** The input request. It carries the worker session identifier and the raw input bytes. */
export interface PluginSetupTokenPtyInputParams {
export interface PluginLoginPtyInputParams {
/** The worker session identifier that the open reply returned. */
workerSessionId: string;
/** The raw input bytes to write to the terminal. */
@@ -1016,13 +1033,13 @@ export interface PluginSetupTokenPtyInputParams {
}
/** The stop request. It carries the worker session identifier. */
export interface PluginSetupTokenPtyStopParams {
export interface PluginLoginPtyStopParams {
/** The worker session identifier that the open reply returned. */
workerSessionId: string;
}
/** The close request. The host route identifier is the authoritative key. */
export interface PluginSetupTokenPtyCloseParams {
export interface PluginLoginPtyCloseParams {
/**
* The host-owned opaque route identifier. This is the authoritative close key,
* so the host closes the terminal even when no worker session identifier
@@ -1038,13 +1055,13 @@ export interface PluginSetupTokenPtyCloseParams {
}
/** The close reply. It acknowledges the close and carries the same host route identifier. */
export interface PluginSetupTokenPtyCloseResult {
export interface PluginLoginPtyCloseResult {
/** The close acknowledgement. It carries the same host route identifier the close sent. */
hostRouteId: string;
}
/** The worker→host pseudo-terminal output notification parameters. Modeled on `execute.log`. */
export interface PluginSetupTokenPtyOutputParams {
export interface PluginLoginPtyOutputParams {
/** The worker session identifier that the open reply returned. */
workerSessionId: string;
/** The raw terminal output bytes. */
@@ -1052,7 +1069,7 @@ export interface PluginSetupTokenPtyOutputParams {
}
/** The worker→host pseudo-terminal exit notification parameters. */
export interface PluginSetupTokenPtyExitParams {
export interface PluginLoginPtyExitParams {
/** The worker session identifier that the open reply returned. */
workerSessionId: string;
/** The child exit code, or null when the child ended with no code. */
@@ -1061,10 +1078,10 @@ export interface PluginSetupTokenPtyExitParams {
/**
* One live login pseudo-terminal session in the worker. The worker opener returns
* it. The shape matches the sandbox provider setup-token pseudo-terminal session,
* it. The shape matches the sandbox provider login pseudo-terminal session,
* so a provider passes its session with no adapter.
*/
export interface PluginSetupTokenPtyWorkerSession {
export interface PluginLoginPtyWorkerSession {
/** Registers the one output listener. The session streams each raw chunk in order. */
onData(listener: (chunk: string) => void): void;
/** Writes raw input bytes to the pseudo-terminal. */
@@ -1078,9 +1095,9 @@ export interface PluginSetupTokenPtyWorkerSession {
}
/** The worker→host notification method for one pseudo-terminal output chunk. */
export const SETUP_TOKEN_PTY_OUTPUT_NOTIFICATION = "setupTokenPty.output";
export const LOGIN_PTY_OUTPUT_NOTIFICATION = "loginPty.output";
/** The worker→host notification method for one pseudo-terminal exit. */
export const SETUP_TOKEN_PTY_EXIT_NOTIFICATION = "setupTokenPty.exit";
export const LOGIN_PTY_EXIT_NOTIFICATION = "loginPty.exit";
// ---------------------------------------------------------------------------
// Generic duplex channel worker methods.
@@ -1088,7 +1105,7 @@ export const SETUP_TOKEN_PTY_EXIT_NOTIFICATION = "setupTokenPty.exit";
// The host drives one persistent duplex channel inside a sandbox provider
// worker. The channel replaces the file transport of the sandbox callback bridge
// with one live bidirectional stream. These messages are generic. They model the
// setup-token pseudo-terminal contract above, but they carry no login command
// login pseudo-terminal contract above, but they carry no login command
// allowlist. The host owns the route. It mints an opaque host route identifier,
// carries that identifier in the open request, and keys the close on that
// identifier. The worker registers the channel under the host route identifier
@@ -1309,18 +1326,18 @@ export interface HostToWorkerMethods {
result: PluginEnvironmentDeleteTemplateResult,
];
/** Open one live login pseudo-terminal keyed by a host-owned route identifier. */
setupTokenPtyOpen: [
params: PluginSetupTokenPtyOpenParams,
result: PluginSetupTokenPtyOpenResult,
loginPtyOpen: [
params: PluginLoginPtyOpenParams,
result: PluginLoginPtyOpenResult,
];
/** Write delayed input to a live login pseudo-terminal, keyed by the worker session identifier. */
setupTokenPtyInput: [params: PluginSetupTokenPtyInputParams, result: void];
loginPtyInput: [params: PluginLoginPtyInputParams, result: void];
/** Stop a live login pseudo-terminal child, keyed by the worker session identifier. */
setupTokenPtyStop: [params: PluginSetupTokenPtyStopParams, result: void];
loginPtyStop: [params: PluginLoginPtyStopParams, result: void];
/** Close a live login pseudo-terminal by the host route identifier and return a bound acknowledgement. */
setupTokenPtyClose: [
params: PluginSetupTokenPtyCloseParams,
result: PluginSetupTokenPtyCloseResult,
loginPtyClose: [
params: PluginLoginPtyCloseParams,
result: PluginLoginPtyCloseResult,
];
/** Open one persistent duplex channel keyed by a host-owned route identifier. */
duplexChannelOpen: [
@@ -1377,10 +1394,10 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[]
"environmentCaptureTemplate",
"environmentCancelInteractiveSetup",
"environmentDeleteTemplate",
"setupTokenPtyOpen",
"setupTokenPtyInput",
"setupTokenPtyStop",
"setupTokenPtyClose",
"loginPtyOpen",
"loginPtyInput",
"loginPtyStop",
"loginPtyClose",
"duplexChannelOpen",
"duplexChannelWrite",
"duplexChannelStop",
+1 -1
View File
@@ -2478,7 +2478,7 @@ export function createTestHarness(options: TestHarnessOptions): TestHarness {
// No-op in test harness — the host runner log sink is not wired here.
},
},
setupTokenPty: {
loginPty: {
output(_workerSessionId: string, _chunk: string) {
// No-op in test harness — the host login route is not wired here.
},
+4 -4
View File
@@ -2009,7 +2009,7 @@ export interface PluginExecutionClient {
}
/**
* `ctx.setupTokenPty` — stream one live login pseudo-terminal's output and exit
* `ctx.loginPty` — stream one live login pseudo-terminal's output and exit
* from a sandbox provider worker to the host.
*
* The worker opener registers the output listener on the session and forwards
@@ -2020,7 +2020,7 @@ export interface PluginExecutionClient {
* chunk or an exit that carries an unknown or a mismatched identifier, and it
* never logs the raw bytes. The default is a no-op that never throws.
*/
export interface PluginSetupTokenPtyClient {
export interface PluginLoginPtyClient {
/**
* Deliver one raw output chunk of a live login pseudo-terminal.
*
@@ -2048,7 +2048,7 @@ export interface PluginSetupTokenPtyClient {
* by that identifier while the route is open. The host drops a chunk or an exit
* that carries an unknown or a mismatched identifier, and it never logs the raw
* bytes. The default is a no-op that never throws. This client models the
* `setupTokenPty` client, but it carries no login command allowlist.
* `loginPty` client, but it carries no login command allowlist.
*/
export interface PluginDuplexChannelClient {
/**
@@ -2193,7 +2193,7 @@ export interface PluginContext {
/** Stream one live login pseudo-terminal's output and exit to the host.
* The default is a no-op for a provider that opens no login
* pseudo-terminal. */
setupTokenPty: PluginSetupTokenPtyClient;
loginPty: PluginLoginPtyClient;
/** Stream one persistent duplex channel's data and exit to the host. The
* default is a no-op for a provider that opens no duplex channel. */
+37 -37
View File
@@ -100,10 +100,10 @@ import type {
PluginEnvironmentCaptureTemplateParams,
PluginEnvironmentCancelInteractiveSetupParams,
PluginEnvironmentDeleteTemplateParams,
PluginSetupTokenPtyOpenParams,
PluginSetupTokenPtyInputParams,
PluginSetupTokenPtyStopParams,
PluginSetupTokenPtyCloseParams,
PluginLoginPtyOpenParams,
PluginLoginPtyInputParams,
PluginLoginPtyStopParams,
PluginLoginPtyCloseParams,
PluginDuplexChannelOpenParams,
PluginDuplexChannelWriteParams,
PluginDuplexChannelStopParams,
@@ -113,8 +113,8 @@ import type {
WorkerToHostMethods,
} from "./protocol.js";
import {
SETUP_TOKEN_PTY_OUTPUT_NOTIFICATION,
SETUP_TOKEN_PTY_EXIT_NOTIFICATION,
LOGIN_PTY_OUTPUT_NOTIFICATION,
LOGIN_PTY_EXIT_NOTIFICATION,
DUPLEX_CHANNEL_DATA_NOTIFICATION,
DUPLEX_CHANNEL_EXIT_NOTIFICATION,
JSONRPC_VERSION,
@@ -1378,7 +1378,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
},
},
setupTokenPty: {
loginPty: {
output(workerSessionId: string, chunk: string): void {
// Forward one raw output chunk of a live login pseudo-terminal. The
// notification carries the worker session identifier, so the host binds
@@ -1388,14 +1388,14 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
// because it fires after the open reply returns.
if (typeof workerSessionId !== "string" || workerSessionId.length === 0) return;
if (typeof chunk !== "string" || chunk.length === 0) return;
notifyHost(SETUP_TOKEN_PTY_OUTPUT_NOTIFICATION, { workerSessionId, chunk });
notifyHost(LOGIN_PTY_OUTPUT_NOTIFICATION, { workerSessionId, chunk });
},
exit(workerSessionId: string, exitCode: number | null): void {
// Forward the child exit of a live login pseudo-terminal. The host
// resolves the open route's wait promise by the worker session
// identifier while the route is open.
if (typeof workerSessionId !== "string" || workerSessionId.length === 0) return;
notifyHost(SETUP_TOKEN_PTY_EXIT_NOTIFICATION, {
notifyHost(LOGIN_PTY_EXIT_NOTIFICATION, {
workerSessionId,
exitCode: typeof exitCode === "number" ? exitCode : null,
});
@@ -1652,17 +1652,17 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
case "environmentDeleteTemplate":
return handleEnvironmentDeleteTemplate(params as PluginEnvironmentDeleteTemplateParams);
case "setupTokenPtyOpen":
return handleSetupTokenPtyOpen(params as PluginSetupTokenPtyOpenParams);
case "loginPtyOpen":
return handleLoginPtyOpen(params as PluginLoginPtyOpenParams);
case "setupTokenPtyInput":
return handleSetupTokenPtyInput(params as PluginSetupTokenPtyInputParams);
case "loginPtyInput":
return handleLoginPtyInput(params as PluginLoginPtyInputParams);
case "setupTokenPtyStop":
return handleSetupTokenPtyStop(params as PluginSetupTokenPtyStopParams);
case "loginPtyStop":
return handleLoginPtyStop(params as PluginLoginPtyStopParams);
case "setupTokenPtyClose":
return handleSetupTokenPtyClose(params as PluginSetupTokenPtyCloseParams);
case "loginPtyClose":
return handleLoginPtyClose(params as PluginLoginPtyCloseParams);
case "duplexChannelOpen":
return handleDuplexChannelOpen(params as PluginDuplexChannelOpenParams);
@@ -1727,10 +1727,10 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
if (plugin.definition.onEnvironmentCaptureTemplate) supportedMethods.push("environmentCaptureTemplate");
if (plugin.definition.onEnvironmentCancelInteractiveSetup) supportedMethods.push("environmentCancelInteractiveSetup");
if (plugin.definition.onEnvironmentDeleteTemplate) supportedMethods.push("environmentDeleteTemplate");
if (plugin.definition.onSetupTokenPtyOpen) supportedMethods.push("setupTokenPtyOpen");
if (plugin.definition.onSetupTokenPtyInput) supportedMethods.push("setupTokenPtyInput");
if (plugin.definition.onSetupTokenPtyStop) supportedMethods.push("setupTokenPtyStop");
if (plugin.definition.onSetupTokenPtyClose) supportedMethods.push("setupTokenPtyClose");
if (plugin.definition.onLoginPtyOpen) supportedMethods.push("loginPtyOpen");
if (plugin.definition.onLoginPtyInput) supportedMethods.push("loginPtyInput");
if (plugin.definition.onLoginPtyStop) supportedMethods.push("loginPtyStop");
if (plugin.definition.onLoginPtyClose) supportedMethods.push("loginPtyClose");
if (plugin.definition.onDuplexChannelOpen) supportedMethods.push("duplexChannelOpen");
if (plugin.definition.onDuplexChannelWrite) supportedMethods.push("duplexChannelWrite");
if (plugin.definition.onDuplexChannelStop) supportedMethods.push("duplexChannelStop");
@@ -2083,32 +2083,32 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
return plugin.definition.onEnvironmentDeleteTemplate(params);
}
async function handleSetupTokenPtyOpen(params: PluginSetupTokenPtyOpenParams) {
if (!plugin.definition.onSetupTokenPtyOpen) {
throw methodNotImplemented("setupTokenPtyOpen");
async function handleLoginPtyOpen(params: PluginLoginPtyOpenParams) {
if (!plugin.definition.onLoginPtyOpen) {
throw methodNotImplemented("loginPtyOpen");
}
return plugin.definition.onSetupTokenPtyOpen(params);
return plugin.definition.onLoginPtyOpen(params);
}
async function handleSetupTokenPtyInput(params: PluginSetupTokenPtyInputParams) {
if (!plugin.definition.onSetupTokenPtyInput) {
throw methodNotImplemented("setupTokenPtyInput");
async function handleLoginPtyInput(params: PluginLoginPtyInputParams) {
if (!plugin.definition.onLoginPtyInput) {
throw methodNotImplemented("loginPtyInput");
}
return plugin.definition.onSetupTokenPtyInput(params);
return plugin.definition.onLoginPtyInput(params);
}
async function handleSetupTokenPtyStop(params: PluginSetupTokenPtyStopParams) {
if (!plugin.definition.onSetupTokenPtyStop) {
throw methodNotImplemented("setupTokenPtyStop");
async function handleLoginPtyStop(params: PluginLoginPtyStopParams) {
if (!plugin.definition.onLoginPtyStop) {
throw methodNotImplemented("loginPtyStop");
}
return plugin.definition.onSetupTokenPtyStop(params);
return plugin.definition.onLoginPtyStop(params);
}
async function handleSetupTokenPtyClose(params: PluginSetupTokenPtyCloseParams) {
if (!plugin.definition.onSetupTokenPtyClose) {
throw methodNotImplemented("setupTokenPtyClose");
async function handleLoginPtyClose(params: PluginLoginPtyCloseParams) {
if (!plugin.definition.onLoginPtyClose) {
throw methodNotImplemented("loginPtyClose");
}
return plugin.definition.onSetupTokenPtyClose(params);
return plugin.definition.onLoginPtyClose(params);
}
async function handleDuplexChannelOpen(params: PluginDuplexChannelOpenParams) {
@@ -774,28 +774,32 @@ describe("worker setup-token pseudo-terminal dispatch", () => {
let killed = 0;
let closed = 0;
// The worker emits output and exit through `ctx.setupTokenPty`, bound to the
// The worker emits output and exit through `ctx.loginPty`, bound to the
// worker session id. The test drives them through the captured emitters.
const controllablePlugin = definePlugin({
async setup(ctx) {
emitOutput = (chunk: string) => ctx.setupTokenPty.output("ws-1", chunk);
resolveWait = (value) => ctx.setupTokenPty.exit("ws-1", value.exitCode);
emitOutput = (chunk: string) => ctx.loginPty.output("ws-1", chunk);
resolveWait = (value) => ctx.loginPty.exit("ws-1", value.exitCode);
},
async onSetupTokenPtyOpen(params) {
// The open carries the host route id and the fixed command. The worker
// returns a worker session id for the output binding only.
async onLoginPtyOpen(params) {
// The open carries the host route id, the closed command key, and the
// validated session home. The worker returns a worker session id for the
// output binding only. The open carries no command string.
expect(params.hostRouteId).toBe("route-1");
expect(params.command).toBe("claude setup-token");
expect(params.loginCommandKey).toBe("claude");
expect(params.sessionHome).toBe(
"/tmp/paperclip-adapter-login/11111111-2222-4333-8444-555555555555",
);
expect(params.providerLeaseId).toBe("lease-1");
return { workerSessionId: "ws-1" };
},
async onSetupTokenPtyInput(params) {
async onLoginPtyInput(params) {
inputs.push(params.data);
},
async onSetupTokenPtyStop() {
async onLoginPtyStop() {
killed += 1;
},
async onSetupTokenPtyClose(params) {
async onLoginPtyClose(params) {
// The close keys on the host route id and returns a bound acknowledgement.
closed += 1;
return { hostRouteId: params.hostRouteId };
@@ -839,10 +843,10 @@ describe("worker setup-token pseudo-terminal dispatch", () => {
await expect(
callWorker("initialize", {
manifest: {
id: "paperclip.setup-token-pty",
id: "paperclip.login-pty",
apiVersion: 1,
version: "1.0.0",
displayName: "Setup Token PTY Test",
displayName: "Login PTY Test",
description: "Test plugin",
author: "Paperclip",
categories: ["automation"],
@@ -855,31 +859,32 @@ describe("worker setup-token pseudo-terminal dispatch", () => {
).resolves.toMatchObject({
ok: true,
supportedMethods: expect.arrayContaining([
"setupTokenPtyOpen",
"setupTokenPtyInput",
"setupTokenPtyStop",
"setupTokenPtyClose",
"loginPtyOpen",
"loginPtyInput",
"loginPtyStop",
"loginPtyClose",
]),
});
await expect(
callWorker("setupTokenPtyOpen", {
callWorker("loginPtyOpen", {
hostRouteId: "route-1",
driverKey: "daytona",
companyId: "company-1",
environmentId: "env-1",
providerLeaseId: "lease-1",
command: "claude setup-token",
loginCommandKey: "claude",
sessionHome: "/tmp/paperclip-adapter-login/11111111-2222-4333-8444-555555555555",
}),
).resolves.toEqual({ workerSessionId: "ws-1" });
// The worker streams output as a notification bound to the worker session id.
emitOutput?.("prompt output");
await callWorker("setupTokenPtyInput", { workerSessionId: "ws-1", data: "browser-code" });
await callWorker("setupTokenPtyStop", { workerSessionId: "ws-1" });
await callWorker("loginPtyInput", { workerSessionId: "ws-1", data: "browser-code" });
await callWorker("loginPtyStop", { workerSessionId: "ws-1" });
resolveWait?.({ exitCode: 0 });
await expect(
callWorker("setupTokenPtyClose", { hostRouteId: "route-1" }),
callWorker("loginPtyClose", { hostRouteId: "route-1" }),
).resolves.toEqual({ hostRouteId: "route-1" });
await new Promise((resolve) => setImmediate(resolve));
@@ -888,13 +893,13 @@ describe("worker setup-token pseudo-terminal dispatch", () => {
expect(killed).toBe(1);
expect(closed).toBe(1);
const outputNotes = notifications.filter(
(note) => note.method === "setupTokenPty.output",
(note) => note.method === "loginPty.output",
);
expect(outputNotes.map((note) => note.params)).toEqual([
{ workerSessionId: "ws-1", chunk: "prompt output" },
]);
const exitNotes = notifications.filter(
(note) => note.method === "setupTokenPty.exit",
(note) => note.method === "loginPty.exit",
);
expect(exitNotes.map((note) => note.params)).toEqual([
{ workerSessionId: "ws-1", exitCode: 0 },