Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions apps/server/src/sandbox/SandboxProvisioner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import { layerHttpClient, requestJson } from "./SandboxProvider.ts";
import { bridgeLinkSecretName } from "@t3tools/sandbox-bridge/link";
import { boatDriver } from "./providers/boat.ts";
import { SANDBOX_FILES_SKILL } from "./sandboxSetup.ts";
import { celestoDriver } from "./providers/celesto.ts";
import { daytonaDriver } from "./providers/daytona.ts";
import { upstashDriver } from "./providers/upstash.ts";
Expand Down Expand Up @@ -6599,6 +6600,124 @@ describe("SandboxProvisioner per-thread launches", () => {
},
);

const skillWarning =
"T3 Code's t3-sandbox-files skill could not be added, so agents on this sandbox may keep files in /tmp, which a stop empties.";
const skillCommands = (fake: BoatFake) =>
fake.commands.filter((command) => command.includes("skills/t3-sandbox-files"));

it.effect("gives every launched sandbox T3 Code's skill, even with no skills chosen", () => {
const fake = boatFake();
const configs = memoryConfigs();
return Effect.gen(function* () {
const provisioner = yield* SandboxProvisioner.SandboxProvisioner;
const { config } = yield* provisioner.saveConfig({
config: configInput,
apiKey: "boat_test",
});
expect(config.skills ?? []).toEqual([]);
expect(config.claudeMd).not.toBe(true);
yield* provisioner.launch({ configId: config.id, threadId, project });
const done = yield* snapshotWhere(provisioner, (snapshot) => snapshot.phase === "done");
// A launch writes it whether or not a copy is there, so a template's older one goes.
const [written, ...rest] = skillCommands(fake);
expect(rest).toEqual([]);
expect(written).toContain('"${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/t3-sandbox-files"');
expect(written).not.toContain("exit 0");
expect(written).toContain(Buffer.from(SANDBOX_FILES_SKILL, "utf8").toString("base64"));
// Nothing the config asked for, so the step still reads as nothing to set up.
expect(stageOf(done, "tools")).toMatchObject({ status: "skipped" });
expect(done.warnings).not.toContain(skillWarning);
}).pipe(
Effect.provide(provisionerLayer({}, memoryRepository().layer, { configs: configs.layer })),
Effect.provideService(HttpClient.HttpClient, fake.client),
);
});

it.effect("only warns when the launch cannot write T3 Code's skill", () => {
const fake = boatFake({ failing: { text: "skills/t3-sandbox-files", times: 1 } });
const repository = memoryRepository();
const configs = memoryConfigs();
return Effect.gen(function* () {
const provisioner = yield* SandboxProvisioner.SandboxProvisioner;
const { config } = yield* provisioner.saveConfig({
config: configInput,
apiKey: "boat_test",
});
const { instanceId } = yield* provisioner.launch({ configId: config.id, threadId, project });
const done = yield* snapshotWhere(provisioner, (snapshot) => snapshot.phase === "done");
expect(done.warnings).toContain(skillWarning);
expect(stageOf(done, "tools")).toMatchObject({
status: "warning",
detail: "Finished with warnings",
});
expect(repository.records.get(instanceId)?.state).toBe("running");
expect(deletes(fake)).toEqual([]);
}).pipe(
Effect.provide(provisionerLayer({}, repository.layer, { configs: configs.layer })),
Effect.provideService(HttpClient.HttpClient, fake.client),
);
});

it.effect(
"adds T3 Code's skill on a resume when it is missing, before T3 starts, and only warns when it cannot",
() => {
const fake = boatFake({ failing: { text: "skills/t3-sandbox-files", times: 1 } });
const config: SandboxEnvironmentConfig = {
...configInput,
id: "config-before-skill",
createdAt: "1970-01-01T00:00:00.000Z",
updatedAt: "1970-01-01T00:00:00.000Z",
};
// A thread's sandbox made before T3 Code wrote its skill.
const older: SandboxRecord = {
instanceId: "before-skill",
environmentId: testEnvironmentId,
configId: config.id,
threadId,
provider: "boat",
sandboxId: boatSandboxId,
label: "hello on Boat small",
size: "small",
state: "stopped",
createdAt: "1970-01-01T00:00:00.000Z",
updatedAt: "1970-01-01T00:00:00.000Z",
httpBaseUrl: "https://boat.example/t3",
runningSince: null,
maxRunningMinutes: 480,
repoDir: "/home/boat/work/hello",
};
const repository = memoryRepository([older]);
return Effect.gen(function* () {
const provisioner = yield* SandboxProvisioner.SandboxProvisioner;
// The first try fails: the sandbox still resumes, with a warning.
const failed = yield* provisioner.resume({ instanceId: "before-skill" });
expect(failed.sandbox.state).toBe("running");
expect(failed.warnings).toContain(skillWarning);

yield* provisioner.stop({ instanceId: "before-skill" });
fake.commands.length = 0;
const resumed = yield* provisioner.resume({ instanceId: "before-skill" });
expect(resumed.warnings ?? []).not.toContain(skillWarning);
// Only a missing skill is written, so one already there keeps its copy.
const [backfill, ...rest] = skillCommands(fake);
expect(rest).toEqual([]);
expect(backfill).toContain('[ -f "$dir/SKILL.md" ] && exit 0');
expect(fake.commands.indexOf(backfill!)).toBeLessThan(
fake.commands.findIndex((command) => command.includes("t3 serve")),
);
}).pipe(
Effect.provide(
provisionerLayer(
{ sandboxProviders: { boat: { apiKey: "boat_test" } } },
repository.layer,
{ configs: memoryConfigs([config]).layer },
),
),
Effect.provideService(HttpClient.HttpClient, fake.client),
);
},
);

it.effect("keeps the sandbox and revokes the key when the boat CLI cannot sign in", () => {
const fake = boatFake({ failing: { text: "boat login", times: 1 } });
const repository = memoryRepository();
Expand Down
33 changes: 30 additions & 3 deletions apps/server/src/sandbox/SandboxProvisioner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ import {
RAILWAY_LOGIN_SCRUB,
railwayLoginScript,
parseSetupScriptReport,
sandboxFilesSkillScript,
sandboxKeepAliveScript,
setupScriptScript,
TAILSCALE_PROXY_URL,
Expand Down Expand Up @@ -489,6 +490,8 @@ const scriptHash = (script: string) => {

// A minted Maple key also expires on its own, in case a revoke never reaches Maple.
const MAPLE_KEY_SECONDS = 30 * 24 * 60 * 60;
const SANDBOX_FILES_SKILL_WARNING =
"T3 Code's t3-sandbox-files skill could not be added, so agents on this sandbox may keep files in /tmp, which a stop empties.";
// A sandbox's GitHub token is replaced this long before it expires.
const GITHUB_TOKEN_REFRESH_MS = 20 * 60 * 1000;
// A keep-alive key outlives any one running stretch and is replaced on a resume once it is close
Expand Down Expand Up @@ -2982,6 +2985,13 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
steps += 1;
yield* copyClaudeFiles(machine, { claudeMd: config.claudeMd === true, skills }, fail);
}
// T3 Code's own skill goes on every sandbox, after the user's so a template's copy is replaced.
// It is not something the config asked for, so only a failure shows in the step.
const skillWritten = yield* machine.run(sandboxFilesSkillScript("write"), 30).pipe(Effect.exit);
if (Exit.isFailure(skillWritten)) {
steps += 1;
yield* fail(SANDBOX_FILES_SKILL_WARNING);
}
return { steps, failed };
});

Expand Down Expand Up @@ -4033,6 +4043,19 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
};
};
}
// A sandbox made before T3 Code's agent skill existed gets it before T3 starts, so the first
// Claude session after the resume already sees it; one that has it keeps its copy.
const skill = yield* onHttp(
driver.execute({
config,
sandboxId: record.sandboxId,
command: sandboxFilesSkillScript("if-missing"),
timeoutSeconds: SANDBOX_RESUME_STEP_SECONDS.agentSkill,
}),
).pipe(
Effect.as<string | null>(null),
Effect.orElseSucceed(() => SANDBOX_FILES_SKILL_WARNING),
);
yield* onHttp(
driver.execute({
config,
Expand Down Expand Up @@ -4109,9 +4132,13 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
),
);
if (bridged.record !== updated) yield* records.put(bridged.record).pipe(Effect.orDie);
const warnings = [rejoined.warning, kept.warning, github.warning, bridged.warning].filter(
(warning): warning is string => warning !== null,
);
const warnings = [
rejoined.warning,
kept.warning,
skill,
github.warning,
bridged.warning,
].filter((warning): warning is string => warning !== null);
return {
sandbox: bridged.record,
httpBaseUrl: bridged.record.httpBaseUrl,
Expand Down
38 changes: 38 additions & 0 deletions apps/server/src/sandbox/sandboxSetup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ import {
parseTailscaleReport,
RAILWAY_LOGIN_SCRUB,
railwayLoginScript,
SANDBOX_FILES_SKILL,
SANDBOX_FILES_SKILL_NAME,
sandboxFilesSkillScript,
sandboxKeepAliveScript,
type SandboxScript,
tailscaleScript,
Expand Down Expand Up @@ -357,6 +360,41 @@ describe("setupScriptScript", () => {
);
});

describe("sandboxFilesSkillScript", () => {
it("names the skill so it can't replace one of the user's, and says when to load it", () => {
expect(SANDBOX_FILES_SKILL_NAME).toBe("t3-sandbox-files");
const frontmatter = /^---\n([\s\S]*?)\n---\n/u.exec(SANDBOX_FILES_SKILL)?.[1] ?? "";
expect(frontmatter).toContain("name: t3-sandbox-files\n");
const description = /^description: (.*)$/mu.exec(frontmatter)?.[1] ?? "";
for (const trigger of ["/tmp", "$TMPDIR", "screenshots", "logs", "worktrees", "drafts"]) {
expect(description).toContain(trigger);
}
});

it.live("writes the skill into Claude's folder, and on a resume only when it is missing", () =>
withHome((home) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const file = `${home}/.claude/skills/t3-sandbox-files/SKILL.md`;
yield* runIn(home, sandboxFilesSkillScript("write"));
expect(yield* fs.readFileString(file)).toBe(SANDBOX_FILES_SKILL);

// A copy already there stays as it is on a resume, and goes on a launch.
yield* fs.writeFileString(file, "edited");
yield* runIn(home, sandboxFilesSkillScript("if-missing"));
expect(yield* fs.readFileString(file)).toBe("edited");
yield* runIn(home, sandboxFilesSkillScript("write"));
expect(yield* fs.readFileString(file)).toBe(SANDBOX_FILES_SKILL);

yield* fs.remove(`${home}/.claude/skills`, { recursive: true });
yield* runIn(home, sandboxFilesSkillScript("if-missing"));
expect(yield* fs.readFileString(file)).toBe(SANDBOX_FILES_SKILL);
expect(yield* fs.exists(`${file}.t3-tmp`)).toBe(false);
}),
),
);
});

describe("mcpServersScript", () => {
it.live("merges servers into ~/.claude.json, and the template scrub removes only those", () =>
withHome((home) =>
Expand Down
43 changes: 43 additions & 0 deletions apps/server/src/sandbox/sandboxSetup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -894,3 +894,46 @@ export const KEEP_ALIVE_SCRUB = `if [ -f "${KEEP_ALIVE_DIR}/loop.sh" ]; then
sh "${KEEP_ALIVE_DIR}/loop.sh" stop >/dev/null 2>&1 || true
fi
rm -rf "${KEEP_ALIVE_DIR}"`;

/** The skill every sandbox's Claude gets from T3 Code, named so it never replaces one of the user's. */
export const SANDBOX_FILES_SKILL_NAME = "t3-sandbox-files";

/**
* Tells agents on a sandbox to keep what they need later out of `/tmp`, which a stop empties. The
* description is what makes Claude load it, so it names every moment an agent reaches for `/tmp`.
*/
export const SANDBOX_FILES_SKILL = `---
name: ${SANDBOX_FILES_SKILL_NAME}
description: Where to save files on this T3 Code sandbox, whose /tmp is wiped every time the sandbox stops. Use before writing anything that must still exist later (screenshots or images you embed in a reply, logs you will point the user to, downloads, PR or doc drafts, extra git worktrees, build artifacts), and whenever you would reach for /tmp or $TMPDIR.
---

# Files on a sandbox

This machine is a T3 Code sandbox. It stops on its own: when its agents go idle, at its running limit, or when the user stops it. Resuming it boots the machine again, and the boot empties \`/tmp\`. Everything under \`$HOME\` survives, including the project under \`~/work\`, \`~/.t3\` and \`~/.claude\`.

## Rules

- **Never put anything in \`/tmp\` that someone needs after your current command finishes.** Use a folder under \`$HOME\` instead: an existing work folder the user already uses (such as \`~/work\`), or \`~/scratch/<task>/\`.
- **Images you show the user:** save screenshots and generated images under \`$HOME\` before embedding them. An image embedded from \`/tmp\` breaks for the user after the next stop.
- **Extra git worktrees:** create them under \`$HOME\`, for example \`~/scratch/worktrees/<name>\`, not in \`/tmp\`. A worktree in \`/tmp\` leaves stale git metadata behind; \`git worktree prune\` cleans it up.
- **Logs and long outputs** you will cite later go to a file under \`$HOME\`, for example with \`tee ~/scratch/<task>/run.log\`.
- **Delegated agents:** when you brief one, tell it the same, and give it the folder to use.
- **Throwaway files** that nothing reads after the command ends, such as a pipe's temporary file, may stay in \`/tmp\`.
- **Large downloads and build outputs** under \`~/scratch\` count against the sandbox's disk. Delete them when the task is done.
`;

/**
* Writes the built-in skill into Claude's skills folder: always at launch, so a template's older
* copy goes, and on a resume only when it is missing, for sandboxes made before it existed. Exits
* nonzero when it cannot write it.
*/
export const sandboxFilesSkillScript = (mode: "write" | "if-missing") => `set -eu
dir="\${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills/${SANDBOX_FILES_SKILL_NAME}"
${
mode === "if-missing"
? `[ -f "$dir/SKILL.md" ] && exit 0
`
: ""
}mkdir -p "$dir"
printf '%s' '${base64(SANDBOX_FILES_SKILL)}' | base64 -d >"$dir/SKILL.md.t3-tmp"
mv "$dir/SKILL.md.t3-tmp" "$dir/SKILL.md"`;
11 changes: 10 additions & 1 deletion docs/internals/sandbox-environments.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,15 @@ server except into the sandbox.
the machine, and the environment only when nothing is left in it, since it is the only way to
find a fork again. The sweep's abandoned-launch delete never touches forks. The driver hides
`t3-sandbox-*` environments from `listEnvironments`, so they never show as credential choices.
- **Every sandbox's Claude gets T3 Code's `t3-sandbox-files` skill.** A stop empties `/tmp`, so
agents need telling to keep files under `$HOME`. The skill's text lives once, as
`SANDBOX_FILES_SKILL` in [`sandboxSetup.ts`](../../apps/server/src/sandbox/sandboxSetup.ts), and
`sandboxFilesSkillScript` writes it into `${CLAUDE_CONFIG_DIR:-~/.claude}/skills/t3-sandbox-files/`.
The launch's tools step always writes it, after the user's own skills, so a template's older copy
goes; it counts in that step only when it fails, so a config that asks for nothing still reads
"Nothing to set up". A resume writes it before `t3 serve` only when `SKILL.md` is missing. Either
failure is a warning. Nothing writes instructions for Codex on a sandbox, so Codex does not get
it.
- **A GitHub App token covers the whole installation.** `mintGithubToken` finds the installation
through the sandbox's repository (`GET /repos/{owner}/{repo}/installation`; a 404 is "not
installed", a launch warning with the install link), then mints with no `repositories` in the
Expand Down Expand Up @@ -419,7 +428,7 @@ without pairing with the sandbox.
- **Placeholder projects.** A project whose root `isSandboxHostProjectRoot` matches gets no git
status, scripts, open-in, files or terminal in the web app.
- **Stopped sandbox.** A run starting on a `sandboxes` thread whose sandbox is stopped makes the
host resume it. Meanwhile the bridge retries for `SANDBOX_RESUME_WAIT_SECONDS` (15 minutes:
host resume it. Meanwhile the bridge retries for `SANDBOX_RESUME_WAIT_SECONDS` (15½ minutes:
every step of a resume at its limit, `SANDBOX_RESUME_STEP_SECONDS`, plus a minute), showing
"Starting sandbox bx_…", then says the sandbox is not answering. Messages sent meanwhile queue
behind that run on the host, so they go out after it whether or not a client stays open.
Expand Down
7 changes: 7 additions & 0 deletions docs/user/remote-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ with a key scoped to it. T3 Code also
installs git, the GitHub CLI, and Claude Code when the provider's image lacks them; sign Codex in
from the sandbox's **Settings → Providers**.

Every sandbox's Claude also gets a skill from T3 Code, `t3-sandbox-files`, whether or not you copy
any skills of your own. A stop empties the sandbox's `/tmp`, so the skill tells the agent to keep
screenshots, drafts, logs, downloads and extra git worktrees under its home folder (for example
`~/scratch/<task>/`) instead. A launch writes it; a resume adds it when it is missing, so sandboxes
made before it get it too. A sandbox where it could not be written still works and shows a warning.
Codex agents on a sandbox do not get it.

**Projects** limits which repositories can start a thread on the config. It lists the github.com
repositories of projects on every connected machine, once each, so a project that lives only on a
paired machine counts too: the sandbox clones from GitHub, not from that machine. With none picked,
Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/src/sandbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ describe("isSandboxHostProjectRoot", () => {

describe("SANDBOX_RESUME_WAIT_SECONDS", () => {
it("outlasts every resume step at its limit, the T3 start the slowest Boat resume adds", () => {
expect(SANDBOX_RESUME_WAIT_SECONDS).toBe(15 * 60);
expect(SANDBOX_RESUME_WAIT_SECONDS).toBe(15 * 60 + 30);
const steps = Object.values(SANDBOX_RESUME_STEP_SECONDS);
expect(SANDBOX_RESUME_WAIT_SECONDS).toBeGreaterThan(
steps.reduce((sum: number, step) => sum + step, 0),
Expand Down
3 changes: 2 additions & 1 deletion packages/contracts/src/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -253,13 +253,14 @@ export const DEFAULT_SANDBOX_MAX_RUNNING_MINUTES = 480;
/**
* The longest each step of a sandbox resume may take on the host: the provider starting the
* machine (every driver polls 90 times, 2 seconds apart), installing a keep-alive key, rejoining a
* tailnet, and starting T3 Code on it.
* tailnet, starting T3 Code on it, and adding T3 Code's agent skill when it is missing.
*/
export const SANDBOX_RESUME_STEP_SECONDS = {
machineStart: 180,
keepAlive: 60,
tailnetRejoin: 420,
t3Start: 180,
agentSkill: 30,
} as const;

/**
Expand Down
Loading