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
128 changes: 128 additions & 0 deletions apps/server/src/sandbox/SandboxProvisioner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3634,6 +3634,8 @@ describe("SandboxProvisioner lifecycle", () => {
]);
expect(commands[0]).toContain("t3 service uninstall");
expect(commands[0]).toContain(`rm -rf "$HOME/.t3/userdata" "$HOME/.t3/environment-label"`);
// The sub-sandbox helper's queue goes, pending requests included, before T3's userdata.
expect(commands[0]).toContain(`rm -rf "$HOME/.t3/userdata/sub-sandbox"`);
expect(commands[0]).not.toContain("pkill");
// Without its T3 identity the source could only come back as a different environment.
expect(repository.byEnvironment(testEnvironmentId) !== undefined).toBe(false);
Expand Down Expand Up @@ -5819,6 +5821,10 @@ describe("SandboxProvisioner per-thread launches", () => {
});
expect(record?.threadId).toBeUndefined();
expect(record?.bridge).toBeUndefined();
// A subagent's sandbox has no chat here to hold more tasks, so it never gets the helper.
expect(fake.commands.filter((command) => command.includes("userdata/sub-sandbox"))).toEqual(
[],
);
// The same clone and env files as a thread's launch, at the parent's pushed branch.
const clone = fake.commands.find((command) =>
command.includes("https://github.com/octo/hello.git"),
Expand Down Expand Up @@ -6718,6 +6724,128 @@ describe("SandboxProvisioner per-thread launches", () => {
},
);

const helperWarning =
"T3 Code's sub-sandbox helper could not be added, so agents on this sandbox cannot ask this computer for a sandbox of their own.";
const helperCommands = (fake: BoatFake) =>
fake.commands.filter((command) => command.includes('dir="$HOME/.t3/userdata/sub-sandbox"'));

it.effect("installs the sub-sandbox helper on a launched chat's sandbox", () => {
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",
});
yield* provisioner.launch({ configId: config.id, threadId, project });
const done = yield* snapshotWhere(provisioner, (snapshot) => snapshot.phase === "done");
const [installed, ...rest] = helperCommands(fake);
expect(rest).toEqual([]);
// Registered in Claude's MCP list, and named so a template save removes the entry.
expect(installed).toContain('"$HOME/.t3/mcp-servers.json" "$dir/mcp.mjs" t3-sub-sandbox');
expect(installed).toContain('mv "$dir/mcp.mjs.tmp" "$dir/mcp.mjs"');
// Not something 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(helperWarning);
}).pipe(
Effect.provide(provisionerLayer({}, memoryRepository().layer, { configs: configs.layer })),
Effect.provideService(HttpClient.HttpClient, fake.client),
);
});

it.effect("only warns when the launch cannot install the sub-sandbox helper", () => {
const fake = boatFake({ failing: { text: "userdata/sub-sandbox", 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(helperWarning);
expect(stageOf(done, "tools")).toMatchObject({ status: "warning" });
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(
"installs the sub-sandbox helper again on every resume of a chat's sandbox, before T3 starts, and only warns when it cannot",
() => {
const fake = boatFake({ failing: { text: "userdata/sub-sandbox", times: 1 } });
const config: SandboxEnvironmentConfig = {
...configInput,
id: "config-before-helper",
createdAt: "1970-01-01T00:00:00.000Z",
updatedAt: "1970-01-01T00:00:00.000Z",
};
// A chat's sandbox made before T3 Code installed the helper, and a subagent's sandbox.
const older: SandboxRecord = {
instanceId: "before-helper",
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 { threadId: _threadId, ...withoutThread } = older;
const subagents: SandboxRecord = {
...withoutThread,
instanceId: "subagent-sandbox",
parentThreadId: threadId,
};
const repository = memoryRepository([older, subagents]);
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-helper" });
expect(failed.sandbox.state).toBe("running");
expect(failed.warnings).toContain(helperWarning);

yield* provisioner.stop({ instanceId: "before-helper" });
fake.commands.length = 0;
const resumed = yield* provisioner.resume({ instanceId: "before-helper" });
expect(resumed.warnings ?? []).not.toContain(helperWarning);
// Rewritten every time, so an older helper is replaced and Node's path stays current.
const [backfill, ...rest] = helperCommands(fake);
expect(rest).toEqual([]);
expect(fake.commands.indexOf(backfill!)).toBeLessThan(
fake.commands.findIndex((command) => command.includes("t3 serve")),
);

yield* provisioner.stop({ instanceId: "before-helper" });
fake.commands.length = 0;
yield* provisioner.resume({ instanceId: "subagent-sandbox" });
expect(helperCommands(fake)).toEqual([]);
}).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
55 changes: 55 additions & 0 deletions apps/server/src/sandbox/SandboxProvisioner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
import { type CliproxyHub, makeCliproxyApi } from "../usage/cliproxyApi.ts";
import * as SandboxHostAccess from "./SandboxHostAccess.ts";
import { SUB_SANDBOX_HELPER_SCRUB, subSandboxHelperScript } from "./subSandboxHelper.ts";
import {
CLAUDE_SETTINGS_SCRUB,
claudeSettingsScript,
Expand Down Expand Up @@ -287,6 +288,7 @@ while answering; do
sleep 1
done
${KEEP_ALIVE_SCRUB}
${SUB_SANDBOX_HELPER_SCRUB}
rm -rf "$HOME/.t3/userdata" "$HOME/.t3/environment-label" "$HOME/.t3/usage-host-id"
${CLAUDE_SETTINGS_SCRUB}
${GITHUB_LOGIN_SCRUB}
Expand Down Expand Up @@ -490,6 +492,9 @@ 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 SUB_SANDBOX_HELPER_WARNING =
"T3 Code's sub-sandbox helper could not be added, so agents on this sandbox cannot ask this computer for a sandbox of their own.";

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.
Expand Down Expand Up @@ -613,6 +618,15 @@ export class SandboxProvisioner extends Context.Service<
readonly checkWork: (
input: SandboxLifecycleInput,
) => Effect.Effect<SandboxCheckWorkResult, SandboxProviderError>;
/**
* Runs one of T3 Code's own scripts on a running sandbox through its provider, as the poll for
* its agents' sub-sandbox requests does. Fails when the sandbox is gone or not running.
*/
readonly runScript: (input: {
readonly instanceId: string;
readonly script: SandboxScript;
readonly timeoutSeconds: number;
}) => Effect.Effect<SandboxExecResult, SandboxProviderError>;
readonly templates: (
input: SandboxTemplatesInput,
) => Effect.Effect<SandboxTemplatesResult, SandboxProviderError>;
Expand Down Expand Up @@ -2992,6 +3006,15 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
steps += 1;
yield* fail(SANDBOX_FILES_SKILL_WARNING);
}
// A chat's agents can ask this host for sandboxes of their own; a subagent's sandbox has no
// chat on this host to hold their tasks, so it never gets the helper. Only a failure shows.
if (machine.record().parentThreadId === undefined) {
const helperWritten = yield* machine.run(subSandboxHelperScript(), 60).pipe(Effect.exit);
if (Exit.isFailure(helperWritten)) {
steps += 1;
yield* fail(SUB_SANDBOX_HELPER_WARNING);
}
}
return { steps, failed };
});

Expand Down Expand Up @@ -3808,6 +3831,20 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
} satisfies SandboxCheckWorkResult;
});

const runScript: SandboxProvisioner["Service"]["runScript"] = Effect.fn(
"SandboxProvisioner.runScript",
)(function* (input) {
const found = yield* records.get(input.instanceId).pipe(Effect.orDie);
if (Option.isNone(found) || found.value.state !== "running") {
return yield* new SandboxProviderError({
provider: Option.isNone(found) ? "boat" : found.value.provider,
stage: "start",
detail: "The sandbox is not running.",
});
}
return yield* runOnRecord(found.value)(input.script, input.timeoutSeconds);
});

// A sandbox made before keep-alive has no idle window of its own, so its config's applies.
const keepAliveSettingsOf = Effect.fn("SandboxProvisioner.keepAliveSettingsOf")(function* (
record: SandboxRecord,
Expand Down Expand Up @@ -4056,6 +4093,22 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
Effect.as<string | null>(null),
Effect.orElseSucceed(() => SANDBOX_FILES_SKILL_WARNING),
);
// Every resume rewrites the sub-sandbox helper, so one made before it existed gets it and an
// older copy is replaced, again before T3 starts. Only a chat's sandbox has it.
const helper =
record.threadId === undefined || record.parentThreadId !== undefined
? null
: yield* onHttp(
driver.execute({
config,
sandboxId: record.sandboxId,
timeoutSeconds: SANDBOX_RESUME_STEP_SECONDS.subSandboxHelper,
...subSandboxHelperScript(),
}),
).pipe(
Effect.as<string | null>(null),
Effect.orElseSucceed(() => SUB_SANDBOX_HELPER_WARNING),
);
yield* onHttp(
driver.execute({
config,
Expand Down Expand Up @@ -4136,6 +4189,7 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
rejoined.warning,
kept.warning,
skill,
helper,
github.warning,
bridged.warning,
].filter((warning): warning is string => warning !== null);
Expand Down Expand Up @@ -4682,6 +4736,7 @@ mkdir -p ${parents.map(shellQuote).join(" ")}`,
stop,
resume,
checkWork,
runScript,
templates,
saveTemplate,
deleteTemplate,
Expand Down
Loading
Loading