ai-sdk-sandbox-gce 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # ai-sdk-sandbox-gce
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4b95a30: `spawn({ command, stdin: true })` hands back a process with a writable `stdin` in a Cloud Run or a Compute Engine sandbox too, whose close is the end of the command's input. Each write reaches the service in a request of its own: what is written meanwhile leaves with the next one, and a request that fails on the way is sent again, the service writing nothing twice.
8
+
9
+ BREAKING: the client and the service speak version 2 of their protocol, which a service of an earlier version refuses. Deploy the sandbox service with this version of the package; for Compute Engine, build the sandbox image and the proxy's again with it too.
10
+
3
11
  ## 0.1.1
4
12
 
5
13
  ### Patch Changes
package/README.md CHANGED
@@ -144,7 +144,7 @@ systemctl restart systemd-networkd systemd-resolved
144
144
  if ! command -v ai-sdk-sandbox-gce >/dev/null; then
145
145
  curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
146
146
  apt-get install -y nodejs
147
- npm install --global ai-sdk-sandbox-gce@0.1.0
147
+ npm install --global ai-sdk-sandbox-gce@0.2.0
148
148
  fi
149
149
  # Its logs, the refusals among them, sent to Cloud Logging by the Ops Agent.
150
150
  if [ ! -d /opt/google-cloud-ops-agent ]; then
@@ -214,7 +214,7 @@ apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin do
214
214
  # Node.js, the agent, and pnpm: the Claude Code and Codex bridges install their dependencies with it.
215
215
  curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
216
216
  apt-get install -y nodejs
217
- npm install --global ai-sdk-sandbox-gce@0.1.0 pnpm@10
217
+ npm install --global ai-sdk-sandbox-gce@0.2.0 pnpm@10
218
218
 
219
219
  # The sandbox's user: sudo without a password, and Docker.
220
220
  useradd --create-home --shell /bin/bash agent
@@ -245,7 +245,7 @@ The service's image is the package and Node.js:
245
245
 
246
246
  ```dockerfile title="Dockerfile"
247
247
  FROM node:24-bookworm-slim
248
- RUN npm install --global --silent ai-sdk-sandbox-gce@0.1.0 && npm cache clean --force
248
+ RUN npm install --global --silent ai-sdk-sandbox-gce@0.2.0 && npm cache clean --force
249
249
  CMD ["ai-sdk-sandbox-gce", "serve"]
250
250
  ```
251
251
 
@@ -642,7 +642,7 @@ The steps above set up the network, the proxy and the service as they ran on Goo
642
642
  - **32 MiB per request.** Cloud Run limits HTTP/1 request bodies: a larger file cannot be written in one call.
643
643
  - **A process's output stops after an hour**, the request timeout of the service. Its exit code is still found.
644
644
  - **One bridge per port.** Run one harness session at a time per sandbox view, and give each session a view of its own with `fork()`.
645
- - **No writable stdin.** `spawn({ stdin: true })` is refused before the command starts: the service carries no input to a process. Write the input to a file first, or pipe it in the command.
645
+ - **A writable stdin costs a request per write.** `spawn({ stdin: true })` hands a process a writable `stdin`, but each write reaches the service in a request of its own: what is written meanwhile leaves with the next one, and a request that fails on the way is sent again without writing anything twice. Fine for the messages of a protocol; for a large input written in small pieces, write a file first.
646
646
 
647
647
  ## Development
648
648
 
@@ -1,6 +1,7 @@
1
1
  import { posix } from 'node:path';
2
2
  import { FrameType, readFrames, STDERR, STDOUT } from '../../protocol/frames.js';
3
3
  import { abortReason } from '../utils/abort.js';
4
+ import { processInput } from './process-input.js';
4
5
  const READ_MISSING = 44;
5
6
  const READ_DIRECTORY = 45;
6
7
  /** `cat` the file `$0`, with exit statuses of its own for a missing path and for a directory. */
@@ -70,24 +71,33 @@ export class GceSandboxSession {
70
71
  ]);
71
72
  return { exitCode, stdout, stderr };
72
73
  };
73
- // The overloads of `spawn` promise a writable stdin when `stdin` is `true`: the protocol of the
74
- // service carries none yet, so such a call is refused before the command starts.
74
+ // The overloads of `spawn` promise a writable stdin when `stdin` is `true`: a function type
75
+ // cannot check them.
75
76
  spawn = (async ({ command, workingDirectory, env = {}, abortSignal, stdin = false, }) => {
76
77
  if (abortSignal?.aborted)
77
78
  throw abortReason(abortSignal);
78
- if (stdin) {
79
- throw new Error('A Compute Engine sandbox does not give a process a writable stdin yet: spawn it without `stdin`.');
80
- }
81
79
  const invalid = Object.keys(env).find((name) => !ENV_NAME.test(name));
82
80
  if (invalid !== undefined)
83
81
  throw new Error(`Not an environment variable name: ${invalid}`);
84
82
  const { client, name, processes } = this.handle;
85
83
  const response = await client.exec(name, {
86
- command: { command, workingDirectory: this.resolve(workingDirectory ?? '.'), env },
84
+ command: {
85
+ command,
86
+ workingDirectory: this.resolve(workingDirectory ?? '.'),
87
+ env,
88
+ ...(stdin ? { stdin } : {}),
89
+ },
87
90
  });
88
91
  const id = response.headers.get('x-process-id') ?? '';
89
92
  processes.add(id);
90
- return this.attach(response, id, abortSignal);
93
+ const spawned = this.attach(response, id, abortSignal);
94
+ if (!stdin)
95
+ return spawned;
96
+ const input = processInput({
97
+ write: (offset, bytes) => client.writeInput(name, id, { offset, bytes }),
98
+ end: () => client.endInput(name, id),
99
+ });
100
+ return { ...spawned, stdin: input };
91
101
  });
92
102
  readBinaryFile = async ({ path, abortSignal }) => {
93
103
  const target = this.resolve(path);
@@ -0,0 +1,11 @@
1
+ /** How the input of a process reaches the service: a write names where its bytes start. */
2
+ export interface InputSender {
3
+ write(offset: number, bytes: Uint8Array): Promise<void>;
4
+ end(): Promise<void>;
5
+ }
6
+ /**
7
+ * The standard input of a process started with `stdin`, written through the service. A write
8
+ * resolves once its bytes are queued, and throws if an earlier one could not be sent; closing
9
+ * waits for every byte to leave, then ends the input.
10
+ */
11
+ export declare function processInput(sender: InputSender): WritableStream<Uint8Array>;
@@ -0,0 +1,104 @@
1
+ import { MAX_INPUT_WRITE_BYTES } from '../../protocol/api.js';
2
+ /** How many bytes may wait for their request before a write waits for them to leave. */
3
+ const MAX_WAITING_BYTES = 2 * MAX_INPUT_WRITE_BYTES;
4
+ /**
5
+ * Sends what is written, in order, one request at a time. What is written while a request is on
6
+ * its way waits, then leaves with the next one: many small writes cost few requests.
7
+ */
8
+ class InputQueue {
9
+ send;
10
+ waiting = [];
11
+ waitingBytes = 0;
12
+ /** How many bytes the service was given: where the next request starts. */
13
+ sent = 0;
14
+ sending;
15
+ failure;
16
+ constructor(send) {
17
+ this.send = send;
18
+ }
19
+ get full() {
20
+ return this.waitingBytes > MAX_WAITING_BYTES;
21
+ }
22
+ push(chunk) {
23
+ this.throwIfFailed();
24
+ if (chunk.byteLength === 0)
25
+ return;
26
+ // A copy: the writer may reuse its buffer once the write resolves, before the bytes leave.
27
+ this.waiting.push(chunk.slice());
28
+ this.waitingBytes += chunk.byteLength;
29
+ this.sending ??= this.sendAll();
30
+ }
31
+ /** Drops what did not leave yet. */
32
+ clear() {
33
+ this.waiting.length = 0;
34
+ this.waitingBytes = 0;
35
+ }
36
+ /** Resolves once every byte written has left, or throws why one could not. */
37
+ async drained() {
38
+ while (this.sending !== undefined)
39
+ await this.sending;
40
+ this.throwIfFailed();
41
+ }
42
+ throwIfFailed() {
43
+ if (this.failure !== undefined)
44
+ throw this.failure.error;
45
+ }
46
+ async sendAll() {
47
+ try {
48
+ while (this.waiting.length > 0) {
49
+ const bytes = this.take();
50
+ await this.send(this.sent, bytes);
51
+ this.sent += bytes.byteLength;
52
+ }
53
+ }
54
+ catch (error) {
55
+ this.failure = { error };
56
+ this.clear();
57
+ }
58
+ finally {
59
+ this.sending = undefined;
60
+ }
61
+ }
62
+ /** The bytes waiting, up to what one request carries. */
63
+ take() {
64
+ const size = Math.min(this.waitingBytes, MAX_INPUT_WRITE_BYTES);
65
+ const bytes = new Uint8Array(size);
66
+ let filled = 0;
67
+ while (filled < size) {
68
+ const chunk = this.waiting[0] ?? new Uint8Array();
69
+ const part = chunk.subarray(0, size - filled);
70
+ bytes.set(part, filled);
71
+ filled += part.byteLength;
72
+ if (part.byteLength === chunk.byteLength)
73
+ this.waiting.shift();
74
+ else
75
+ this.waiting[0] = chunk.subarray(part.byteLength);
76
+ }
77
+ this.waitingBytes -= size;
78
+ return bytes;
79
+ }
80
+ }
81
+ /**
82
+ * The standard input of a process started with `stdin`, written through the service. A write
83
+ * resolves once its bytes are queued, and throws if an earlier one could not be sent; closing
84
+ * waits for every byte to leave, then ends the input.
85
+ */
86
+ export function processInput(sender) {
87
+ const queue = new InputQueue((offset, bytes) => sender.write(offset, bytes));
88
+ return new WritableStream({
89
+ write: async (chunk) => {
90
+ queue.push(chunk);
91
+ if (queue.full)
92
+ await queue.drained();
93
+ },
94
+ close: async () => {
95
+ await queue.drained();
96
+ await sender.end();
97
+ },
98
+ // What did not leave yet is dropped: the process reads the end of its input.
99
+ abort: async () => {
100
+ queue.clear();
101
+ await sender.end().catch(() => undefined);
102
+ },
103
+ });
104
+ }
@@ -45,6 +45,16 @@ export declare class SandboxServiceClient {
45
45
  }, abortSignal?: AbortSignal): Promise<Response>;
46
46
  /** Waits for a process to exit, a few minutes at most: its exit code, or `undefined`. */
47
47
  wait(name: string, id: string): Promise<number | undefined>;
48
+ /**
49
+ * Gives a process started with `stdin` the bytes of its input from `offset` on. Sent again after
50
+ * a passing error: the service writes nothing twice.
51
+ */
52
+ writeInput(name: string, id: string, { offset, bytes }: {
53
+ bytes: Uint8Array;
54
+ offset: number;
55
+ }): Promise<void>;
56
+ /** Ends the input of a process started with `stdin`. */
57
+ endInput(name: string, id: string): Promise<void>;
48
58
  /** Stops a process and everything it started. A process already gone is no error. */
49
59
  kill(name: string, id: string): Promise<void>;
50
60
  /** Stops every process started in the sandbox. */
@@ -65,6 +75,8 @@ export declare class SandboxServiceClient {
65
75
  portEndpoint(name: string, port: number, protocol: 'http' | 'https' | 'ws'): HarnessV1PortEndpoint;
66
76
  /** What every call carries but the identity token: the protocol it speaks, the service token. */
67
77
  private fixedHeaders;
78
+ /** A call that may be sent again, sent again while it fails on the way rather than at the service. */
79
+ private retried;
68
80
  private call;
69
81
  private failure;
70
82
  }
@@ -1,4 +1,5 @@
1
1
  import { HarnessSandboxAuthenticationError } from '@ai-sdk/harness';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
2
3
  import { PROTOCOL_HEADER, PROTOCOL_VERSION, SERVICE_TOKEN_HEADER } from '../../protocol/version.js';
3
4
  import { GceSandboxServiceError } from '../errors/gce-sandbox-service-error.js';
4
5
  import { GCE_SANDBOX_PROVIDER_ID } from '../provider-id.js';
@@ -7,6 +8,10 @@ const encoder = new TextEncoder();
7
8
  const templatePath = (id, image) => image === undefined
8
9
  ? `v1/templates/${id}`
9
10
  : `v1/templates/${id}?image=${encodeURIComponent(image)}`;
11
+ /** Statuses of a call worth sending again: Cloud Run's front end, or an instance starting. */
12
+ const TRANSIENT_STATUSES = new Set([429, 500, 502, 503, 504]);
13
+ /** How long to wait before each new attempt of a call that may be sent again. */
14
+ const RETRY_DELAYS_MS = [200, 500, 1000, 2000];
10
15
  /**
11
16
  * The HTTP API of the sandbox service (`ai-sdk-sandbox-gce serve`). Each call carries an
12
17
  * identity token when there is one: Cloud Run's IAM checks it. Nothing else of this process goes
@@ -74,6 +79,18 @@ export class SandboxServiceClient {
74
79
  const { exitCode } = (await response.json());
75
80
  return exitCode;
76
81
  }
82
+ /**
83
+ * Gives a process started with `stdin` the bytes of its input from `offset` on. Sent again after
84
+ * a passing error: the service writes nothing twice.
85
+ */
86
+ async writeInput(name, id, { offset, bytes }) {
87
+ const path = `v1/sandboxes/${name}/processes/${id}/stdin?offset=${offset}`;
88
+ await this.retried(() => this.call('POST', path, { body: bytes }));
89
+ }
90
+ /** Ends the input of a process started with `stdin`. */
91
+ async endInput(name, id) {
92
+ await this.retried(() => this.call('DELETE', `v1/sandboxes/${name}/processes/${id}/stdin`));
93
+ }
77
94
  /** Stops a process and everything it started. A process already gone is no error. */
78
95
  async kill(name, id) {
79
96
  await this.call('DELETE', `v1/sandboxes/${name}/processes/${id}`, { accept: [404] });
@@ -132,6 +149,22 @@ export class SandboxServiceClient {
132
149
  ...(this.serviceToken === undefined ? {} : { [SERVICE_TOKEN_HEADER]: this.serviceToken }),
133
150
  };
134
151
  }
152
+ /** A call that may be sent again, sent again while it fails on the way rather than at the service. */
153
+ async retried(call) {
154
+ for (const delay of RETRY_DELAYS_MS) {
155
+ try {
156
+ return await call();
157
+ }
158
+ catch (error) {
159
+ const transient = error instanceof TypeError ||
160
+ (error instanceof GceSandboxServiceError && TRANSIENT_STATUSES.has(error.status));
161
+ if (!transient)
162
+ throw error;
163
+ }
164
+ await sleep(delay);
165
+ }
166
+ return call();
167
+ }
135
168
  async call(method, path, options = {}) {
136
169
  const { body, abortSignal, accept = [] } = options;
137
170
  const headers = this.fixedHeaders();
@@ -1,4 +1,4 @@
1
- import { optionalString, parseObject, requiredString, stringRecord } from './http-body.js';
1
+ import { optionalBoolean, optionalString, parseObject, requiredString, stringRecord, } from './http-body.js';
2
2
  import { HttpError } from './http-error.js';
3
3
  /** The longest command line accepted before its standard input. */
4
4
  const MAX_COMMAND_BYTES = 1 << 20;
@@ -29,6 +29,7 @@ export function readCommandLine(request) {
29
29
  command: requiredString(body, 'command'),
30
30
  workingDirectory: optionalString(body, 'workingDirectory'),
31
31
  env: stringRecord(body, 'env'),
32
+ stdin: optionalBoolean(body, 'stdin'),
32
33
  },
33
34
  line,
34
35
  rest: buffered.subarray(newline + 1),
@@ -3,9 +3,14 @@ import type { IncomingMessage } from 'node:http';
3
3
  type Json = Record<string, unknown>;
4
4
  /** The request's JSON body, an object; `{}` when it has none. */
5
5
  export declare function readJson(request: IncomingMessage): Promise<Json>;
6
+ /** The request's body as it came, `max` bytes at most. */
7
+ export declare function readBytes(request: IncomingMessage, max: number): Promise<Buffer>;
8
+ /** Where a write starts in the input of a process: the `offset` of the query. */
9
+ export declare function offsetOf(request: IncomingMessage): number;
6
10
  /** `text` as a JSON object. */
7
11
  export declare function parseObject(text: string): Json;
8
12
  export declare function optionalString(body: Json, field: string): string | undefined;
13
+ export declare function optionalBoolean(body: Json, field: string): boolean | undefined;
9
14
  export declare function requiredString(body: Json, field: string): string;
10
15
  export declare function stringList(body: Json, field: string): string[] | undefined;
11
16
  export declare function stringRecord(body: Json, field: string): Record<string, string> | undefined;
@@ -4,15 +4,27 @@ const MAX_JSON_BYTES = 1 << 20;
4
4
  const invalid = (message) => new HttpError(400, message);
5
5
  /** The request's JSON body, an object; `{}` when it has none. */
6
6
  export async function readJson(request) {
7
+ return parseObject((await readBytes(request, MAX_JSON_BYTES)).toString() || '{}');
8
+ }
9
+ /** The request's body as it came, `max` bytes at most. */
10
+ export async function readBytes(request, max) {
7
11
  const chunks = [];
8
12
  let size = 0;
9
13
  for await (const chunk of request) {
10
14
  size += chunk.length;
11
- if (size > MAX_JSON_BYTES)
15
+ if (size > max)
12
16
  throw new HttpError(413, 'The request body is too large.');
13
17
  chunks.push(chunk);
14
18
  }
15
- return parseObject(Buffer.concat(chunks).toString() || '{}');
19
+ return Buffer.concat(chunks);
20
+ }
21
+ /** Where a write starts in the input of a process: the `offset` of the query. */
22
+ export function offsetOf(request) {
23
+ const offset = new URL(request.url ?? '/', 'http://service').searchParams.get('offset') ?? '';
24
+ if (!/^\d+$/.test(offset) || !Number.isSafeInteger(Number(offset))) {
25
+ throw invalid('`offset` must be a whole number of bytes.');
26
+ }
27
+ return Number(offset);
16
28
  }
17
29
  /** `text` as a JSON object. */
18
30
  export function parseObject(text) {
@@ -36,6 +48,14 @@ export function optionalString(body, field) {
36
48
  throw invalid(`\`${field}\` must be a string.`);
37
49
  return value;
38
50
  }
51
+ export function optionalBoolean(body, field) {
52
+ const value = body[field];
53
+ if (value === undefined)
54
+ return undefined;
55
+ if (typeof value !== 'boolean')
56
+ throw invalid(`\`${field}\` must be a boolean.`);
57
+ return value;
58
+ }
39
59
  export function requiredString(body, field) {
40
60
  const value = optionalString(body, field);
41
61
  if (value === undefined)
@@ -29,11 +29,16 @@ export declare class Agent {
29
29
  private get configFile();
30
30
  /** Answers a call, or streams its own answer and replies with nothing. */
31
31
  handle(request: IncomingMessage, response: ServerResponse, path: string): Promise<Reply | undefined>;
32
+ /** A call about one process, its input included: `undefined` for any other path. */
33
+ private processCall;
32
34
  private configure;
33
35
  private process;
36
+ /** Writes or ends the standard input of a process started with `stdin`. */
37
+ private input;
34
38
  /**
35
- * `POST /v1/exec`: starts the command, its standard input the rest of the request, and streams
36
- * its output as frames, then its exit code. The process outlives the request.
39
+ * `POST /v1/exec`: starts the command, its standard input the rest of the request (or written
40
+ * by requests of their own, with `stdin`), and streams its output as frames, then its exit code.
41
+ * The process outlives the request.
37
42
  */
38
43
  private exec;
39
44
  }
@@ -1,9 +1,10 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { readCommandLine } from '../common/command-line.js';
4
- import { parseObject, readJson, requiredString, stringRecord } from '../common/http-body.js';
4
+ import { offsetOf, parseObject, readBytes, readJson, requiredString, stringRecord, } from '../common/http-body.js';
5
5
  import { HttpError } from '../common/http-error.js';
6
6
  import { NO_CONTENT, waitForExit } from '../common/http-reply.js';
7
+ import { MAX_INPUT_WRITE_BYTES } from '../protocol/api.js';
7
8
  import { encodeData, encodeFrame, FrameType, STDERR, STDOUT } from '../protocol/frames.js';
8
9
  import { configureDocker } from './docker-proxy.js';
9
10
  import { commandEnvironment } from './environment.js';
@@ -12,6 +13,7 @@ import { Processes } from './processes.js';
12
13
  const WAIT_MS = 5 * 60_000;
13
14
  const VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
15
  const PROCESS = /^\/v1\/processes\/([^/]+)$/;
16
+ const PROCESS_INPUT = /^\/v1\/processes\/([^/]+)\/stdin$/;
15
17
  function toConfig(body) {
16
18
  const proxy = requiredString(body, 'proxy');
17
19
  if (!URL.canParse(proxy))
@@ -53,11 +55,22 @@ export class Agent {
53
55
  await this.processes.killAll();
54
56
  return NO_CONTENT;
55
57
  }
58
+ const reply = this.processCall(method, path, request);
59
+ if (reply === undefined)
60
+ throw new HttpError(404, `No route for ${method} ${path}.`);
61
+ return reply;
62
+ }
63
+ /** A call about one process, its input included: `undefined` for any other path. */
64
+ processCall(method, path, request) {
65
+ const inputOf = PROCESS_INPUT.exec(path)?.[1];
66
+ if (inputOf !== undefined && (method === 'POST' || method === 'DELETE')) {
67
+ return this.input(method, decodeURIComponent(inputOf), request);
68
+ }
56
69
  const id = PROCESS.exec(path)?.[1];
57
70
  if (id !== undefined && (method === 'GET' || method === 'DELETE')) {
58
71
  return this.process(method, decodeURIComponent(id));
59
72
  }
60
- throw new HttpError(404, `No route for ${method} ${path}.`);
73
+ return undefined;
61
74
  }
62
75
  async configure(config) {
63
76
  const { settings } = this;
@@ -78,9 +91,24 @@ export class Agent {
78
91
  await this.processes.kill(id);
79
92
  return NO_CONTENT;
80
93
  }
94
+ /** Writes or ends the standard input of a process started with `stdin`. */
95
+ async input(method, id, request) {
96
+ const started = this.processes.get(id);
97
+ if (started === undefined)
98
+ throw new HttpError(404, `No process ${id}.`);
99
+ if (started.input === undefined) {
100
+ throw new HttpError(409, `The process ${id} was started without a writable standard input.`);
101
+ }
102
+ if (method === 'DELETE')
103
+ started.input.end();
104
+ else
105
+ await started.input.write(offsetOf(request), await readBytes(request, MAX_INPUT_WRITE_BYTES));
106
+ return NO_CONTENT;
107
+ }
81
108
  /**
82
- * `POST /v1/exec`: starts the command, its standard input the rest of the request, and streams
83
- * its output as frames, then its exit code. The process outlives the request.
109
+ * `POST /v1/exec`: starts the command, its standard input the rest of the request (or written
110
+ * by requests of their own, with `stdin`), and streams its output as frames, then its exit code.
111
+ * The process outlives the request.
84
112
  */
85
113
  async exec(request, response) {
86
114
  const { command, rest } = await readCommandLine(request);
@@ -88,12 +116,18 @@ export class Agent {
88
116
  const invalid = Object.keys(env).find((name) => !VARIABLE.test(name));
89
117
  if (invalid !== undefined)
90
118
  throw new HttpError(400, `Invalid variable name: ${invalid}`);
91
- const { id, child, exited } = this.processes.exec(command.command, command.workingDirectory ?? this.settings.workingDirectory, commandEnvironment(this.settings, this.config, env));
119
+ const { id, child, exited } = this.processes.exec(command.command, {
120
+ directory: command.workingDirectory ?? this.settings.workingDirectory,
121
+ env: commandEnvironment(this.settings, this.config, env),
122
+ stdin: command.stdin,
123
+ });
92
124
  response.writeHead(200, { 'content-type': 'application/octet-stream', 'x-process-id': id });
93
125
  response.flushHeaders();
94
126
  response.write(encodeFrame(FrameType.Open, 0, Buffer.from(id)));
95
- child.stdin.write(rest);
96
- request.pipe(child.stdin);
127
+ if (command.stdin !== true) {
128
+ child.stdin.write(rest);
129
+ request.pipe(child.stdin);
130
+ }
97
131
  request.resume();
98
132
  // Once the caller is gone, the output is drained still: the process must not block on it.
99
133
  const write = (frame) => {
@@ -0,0 +1,17 @@
1
+ import type { Writable } from 'node:stream';
2
+ /**
3
+ * The standard input of a process started with `stdin`, written by requests of their own. Each
4
+ * names the offset of its first byte in the input: a request sent again after an error writes
5
+ * nothing twice, and one that would leave a gap is refused.
6
+ */
7
+ export declare class ProcessInput {
8
+ private readonly stdin;
9
+ /** How many bytes of its input the process was given. */
10
+ private received;
11
+ private ended;
12
+ constructor(stdin: Writable);
13
+ /** Gives the process what it was not given yet of `bytes`, the input from `offset` on. */
14
+ write(offset: number, bytes: Buffer): Promise<void>;
15
+ /** Ends the input, as many times as it is asked to. */
16
+ end(): void;
17
+ }
@@ -0,0 +1,43 @@
1
+ import { HttpError } from '../common/http-error.js';
2
+ /**
3
+ * The standard input of a process started with `stdin`, written by requests of their own. Each
4
+ * names the offset of its first byte in the input: a request sent again after an error writes
5
+ * nothing twice, and one that would leave a gap is refused.
6
+ */
7
+ export class ProcessInput {
8
+ stdin;
9
+ /** How many bytes of its input the process was given. */
10
+ received = 0;
11
+ ended = false;
12
+ constructor(stdin) {
13
+ this.stdin = stdin;
14
+ }
15
+ /** Gives the process what it was not given yet of `bytes`, the input from `offset` on. */
16
+ async write(offset, bytes) {
17
+ if (offset > this.received) {
18
+ throw new HttpError(409, `The input of the process is at byte ${this.received}, not ${offset}: a write is missing.`);
19
+ }
20
+ const unseen = bytes.subarray(this.received - offset);
21
+ if (unseen.length === 0)
22
+ return;
23
+ if (this.ended)
24
+ throw new HttpError(409, 'The standard input of the process is closed.');
25
+ // Counted at once: a request sent again meanwhile finds these bytes given already.
26
+ this.received += unseen.length;
27
+ await new Promise((resolve, reject) => {
28
+ this.stdin.write(unseen, (error) => {
29
+ if (error === null || error === undefined)
30
+ resolve();
31
+ else
32
+ reject(new HttpError(409, `The process no longer reads its input: ${error.message}`));
33
+ });
34
+ });
35
+ }
36
+ /** Ends the input, as many times as it is asked to. */
37
+ end() {
38
+ if (this.ended)
39
+ return;
40
+ this.ended = true;
41
+ this.stdin.end();
42
+ }
43
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ChildProcessWithoutNullStreams } from 'node:child_process';
2
+ import { ProcessInput } from './process-input.js';
2
3
  /** The user commands run as, when the agent runs as root and switches to it. */
3
4
  export interface CommandUser {
4
5
  uid: number;
@@ -10,6 +11,8 @@ export interface StartedProcess {
10
11
  readonly child: ChildProcessWithoutNullStreams;
11
12
  /** Its exit code, once it exited: 128 and the signal's number when a signal ended it. */
12
13
  readonly exited: Promise<number>;
14
+ /** Its standard input, when it was started with `stdin`: written by requests of their own. */
15
+ readonly input?: ProcessInput;
13
16
  }
14
17
  /**
15
18
  * The processes of the sandbox. Each runs in a process group of its own, so that stopping it stops
@@ -20,8 +23,15 @@ export declare class Processes {
20
23
  private readonly user?;
21
24
  private readonly started;
22
25
  constructor(user?: CommandUser | undefined);
23
- /** Starts `command` in `directory`, with `env` and nothing else; its stdin is the caller's. */
24
- exec(command: string, directory: string, env: Record<string, string>): StartedProcess;
26
+ /**
27
+ * Starts `command` in `directory`, with `env` and nothing else; its stdin is the caller's, written
28
+ * through {@link StartedProcess.input} with `stdin`.
29
+ */
30
+ exec(command: string, { directory, env, stdin, }: {
31
+ directory: string;
32
+ env: Record<string, string>;
33
+ stdin?: boolean;
34
+ }): StartedProcess;
25
35
  /** A process {@link exec} started, while it runs and for a while after it exits. */
26
36
  get(id: string): StartedProcess | undefined;
27
37
  /** Stops a process and everything it started. */
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
3
3
  import { readdirSync, readFileSync } from 'node:fs';
4
4
  import { constants } from 'node:os';
5
5
  import { setTimeout as sleep } from 'node:timers/promises';
6
+ import { ProcessInput } from './process-input.js';
6
7
  /**
7
8
  * Runs the command `$1` in the directory `$2`, with bash as the AI SDK's Vercel sandbox does and the
8
9
  * harnesses expect (Pi writes bash), or with sh in an image without bash. Both come as positional
@@ -72,8 +73,11 @@ export class Processes {
72
73
  constructor(user) {
73
74
  this.user = user;
74
75
  }
75
- /** Starts `command` in `directory`, with `env` and nothing else; its stdin is the caller's. */
76
- exec(command, directory, env) {
76
+ /**
77
+ * Starts `command` in `directory`, with `env` and nothing else; its stdin is the caller's, written
78
+ * through {@link StartedProcess.input} with `stdin`.
79
+ */
80
+ exec(command, { directory, env, stdin = false, }) {
77
81
  const id = randomUUID();
78
82
  const shell = ['/bin/sh', '-c', COMMAND, 'sh', command, directory];
79
83
  // `setpriv` takes the user's groups too, `docker` among them, which Node.js's `uid` drops.
@@ -94,7 +98,7 @@ export class Processes {
94
98
  child.once('error', () => resolve(127));
95
99
  child.once('close', (code, name) => resolve(code ?? 128 + (name === null ? 0 : (constants.signals[name] ?? 15))));
96
100
  });
97
- const started = { id, child, exited };
101
+ const started = { id, child, exited, input: stdin ? new ProcessInput(child.stdin) : undefined };
98
102
  this.started.set(id, started);
99
103
  void exited.then(() => setTimeout(() => this.started.delete(id), EXITED_KEPT_MS).unref());
100
104
  return started;
@@ -8,6 +8,8 @@
8
8
  * answer streams the frames of `frames.ts`, the process named in `x-process-id`;
9
9
  * - `GET /v1/processes/:id`: waits for the process to exit, a few minutes at most:
10
10
  * `{ exitCode }`, or `{ running: true }`;
11
+ * - `POST /v1/processes/:id/stdin?offset=…`: bytes of the standard input of a process started with
12
+ * `stdin`, from that offset on; `DELETE /v1/processes/:id/stdin` ends it;
11
13
  * - `DELETE /v1/processes/:id`, `DELETE /v1/processes`: stop one process, or every one;
12
14
  * - `GET /v1/ports/:port/…` with `Upgrade`: the request passed on to `127.0.0.1:<port>`.
13
15
  */
@@ -8,6 +8,8 @@
8
8
  * answer streams the frames of `frames.ts`, the process named in `x-process-id`;
9
9
  * - `GET /v1/processes/:id`: waits for the process to exit, a few minutes at most:
10
10
  * `{ exitCode }`, or `{ running: true }`;
11
+ * - `POST /v1/processes/:id/stdin?offset=…`: bytes of the standard input of a process started with
12
+ * `stdin`, from that offset on; `DELETE /v1/processes/:id/stdin` ends it;
11
13
  * - `DELETE /v1/processes/:id`, `DELETE /v1/processes`: stop one process, or every one;
12
14
  * - `GET /v1/ports/:port/…` with `Upgrade`: the request passed on to `127.0.0.1:<port>`.
13
15
  */
@@ -20,4 +20,15 @@ export interface SandboxCommand {
20
20
  workingDirectory?: string;
21
21
  /** Variables of its own, beside those of the sandbox. */
22
22
  env?: Record<string, string>;
23
+ /**
24
+ * Keep its standard input open once the request ends: it is then written by
25
+ * `POST …/processes/:id/stdin` and ended by `DELETE …/processes/:id/stdin`. Without it, the
26
+ * standard input is what follows the command in the request, and ends with it.
27
+ */
28
+ stdin?: boolean;
23
29
  }
30
+ /**
31
+ * The most bytes one `POST …/processes/:id/stdin` carries, well under the 32 MiB Cloud Run
32
+ * accepts in an HTTP/1 request.
33
+ */
34
+ export declare const MAX_INPUT_WRITE_BYTES: number;
@@ -2,4 +2,8 @@
2
2
  * The bodies of the HTTP API between the client and the sandbox service: both sides read and write
3
3
  * them, so they are declared once, here.
4
4
  */
5
- export {};
5
+ /**
6
+ * The most bytes one `POST …/processes/:id/stdin` carries, well under the 32 MiB Cloud Run
7
+ * accepts in an HTTP/1 request.
8
+ */
9
+ export const MAX_INPUT_WRITE_BYTES = 8 << 20;
@@ -4,7 +4,7 @@
4
4
  * speaks the same; a side that speaks another one is refused, rather than answered with errors
5
5
  * nobody could make sense of.
6
6
  */
7
- export declare const PROTOCOL_VERSION = 1;
7
+ export declare const PROTOCOL_VERSION = 2;
8
8
  /** The header a caller names its protocol version in, and the callee answers with its own. */
9
9
  export declare const PROTOCOL_HEADER = "x-ai-sdk-sandbox-protocol";
10
10
  /** The header carrying the secret the client and the service may share, beside Cloud Run's IAM. */
@@ -4,7 +4,7 @@
4
4
  * speaks the same; a side that speaks another one is refused, rather than answered with errors
5
5
  * nobody could make sense of.
6
6
  */
7
- export const PROTOCOL_VERSION = 1;
7
+ export const PROTOCOL_VERSION = 2;
8
8
  /** The header a caller names its protocol version in, and the callee answers with its own. */
9
9
  export const PROTOCOL_HEADER = 'x-ai-sdk-sandbox-protocol';
10
10
  /** The header carrying the secret the client and the service may share, beside Cloud Run's IAM. */
@@ -3,7 +3,8 @@ import type { Sandboxes } from '../sandboxes/sandboxes.js';
3
3
  /**
4
4
  * `POST /v1/sandboxes/:name/exec`, passed on to the agent of the sandbox's machine once the proxy
5
5
  * found no credential of the sandbox in the command. The body is a line of JSON,
6
- * `{ command, workingDirectory?, env? }`, then the command's standard input; the answer streams the
6
+ * `{ command, workingDirectory?, env?, stdin? }`, then the command's standard input (with `stdin`,
7
+ * the line alone: the input is written by requests of their own); the answer streams the
7
8
  * agent's frames, the process named in `X-Process-Id`. The process outlives the request: Cloud Run
8
9
  * cuts any request after its timeout, and the caller then waits for its exit by id.
9
10
  */
@@ -18,7 +18,8 @@ async function errorOf(answer) {
18
18
  /**
19
19
  * `POST /v1/sandboxes/:name/exec`, passed on to the agent of the sandbox's machine once the proxy
20
20
  * found no credential of the sandbox in the command. The body is a line of JSON,
21
- * `{ command, workingDirectory?, env? }`, then the command's standard input; the answer streams the
21
+ * `{ command, workingDirectory?, env?, stdin? }`, then the command's standard input (with `stdin`,
22
+ * the line alone: the input is written by requests of their own); the answer streams the
22
23
  * agent's frames, the process named in `X-Process-Id`. The process outlives the request: Cloud Run
23
24
  * cuts any request after its timeout, and the caller then waits for its exit by id.
24
25
  */
@@ -1,6 +1,7 @@
1
- import { optionalString, readJson, requiredString, stringList, stringRecord, transformationList, } from '../../common/http-body.js';
1
+ import { offsetOf, optionalString, readBytes, readJson, requiredString, stringList, stringRecord, transformationList, } from '../../common/http-body.js';
2
2
  import { NO_CONTENT } from '../../common/http-reply.js';
3
3
  import { PACKAGE_VERSION } from '../../common/package-version.js';
4
+ import { MAX_INPUT_WRITE_BYTES } from '../../protocol/api.js';
4
5
  import { PROTOCOL_VERSION } from '../../protocol/version.js';
5
6
  import { execRelay } from './exec-relay.js';
6
7
  const network = async (request) => {
@@ -55,6 +56,16 @@ export const ROUTES = [
55
56
  await (await sandboxes.agent(name)).kill(id);
56
57
  return NO_CONTENT;
57
58
  }),
59
+ route('POST', new RegExp(`^${SANDBOX}/processes/([^/]+)/stdin$`), async ({ sandboxes, params: [name = '', id = ''], request }) => {
60
+ const offset = offsetOf(request);
61
+ const bytes = await readBytes(request, MAX_INPUT_WRITE_BYTES);
62
+ await (await sandboxes.agent(name)).writeInput(id, offset, bytes);
63
+ return NO_CONTENT;
64
+ }),
65
+ route('DELETE', new RegExp(`^${SANDBOX}/processes/([^/]+)/stdin$`), async ({ sandboxes, params: [name = '', id = ''] }) => {
66
+ await (await sandboxes.agent(name)).endInput(id);
67
+ return NO_CONTENT;
68
+ }),
58
69
  route('DELETE', new RegExp(`^${SANDBOX}/processes$`), async ({ sandboxes, params: [name = ''] }) => {
59
70
  await (await sandboxes.agent(name)).killAll();
60
71
  return NO_CONTENT;
@@ -23,6 +23,10 @@ export declare class AgentClient {
23
23
  /** Waits for a process to exit, a few minutes at most: the agent's answer, as it is. */
24
24
  wait(id: string): Promise<unknown>;
25
25
  kill(id: string): Promise<void>;
26
+ /** Gives a process started with `stdin` the bytes of its input from `offset` on. */
27
+ writeInput(id: string, offset: number, bytes: Uint8Array): Promise<void>;
28
+ /** Ends the input of a process started with `stdin`. */
29
+ endInput(id: string): Promise<void>;
26
30
  killAll(): Promise<void>;
27
31
  /**
28
32
  * `POST /v1/exec`, its body the caller's to write: the agent's answer streams the process's
@@ -45,6 +45,14 @@ export class AgentClient {
45
45
  async kill(id) {
46
46
  await this.call('DELETE', `/v1/processes/${encodeURIComponent(id)}`);
47
47
  }
48
+ /** Gives a process started with `stdin` the bytes of its input from `offset` on. */
49
+ async writeInput(id, offset, bytes) {
50
+ await this.call('POST', `/v1/processes/${encodeURIComponent(id)}/stdin?offset=${offset}`, bytes);
51
+ }
52
+ /** Ends the input of a process started with `stdin`. */
53
+ async endInput(id) {
54
+ await this.call('DELETE', `/v1/processes/${encodeURIComponent(id)}/stdin`);
55
+ }
48
56
  async killAll() {
49
57
  await this.call('DELETE', '/v1/processes');
50
58
  }
@@ -74,10 +82,15 @@ export class AgentClient {
74
82
  async call(method, path, body) {
75
83
  let response;
76
84
  try {
85
+ const bytes = body instanceof Uint8Array;
77
86
  response = await fetch(`${this.origin}${path}`, {
78
87
  method,
79
- headers: this.headers(body === undefined ? {} : { 'content-type': 'application/json' }),
80
- body: body === undefined ? undefined : JSON.stringify(body),
88
+ headers: this.headers(body === undefined || bytes ? {} : { 'content-type': 'application/json' }),
89
+ body: bytes
90
+ ? body
91
+ : body === undefined
92
+ ? undefined
93
+ : JSON.stringify(body),
81
94
  });
82
95
  }
83
96
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-sdk-sandbox-gce",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Compute Engine sandboxes for AI SDK harness agents: Claude Code, Codex and friends in a virtual machine of their own on Google Cloud, Docker included, stopped between turns.",
5
5
  "keywords": [
6
6
  "ai",
@@ -59,9 +59,9 @@
59
59
  "zod": "^4.6.7",
60
60
  "@repo/build": "0.0.0",
61
61
  "@repo/eslint-config": "0.0.0",
62
+ "@repo/vitest-config": "0.0.0",
62
63
  "@repo/prettier-config": "0.0.0",
63
- "@repo/typescript-config": "0.0.0",
64
- "@repo/vitest-config": "0.0.0"
64
+ "@repo/typescript-config": "0.0.0"
65
65
  },
66
66
  "author": {
67
67
  "name": "Fabien Pasquet",