@archildata/ai-sdk-harness 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Archil, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,38 @@
1
- # Temporary Holding Version
1
+ # @archildata/ai-sdk-harness
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Archil sandboxes for [AI SDK harness](https://ai-sdk.dev/v7/docs/ai-sdk-harnesses/overview) agents.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install disk @archildata/ai-sdk @archildata/ai-sdk-harness @ai-sdk/harness
9
+ ```
10
+
11
+ Set `ARCHIL_API_KEY` and `ARCHIL_REGION`, or pass an Archil client as `client`.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { createArchilNetworkSandboxSession } from "@archildata/ai-sdk-harness";
17
+
18
+ const sandboxSession = await createArchilNetworkSandboxSession({
19
+ ports: [4000],
20
+ setupCommands: ["corepack enable pnpm"],
21
+ template: await agent.getSandboxTemplate(),
22
+ });
23
+ const session = await agent.createSession({ sandboxSession });
24
+ ```
25
+
26
+ Any `sandboxes.create()` setting can be passed, such as `baseImage`, `vcpuCount`, `memSizeMiB`, or `env`. `setupCommands` run once on a fresh sandbox before the harness sets it up; the Claude Code and Codex adapters need `pnpm`, which the default image enables through corepack. Sandboxes get `IS_SANDBOX=1`, which lets Claude Code run as root.
27
+
28
+ - **Ports** are private. Each endpoint carries a port token that Archil's proxy checks, so nothing is exposed publicly.
29
+ - **Network policy and request transformations** use Archil egress rules, so credentials are added to requests outside the sandbox. They are unavailable on free plans, whose network policy cannot be changed.
30
+ - **Templates** are prepared once in a sandbox that is then stopped, and each session forks from it.
31
+ - **`stop()`** pauses the sandbox and **`destroy()`** deletes it.
32
+ - **Resume** finds the sandbox by name, the session's `id`:
33
+
34
+ ```ts
35
+ import { resumeArchilNetworkSandboxSession } from "@archildata/ai-sdk-harness";
36
+
37
+ const sandbox = await resumeArchilNetworkSandboxSession({ sandboxId, ports: [4000] });
38
+ ```
@@ -0,0 +1,118 @@
1
+ import { HarnessV1NetworkPolicy, HarnessV1NetworkSandboxSession, HarnessV1PortEndpoint, HarnessV1RequestTransformation, HarnessV1SandboxSessionCreateOptions, HarnessV1SandboxSessionResumeOptions } from "@ai-sdk/harness";
2
+ import { ArchilSandboxSession } from "@archildata/ai-sdk";
3
+ import { Archil, CreateSandboxRequest, Sandbox, SandboxNetwork } from "disk";
4
+ import { Experimental_SandboxSession } from "ai";
5
+
6
+ //#region src/network-sandbox-session.d.ts
7
+ interface ArchilNetworkSandboxSessionInput {
8
+ sandbox: Sandbox;
9
+ workingDirectory: string;
10
+ /** Ports the harness may reach; see {@link ArchilNetworkSandboxSession.getPortEndpoint}. */
11
+ ports: ReadonlyArray<number>;
12
+ /** The sandbox's network policy when the session was created. */
13
+ network: SandboxNetwork;
14
+ }
15
+ /**
16
+ * `HarnessV1NetworkSandboxSession` backed by an Archil sandbox. Its `id` is the
17
+ * sandbox name, which resume looks up.
18
+ *
19
+ * Ports are never exposed publicly: each endpoint carries a port token that
20
+ * Archil's proxy checks. `stop()` pauses the sandbox, keeping memory and
21
+ * processes for resume, and `destroy()` deletes it.
22
+ *
23
+ * Network policy and request transformations are unavailable on sandboxes
24
+ * with Archil's managed free-plan network policy, which cannot be changed, so
25
+ * harness adapters fall back to their own credential handling there.
26
+ */
27
+ declare class ArchilNetworkSandboxSession extends ArchilSandboxSession implements HarnessV1NetworkSandboxSession {
28
+ readonly id: string;
29
+ readonly defaultWorkingDirectory: string;
30
+ readonly setNetworkPolicy?: (policy: HarnessV1NetworkPolicy) => Promise<void>;
31
+ readonly setRequestTransformations?: (transformations: ReadonlyArray<HarnessV1RequestTransformation>) => Promise<void>;
32
+ readonly addRequestTransformations?: (transformations: ReadonlyArray<HarnessV1RequestTransformation>) => Promise<void>;
33
+ private advertisedPorts;
34
+ private readonly portTokens;
35
+ private readonly baselineNetwork;
36
+ private networkState;
37
+ private networkQueue;
38
+ private stopped;
39
+ private destroyed;
40
+ constructor(input: ArchilNetworkSandboxSessionInput);
41
+ get ports(): ReadonlyArray<number>;
42
+ restricted(): Experimental_SandboxSession;
43
+ /**
44
+ * Any port can be reached, not only the advertised ones. The first request
45
+ * for a port creates a non-expiring port token, which is reused for the
46
+ * life of this session object and revoked when the port is removed with
47
+ * `setPorts`.
48
+ */
49
+ getPortEndpoint: ({
50
+ port,
51
+ protocol
52
+ }: {
53
+ port: number;
54
+ protocol?: "http" | "https" | "ws";
55
+ }) => Promise<HarnessV1PortEndpoint>;
56
+ /** @deprecated Use `getPortEndpoint`; Archil port endpoints need a token header a bare URL cannot carry. */
57
+ getPortUrl: () => Promise<string>;
58
+ setPorts: (ports: ReadonlyArray<number>, options?: {
59
+ abortSignal?: AbortSignal;
60
+ }) => Promise<void>;
61
+ stop: () => Promise<void>;
62
+ destroy: () => Promise<void>;
63
+ private updateNetwork;
64
+ }
65
+ //#endregion
66
+ //#region src/index.d.ts
67
+ interface ArchilSessionSettings {
68
+ /** Archil client. Created from `ARCHIL_API_KEY` and `ARCHIL_REGION` when omitted. */
69
+ client?: Archil;
70
+ /**
71
+ * Ports the harness can reach, advertised on `session.ports`; the harness
72
+ * bridge listens on the first. They are reached through private port
73
+ * tokens and never exposed publicly.
74
+ */
75
+ ports?: number[];
76
+ }
77
+ type ArchilCreateSettings = ArchilSessionSettings & Omit<CreateSandboxRequest, "ports"> & {
78
+ /**
79
+ * Name of the stopped sandbox that holds a prepared `template`. Defaults to
80
+ * a name derived from the template's identity and the creation settings.
81
+ * An existing template sandbox under this name is reused as is.
82
+ */
83
+ templateName?: string;
84
+ /**
85
+ * Shell commands run once on a fresh sandbox, in order, before the
86
+ * harness sets it up. With a `template` they run in the template sandbox,
87
+ * so they are baked into it. Use them for tools an adapter expects but the
88
+ * image lacks, such as `corepack enable pnpm`.
89
+ */
90
+ setupCommands?: string[];
91
+ };
92
+ type ArchilNetworkSandboxSessionCreateOptions = HarnessV1SandboxSessionCreateOptions<ArchilCreateSettings>;
93
+ type ArchilNetworkSandboxSessionResumeOptions = HarnessV1SandboxSessionResumeOptions<ArchilSessionSettings>;
94
+ /**
95
+ * Create an Archil sandbox for a harness session.
96
+ *
97
+ * `sandboxId` (or `name`) names the sandbox; resume finds it by that name.
98
+ * With a `template`, the template is prepared once in a sandbox that is then
99
+ * stopped, and every session forks from it.
100
+ *
101
+ * ```ts
102
+ * const sandbox = await createArchilNetworkSandboxSession({ ports: [4000] });
103
+ * const session = await agent.createSession({ sandbox });
104
+ * ```
105
+ */
106
+ declare function createArchilNetworkSandboxSession(options?: ArchilNetworkSandboxSessionCreateOptions): Promise<HarnessV1NetworkSandboxSession>;
107
+ /**
108
+ * Reattach to the sandbox named `sandboxId`, resuming it if it is paused or
109
+ * starting it if it is stopped. Ports are not stored on the sandbox, so pass
110
+ * the same `ports` the session was created with.
111
+ */
112
+ declare function resumeArchilNetworkSandboxSession(options: ArchilNetworkSandboxSessionResumeOptions): Promise<HarnessV1NetworkSandboxSession>;
113
+ /** Adapt a running Archil sandbox. The session's `stop()` and `destroy()` act on it. */
114
+ declare function createArchilNetworkSandboxSessionFromNativeSandbox(sandbox: Sandbox, options?: {
115
+ ports?: ReadonlyArray<number>;
116
+ }): Promise<HarnessV1NetworkSandboxSession>;
117
+ //#endregion
118
+ export { ArchilNetworkSandboxSession, ArchilNetworkSandboxSessionCreateOptions, ArchilNetworkSandboxSessionResumeOptions, createArchilNetworkSandboxSession, createArchilNetworkSandboxSessionFromNativeSandbox, resumeArchilNetworkSandboxSession };
package/dist/index.mjs ADDED
@@ -0,0 +1,413 @@
1
+ import { createHash } from "node:crypto";
2
+ import { HarnessCapabilityUnsupportedError, HarnessSandboxAuthenticationError } from "@ai-sdk/harness";
3
+ import { ArchilSandboxSession } from "@archildata/ai-sdk";
4
+ import { Archil } from "disk";
5
+ //#region src/network-policy.ts
6
+ const ARCHIL_PROVIDER_ID = "archil";
7
+ /**
8
+ * Archil egress rules match requests by host only, so each transformation
9
+ * applies to every request to its host. That grants the sandbox nothing it
10
+ * lacked: path, method, query, and header matchers all test request data the
11
+ * sandbox chooses, including the credential placeholder it was given, so it
12
+ * could always send a request that matches. The host is the only part of a
13
+ * rule that limits where a credential goes, and Archil enforces it.
14
+ */
15
+ function hostScopedTransformations(transformations) {
16
+ return transformations.map(({ match, transform }) => ({
17
+ match: { host: match.host },
18
+ transform: { headers: { ...transform.headers } }
19
+ }));
20
+ }
21
+ /**
22
+ * The complete Archil network policy for a harness policy plus the session's
23
+ * request transformations. `baseline` is the sandbox's policy before the
24
+ * session changed anything; it applies while no harness policy has been set.
25
+ *
26
+ * Archil applies the first allow rule matching a host, so each host's
27
+ * transformations merge into one rule placed ahead of the others, keeping any
28
+ * forwarding a baseline rule for that host had. A transformation is installed
29
+ * only for hosts the policy already reaches, because an Archil rule with a
30
+ * transform is also an allow rule.
31
+ */
32
+ function toArchilNetwork(baseline, policy, transformations) {
33
+ const base = policy === null ? baseline.egress ?? { default: "allow" } : {
34
+ ...policyEgress(policy),
35
+ ...baseline.egress?.drain_on_pause && { drain_on_pause: baseline.egress.drain_on_pause }
36
+ };
37
+ const headersByHost = /* @__PURE__ */ new Map();
38
+ for (const { match, transform } of transformations) {
39
+ const host = match.host.toLowerCase();
40
+ headersByHost.set(host, {
41
+ ...headersByHost.get(host),
42
+ ...transform.headers
43
+ });
44
+ }
45
+ const allow = [...base.allow ?? []];
46
+ const rules = [];
47
+ for (const [host, headers] of headersByHost) {
48
+ if (!reaches(base, host)) continue;
49
+ const index = allow.findIndex((entry) => typeof entry !== "string" && entry.target === host);
50
+ const existing = index >= 0 ? allow.splice(index, 1)[0] : void 0;
51
+ rules.push({
52
+ ...existing,
53
+ target: host,
54
+ transform: { headers: {
55
+ ...existing?.transform?.headers,
56
+ ...headers
57
+ } }
58
+ });
59
+ }
60
+ const egress = { ...base };
61
+ if (rules.length > 0 || allow.length > 0) egress.allow = [...rules, ...allow];
62
+ else delete egress.allow;
63
+ return { egress };
64
+ }
65
+ function policyEgress(policy) {
66
+ switch (policy.mode) {
67
+ case "allow-all": return { default: "allow" };
68
+ case "deny-all": return { default: "deny" };
69
+ case "custom": {
70
+ const allow = [...(policy.allowedHosts ?? []).map((host) => host.toLowerCase()), ...policy.allowedCIDRs ?? []];
71
+ const deny = [...policy.deniedCIDRs ?? []];
72
+ return {
73
+ default: "deny",
74
+ ...allow.length > 0 && { allow },
75
+ ...deny.length > 0 && { deny }
76
+ };
77
+ }
78
+ }
79
+ }
80
+ /** Whether `host` is allowed under `egress` before any transformation rules. */
81
+ function reaches(egress, host) {
82
+ if (egress.default === "allow") return true;
83
+ return (egress.allow ?? []).some((entry) => matchesDomain(typeof entry === "string" ? entry : entry.target, host));
84
+ }
85
+ function matchesDomain(pattern, host) {
86
+ const glob = (text) => text.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
87
+ const source = pattern.startsWith("*.") ? `.+\\.${glob(pattern.slice(2))}` : glob(pattern);
88
+ return new RegExp(`^${source}$`).test(host);
89
+ }
90
+ //#endregion
91
+ //#region src/network-sandbox-session.ts
92
+ const PORT_TOKEN_HEADER = "X-Archil-Token";
93
+ /**
94
+ * `HarnessV1NetworkSandboxSession` backed by an Archil sandbox. Its `id` is the
95
+ * sandbox name, which resume looks up.
96
+ *
97
+ * Ports are never exposed publicly: each endpoint carries a port token that
98
+ * Archil's proxy checks. `stop()` pauses the sandbox, keeping memory and
99
+ * processes for resume, and `destroy()` deletes it.
100
+ *
101
+ * Network policy and request transformations are unavailable on sandboxes
102
+ * with Archil's managed free-plan network policy, which cannot be changed, so
103
+ * harness adapters fall back to their own credential handling there.
104
+ */
105
+ var ArchilNetworkSandboxSession = class extends ArchilSandboxSession {
106
+ id;
107
+ defaultWorkingDirectory;
108
+ setNetworkPolicy;
109
+ setRequestTransformations;
110
+ addRequestTransformations;
111
+ advertisedPorts;
112
+ portTokens = /* @__PURE__ */ new Map();
113
+ baselineNetwork;
114
+ networkState = {
115
+ policy: null,
116
+ transformations: []
117
+ };
118
+ networkQueue = Promise.resolve();
119
+ stopped = false;
120
+ destroyed = false;
121
+ constructor(input) {
122
+ super(input.sandbox, { workingDirectory: input.workingDirectory });
123
+ this.id = input.sandbox.name;
124
+ this.defaultWorkingDirectory = input.workingDirectory;
125
+ this.advertisedPorts = [...input.ports];
126
+ this.baselineNetwork = input.network;
127
+ if (input.network.managed !== true) {
128
+ this.setNetworkPolicy = async (policy) => {
129
+ await this.updateNetwork((current) => ({
130
+ ...current,
131
+ policy
132
+ }));
133
+ };
134
+ this.setRequestTransformations = async (transformations) => {
135
+ const replacement = hostScopedTransformations(transformations);
136
+ await this.updateNetwork((current) => ({
137
+ ...current,
138
+ transformations: replacement
139
+ }));
140
+ };
141
+ this.addRequestTransformations = async (transformations) => {
142
+ const added = hostScopedTransformations(transformations);
143
+ await this.updateNetwork((current) => ({
144
+ ...current,
145
+ transformations: [...current.transformations, ...added]
146
+ }));
147
+ };
148
+ }
149
+ }
150
+ get ports() {
151
+ return this.advertisedPorts;
152
+ }
153
+ restricted() {
154
+ return new ArchilSandboxSession(this.sandbox, { workingDirectory: this.defaultWorkingDirectory });
155
+ }
156
+ /**
157
+ * Any port can be reached, not only the advertised ones. The first request
158
+ * for a port creates a non-expiring port token, which is reused for the
159
+ * life of this session object and revoked when the port is removed with
160
+ * `setPorts`.
161
+ */
162
+ getPortEndpoint = async ({ port, protocol = "https" }) => {
163
+ let token = this.portTokens.get(port);
164
+ if (token === void 0) {
165
+ token = this.sandbox.createPortToken(port);
166
+ this.portTokens.set(port, token);
167
+ token.catch(() => this.portTokens.delete(port));
168
+ }
169
+ const { hostname, token: secret } = await token;
170
+ return {
171
+ url: `${protocol === "ws" ? "wss" : "https"}://${hostname}`,
172
+ headers: { [PORT_TOKEN_HEADER]: secret }
173
+ };
174
+ };
175
+ /** @deprecated Use `getPortEndpoint`; Archil port endpoints need a token header a bare URL cannot carry. */
176
+ getPortUrl = async () => {
177
+ throw new HarnessCapabilityUnsupportedError({
178
+ harnessId: ARCHIL_PROVIDER_ID,
179
+ message: "Archil port endpoints require a token header; use getPortEndpoint instead of getPortUrl."
180
+ });
181
+ };
182
+ setPorts = async (ports, options) => {
183
+ options?.abortSignal?.throwIfAborted();
184
+ const kept = new Set(ports);
185
+ const revoked = [...this.portTokens].filter(([port]) => !kept.has(port));
186
+ for (const [port] of revoked) this.portTokens.delete(port);
187
+ this.advertisedPorts = [...ports];
188
+ await Promise.all(revoked.map(async ([, token]) => {
189
+ const created = await token.catch(() => void 0);
190
+ if (created) await this.sandbox.deletePortToken(created.id);
191
+ }));
192
+ };
193
+ stop = async () => {
194
+ if (this.stopped || this.destroyed) return;
195
+ try {
196
+ await this.sandbox.pause();
197
+ } catch (error) {
198
+ await this.sandbox.refresh();
199
+ if (this.sandbox.status !== "paused" && this.sandbox.status !== "stopped") throw error;
200
+ }
201
+ this.stopped = true;
202
+ };
203
+ destroy = async () => {
204
+ if (this.destroyed) return;
205
+ await deleteSandbox(this.sandbox);
206
+ this.destroyed = true;
207
+ };
208
+ updateNetwork(next) {
209
+ const run = this.networkQueue.then(async () => {
210
+ const state = next(this.networkState);
211
+ await this.sandbox.updateNetwork(toArchilNetwork(this.baselineNetwork, state.policy, state.transformations));
212
+ this.networkState = state;
213
+ });
214
+ this.networkQueue = run.catch(() => {});
215
+ return run;
216
+ }
217
+ };
218
+ /**
219
+ * Delete a sandbox in any state. Archil deletes only inactive sandboxes, so a
220
+ * live one is stopped first; one that is already gone counts as deleted.
221
+ */
222
+ async function deleteSandbox(sandbox) {
223
+ try {
224
+ await sandbox.refresh();
225
+ if (![
226
+ "stopped",
227
+ "exited",
228
+ "failed",
229
+ "deleting",
230
+ "deleted"
231
+ ].includes(sandbox.status)) await sandbox.stop();
232
+ await sandbox.delete();
233
+ } catch (error) {
234
+ if (error.status !== 404) throw error;
235
+ }
236
+ }
237
+ //#endregion
238
+ //#region src/index.ts
239
+ const TEMPLATE_VERSION = 1;
240
+ const TEMPLATE_POLL_MS = 2e3;
241
+ const TEMPLATE_WAIT_MS = 30 * 6e4;
242
+ /**
243
+ * Create an Archil sandbox for a harness session.
244
+ *
245
+ * `sandboxId` (or `name`) names the sandbox; resume finds it by that name.
246
+ * With a `template`, the template is prepared once in a sandbox that is then
247
+ * stopped, and every session forks from it.
248
+ *
249
+ * ```ts
250
+ * const sandbox = await createArchilNetworkSandboxSession({ ports: [4000] });
251
+ * const session = await agent.createSession({ sandbox });
252
+ * ```
253
+ */
254
+ async function createArchilNetworkSandboxSession(options = {}) {
255
+ const { client, ports, template, templateName, setupCommands = [], sandboxId, abortSignal, ...request } = options;
256
+ abortSignal?.throwIfAborted();
257
+ if (sandboxId !== void 0 && request.name !== void 0 && sandboxId !== request.name) throw new Error("createArchilNetworkSandboxSession: sandboxId and name must match when both are provided.");
258
+ const name = sandboxId ?? request.name;
259
+ request.env = {
260
+ IS_SANDBOX: "1",
261
+ ...request.env
262
+ };
263
+ return withAuthenticationError(async () => {
264
+ const archil = client ?? new Archil();
265
+ const sandbox = template === void 0 ? await archil.sandboxes.create({
266
+ ...request,
267
+ name
268
+ }) : await (await ensureTemplate({
269
+ archil,
270
+ request,
271
+ setupCommands,
272
+ template,
273
+ templateName,
274
+ abortSignal
275
+ })).fork({ name });
276
+ try {
277
+ if (template === void 0) await runSetupCommands(sandbox, setupCommands, abortSignal);
278
+ abortSignal?.throwIfAborted();
279
+ return await createArchilNetworkSandboxSessionFromNativeSandbox(sandbox, { ports });
280
+ } catch (error) {
281
+ await deleteSandbox(sandbox).catch(() => {});
282
+ throw error;
283
+ }
284
+ });
285
+ }
286
+ /**
287
+ * Reattach to the sandbox named `sandboxId`, resuming it if it is paused or
288
+ * starting it if it is stopped. Ports are not stored on the sandbox, so pass
289
+ * the same `ports` the session was created with.
290
+ */
291
+ async function resumeArchilNetworkSandboxSession(options) {
292
+ const { sandboxId, client, ports, abortSignal } = options;
293
+ abortSignal?.throwIfAborted();
294
+ return withAuthenticationError(async () => {
295
+ const [sandbox] = await (client ?? new Archil()).sandboxes.list({ name: sandboxId });
296
+ if (sandbox === void 0) throw new Error(`No Archil sandbox is named "${sandboxId}".`);
297
+ if (sandbox.status === "paused") await sandbox.resume();
298
+ else if (sandbox.status === "stopped") await sandbox.start();
299
+ else if (sandbox.status !== "running") throw new Error(`Archil sandbox "${sandboxId}" is ${sandbox.status} and cannot be resumed.`);
300
+ abortSignal?.throwIfAborted();
301
+ return createArchilNetworkSandboxSessionFromNativeSandbox(sandbox, { ports });
302
+ });
303
+ }
304
+ /** Adapt a running Archil sandbox. The session's `stop()` and `destroy()` act on it. */
305
+ async function createArchilNetworkSandboxSessionFromNativeSandbox(sandbox, options = {}) {
306
+ const [pwd, network] = await Promise.all([sandbox.exec("pwd"), sandbox.getNetwork()]);
307
+ const workingDirectory = pwd.stdout.trim();
308
+ if (pwd.exitCode !== 0 || !workingDirectory.startsWith("/")) throw new Error(`Could not read the sandbox working directory: ${pwd.stderr.trim() || pwd.status}`);
309
+ return new ArchilNetworkSandboxSession({
310
+ sandbox,
311
+ workingDirectory,
312
+ ports: options.ports ?? [],
313
+ network
314
+ });
315
+ }
316
+ /**
317
+ * Find or build the stopped sandbox holding a prepared template. Another
318
+ * process may be building it at the same time; whoever creates the name
319
+ * builds it and the others wait for it to stop.
320
+ */
321
+ async function ensureTemplate({ archil, request, setupCommands, template, templateName, abortSignal }) {
322
+ const { name: _name, ...settings } = request;
323
+ const digest = createHash("sha256").update(stableStringify([
324
+ TEMPLATE_VERSION,
325
+ template.identity,
326
+ settings,
327
+ setupCommands
328
+ ])).digest("hex");
329
+ const name = templateName ?? `ai-sdk-harness-v${TEMPLATE_VERSION}-${digest.slice(0, 24)}`;
330
+ const deadline = Date.now() + TEMPLATE_WAIT_MS;
331
+ for (;;) {
332
+ abortSignal?.throwIfAborted();
333
+ const [existing] = await archil.sandboxes.list({ name });
334
+ if (existing === void 0) {
335
+ let created;
336
+ try {
337
+ created = await archil.sandboxes.create({
338
+ ...settings,
339
+ name
340
+ });
341
+ } catch (error) {
342
+ if (error.status !== 409) throw error;
343
+ await waitForTemplate(name, deadline, abortSignal);
344
+ continue;
345
+ }
346
+ try {
347
+ await runSetupCommands(created, setupCommands, abortSignal);
348
+ await template.prepare({
349
+ session: new ArchilSandboxSession(created),
350
+ abortSignal
351
+ });
352
+ return await created.stop();
353
+ } catch (error) {
354
+ await deleteSandbox(created).catch(() => {});
355
+ throw error;
356
+ }
357
+ }
358
+ if (existing.status === "stopped") return existing;
359
+ if (![
360
+ "pending",
361
+ "running",
362
+ "stopping"
363
+ ].includes(existing.status)) throw new Error(`Template sandbox "${name}" is ${existing.status}; delete it to rebuild the template.`);
364
+ await waitForTemplate(name, deadline, abortSignal);
365
+ }
366
+ }
367
+ async function waitForTemplate(name, deadline, abortSignal) {
368
+ if (Date.now() > deadline) throw new Error(`Timed out waiting for template sandbox "${name}" to finish preparing.`);
369
+ await sleep(TEMPLATE_POLL_MS, abortSignal);
370
+ }
371
+ async function runSetupCommands(sandbox, commands, abortSignal) {
372
+ const session = new ArchilSandboxSession(sandbox);
373
+ for (const command of commands) {
374
+ const result = await session.run({
375
+ command,
376
+ abortSignal
377
+ });
378
+ if (result.exitCode !== 0) throw new Error(`Setup command failed with exit code ${result.exitCode}: ${command}\n${result.stderr.trim()}`);
379
+ }
380
+ }
381
+ async function withAuthenticationError(operation) {
382
+ try {
383
+ return await operation();
384
+ } catch (error) {
385
+ const status = error.status;
386
+ const missingKey = error instanceof Error && error.message.startsWith("Missing API key");
387
+ if (status === 401 || status === 403 || missingKey) throw new HarnessSandboxAuthenticationError({
388
+ message: `Archil could not authenticate: ${error.message}. Set ARCHIL_API_KEY and ARCHIL_REGION, or pass an Archil client as \`client\`.`,
389
+ sandboxProviderId: ARCHIL_PROVIDER_ID,
390
+ cause: error
391
+ });
392
+ throw error;
393
+ }
394
+ }
395
+ /** JSON with object keys sorted, so equal settings always hash the same. */
396
+ function stableStringify(value) {
397
+ return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item);
398
+ }
399
+ function sleep(ms, signal) {
400
+ return new Promise((resolve, reject) => {
401
+ const timer = setTimeout(() => {
402
+ signal?.removeEventListener("abort", onAbort);
403
+ resolve();
404
+ }, ms);
405
+ const onAbort = () => {
406
+ clearTimeout(timer);
407
+ reject(signal?.reason);
408
+ };
409
+ signal?.addEventListener("abort", onAbort, { once: true });
410
+ });
411
+ }
412
+ //#endregion
413
+ export { ArchilNetworkSandboxSession, createArchilNetworkSandboxSession, createArchilNetworkSandboxSessionFromNativeSandbox, resumeArchilNetworkSandboxSession };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "@archildata/ai-sdk-harness",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "Archil sandboxes for AI SDK harness agents",
5
+ "keywords": [
6
+ "archil",
7
+ "ai sdk",
8
+ "harness",
9
+ "agent",
10
+ "sandbox"
11
+ ],
12
+ "homepage": "https://archil.com",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "url": "https://github.com/archil-data/archil-sdk"
16
+ },
17
+ "type": "module",
18
+ "types": "dist/index.d.mts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.mts",
22
+ "import": "./dist/index.mjs"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "peerDependencies": {
31
+ "@ai-sdk/harness": "^1.0.196",
32
+ "@archildata/ai-sdk": "0.0.30",
33
+ "ai": "^7.0.184",
34
+ "disk": "1.16.0"
35
+ },
36
+ "devDependencies": {
37
+ "@ai-sdk/harness": "^1.0.196",
38
+ "@archildata/ai-sdk": "0.0.30",
39
+ "@types/node": "^20.19.43",
40
+ "ai": "^7.0.184",
41
+ "disk": "1.16.0",
42
+ "tsdown": "^0.22.3",
43
+ "typescript": "^6.0.3",
44
+ "vitest": "^4.1.9"
45
+ },
46
+ "engines": {
47
+ "node": ">= 22"
48
+ },
49
+ "scripts": {
50
+ "build": "tsdown",
51
+ "dev": "tsdown --watch",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run",
54
+ "release": "sh ../../scripts/release/npm.sh"
55
+ }
6
56
  }