feat(ai-sandbox-runta): add Runta sandbox provider #2249
OpenSASUKE40(GitHub profile, opens in a new tab)wants to merge 5 commits into
main fromrefs/pull/2249/headopened View on GitHubPushedacdbf09
- @@ -0,0 +346,21 @@346+ pollMs?: number347+ signal?: AbortSignal | undefined348+ } = {},349+ ): Promise<RuntaRuntime> {350+ return this.waitForStatus(idOrName, 'running', options)351+ }352+353+ /** Poll until the runtime reports `target`. */354+ async waitForStatus(355+ idOrName: string,356+ target: string,357+ options: {358+ timeoutMs?: number | undefined359+ pollMs?: number360+ signal?: AbortSignal | undefined361+ } = {},362+ ): Promise<RuntaRuntime> {363+ const timeoutMs = options.timeoutMs ?? 240_000364+ const deadline = Date.now() + timeoutMs365+ for (;;) {366+ const runtime = await this.getRuntime(idOrName, options.signal)@@ -0,0 +380,21 @@380+ await delay(options.pollMs ?? 500, options.signal)381+ }382+ }383+384+ /**385+ * Wait out a lifecycle change that is still in flight. A runtime that was386+ * just told to pause still reports `running` for a moment; acting on that387+ * stale status would skip the resume it needs.388+ */389+ private async settle(390+ runtime: RuntaRuntime,391+ wait: { timeoutMs?: number | undefined; signal?: AbortSignal | undefined },392+ ): Promise<RuntaRuntime> {393+ if (394+ runtime.status === runtime.desiredStatus ||395+ !SETTLED_STATUSES.includes(runtime.desiredStatus) ||396+ !['creating', ...SETTLED_STATUSES].includes(runtime.status)397+ ) {398+ return runtime399+ }400+ return this.waitForStatus(runtime.id, runtime.desiredStatus, wait)@@ -0,0 +459,21 @@459+ } catch (error) {460+ if (error instanceof RuntaApiError && error.status === 404) return461+ throw error462+ }463+ }464+465+ // ------------------------------------------------------------------- ports466+467+ /**468+ * Publish `port` and return its public URL. Published URLs carry no auth:469+ * anyone with the URL can reach the service.470+ */471+ async publishPort(472+ idOrName: string,473+ port: number,474+ options: { protocol?: 'http' | 'https'; signal?: AbortSignal } = {},475+ ): Promise<string> {476+ let runtime = await this.getRuntime(idOrName, options.signal)477+ let spec = runtime.ingressSpecs.find((entry) => entry.runtimePort === port)478+ if (!spec) {479+ runtime = await this.patchRuntime(@@ -0,0 +551,21 @@551+ // If cat fails too, the endpoint's own error says more (for example "not a regular file").552+ if (result.exitCode !== 0) throw error553+ return result.stdoutBytes554+ }555+ }556+557+ /**558+ * Write a file by absolute path. Bodies above the file endpoint's limit are559+ * streamed through the exec WebSocket into `cat`.560+ */561+ async writeFile(562+ runtimeId: string,563+ path: string,564+ data: string | Uint8Array,565+ signal?: AbortSignal,566+ ): Promise<void> {567+ const bytes =568+ typeof data === 'string' ? new TextEncoder().encode(data) : data569+ if (bytes.byteLength > this.maxFilePutBytes) {570+ const result = await this.exec(runtimeId, {571+ argv: ['sh', '-c', 'cat > "$1"', 'runta-write', path],@@ -0,0 +805,21 @@805+ if (settled) return806+ const text = JSON.stringify(frame)807+ if (opened) ws.send(text)808+ else outbox.push(text)809+ }810+811+ const connectTimer: ReturnType<typeof setTimeout> = setTimeout(() => {812+ if (opened) return813+ failure ??= new RuntaApiError(814+ `Runta: exec socket did not connect within ${connectTimeoutMs}ms (${url}).`,815+ { code: 'deadline_exceeded' },816+ )817+ closeSocket()818+ finish()819+ }, connectTimeoutMs)820+ unref(connectTimer)821+822+ ws.addEventListener('open', () => {823+ opened = true824+ clearTimeout(connectTimer)825+ const command = withCwd(options.argv, options.cwd)@@ -0,0 +852,21 @@852+ } else if (frame.type === 'error') {853+ failure ??= new RuntaApiError(854+ `Runta: exec failed: ${typeof frame.message === 'string' ? frame.message : 'unknown error'}`,855+ { code: 'command_failed' },856+ )857+ closeSocket()858+ finish()859+ } else if (frame.type === 'heartbeat') {860+ send({ type: 'heartbeat' })861+ }862+ })863+864+ ws.addEventListener('error', (event: Event) => {865+ const message = (event as Partial<ErrorEvent>).message866+ failure ??= new RuntaApiError(867+ `Runta: exec socket error for ${url}: ${message || 'connection failed'}`,868+ {869+ code: 'unavailable',870+ },871+ )872+ })@@ -0,0 +893,21 @@893+ }894+895+ const write = async (data: string | Uint8Array): Promise<void> => {896+ const bytes =897+ typeof data === 'string' ? new TextEncoder().encode(data) : data898+ for (899+ let offset = 0;900+ offset < bytes.byteLength;901+ offset += STDIN_CHUNK_BYTES902+ ) {903+ if (settled) {904+ throw (905+ failure ??906+ new RuntaApiError('Runta: exec stdin is closed.', {907+ code: 'failed_precondition',908+ })909+ )910+ }911+ while (opened && !settled && ws.bufferedAmount > SEND_HIGH_WATER_BYTES)912+ await delay(5)913+ send({@@ -0,0 +97,21 @@97+ throw new Error(`${what} failed: ${r.stderr.trim() || '(no output)'}`)98+ }99+ return r100+ }101+102+ this.fs = {103+ read: async (p, o) =>104+ new TextDecoder().decode(105+ await this.client.readFile(this.runtimeId, this.abs(p), o?.signal),106+ ),107+ readBytes: (p, o) =>108+ this.client.readFile(this.runtimeId, this.abs(p), o?.signal),109+ write: (p, data, o) =>110+ this.client.writeFile(this.runtimeId, this.abs(p), data, o?.signal),111+ list: async (p, o) => {112+ // ponytail: `ls` output, so a file name with a newline lists as two113+ // entries. Switch to `find -print0` if that matters.114+ const r = await run('list', `ls -1Ap -- ${q(this.abs(p))}`, o?.signal)115+ const base = p.replace(/\/$/, '')116+ return r.stdout117+ .split('\n')@@ -0,0 +131,21 @@131+ lstatCommand(this.abs(p)),132+ o?.signal ? { signal: o.signal } : undefined,133+ )134+ if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) {135+ return undefined136+ }137+ if (r.exitCode !== 0) {138+ throw new Error(`lstat failed: ${r.stderr.trim() || '(no output)'}`)139+ }140+ return parseLstatOutput(r.stdout)141+ },142+ mkdir: async (p, o) => {143+ await run('mkdir', `mkdir -p -- ${q(this.abs(p))}`, o?.signal)144+ },145+ remove: async (p, o) => {146+ await run('remove', `rm -rf -- ${q(this.abs(p))}`, o?.signal)147+ },148+ rename: async (from, to, o) => {149+ await run(150+ 'rename',151+ `mv -- ${q(this.abs(from))} ${q(this.abs(to))}`,@@ -0,0 +144,21 @@144+ },145+ remove: async (p, o) => {146+ await run('remove', `rm -rf -- ${q(this.abs(p))}`, o?.signal)147+ },148+ rename: async (from, to, o) => {149+ await run(150+ 'rename',151+ `mv -- ${q(this.abs(from))} ${q(this.abs(to))}`,152+ o?.signal,153+ )154+ },155+ exists: async (p, o) => {156+ const r = await this.exec(157+ `test -e ${q(this.abs(p))}`,158+ o?.signal ? { signal: o.signal } : undefined,159+ )160+ return r.exitCode === 0161+ },162+ }163+164+ this.git = createExecBackedGit(this.process, this.workdir)@@ -0,0 +107,21 @@107+ if (input.env) await handle.env.set(input.env)108+ return handle109+ }110+111+ private handle(runtime: RuntaRuntime): RuntaHandle {112+ return new RuntaHandle({113+ client: this.client,114+ name: runtime.name,115+ runtimeId: runtime.id,116+ workdir: this.workdir,117+ })118+ }119+120+ private randomName(): string {121+ return `${NAME_PREFIX}-${randomUUID().replace(/-/g, '').slice(0, 12)}`122+ }123+124+ async create(input: SandboxCreateInput): Promise<SandboxHandle> {125+ // Honor the deterministic id ensure() supplies (see SandboxCreateInput.id):126+ // a Runta runtime is addressable by its unique name.127+ const runtime = await this.client.createRuntime({@@ -0,0 +127,21 @@127+ const runtime = await this.client.createRuntime({128+ name: input.id ?? this.randomName(),129+ ...(this.config.image !== undefined ? { image: this.config.image } : {}),130+ ...(this.config.vcpus !== undefined ? { vcpus: this.config.vcpus } : {}),131+ ...(this.config.memoryMib !== undefined132+ ? { memoryMib: this.config.memoryMib }133+ : {}),134+ ...this.runtimeOptions(input),135+ })136+ return this.ready(runtime, input)137+ }138+139+ async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {140+ const runtime = await this.client.findRuntime(input.id, input.signal)141+ if (!runtime) return null142+ // Exec does not wake a paused or suspended runtime, so do it here.143+ return this.handle(144+ await this.client.ensureRunning(145+ runtime.id,146+ input.signal ? { signal: input.signal } : {},147+ ),@@ -0,0 +282,21 @@282+ expect(fake.calls.some((call) => call.method === 'PUT')).toBe(false)283+ expect(new Uint8Array(await readFile(path))).toEqual(bytes)284+ expect(await small.readFile(runtime.id, path)).toEqual(bytes)285+ expect(fake.execStarts.at(-1)).toMatchObject({286+ command: 'cat',287+ args: ['--', path],288+ })289+ })290+291+ it('keeps the endpoint error when a large read is not a readable file', async () => {292+ fake = new FakeRunta({ root, maxFilePutBytes: 4 })293+ const small = new RuntaClient({294+ apiKey: fake.apiKey,295+ endpoint: fake.endpoint,296+ fetch: fake.fetch,297+ WebSocket: fake.WebSocket,298+ })299+ const { runtime } = await small.getOrCreateRuntime('box')300+ await expect(301+ small.readFile(runtime.id, join(root, 'missing')),302+ ).rejects.toMatchObject({ status: 404 })@@ -0,0 +63,21 @@63+ } finally {64+ await sbx?.destroy()65+ }66+ }, 180_000)67+68+ it('restores a snapshot into a new runtime after the source is gone', async () => {69+ const provider = runtaSandbox({ apiKey })70+ let restored: SandboxHandle | undefined71+ let snapshotId: string | undefined72+ const sbx = await provider.create({})73+ try {74+ await sbx.fs.write('/workspace/state.txt', 'original')75+ const ref = await sbx.snapshot?.('baseline')76+ snapshotId = ref?.id77+ await sbx.destroy()78+79+ restored = await provider.restoreSnapshot?.({ snapshotId: ref?.id ?? '' })80+ expect(restored?.id).not.toBe(sbx.id)81+ expect(await restored?.fs.read('/workspace/state.txt')).toBe('original')82+ } finally {83+ await sbx.destroy()@@ -0,0 +436,21 @@436+ static readonly CLOSED = 3437+ readonly url: string438+ readyState = 0439+ bufferedAmount = 0440+ binaryType: BinaryType = 'blob'441+ private child: ChildProcessWithoutNullStreams | undefined442+ private readonly runtime: FakeRuntime | undefined443+ private pendingOutput = 0444+ private exitCode: number | undefined445+446+ constructor(url: string, options: { headers: Record<string, string> }) {447+ super()448+ this.url = url449+ const headers = lowerCaseKeys(options.headers)450+ const match = /\/v2\/runtimes\/([^/]+)\/exec\/stream$/.exec(451+ new URL(url).pathname,452+ )453+ this.runtime = match454+ ? fake.runtime(decodeURIComponent(match[1] ?? ''))455+ : undefined456+ queueMicrotask(() => {
Pushed7b78203
- @@ -0,0 +238,21 @@238+ /\/+$/,239+ '',240+ )241+ this.userAgent = config.userAgent ?? 'runta-sandbox-client'242+ this.maxFilePutBytes = config.maxFilePutBytes ?? DEFAULT_MAX_FILE_PUT_BYTES243+ this.fetchImpl = config.fetch ?? fetch244+ this.webSocketCtor = config.WebSocket245+ }246+247+ /** Authorization header for API requests. */248+ authHeader(): Record<string, string> {249+ return { authorization: `Bearer ${this.apiKey}` }250+ }251+252+ // ---------------------------------------------------------------- runtimes253+254+ async getRuntime(255+ idOrName: string,256+ signal?: AbortSignal,257+ ): Promise<RuntaRuntime> {258+ if (UUID_PATTERN.test(idOrName)) {@@ -0,0 +308,21 @@308+ )309+ if (options.wait === false) return created310+ return this.waitUntilRunning(created.id, {311+ timeoutMs: options.readyTimeoutMs,312+ signal: options.signal,313+ })314+ }315+316+ /**317+ * Attach to the runtime called `name`, or create it. Safe under concurrent318+ * first use: a create that loses the race reads the winner back.319+ */320+ async getOrCreateRuntime(321+ name: string,322+ options: Omit<RuntaCreateRuntimeOptions, 'name'> = {},323+ ): Promise<{ runtime: RuntaRuntime; created: boolean }> {324+ // A runtime that is being deleted holds its name until it is gone, so a325+ // create can answer "already exists" for a while. Wait for the name.326+ const deadline = Date.now() + 120_000327+ for (;;) {328+ const existing = await this.findRuntime(name, options.signal)@@ -0,0 +633,21 @@633+ }634+635+ /**636+ * Write a file by absolute path. Bodies above the file endpoint's limit are637+ * streamed through the exec WebSocket into `cat`. Both paths create missing638+ * parent directories.639+ */640+ async writeFile(641+ runtimeId: string,642+ path: string,643+ data: string | Uint8Array,644+ signal?: AbortSignal,645+ ): Promise<void> {646+ const bytes =647+ typeof data === 'string' ? new TextEncoder().encode(data) : data648+ if (bytes.byteLength > this.maxFilePutBytes) {649+ const result = await this.exec(runtimeId, {650+ argv: [651+ 'sh',652+ '-c',653+ 'mkdir -p -- "$(dirname -- "$1")" && cat > "$1"',@@ -0,0 +951,21 @@951+ `Runta: exec failed: ${typeof frame.message === 'string' ? frame.message : 'unknown error'}`,952+ { code: 'command_failed' },953+ )954+ closeSocket()955+ finish()956+ } else if (frame.type === 'heartbeat') {957+ send({ type: 'heartbeat' })958+ }959+ })960+961+ ws.addEventListener('error', (event: Event) => {962+ // Typed by hand: `ErrorEvent` exists only in the DOM lib.963+ const { message } = event as { message?: string }964+ failure ??= new RuntaApiError(965+ `Runta: exec socket error for ${url}: ${message || 'connection failed'}`,966+ {967+ code: 'unavailable',968+ },969+ )970+ // Do not wait for a close event: not every socket sends one after an error.971+ closeSocket()@@ -0,0 +985,21 @@985+986+ if (options.signal) {987+ onAbort = (): void => {988+ send({ type: 'signal', signal: 'TERM' })989+ closeSocket()990+ finish()991+ }992+ if (options.signal.aborted) onAbort()993+ else options.signal.addEventListener('abort', onAbort)994+ }995+996+ const write = async (data: string | Uint8Array): Promise<void> => {997+ const bytes =998+ typeof data === 'string' ? new TextEncoder().encode(data) : data999+ for (1000+ let offset = 0;1001+ offset < bytes.byteLength;1002+ offset += STDIN_CHUNK_BYTES1003+ ) {1004+ while (opened && !settled && ws.bufferedAmount > SEND_HIGH_WATER_BYTES)1005+ await delay(5)@@ -0,0 +141,21 @@141+ }142+ if (r.exitCode !== 0) {143+ throw new Error(`lstat failed: ${r.stderr.trim() || '(no output)'}`)144+ }145+ return parseLstatOutput(r.stdout)146+ },147+ mkdir: async (p, o) => {148+ await run('mkdir', `mkdir -p -- ${q(this.abs(p))}`, o?.signal)149+ },150+ remove: async (p, o) => {151+ await run('remove', `rm -rf -- ${q(this.abs(p))}`, o?.signal)152+ },153+ rename: async (from, to, o) => {154+ // `mv` puts the source INSIDE a destination that is a directory, and155+ // reports success. Refuse, so a rename lands at `to` or fails.156+ // ponytail: this also refuses a directory that replaces an empty one,157+ // which rename(2) allows. Use `mv -T` if a caller needs that.158+ const target = q(this.abs(to))159+ await run(160+ 'rename',161+ `if [ -d ${target} ] && [ ! -L ${target} ]; then echo 'destination is a directory' >&2; exit 1; fi; mv -- ${q(this.abs(from))} ${target}`,@@ -0,0 +158,21 @@158+ ...this.runtimeOptions(input),159+ wait: false,160+ })161+ return this.adopt(runtime, input)162+ }163+164+ async resume(input: SandboxResumeInput): Promise<SandboxHandle | null> {165+ const runtime = await this.client.findRuntime(input.id, input.signal)166+ // A runtime that is being deleted is gone as far as a resume is concerned.167+ if (!runtime || runtime.status === 'deleting') return null168+ try {169+ // Exec does not wake a paused or suspended runtime, so do it here.170+ return this.handle(171+ await this.client.ensureRunning(172+ runtime.id,173+ input.signal ? { signal: input.signal } : {},174+ ),175+ )176+ } catch (error) {177+ // Deleted between the lookup and the wake: gone, like any missing one.178+ if (error instanceof RuntaApiError && error.status === 404) return null@@ -0,0 +41,21 @@41+ // env + cwd are honored.42+ const env = await sbx.process.exec('echo "$GREETING from $(pwd)"', {43+ env: { GREETING: 'hi' },44+ cwd: '/workspace/dir',45+ })46+ expect(env.stdout.trim()).toBe('hi from /workspace/dir')47+ } finally {48+ await sbx?.destroy()49+ }50+ }, 180_000)51+52+ // Runta addresses a runtime by UUID only, so resume and destroy by the53+ // handle id (the runtime name) must find the runtime first.54+ it('resumes a paused sandbox by id, then destroys it by id', async () => {55+ const provider = runtaSandbox({ apiKey })56+ const created = await provider.create({})57+ try {58+ await created.fs.write('/workspace/kept.txt', 'still here')59+ await created.process.exec('true')60+ const { RuntaClient } = await import('../src/client')61+ const client = new RuntaClient({ apiKey: apiKey ?? '' })
github-actions[bot](GitHub profile, opens in a new tab) assignedjherr
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer
Pushed39cd4af
github-actions[bot](GitHub profile, opens in a new tab) added labelsmerge-conflicts
github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: author
github-actions[bot](GitHub profile, opens in a new tab) removed labelswaiting-on: maintainer
Sign in to join this conversation.
coderabbitai[bot](GitHub profile, opens in a new tab) reviewed
Actionable comments posted: 15
2b7ba911-8e5b-4ddb-8b48-781d09dc173dReviewing files that changed from the base of the PR and between 778f8f627c86ad462c791aeed697005ac7f783ac and acdbf092756257feec543b6b3147da8bb44b6706.
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml.changeset/runta-sandbox-provider.mddocs/config.jsondocs/sandbox/providers-advanced.mddocs/sandbox/providers.mdpackages/ai-sandbox-runta/README.mdpackages/ai-sandbox-runta/package.jsonpackages/ai-sandbox-runta/src/client.tspackages/ai-sandbox-runta/src/handle.tspackages/ai-sandbox-runta/src/index.tspackages/ai-sandbox-runta/src/provider.tspackages/ai-sandbox-runta/tests/client.test.tspackages/ai-sandbox-runta/tests/journal.conformance.test.tspackages/ai-sandbox-runta/tests/provider.test.tspackages/ai-sandbox-runta/tests/runta.test.tspackages/ai-sandbox-runta/tests/support/fake-runta.tspackages/ai-sandbox-runta/tsconfig.jsonpackages/ai-sandbox-runta/vite.config.tspackages/ai-sandbox/README.mdIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.