mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 17:33:51 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agent work runs in sandboxes that provider plugins supply > - Operators can choose a provider to run agent work > - CreateOS adds another provider with workspace-preserving pause and resume > - This pull request adds a CreateOS provider plugin > - The benefit is that operators can preserve a workspace between runs without keeping its compute active ## Linked Issues or Issue Description Refs #13203 and the earlier closed #13096. This continues the CreateOS contribution from @bhautikchudasama and @ashwaq06. The branch preserves the original implementation commit. Thank you to both contributors. When squash-merging, preserve the original author's credit in the squash commit body: ```text Co-Authored-By: bhautikchudasama <BhautikChudasama@users.noreply.github.com> ``` The original fork rejects maintainer pushes. This branch includes the merge-conflict resolution and review fixes. The request is described below using `adapter_request.yml`. **Agent or provider** CreateOS sandbox API (https://api.sb.createos.sh). **Why this adapter is useful** CreateOS can pause a sandbox and resume it by ID. The workspace survives the pause. This adds a reusable-lease option to the existing sandbox provider system. **How the agent is invoked** Build and install the local plugin as described in its README. Open Instance Settings, then Environments. Select the `createos` driver. Supply an API key and shape. The driver then supplies sandbox leases for agent runs. **Are you willing to implement it?** Yes. This pull request is the implementation. ## What Changed - Adds the `createos` sandbox provider under `packages/plugins/sandbox-providers/createos`. - Calls the CreateOS HTTP API directly. The package adds no vendor SDK. - Implements the environment lifecycle hooks, incremental process output, and binary workspace sync. - Registers the optional bundled provider and its trusted host credential fallback. The fallback is limited to the official API origin; custom endpoints require an explicit key. - Lists the package in the release manifest with `publishFromCi: false` until its first npm publish is bootstrapped. - Waits through delayed pause/resume state updates without duplicate action requests. - Cancels queued API requests promptly while preserving request spacing. - Uses direct CLI invocation in the setup guide so paths and IDs are passed without an extra shell expansion. - Includes current master and retains its existing Git-subfolder containment fix. ## Demo Fresh setup and a run against a CreateOS sandbox. https://github.com/user-attachments/assets/e71b9e06-c006-4fb9-b847-52dfd68f6110 https://github.com/user-attachments/assets/43b5ac75-66bd-4f76-8563-67e4c7759084 ## Verification All 25 jobs in [CI run 34884260542](https://github.com/paperclipai/paperclip/actions/runs/34884260542) passed at commit `f8d0997677024b784fdadf9d44a84c01cb4e813c`, including typecheck, build, native runner verification, server and workspace tests, browser tests, and the canary release dry run. Greptile reviewed the same commit at 5/5 with no unresolved review threads. GitHub reports no merge conflicts. The remaining merge gate is code-owner approval for the new `package.json`, as required by `.github/CODEOWNERS` and the `master` ruleset. Reviewers have been requested automatically. Local checks passed: - Provider: `pnpm typecheck`, `pnpm test` (52 passed, one live smoke skipped), and `pnpm build`. - Host: focused credential and bundled-plugin tests (17 passed), plus CLI invocation safety (39 passed). - Release: package manifest check and release policy tests (18 passed). The full local `pnpm test:run` attempt caught the README command issue; its focused rerun now passes. The full local run stopped after its general-server group: 7,804 tests passed, with unrelated embedded PostgreSQL startup failures and 10 failures in unchanged runtime-skill-cache tests (`EACCES` on directory rename on macOS). It did not reach the later test groups. Local `pnpm -r typecheck` and `pnpm build` reach the runner package and stop because this machine has no Rust/Cargo installation. The corresponding CI checks passed on provisioned runners, as linked above. The live CreateOS smoke requires explicit provider credentials and was not run during this review. It is available with `CREATEOS_LIVE_TEST=1 pnpm test` in the provider directory. The author supplied the demo links above. ## Risks The provider is opt-in and is not installed by default. It is available through a local-path install or explicit image inclusion. npm publication remains disabled until a maintainer bootstraps the package and enables publishing. Sandbox creation has no idempotency key. An ambiguous create response can leave a resource that requires provider-account inspection. Process tracking is in memory; durable lease recovery belongs to the host. The provider does not advertise guaranteed expiry, interactive login, snapshots, duplex channels, or ingress. Live native-runner qualification remains outside this PR's tested claims. ## Model Used Original provider implementation: human-authored by @bhautikchudasama, as reported in #13203. The original description reports Claude Opus 5 assistance. Review and follow-up fixes: OpenAI GPT-6 via Codex, with code review, editing, and tool execution. The precise runtime model variant and context-window size are not exposed in this session. ## 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 (focused checks; full-suite environment limits documented above) - [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: bhautikchudasama <bhautikrchudasama@gmail.com> Co-authored-by: Paperclip <noreply@paperclip.ing>
176 lines
9.7 KiB
TypeScript
176 lines
9.7 KiB
TypeScript
import path from "node:path";
|
|
import os from "node:os";
|
|
import { randomUUID } from "node:crypto";
|
|
import { createReadStream, createWriteStream, promises as fs } from "node:fs";
|
|
import { Readable } from "node:stream";
|
|
import { pipeline } from "node:stream/promises";
|
|
import * as tar from "tar";
|
|
import type { PluginEnvironmentSyncInParams, PluginEnvironmentSyncResult } from "@paperclipai/plugin-sdk";
|
|
import { CreateosClient, identifier } from "./client.js";
|
|
import { execute, shellQuote } from "./execute.js";
|
|
|
|
const ROOT = "/paperclip-workspace";
|
|
|
|
export function assertRemotePath(value: string): void {
|
|
if (!path.posix.isAbsolute(value) || value.includes("\0") || value.split("/").includes("..")) {
|
|
throw new Error("CreateOS transfer requires a confined absolute sandbox path.");
|
|
}
|
|
const normalized = path.posix.normalize(value);
|
|
if (normalized !== ROOT && !normalized.startsWith(`${ROOT}/`)) throw new Error("CreateOS transfer path escapes the workspace.");
|
|
}
|
|
|
|
function remoteGuard(candidate: string): string {
|
|
assertRemotePath(candidate);
|
|
// Re-check symlinks inside the sandbox immediately before use. A missing
|
|
// canonicalizer fails the command rather than weakening containment.
|
|
return `root=$(realpath -- ${shellQuote(ROOT)}) && test "$root" = ${shellQuote(ROOT)} && ` +
|
|
`resolved=$(realpath -m -- ${shellQuote(candidate)}) && ` +
|
|
`case "$resolved" in "$root"|"$root"/*) ;; *) exit 1 ;; esac`;
|
|
}
|
|
|
|
export async function validateArchive(file: string): Promise<number> {
|
|
let invalid = false;
|
|
let bytes = 0;
|
|
let files = 0;
|
|
const inside = (entryPath: string) => !path.posix.isAbsolute(entryPath) &&
|
|
!entryPath.split("/").includes("..") && !entryPath.includes("\\") && !entryPath.includes("\0");
|
|
await tar.t({ file, strict: true, onReadEntry(entry) {
|
|
bytes += entry.size;
|
|
if (bytes > 10 * 1024 ** 3 || !inside(entry.path)) invalid = true;
|
|
if (!["File", "OldFile", "Directory", "SymbolicLink", "Link"].includes(entry.type)) invalid = true;
|
|
if (entry.type === "File" || entry.type === "OldFile") files++;
|
|
if (entry.type === "SymbolicLink" || entry.type === "Link") {
|
|
if (!entry.linkpath) { invalid = true; return; }
|
|
const base = entry.type === "SymbolicLink" ? path.posix.dirname(entry.path) : ".";
|
|
const target = path.posix.normalize(path.posix.join(base, entry.linkpath));
|
|
if (path.posix.isAbsolute(entry.linkpath) || entry.linkpath.includes("\\") || !inside(target)) invalid = true;
|
|
}
|
|
} });
|
|
if (invalid) throw new Error("CreateOS archive contains unsafe entries or exceeds the extraction limit.");
|
|
return files;
|
|
}
|
|
|
|
function excluded(name: string, patterns: string[]): boolean {
|
|
name = name.replace(/^\.\//, "").replace(/\/$/, "");
|
|
return patterns.some((pattern) => [pattern, `${pattern}/**`, `**/${pattern}`, `**/${pattern}/**`]
|
|
.some((glob) => path.matchesGlob(name, glob)));
|
|
}
|
|
|
|
export async function syncFiles(
|
|
client: CreateosClient,
|
|
params: PluginEnvironmentSyncInParams,
|
|
direction: "in" | "out",
|
|
signal: AbortSignal,
|
|
): Promise<PluginEnvironmentSyncResult> {
|
|
const id = identifier(params.lease.providerLeaseId);
|
|
const operations: PluginEnvironmentSyncResult["operations"] = [];
|
|
const run = async (command: string, cwd = ROOT, timeoutMs?: number) => {
|
|
assertRemotePath(cwd);
|
|
const result = await execute(client, { ...params, command: "/bin/bash", args: ["-c", command], cwd },
|
|
timeoutMs == null ? signal : AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]));
|
|
if (result.timedOut || result.exitCode !== 0) throw new Error("CreateOS transfer command failed.");
|
|
};
|
|
const upload = async (local: string, remote: string) => {
|
|
const source = createReadStream(local);
|
|
try {
|
|
const init: RequestInit & { duplex: "half" } = {
|
|
method: "PUT", body: Readable.toWeb(source) as ReadableStream<Uint8Array>,
|
|
duplex: "half", headers: { "Content-Type": "application/octet-stream" }, signal,
|
|
};
|
|
const response = await client.request(`/sandboxes/${id}/files?path=${encodeURIComponent(remote)}`, init);
|
|
await response.body?.cancel();
|
|
} finally { source.destroy(); }
|
|
};
|
|
const download = async (remote: string, local: string, mode = 0o600) => {
|
|
const response = await client.request(`/sandboxes/${id}/files?path=${encodeURIComponent(remote)}`, { signal });
|
|
if (!response.body) throw new Error("CreateOS file download has no body.");
|
|
await pipeline(response.body, createWriteStream(local, { flags: "wx", mode }), { signal });
|
|
};
|
|
|
|
// Validate every mapping before beginning side effects. Host paths are
|
|
// orchestrator-authored and checked by its source/target-root guard.
|
|
for (const operation of params.operations) {
|
|
for (const mapping of operation.files) {
|
|
if (!["file", "directory"].includes(mapping.kind)) throw new Error("Unsupported CreateOS transfer kind.");
|
|
if (!path.isAbsolute(direction === "in" ? mapping.sourcePath : mapping.targetPath)) throw new Error("CreateOS transfer requires an absolute host path.");
|
|
if (mapping.mode != null && (!Number.isInteger(mapping.mode) || mapping.mode < 0 || mapping.mode > 0o777)) throw new Error("Invalid CreateOS file mode.");
|
|
assertRemotePath(direction === "in" ? mapping.targetPath : mapping.sourcePath);
|
|
}
|
|
for (const command of operation.postUploadCommands ?? []) {
|
|
assertRemotePath(command.cwd ?? ROOT);
|
|
if (command.timeoutMs != null && (!Number.isInteger(command.timeoutMs) || command.timeoutMs < 1 || command.timeoutMs > 86_400_000)) throw new Error("Invalid CreateOS transfer timeout.");
|
|
}
|
|
if (direction === "out" && operation.postUploadCommands?.length) throw new Error("Outbound CreateOS transfers cannot run post-upload commands.");
|
|
}
|
|
|
|
for (const operation of params.operations) {
|
|
let bytesTransferred = 0;
|
|
let filesTransferred = 0;
|
|
for (const mapping of operation.files) {
|
|
signal.throwIfAborted();
|
|
const local = direction === "in" ? mapping.sourcePath : mapping.targetPath;
|
|
const remote = direction === "in" ? mapping.targetPath : mapping.sourcePath;
|
|
const scratch = `/tmp/paperclip-createos-transfer-${randomUUID()}`;
|
|
// Outbound temporary files are on the target filesystem for atomic rename.
|
|
const parent = direction === "out" ? path.dirname(local) : os.tmpdir();
|
|
await fs.mkdir(parent, { recursive: true });
|
|
const temp = await fs.mkdtemp(path.join(parent, ".paperclip-createos-"));
|
|
const transferFile = path.join(temp, "data");
|
|
try {
|
|
if (direction === "in") {
|
|
let source = local;
|
|
if (mapping.kind === "directory") {
|
|
await tar.c({ file: transferFile, cwd: local, follow: mapping.followSymlinks === true,
|
|
filter: (name) => !excluded(name, mapping.exclude ?? []) }, ["."]);
|
|
source = transferFile;
|
|
}
|
|
await upload(source, scratch);
|
|
const mode = mapping.mode ?? (mapping.kind === "file" ? (await fs.stat(source)).mode & 0o777 : 0o755);
|
|
await run(mapping.kind === "file"
|
|
? `${remoteGuard(remote)} && mkdir -p -- "$(dirname -- "$resolved")" && chmod ${mode.toString(8)} -- ${shellQuote(scratch)} && mv -f -- ${shellQuote(scratch)} "$resolved"`
|
|
: `${remoteGuard(remote)} && mkdir -p -- "$resolved" && tar -xf ${shellQuote(scratch)} -C "$resolved" && chmod ${mode.toString(8)} -- "$resolved"`);
|
|
filesTransferred += mapping.kind === "file" ? 1 : await countArchiveFiles(source);
|
|
bytesTransferred += (await fs.stat(source)).size;
|
|
} else {
|
|
const excludeArgs = (mapping.exclude ?? []).map((pattern) => `--exclude=${shellQuote(pattern)}`).join(" ");
|
|
await run(mapping.kind === "file"
|
|
? `${remoteGuard(remote)} && test -f "$resolved" && cp -- "$resolved" ${shellQuote(scratch)}`
|
|
: `${remoteGuard(remote)} && test -d "$resolved" && tar ${mapping.followSymlinks ? "-h " : ""}${excludeArgs} -cf ${shellQuote(scratch)} -C "$resolved" .`);
|
|
await download(scratch, transferFile, mapping.mode ?? 0o600);
|
|
bytesTransferred += (await fs.stat(transferFile)).size;
|
|
if (mapping.kind === "file") {
|
|
// Apply exact requested mode before promotion, including under a
|
|
// restrictive umask. Never expose secret bytes at the final path first.
|
|
await fs.chmod(transferFile, mapping.mode ?? 0o600);
|
|
await fs.rename(transferFile, local);
|
|
filesTransferred++;
|
|
} else {
|
|
filesTransferred += await validateArchive(transferFile);
|
|
await fs.mkdir(local, { recursive: true, mode: mapping.mode ?? 0o700 });
|
|
if ((await fs.lstat(local)).isSymbolicLink()) throw new Error("CreateOS archive destination cannot be a symlink.");
|
|
// tar rejects traversal through existing symlink parents. Validate
|
|
// all archive entries first so an unsafe archive never partly lands.
|
|
await tar.x({ file: transferFile, cwd: local, strict: true, preservePaths: false });
|
|
if (mapping.mode != null) await fs.chmod(local, mapping.mode);
|
|
}
|
|
}
|
|
} finally {
|
|
await fs.rm(temp, { recursive: true, force: true });
|
|
await client.json(`/sandboxes/${id}/exec`, "POST", { cmd: "/bin/rm", args: ["-f", "--", scratch] }).catch(() => undefined);
|
|
}
|
|
}
|
|
for (const command of operation.postUploadCommands ?? []) {
|
|
await run(remoteGuard(command.cwd ?? ROOT));
|
|
await run(command.command, command.cwd ?? ROOT, command.timeoutMs);
|
|
}
|
|
operations.push({ operationId: operation.operationId, filesTransferred, bytesTransferred });
|
|
}
|
|
return { operations };
|
|
}
|
|
|
|
async function countArchiveFiles(file: string): Promise<number> {
|
|
let count = 0;
|
|
await tar.t({ file, onReadEntry(entry) { if (entry.type === "File" || entry.type === "OldFile") count++; } });
|
|
return count;
|
|
}
|