@coder/ai-sdk-sandbox 0.3.0 → 0.4.1

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/README.md CHANGED
@@ -11,20 +11,23 @@ you pass it as the `sandbox` to a `HarnessAgent` exactly like
11
11
  `@ai-sdk/sandbox-vercel`.
12
12
 
13
13
  > **Status:** experimental. This provider tracks the stable AI SDK v7 harness
14
- > packages (`@ai-sdk/harness@^1.0.23`).
14
+ > packages (see the `@ai-sdk/harness` peer range in
15
+ > [`package.json`](./package.json)).
15
16
 
16
17
  ## Install
17
18
 
18
19
  ```bash
19
- npm add @coder/ai-sdk-sandbox @ai-sdk/harness @ai-sdk/harness-claude-code @ai-sdk/provider-utils
20
+ pnpm add @coder/ai-sdk-sandbox @ai-sdk/harness @ai-sdk/harness-claude-code @ai-sdk/provider-utils
20
21
  ```
21
22
 
22
- On the host you also need:
23
+ Choose one host transport:
23
24
 
24
- - the [`coder` CLI](https://coder.com/docs/install) on PATH and authenticated
25
- (`coder login`); for non-ambient auth, configure the transport explicitly with
26
- `new CoderCliTransport({ url, token })` (see [Settings](#settings));
27
- - an **OpenSSH client** (`ssh`) on PATH — exec runs through it (see "How it works").
25
+ - `CoderNativeTransport` connects directly to Coderd and requires no `coder` or
26
+ `ssh` binary on the host. Pass a deployment URL and token (see
27
+ [Native transport](#native-transport)).
28
+ - The default `CoderCliTransport` requires the
29
+ [`coder` CLI](https://coder.com/docs/install), an authenticated `coder login`,
30
+ and an OpenSSH client (`ssh`) on PATH.
28
31
 
29
32
  ## Quick start
30
33
 
@@ -36,7 +39,7 @@ import { createClaudeCode } from "@ai-sdk/harness-claude-code";
36
39
  import { createCoderWorkspace } from "@coder/ai-sdk-sandbox";
37
40
 
38
41
  const agent = new HarnessAgent({
39
- harness: createClaudeCode({ thinking: "adaptive" }),
42
+ harness: createClaudeCode({ thinking: { type: "adaptive" } }),
40
43
  sandbox: createCoderWorkspace({ workspace: "my-dev-workspace" }),
41
44
  instructions: "You are a careful coding assistant.",
42
45
  });
@@ -55,6 +58,33 @@ try {
55
58
 
56
59
  See [`examples/claude-code.ts`](./examples/claude-code.ts) for a runnable version.
57
60
 
61
+ ### Native transport
62
+
63
+ Use `CoderNativeTransport` when the host should not depend on the Coder CLI or
64
+ OpenSSH:
65
+
66
+ ```ts
67
+ import { CoderNativeTransport, createCoderWorkspace } from "@coder/ai-sdk-sandbox";
68
+
69
+ const transport = new CoderNativeTransport({
70
+ url: process.env.CODER_URL!,
71
+ token: process.env.CODER_SESSION_TOKEN!,
72
+ });
73
+
74
+ const sandbox = createCoderWorkspace({
75
+ workspace: "my-dev-workspace",
76
+ transport,
77
+ });
78
+
79
+ // When the application shuts down, close cached relay WebSockets:
80
+ await transport.close();
81
+ ```
82
+
83
+ The constructor falls back to `CODER_URL` and `CODER_SESSION_TOKEN`, so
84
+ `new CoderNativeTransport()` is sufficient when both are set. The token is sent
85
+ only to Coderd in the `Coder-Session-Token` header; it is never copied into the
86
+ workspace.
87
+
58
88
  ## Creating workspaces on demand
59
89
 
60
90
  Instead of pointing at an existing workspace, you can have the provider **create
@@ -63,7 +93,7 @@ the session ends. Add a `create` block:
63
93
 
64
94
  ```ts
65
95
  const agent = new HarnessAgent({
66
- harness: createClaudeCode({ thinking: "adaptive" }),
96
+ harness: createClaudeCode({ thinking: { type: "adaptive" } }),
67
97
  sandbox: createCoderWorkspace({
68
98
  create: {
69
99
  template: "docker", // required: the template to create from
@@ -96,12 +126,13 @@ createCoderWorkspace({
96
126
 
97
127
  **Parameters vs. presets.** A preset's parameter values take precedence over an
98
128
  overlapping `parameters` entry of the same name (this is Coder's behavior), so
99
- set a given value via the preset _or_ `parameters`, not both. Required
100
- parameters (those without a template default) must be supplied via `parameters`,
101
- `parameterFile`, a `preset`, or `useParameterDefaults` otherwise creation
102
- fails (it can't prompt non-interactively). If you set a `preset`, the provider
103
- preflight-validates the name against the template's presets and fails fast with
104
- the available names (set `validate: false` to skip).
129
+ set a given value via the preset _or_ `parameters`, not both. Every unset
130
+ non-ephemeral parameter must be supplied via `parameters`, `parameterFile`, or a
131
+ `preset`, unless `useParameterDefaults` accepts its template default. Parameters
132
+ marked required have no usable default and must always be supplied; otherwise
133
+ creation fails because it cannot prompt non-interactively. If you set a `preset`,
134
+ the provider preflight-validates the name against the template's presets and
135
+ fails fast with the available names (set `validate: false` to skip).
105
136
 
106
137
  ### Create settings
107
138
 
@@ -171,7 +202,7 @@ For an interactive chat in your terminal instead of one-shot `generate()` calls,
171
202
  wrap the same agent with the AI SDK terminal UI ([`@ai-sdk/tui`](https://ai-sdk.dev/v7/docs/ai-sdk-harnesses/terminal-ui)):
172
203
 
173
204
  ```bash
174
- npm add @ai-sdk/tui
205
+ pnpm add @ai-sdk/tui
175
206
  ```
176
207
 
177
208
  The TUI drives a session-less agent, so adapt the `HarnessAgent` (whose
@@ -185,7 +216,7 @@ import { runAgentTUI, type AgentTUIAgent } from "@ai-sdk/tui";
185
216
  import { createCoderWorkspace } from "@coder/ai-sdk-sandbox";
186
217
 
187
218
  const agent = new HarnessAgent({
188
- harness: createClaudeCode({ thinking: "adaptive" }),
219
+ harness: createClaudeCode({ thinking: { type: "adaptive" } }),
189
220
  sandbox: createCoderWorkspace({ workspace: "my-dev-ws" }),
190
221
  // or, to create a fresh workspace per session from a template:
191
222
  // sandbox: createCoderWorkspace({ create: { template: 'claude-code-test' } }),
@@ -233,7 +264,11 @@ Because the bridge runs inside the workspace, the workspace image must have:
233
264
  [Creating workspaces on demand](#creating-workspaces-on-demand)).
234
265
 
235
266
  ```ts
236
- import { createCoderWorkspace, CoderCliTransport } from "@coder/ai-sdk-sandbox";
267
+ import {
268
+ createCoderWorkspace,
269
+ CoderCliTransport,
270
+ CoderNativeTransport,
271
+ } from "@coder/ai-sdk-sandbox";
237
272
 
238
273
  createCoderWorkspace({
239
274
  // One of these is required (TypeScript enforces it):
@@ -254,6 +289,12 @@ createCoderWorkspace({
254
289
  // url: process.env.CODER_URL, token: process.env.CODER_SESSION_TOKEN,
255
290
  // env: {}, loginShell: true, waitMode: 'no',
256
291
  }),
292
+
293
+ // Or connect directly to Coderd with no host CLI/OpenSSH dependency:
294
+ // transport: new CoderNativeTransport({
295
+ // url: process.env.CODER_URL,
296
+ // token: process.env.CODER_SESSION_TOKEN,
297
+ // }),
257
298
  });
258
299
  ```
259
300
 
@@ -276,10 +317,11 @@ createCoderWorkspace({
276
317
 
277
318
  The adapter binds its bridge to a port and resolves it from
278
319
  `createClaudeCode({ port })` or, by default, `sandbox.ports[0]`. Expose that port
279
- via `ports` (default `[4000]`); `getPortUrl` opens an OpenSSH `-L` local forward
280
- (over the same `coder ssh --stdio` ProxyCommand) to it on demand and returns a
281
- loopback `ws://` URL. The forward is plaintext on loopback, so `https`/`wss`
282
- requests resolve to their `http`/`ws` loopback equivalent.
320
+ via `ports` (default `[4000]`); `getPortUrl` asks the configured transport for a
321
+ local TCP forward and returns a loopback `ws://` URL. The CLI transport uses
322
+ OpenSSH `-L`; the native transport multiplexes TCP over its Coderd WebSocket.
323
+ The forward is plaintext on loopback, so `https`/`wss` requests resolve to their
324
+ `http`/`ws` loopback equivalent.
283
325
 
284
326
  ## How it works
285
327
 
@@ -290,14 +332,13 @@ bridge runs the vendor SDK in-workspace and streams events back to the host.
290
332
 
291
333
  This provider maps that contract onto Coder primitives:
292
334
 
293
- | Harness contract | Coder implementation |
294
- | ------------------------------------------- | ------------------------------------------------------------------------------------------- |
295
- | `run` / `spawn` | OpenSSH `bash -lc '…'` over a `coder ssh --stdio` ProxyCommand |
296
- | `readFile` / `writeFile` / `read*`/`write*` | base64 piped over the SSH connection (binary-safe) |
297
- | `getPortUrl({ port, protocol })` | OpenSSH `-L <local>:127.0.0.1:<port>` over the same ProxyCommand → `ws://127.0.0.1:<local>` |
298
- | `ports` / `setPorts` | the workspace's exposed port set |
299
- | `createSession` / `resumeSession` / `id` | attach to a workspace by name |
300
- | `stop` / `destroy` | `coder stop` / `coder delete` (only when it owns the lifecycle) |
335
+ | Harness contract | CLI transport | Native transport |
336
+ | ------------------------------------------- | -------------------------------------------------- | --------------------------------------------------------- |
337
+ | `run` / `spawn` | OpenSSH over `coder ssh --stdio` | versioned process relay over Coderd's agent PTY WebSocket |
338
+ | `readFile` / `writeFile` / `read*`/`write*` | base64 over SSH | base64 over the native process relay |
339
+ | `getPortUrl({ port, protocol })` | OpenSSH `-L` | multiplexed TCP channels over the relay |
340
+ | `createSession` / `resumeSession` / `id` | CLI workspace lookup | Coderd v2 REST API |
341
+ | `stop` / `destroy` | `coder stop` / `coder delete` when lifecycle-owned | Coderd workspace-build transitions |
301
342
 
302
343
  **Why OpenSSH and not `coder ssh <ws> -- cmd`?** `coder ssh` allocates a PTY for
303
344
  the command, which rewrites newlines to CRLF, merges stdout and stderr onto one
@@ -308,6 +349,15 @@ provider does the programmatic equivalent, running real OpenSSH over a
308
349
  `coder ssh --stdio` ProxyCommand. That yields clean, separated streams and
309
350
  correct exit codes (verified against a live workspace).
310
351
 
352
+ **How the native relay stays byte-clean.** Coderd's browser-terminal endpoint
353
+ is a PTY, which by itself merges stdout/stderr and has no process exit-code
354
+ channel. The native transport uses it only as a carrier: it bootstraps a small,
355
+ dependency-free Node relay, switches the PTY to raw/no-echo mode, and exchanges
356
+ versioned newline-delimited frames with base64 byte payloads. The relay launches
357
+ commands with separate pipes and also opens TCP sockets for `getPortUrl`. It
358
+ does not bind a workspace port or persist credentials/files; one relay is cached
359
+ per selected workspace agent and `transport.close()` tears it down.
360
+
311
361
  The WebSocket the harness opens against `getPortUrl(...)` is the critical path,
312
362
  and it needs no wildcard access URLs — the host running `HarnessAgent` is already
313
363
  a Coder client. We forward via OpenSSH `-L` rather than `coder port-forward`:
@@ -326,6 +376,11 @@ and a full Claude Code turn with tool use (`scripts/e2e-claude.ts`).
326
376
  workspace per session rather than leasing ports from a shared sandbox.
327
377
  - File reads buffer the whole file (binary content moves as base64). Fine for
328
378
  bootstrap-sized files; not intended for streaming very large files.
379
+ - `CoderNativeTransport` currently targets POSIX workspaces with `bash`, `stty`,
380
+ `base64`, and Node.js. Its default relay executable is `node`; override
381
+ `relayNodeCommand` when Node lives at a fixed nonstandard path.
382
+ - A workspace with multiple agents must be selected as `workspace.agent`; the
383
+ native transport refuses to guess.
329
384
  - `@ai-sdk/sandbox-just-bash` cannot expose ports and is rejected by bridge-backed
330
385
  adapters — this provider exists precisely to provide that port.
331
386
  - To run Claude Code / Codex, the **workspace** image needs Node.js (the adapter
@@ -335,21 +390,28 @@ and a full Claude Code turn with tool use (`scripts/e2e-claude.ts`).
335
390
  ## Development
336
391
 
337
392
  ```bash
338
- npm install
339
- npm run typecheck # tsc against the real harness types
340
- npm test # vitest: unit + local integration (fake `coder` + `ssh`)
341
- npm run build # tsup dist/ (ESM + d.ts)
393
+ # From this package's directory (packages/sandbox):
394
+ pnpm install
395
+ pnpm typecheck # tsc against the real harness types
396
+ pnpm test # vitest: unit + local integration (fake `coder` + `ssh`)
397
+ pnpm build # tsup → dist/ (ESM + d.ts)
342
398
 
343
- # Formatting & linting (Biome):
344
- npm run format # biome format --write . (apply formatting)
345
- npm run lint # biome lint . (report lint issues)
346
- npm run check # biome check . (format + lint, read-only; for CI)
399
+ # Formatting & linting are root-level scripts (`-w` runs them from anywhere in the repo):
400
+ pnpm -w format # oxfmt (apply formatting)
401
+ pnpm -w lint # oxlint (report lint issues)
402
+ pnpm -w check # format check + lint + typecheck (CI gate)
347
403
 
348
404
  # End-to-end against a real workspace (needs the coder CLI + a running workspace):
349
- npm run verify:real -- my-ws
405
+ pnpm verify:real my-ws
406
+
407
+ # The same contract through Coderd directly. The CLI is used only to mint a
408
+ # token for this shell; CoderNativeTransport never invokes it:
409
+ CODER_URL=https://coder.example.com \
410
+ CODER_SESSION_TOKEN="$(coder tokens create --name ai-sdk-sandbox)" \
411
+ pnpm verify:native my-ws
350
412
 
351
413
  # End-to-end of create mode (creates a throwaway workspace, then deletes it):
352
- npm run verify:create -- docker
414
+ pnpm verify:create docker
353
415
  ```
354
416
 
355
417
  The local integration tests exercise the real transport (argument building,
package/dist/index.d.ts CHANGED
@@ -1,12 +1,11 @@
1
- import { HarnessV1SandboxProvider, HarnessV1NetworkSandboxSession } from '@ai-sdk/harness';
1
+ import { HarnessV1SandboxProvider, HarnessV1NetworkSandboxSession, HarnessV1PortEndpoint } from '@ai-sdk/harness';
2
2
  import { Experimental_SandboxSession } from '@ai-sdk/provider-utils';
3
3
 
4
4
  /**
5
5
  * Transport abstraction over a Coder workspace. The sandbox session talks to a
6
6
  * workspace exclusively through this interface, which keeps the harness-facing
7
7
  * session decoupled from *how* we reach Coder (the default is the `coder` CLI;
8
- * tests inject a mock, and a future implementation could use the Coder REST API
9
- * or a persistent SSH/SFTP connection).
8
+ * {@link CoderNativeTransport} uses Coderd directly, and tests inject mocks).
10
9
  */
11
10
  interface CoderTransport {
12
11
  /** Run a command to completion, buffering stdout/stderr into strings. */
@@ -227,6 +226,62 @@ declare class CoderCliTransport implements CoderTransport {
227
226
  listPresets(options: ListPresetsOptions): Promise<PresetInfo[]>;
228
227
  }
229
228
 
229
+ interface CoderNativeTransportOptions {
230
+ /** Coder deployment URL. Defaults to `CODER_URL`. */
231
+ url?: string;
232
+ /** Coder session/API token. Defaults to `CODER_SESSION_TOKEN`. */
233
+ token?: string;
234
+ /** Custom fetch implementation, primarily for tests or custom HTTP agents. */
235
+ fetch?: typeof globalThis.fetch;
236
+ /** Additional headers sent to Coderd over both HTTP and WebSocket. */
237
+ headers?: Record<string, string>;
238
+ /** Poll interval while waiting for provisioner builds. Default: 1000ms. */
239
+ buildPollIntervalMs?: number;
240
+ /** Maximum wait for one provisioner build. Default: 30 minutes. */
241
+ buildTimeoutMs?: number;
242
+ /** Maximum wait for the workspace relay handshake. Default: 30000ms. */
243
+ relayConnectTimeoutMs?: number;
244
+ /** Node executable used inside the workspace for the relay. Default: `node`. */
245
+ relayNodeCommand?: string;
246
+ /** Run commands through `bash -lc` instead of `bash -c`. Default: true. */
247
+ loginShell?: boolean;
248
+ }
249
+ /**
250
+ * Native Coder transport: Coderd's REST API supplies the control plane and an
251
+ * authenticated workspace-agent PTY carries a small multiplexed process/TCP
252
+ * relay. No local `coder` or `ssh` binary is launched.
253
+ */
254
+ declare class CoderNativeTransport implements CoderTransport {
255
+ #private;
256
+ constructor(options?: CoderNativeTransportOptions);
257
+ exec(options: TransportExecOptions): Promise<ExecResult>;
258
+ spawn(options: TransportExecOptions): SpawnedProcess;
259
+ forwardPort(options: ForwardPortOptions): Promise<PortForward>;
260
+ start(workspace: string, options?: LifecycleOptions): Promise<void>;
261
+ stop(workspace: string, options?: LifecycleOptions): Promise<void>;
262
+ destroy(workspace: string, options?: LifecycleOptions): Promise<void>;
263
+ status(workspace: string, options?: LifecycleOptions): Promise<WorkspaceStatus | null>;
264
+ create(options: CreateWorkspaceOptions): Promise<void>;
265
+ listPresets(options: ListPresetsOptions): Promise<PresetInfo[]>;
266
+ /** Close every cached workspace relay. Existing local port-forwards close too. */
267
+ close(): Promise<void>;
268
+ }
269
+
270
+ /** Error returned for a non-success response from Coderd's v2 API. */
271
+ declare class CoderNativeApiError extends Error {
272
+ readonly status: number;
273
+ readonly method: string;
274
+ readonly path: string;
275
+ readonly detail?: string;
276
+ constructor(options: {
277
+ status: number;
278
+ method: string;
279
+ path: string;
280
+ message: string;
281
+ detail?: string;
282
+ });
283
+ }
284
+
230
285
  /** Stable provider id reported on the {@link HarnessV1SandboxProvider}. */
231
286
  declare const CODER_WORKSPACE_PROVIDER_ID = "coder-workspace";
232
287
  /**
@@ -474,11 +529,10 @@ interface CoderWorkspaceSessionConfig {
474
529
  /**
475
530
  * A {@link HarnessV1NetworkSandboxSession} backed by a Coder workspace.
476
531
  *
477
- * Exec maps to `coder ssh`, file I/O to base64-over-`coder ssh`, and
478
- * `getPortUrl` to an OpenSSH `-L` local forward over a `coder ssh --stdio`
479
- * ProxyCommand, exposed as a local `ws://127.0.0.1:<port>` URL which is what
480
- * bridge-backed harness adapters (Claude Code, Codex) open their WebSocket
481
- * against.
532
+ * The configured {@link CoderTransport} supplies process execution, lifecycle,
533
+ * and TCP forwarding. `getPortEndpoint` exposes a forwarded port as a local
534
+ * `ws://127.0.0.1:<port>` URL, which is what bridge-backed harness adapters
535
+ * (Claude Code, Codex) open their WebSocket against.
482
536
  */
483
537
  declare class CoderWorkspaceSession implements HarnessV1NetworkSandboxSession {
484
538
  #private;
@@ -495,6 +549,11 @@ declare class CoderWorkspaceSession implements HarnessV1NetworkSandboxSession {
495
549
  readonly writeFile: (options: WriteFileOptions<ReadableStream<Uint8Array>>) => Promise<void>;
496
550
  readonly writeBinaryFile: (options: WriteFileOptions<Uint8Array>) => Promise<void>;
497
551
  readonly writeTextFile: (options: WriteTextFileOptions) => Promise<void>;
552
+ readonly getPortEndpoint: (options: {
553
+ port: number;
554
+ protocol?: "http" | "https" | "ws";
555
+ }) => Promise<HarnessV1PortEndpoint>;
556
+ /** @deprecated Kept for the `HarnessV1NetworkSandboxSession` contract; use `getPortEndpoint`. */
498
557
  readonly getPortUrl: (options: {
499
558
  port: number;
500
559
  protocol?: "http" | "https" | "ws";
@@ -508,4 +567,4 @@ declare class CoderWorkspaceSession implements HarnessV1NetworkSandboxSession {
508
567
  readonly restricted: () => Experimental_SandboxSession;
509
568
  }
510
569
 
511
- export { CODER_WORKSPACE_PROVIDER_ID, CoderCliTransport, type CoderCliTransportOptions, type CoderCreateSettings, type CoderTransport, type CoderWorkspaceBaseSettings, type CoderWorkspaceRef, CoderWorkspaceSession, type CoderWorkspaceSessionConfig, type CoderWorkspaceSettings, type CreateWorkspaceOptions, type EnsureCoderWorkspaceSettings, type EnsuredCoderWorkspace, type ExecResult, type ForwardPortOptions, type LifecycleOptions, type ListPresetsOptions, type PortForward, type PresetInfo, type SpawnedProcess, type TransportExecOptions, type WorkspaceAgentInfo, type WorkspaceAgentLifecycle, type WorkspaceAgentStatus, type WorkspaceBuildStatus, type WorkspaceStatus, createCoderWorkspace, ensureCoderWorkspace };
570
+ export { CODER_WORKSPACE_PROVIDER_ID, CoderCliTransport, type CoderCliTransportOptions, type CoderCreateSettings, CoderNativeApiError, CoderNativeTransport, type CoderNativeTransportOptions, type CoderTransport, type CoderWorkspaceBaseSettings, type CoderWorkspaceRef, CoderWorkspaceSession, type CoderWorkspaceSessionConfig, type CoderWorkspaceSettings, type CreateWorkspaceOptions, type EnsureCoderWorkspaceSettings, type EnsuredCoderWorkspace, type ExecResult, type ForwardPortOptions, type LifecycleOptions, type ListPresetsOptions, type PortForward, type PresetInfo, type SpawnedProcess, type TransportExecOptions, type WorkspaceAgentInfo, type WorkspaceAgentLifecycle, type WorkspaceAgentStatus, type WorkspaceBuildStatus, type WorkspaceStatus, createCoderWorkspace, ensureCoderWorkspace };