@tanstack/ai-sandbox
Version:
Provider-agnostic sandbox layer for TanStack AI — run harness adapters inside isolated sandboxes (defineSandbox, defineWorkspace, withSandbox) with a uniform SandboxHandle, workspace bootstrap, policy, and resumable lifecycle.
395 lines (394 loc) • 13.5 kB
JavaScript
import { delimiter, extname, join, posix } from "node:path";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { access, readFile, rename, rm, writeFile } from "node:fs/promises";
import { stripVTControlCharacters } from "node:util";
// src/host-login.ts
/**
* Sign in with a vendor CLI plan (ChatGPT, SuperGrok) on the host, and lend
* that login to a sandbox for one run.
*
* Server-only: this module starts host processes and reads host files.
*/
var URL_PATTERN = /https:\/\/\S+/;
var CODE_PATTERN = /[A-Z0-9]{4,}-[A-Z0-9]{4,}/;
/**
* A chunk can end in the middle of the URL or the code. The last word of the
* output is read only after the CLI was quiet for this time.
*/
var QUIET_DELAY_MS = 500;
/** The URL and the code in `text`, or `undefined` when it has no URL. */
function parseDeviceCode(text) {
const verificationUri = URL_PATTERN.exec(text)?.[0];
if (verificationUri === void 0) return void 0;
const userCode = CODE_PATTERN.exec(text)?.[0];
return userCode === void 0 ? { verificationUri } : {
verificationUri,
userCode
};
}
/**
* Runs the CLI with no shell (Windows `.cmd` shims go through `cmd.exe`) and collects stdout and stderr together.
* Resolves when the process closes. On abort, kills the process and rejects
* after it closes, so no process stays behind.
*/
function runCli(options) {
const { executable, args, env, signal, onOutput } = options;
const [command, ...leadingArgs] = typeof executable === "string" ? [executable] : executable;
const commandLine = [
command,
...leadingArgs,
...args
].join(" ");
return new Promise((resolve, reject) => {
if (command === void 0) {
reject(/* @__PURE__ */ new Error("The CLI executable is empty."));
return;
}
if (signal?.aborted) {
reject(signal.reason);
return;
}
const childEnv = {
...process.env,
...env
};
const launch = windowsLaunch(command, [...leadingArgs, ...args], childEnv);
const child = spawn(launch.command, launch.args, {
env: childEnv,
stdio: [
"ignore",
"pipe",
"pipe"
],
windowsHide: true,
windowsVerbatimArguments: launch.verbatim
});
let output = "";
const onData = (chunk) => {
output += chunk;
onOutput?.(output);
};
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", onData);
child.stderr.on("data", onData);
const onAbort = () => {
if (launch.verbatim && child.pid !== void 0) spawn("taskkill", [
"/pid",
String(child.pid),
"/T",
"/F"
], {
stdio: "ignore",
windowsHide: true
});
else child.kill();
};
signal?.addEventListener("abort", onAbort, { once: true });
child.on("error", (error) => {
signal?.removeEventListener("abort", onAbort);
reject(error.code === "ENOENT" ? /* @__PURE__ */ new Error(`Could not start "${command}". Install the CLI and make sure it is on the PATH.`) : error);
});
child.on("close", (exitCode) => {
signal?.removeEventListener("abort", onAbort);
if (signal?.aborted) {
reject(signal.reason);
return;
}
resolve({
commandLine,
exitCode,
output
});
});
});
}
/**
* On Windows, npm installs CLIs such as `codex` as `.cmd` shims, and Node can
* start a `.cmd` file only through `cmd.exe`. This finds a bare command on the
* `PATH` with `PATHEXT`, and runs a `.cmd` or `.bat` match through `cmd.exe`.
* A command that is not found stays as it is, so `spawn` reports `ENOENT`.
*/
function windowsLaunch(command, args, env) {
const direct = {
command,
args: [...args],
verbatim: false
};
if (process.platform !== "win32") return direct;
let resolved = command;
if (!/[\\/]/.test(command) && extname(command) === "") {
const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";");
const found = (env.PATH ?? env.Path ?? "").split(delimiter).flatMap((dir) => exts.map((ext) => join(dir, command + ext))).find((candidate) => existsSync(candidate));
if (found === void 0) return direct;
resolved = found;
}
if (!/\.(cmd|bat)$/i.test(resolved)) return {
...direct,
command: resolved
};
const quote = (token) => /[\s&|<>^()]/.test(token) ? `"${token}"` : token;
const line = [resolved, ...args].map(quote).join(" ");
return {
command: env.ComSpec ?? "cmd.exe",
args: [
"/d",
"/s",
"/c",
`"${line}"`
],
verbatim: true
};
}
function failure(result, hint) {
return /* @__PURE__ */ new Error(`"${result.commandLine}" failed with exit code ${result.exitCode}.${hint}\nOutput:\n${result.output}`);
}
/**
* Makes a {@link PlanLogin} for a vendor CLI that has a device-code login,
* for example `codex login --device-auth`. The login lives in the CLI's own
* file. This code keeps no copy of the tokens.
*
* @param options.executable - The CLI command, or `[command, ...leadingArgs]`.
* @param options.loginArgs - Arguments for the device-code login.
* @param options.logoutArgs - Arguments for sign out.
* @param options.authFile - Returns the absolute host path of the CLI login file.
* @param options.planLabel - A name for messages, for example 'ChatGPT plan'.
* @param options.env - Extra environment variables for the CLI.
*
* `signIn` calls `onCode` once with the device URL and code, and resolves
* when the CLI exits with 0. It rejects with an `Error` that holds the CLI
* output when the CLI fails, and with `signal.reason` when the signal aborts.
*
* @example
* ```ts
* const login = cliPlanLogin({
* executable: 'codex',
* loginArgs: ['login', '--device-auth'],
* logoutArgs: ['logout'],
* authFile: () => join(homedir(), '.codex', 'auth.json'),
* planLabel: 'ChatGPT plan',
* })
* await login.signIn({ onCode: (code) => show(code) })
* ```
*/
function cliPlanLogin(options) {
const { executable, loginArgs, logoutArgs, authFile, planLabel, env } = options;
return {
planLabel,
signIn: async ({ onCode, signal }) => {
let reported = false;
let quietTimer;
const report = (code) => {
clearTimeout(quietTimer);
if (reported) return;
reported = true;
onCode(code);
};
const onOutput = (output) => {
if (reported) return;
const text = stripVTControlCharacters(output);
clearTimeout(quietTimer);
const complete = parseDeviceCode(text.slice(0, text.search(/\S*$/)));
if (complete?.userCode !== void 0) {
report(complete);
return;
}
quietTimer = setTimeout(() => {
const settled = parseDeviceCode(text);
if (settled !== void 0) report(settled);
}, QUIET_DELAY_MS);
};
try {
const result = await runCli({
executable,
args: loginArgs,
env,
signal,
onOutput
});
if (result.exitCode === 0) return;
throw failure(result, URL_PATTERN.test(stripVTControlCharacters(result.output)) ? "" : " It printed no sign-in URL.");
} finally {
clearTimeout(quietTimer);
}
},
signOut: async () => {
const result = await runCli({
executable,
args: logoutArgs,
env
});
if (result.exitCode !== 0) throw failure(result, "");
},
status: () => access(authFile()).then(() => true, () => false)
};
}
/**
* Copies the host login file of a CLI into the sandbox home for one run.
* Call `release()` in a `finally` after the run. It writes the sandbox file
* back to the host when the CLI changed it (a refreshed token) and the host
* file did not change during the run. Then it removes the file from the
* sandbox, also when the read-back fails.
*
* Runs on the same sandbox share one copy. The last `release()` writes it
* back and removes it.
*
* A durable agent can outlive the stream of its host. For that run, call
* `release({ keep: true })` to leave the login in the sandbox, and mount with
* `adopt: true` on the host that attaches. That host then uses the login
* that is already there, which can hold a refreshed token.
*
* On a `local-process` sandbox, nothing is copied: the CLI reads the host
* file.
*
* @param sandbox - The sandbox of the run.
* @param options.hostPath - Absolute host path of the login file.
* @param options.sandboxHomePath - Path in the sandbox, relative to `$HOME`.
* @param options.label - The CLI name for the error, for example 'Codex'.
* @param options.connectCommand - The command that signs in, for example '/connect:codex'.
* @param options.adopt - Keep a login that is already in the sandbox. For a host that attaches to a running agent.
*
* Throws an `Error` when the host has no login file, unless `adopt` finds a
* login already in the sandbox.
*
* @example
* ```ts
* const login = await mountHostLogin(sandbox, {
* hostPath: join(homedir(), '.codex', 'auth.json'),
* sandboxHomePath: '.codex/auth.json',
* label: 'Codex',
* connectCommand: '/connect:codex',
* })
* try {
* await run()
* } finally {
* await login.release()
* }
* ```
*/
async function mountHostLogin(sandbox, options) {
if (sandbox.provider === "local-process") return { release: () => Promise.resolve() };
const key = `${sandbox.provider}\0${sandbox.id}\0${options.sandboxHomePath}`;
let mount = mounts.get(key);
while (mount?.released !== void 0) {
await mount.released.catch(() => void 0);
mount = mounts.get(key);
}
if (mount === void 0) {
mount = {
runs: 0,
hostPath: options.hostPath,
borrowed: borrowHostLogin(sandbox, options)
};
mounts.set(key, mount);
} else if (mount.hostPath !== options.hostPath) throw new Error(`The ${options.label} login in this sandbox is from ${mount.hostPath}, not ${options.hostPath}. Use one login file for each sandbox.`);
const shared = mount;
shared.runs += 1;
let borrowed;
try {
borrowed = await shared.borrowed;
} catch (error) {
shared.runs -= 1;
if (shared.runs === 0 && mounts.get(key) === shared) mounts.delete(key);
throw error;
}
if (borrowed.kept) shared.keep = true;
let isReleased = false;
return {
/** `keep: true` leaves the login in the sandbox for a host that attaches. */
release: async (releaseOptions) => {
if (isReleased) return;
isReleased = true;
shared.runs -= 1;
if (releaseOptions?.keep === true) shared.keep = true;
if (shared.runs > 0) return;
if (shared.keep === true) {
if (mounts.get(key) === shared) mounts.delete(key);
return;
}
shared.released = returnHostLogin(sandbox, options.hostPath, borrowed).finally(() => {
if (mounts.get(key) === shared) mounts.delete(key);
});
await shared.released;
} };
}
/** The mounts in use, by sandbox and login file. */
var mounts = /* @__PURE__ */ new Map();
/** Sidecar next to the sandbox login. Holds the host bytes from the first copy. */
function hostBaselinePath(loginPath) {
return `${loginPath}.tanstack-host`;
}
/** Host login bytes, or `undefined` when the file is missing. */
function readHostFile(hostPath) {
return readFile(hostPath, "utf8").catch((error) => {
if (error.code !== "ENOENT") throw error;
});
}
/** Copy the host login file into the sandbox. */
async function borrowHostLogin(sandbox, options) {
const { hostPath, sandboxHomePath, label, connectCommand } = options;
const home = await sandbox.process.exec("printf %s \"$HOME\"");
const homePath = home.stdout.trim();
if (home.exitCode !== 0 || homePath === "") throw new Error(`Could not find $HOME in the sandbox to copy the ${label} login.\n${home.stderr}`);
const path = posix.join(homePath, sandboxHomePath);
const baselinePath = hostBaselinePath(path);
if (options.adopt === true && await sandbox.fs.exists(path)) return {
path,
content: (await sandbox.fs.exists(baselinePath) ? await sandbox.fs.read(baselinePath) : await readHostFile(hostPath)) ?? await sandbox.fs.read(path)
};
if (await sandbox.fs.exists(baselinePath)) {
if (await sandbox.fs.exists(path)) return {
path,
content: await sandbox.fs.read(baselinePath),
kept: true
};
await sandbox.fs.remove(baselinePath);
}
const content = await readHostFile(hostPath);
if (content === void 0) throw new Error(`No ${label} login on this machine. Run ${connectCommand}.`);
await sandbox.fs.mkdir(posix.dirname(path));
try {
await sandbox.fs.write(path, content);
await sandbox.fs.write(baselinePath, content);
} catch (error) {
await sandbox.fs.remove(path).catch(() => void 0);
await sandbox.fs.remove(baselinePath).catch(() => void 0);
throw error;
}
return {
path,
content
};
}
/**
* Copy a refreshed token back to the host, then remove the sandbox file, also
* when the read-back fails.
*/
async function returnHostLogin(sandbox, hostPath, { path, content }) {
const copyBack = async () => {
const after = await sandbox.fs.read(path);
if (after === content) return;
if (await readFile(hostPath, "utf8").catch(() => void 0) === content) await replaceHostFile(hostPath, after);
};
const [copied] = await Promise.allSettled([copyBack()]);
const [login] = await Promise.allSettled([sandbox.fs.remove(path), sandbox.fs.remove(hostBaselinePath(path))]);
if (login.status === "rejected") throw login.reason;
if (copied.status === "rejected") throw copied.reason;
}
/**
* Write the whole file next to the login, then rename it over the login. A
* run that copies the login at the same time never reads half a file.
*/
async function replaceHostFile(hostPath, content) {
const temp = `${hostPath}.${process.pid}.${Date.now()}.tmp`;
try {
await writeFile(temp, content, { mode: 384 });
await rename(temp, hostPath);
} catch (error) {
await rm(temp, { force: true });
throw error;
}
}
export { cliPlanLogin, mountHostLogin };
//# sourceMappingURL=host-login.js.map