type SandboxContext = {sandbox: SandboxClient};
const coder = agent<SandboxContext>({
model,
instructions: "You are a coding agent. Work in the sandbox, where your files stay between requests.",
tools: {
readFile: asyncTool({
description: "Read a file in the sandbox.",
input: z.object({path: z.string()}),
execute: ({path}, {context}) => context.sandbox.readFile(path),
}),
writeFile: asyncTool({
description: "Create or replace a file in the sandbox.",
input: z.object({path: z.string(), content: z.string()}),
async execute({path, content}, {context}) {
await context.sandbox.writeFile(path, content);
return {path};
},
}),
runCommand: asyncTool({
description: "Run a shell command in the sandbox.",
input: z.object({command: z.string()}),
// A command isn't safe to repeat, so a failure goes to the model instead of a retry
retry: {maxAttempts: 1},
execute: ({command}, {context}) => context.sandbox.exec(command),
}),
},
});
export const codingSession = restate.object({
name: "CodingSession",
handlers: {
*chat(message: string) {
const ref = yield* openSandbox();
try {
const result = yield* coder.run(message, {
conversation: new Conversation(),
context: {sandbox: provider.connect(ref)},
});
if (result.status !== "completed") return result.output ?? result.reason;
return result.output;
} finally {
const suspended = yield* restate.run(() => provider.suspend(ref), {name: "Suspend sandbox"});
restate.state().set("sandbox", suspended);
}
},
*close() {
const ref = yield* restate.state().get<SandboxRef>("sandbox");
if (ref) yield* restate.run(() => provider.destroy(ref), {name: "Destroy sandbox"});
// Deletes the conversation and the sandbox reference
restate.state().clearAll();
},
},
});
/** Resumes the session's sandbox, or provisions one on the first request. */
function* openSandbox(): restate.Operation<SandboxRef> {
const key = restate.handlerRequest().key!;
const stored = yield* restate.state().get<SandboxRef>("sandbox");
const ref = stored
? yield* restate.run(() => provider.resume(stored), {name: "Resume sandbox"})
: yield* restate.run(() => provider.provision(key), {name: "Provision sandbox"});
// Store the reference right away, so that the next request finds the sandbox even if this one fails
restate.state().set("sandbox", ref);
return ref;
}