@finalai/agent-provider 0.1.5 → 0.1.6
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/HOSTING.md +49 -9
- package/dist/modules/conformance/sandbox-kit.d.mts +8 -0
- package/dist/modules/conformance/sandbox-kit.mjs +160 -3
- package/dist/modules/conformance/sandbox-kit.mjs.map +2 -2
- package/dist/modules/harness.mjs +2 -1
- package/dist/modules/harness.mjs.map +2 -2
- package/dist/modules/sandbox/memory-sandbox.d.mts +1 -0
- package/dist/modules/sandbox/memory-sandbox.mjs +25 -10
- package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
- package/dist/modules/sandbox/memory-shell.d.mts +1 -0
- package/dist/modules/sandbox/memory-shell.mjs +14 -0
- package/dist/modules/sandbox/memory-shell.mjs.map +2 -2
- package/dist/modules/sandbox/types.d.mts +8 -1
- package/dist/modules/sandbox/types.mjs +32 -1
- package/dist/modules/sandbox/types.mjs.map +2 -2
- package/dist/modules/schemas.mjs +1 -1
- package/dist/modules/schemas.mjs.map +1 -1
- package/package.json +1 -1
package/HOSTING.md
CHANGED
|
@@ -21,6 +21,24 @@ Neither rewrites authored URLs. A GitHub-backed definition uses remote source;
|
|
|
21
21
|
push edits before explicitly publishing a ref. Caller API keys never become agent
|
|
22
22
|
credentials merely because they were used to publish.
|
|
23
23
|
|
|
24
|
+
## Hosted model resolution (SDK 0.2.0)
|
|
25
|
+
|
|
26
|
+
Hosted Final, Pi, Codex and Claude configurations accept string model references.
|
|
27
|
+
`serverless*ConfigSchema.parse(...).model` can be undefined: the host must choose
|
|
28
|
+
its catalog default, resolve aliases and validate availability before dispatch.
|
|
29
|
+
The host owns current candidates, runtime capabilities and dated prices, and
|
|
30
|
+
advertises picker choices through its harness descriptions. Compilation remains
|
|
31
|
+
offline and checks reference syntax.
|
|
32
|
+
|
|
33
|
+
SDK 0.2.0 removes `@finalai/agents/models` and
|
|
34
|
+
`@finalai/final-agent-provider/harnesses/models`, including their model arrays,
|
|
35
|
+
defaults, model-ID unions and pricing helpers. Migrate callers to string model
|
|
36
|
+
references and host-owned discovery, metadata and pricing.
|
|
37
|
+
|
|
38
|
+
Publish the SDK release before upgrading host dependencies. Ship the host's
|
|
39
|
+
catalog/default implementation together with its SDK dependency upgrade; a host
|
|
40
|
+
that only changes the dependency will lose the old default and catalog APIs.
|
|
41
|
+
|
|
24
42
|
## Hosted connections
|
|
25
43
|
|
|
26
44
|
```ts
|
|
@@ -99,15 +117,37 @@ export default defineFinalConnection({
|
|
|
99
117
|
});
|
|
100
118
|
```
|
|
101
119
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
120
|
+
With `load`, the host lists only the loaded tools and must keep every other exposed
|
|
121
|
+
tool reachable: it serves a search over the connection's remaining exposed tools
|
|
122
|
+
(name, description, input schema) and a call that runs a found tool by its real
|
|
123
|
+
name, with the same exposure and approval checks as a direct call. A host may
|
|
124
|
+
instead add a found tool to the list and send `notifications/tools/list_changed`;
|
|
125
|
+
harnesses that ignore that notification still need the call path. `load: []`
|
|
126
|
+
leaves every tool to search. Entries are tool names or `*` patterns.
|
|
127
|
+
`isToolLoaded` from `@finalai/agent-provider` applies the rule after exposure.
|
|
128
|
+
|
|
129
|
+
Without `load`, the harness lists the connection's exposed tools except:
|
|
130
|
+
|
|
131
|
+
- **Connector tools.** A server can label a tool with the connector it belongs to
|
|
132
|
+
in the tool's `_meta`:
|
|
133
|
+
`{ "ai.final/connector": { "namespace": "salesforce", "name": "Salesforce" } }`.
|
|
134
|
+
The namespace identifies the connector (unique within the server's tools); the
|
|
135
|
+
name is for display, and two connectors may share one. Final's server labels
|
|
136
|
+
every connector tool with the namespace and name of the install it comes from.
|
|
137
|
+
The host never lists labelled tools up front. Its search tool names each
|
|
138
|
+
connector and how many tools it has, so the agent knows what is connected
|
|
139
|
+
without any of those definitions in its context, and searches for the tools it
|
|
140
|
+
needs. A `load` entry that names a labelled tool still lists it.
|
|
141
|
+
- **Tools past a size limit.** When a connection exposes more unlabelled tools
|
|
142
|
+
than the host lists directly (100 in Final's host), those are searched too.
|
|
143
|
+
|
|
144
|
+
A harness that declares `supports.deferredToolSearch` defers and searches tools
|
|
145
|
+
itself, so the host lists every exposed tool to it and serves no search.
|
|
146
|
+
|
|
147
|
+
A host's search should name the connectors it covers and accept a connector's
|
|
148
|
+
namespace to narrow to. Once a host has listed its search and call tools, it keeps answering them for
|
|
149
|
+
that harness even if the connection stops hiding tools, unless the connection
|
|
150
|
+
then lists its own tool by one of those names.
|
|
111
151
|
|
|
112
152
|
## Selecting tools by annotation
|
|
113
153
|
|
|
@@ -11,6 +11,14 @@ export interface RunSandboxConformanceArgsIface {
|
|
|
11
11
|
viaWire?: boolean;
|
|
12
12
|
largeFileBytes?: number;
|
|
13
13
|
timeoutMs?: number;
|
|
14
|
+
platform?: SandboxPlatformConformanceIface;
|
|
15
|
+
}
|
|
16
|
+
export interface SandboxPlatformConformanceIface {
|
|
17
|
+
environmentOptions(args: {
|
|
18
|
+
env: Record<string, string>;
|
|
19
|
+
allow?: string[];
|
|
20
|
+
}): JsonValue;
|
|
21
|
+
observedAllowlist?(sandbox: NetworkSandboxSessionIface): Promise<readonly string[] | null>;
|
|
14
22
|
}
|
|
15
23
|
export interface SandboxConformanceReportIface {
|
|
16
24
|
passed: boolean;
|
|
@@ -182,8 +182,10 @@ const sandboxCases = (largeFileBytes) => [
|
|
|
182
182
|
}
|
|
183
183
|
}
|
|
184
184
|
];
|
|
185
|
-
const startFromProvider = async (args, provider) => {
|
|
186
|
-
const implementation = provider.definition.environment(
|
|
185
|
+
const startFromProvider = async (args, provider, overrides = {}) => {
|
|
186
|
+
const implementation = provider.definition.environment(
|
|
187
|
+
overrides.environmentOptions ?? args.environmentOptions
|
|
188
|
+
);
|
|
187
189
|
const prepareContext = {
|
|
188
190
|
files: {},
|
|
189
191
|
resources: {},
|
|
@@ -209,11 +211,151 @@ const startFromProvider = async (args, provider) => {
|
|
|
209
211
|
variables: noSandboxVariables,
|
|
210
212
|
repositories: noSandboxRepositories,
|
|
211
213
|
actingUser: noSandboxActingUser,
|
|
212
|
-
...args.startContext
|
|
214
|
+
...args.startContext,
|
|
215
|
+
...overrides.startContext
|
|
213
216
|
};
|
|
217
|
+
if (overrides.ownBinding === true) {
|
|
218
|
+
startContext.session = {
|
|
219
|
+
...startContext.session,
|
|
220
|
+
id: crypto.randomUUID(),
|
|
221
|
+
bindingId: crypto.randomUUID(),
|
|
222
|
+
conversationId: null
|
|
223
|
+
};
|
|
224
|
+
}
|
|
214
225
|
const { handle } = await implementation.start(startContext, args.openOptions, artifact);
|
|
215
226
|
return handle;
|
|
216
227
|
};
|
|
228
|
+
const PLATFORM_VARIABLE = "FINAL_CONFORMANCE_PLATFORM";
|
|
229
|
+
const SPEC_VARIABLE = "FINAL_CONFORMANCE_SPEC";
|
|
230
|
+
const SHARED_VARIABLE = "FINAL_CONFORMANCE_SHARED";
|
|
231
|
+
const SPEC_ENV = { [SPEC_VARIABLE]: "spec", [SHARED_VARIABLE]: "spec" };
|
|
232
|
+
const SPEC_ALLOW = ["conformance.example.com"];
|
|
233
|
+
const PLATFORM_EGRESS_HOSTS = ["egress.conformance.example.com"];
|
|
234
|
+
const variableIn = async (sandbox, name) => {
|
|
235
|
+
const process = await sandbox.spawn({ command: "printenv", args: [name] });
|
|
236
|
+
const [stdout, { exitCode }] = await Promise.all([
|
|
237
|
+
streamToString(process.stdout),
|
|
238
|
+
process.wait()
|
|
239
|
+
]);
|
|
240
|
+
return exitCode === 0 ? stdout.replace(/\n$/, "") : null;
|
|
241
|
+
};
|
|
242
|
+
const expectVariables = async (sandbox, expected) => {
|
|
243
|
+
for (const [name, value] of Object.entries(expected)) {
|
|
244
|
+
const actual = await variableIn(sandbox, name);
|
|
245
|
+
check(
|
|
246
|
+
actual === value,
|
|
247
|
+
`${name} is ${JSON.stringify(actual)}, expected ${JSON.stringify(value)}`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
const runPlatformCases = async (args) => {
|
|
252
|
+
const { kit, provider, platform, record } = args;
|
|
253
|
+
let platformValues = {
|
|
254
|
+
[PLATFORM_VARIABLE]: "first",
|
|
255
|
+
[SHARED_VARIABLE]: "platform"
|
|
256
|
+
};
|
|
257
|
+
const filePath = `/tmp/final-conformance-${crypto.randomUUID().slice(0, 8)}/platform/ca.pem`;
|
|
258
|
+
const order = [];
|
|
259
|
+
const withPlatform = { handle: null };
|
|
260
|
+
await record("platform environment: provider start", async () => {
|
|
261
|
+
withPlatform.handle = await startFromProvider(kit, provider, {
|
|
262
|
+
environmentOptions: platform.environmentOptions({ env: SPEC_ENV }),
|
|
263
|
+
startContext: {
|
|
264
|
+
platformFiles: async () => {
|
|
265
|
+
order.push("files");
|
|
266
|
+
return { [filePath]: "conformance CA\n" };
|
|
267
|
+
},
|
|
268
|
+
platformEnvironment: async () => {
|
|
269
|
+
order.push("environment");
|
|
270
|
+
return { ...platformValues };
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
ownBinding: true
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
const sandbox = withPlatform.handle?.sandbox;
|
|
277
|
+
if (sandbox != null) {
|
|
278
|
+
try {
|
|
279
|
+
await record("platform files: written before any process", async () => {
|
|
280
|
+
check(
|
|
281
|
+
order.indexOf("files") === 0,
|
|
282
|
+
`platformEnvironment was read before platformFiles: ${order.join(", ")}`
|
|
283
|
+
);
|
|
284
|
+
const content = await sandbox.readTextFile({ path: filePath });
|
|
285
|
+
check(content === "conformance CA\n", `${filePath} holds ${JSON.stringify(content)}`);
|
|
286
|
+
});
|
|
287
|
+
await record("platform environment: reaches spawned processes", async () => {
|
|
288
|
+
await expectVariables(sandbox, { [PLATFORM_VARIABLE]: "first" });
|
|
289
|
+
const run = await sandbox.run({ command: "printenv", args: [PLATFORM_VARIABLE] });
|
|
290
|
+
check(run.stdout === "first\n", `run saw ${JSON.stringify(run.stdout)}`);
|
|
291
|
+
});
|
|
292
|
+
await record("platform environment: read again for every process", async () => {
|
|
293
|
+
platformValues = { ...platformValues, [PLATFORM_VARIABLE]: "second" };
|
|
294
|
+
await expectVariables(sandbox, { [PLATFORM_VARIABLE]: "second" });
|
|
295
|
+
});
|
|
296
|
+
await record("platform environment: overrides the spec env", async () => {
|
|
297
|
+
await expectVariables(sandbox, { [SHARED_VARIABLE]: "platform", [SPEC_VARIABLE]: "spec" });
|
|
298
|
+
});
|
|
299
|
+
await record("platform environment: {} leaves the spec env", async () => {
|
|
300
|
+
platformValues = {};
|
|
301
|
+
await expectVariables(sandbox, {
|
|
302
|
+
[PLATFORM_VARIABLE]: null,
|
|
303
|
+
[SHARED_VARIABLE]: "spec",
|
|
304
|
+
[SPEC_VARIABLE]: "spec"
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
} finally {
|
|
308
|
+
await withPlatform.handle?.onSandboxDelete({ reason: "conformance" }).catch(() => void 0);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const withoutPlatform = { handle: null };
|
|
312
|
+
await record("platform environment: provider start without it", async () => {
|
|
313
|
+
withoutPlatform.handle = await startFromProvider(kit, provider, {
|
|
314
|
+
environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),
|
|
315
|
+
startContext: { platformEnvironment: void 0, platformEgressHosts: PLATFORM_EGRESS_HOSTS },
|
|
316
|
+
ownBinding: true
|
|
317
|
+
});
|
|
318
|
+
});
|
|
319
|
+
const plain = withoutPlatform.handle?.sandbox;
|
|
320
|
+
if (plain != null) {
|
|
321
|
+
try {
|
|
322
|
+
await record(
|
|
323
|
+
"platform environment: absent leaves the spec env",
|
|
324
|
+
() => expectVariables(plain, {
|
|
325
|
+
[PLATFORM_VARIABLE]: null,
|
|
326
|
+
[SHARED_VARIABLE]: "spec",
|
|
327
|
+
[SPEC_VARIABLE]: "spec"
|
|
328
|
+
})
|
|
329
|
+
);
|
|
330
|
+
const observe = platform.observedAllowlist;
|
|
331
|
+
if (observe == null) {
|
|
332
|
+
args.skip("platform egress hosts: appended to an allowlist", "no observedAllowlist");
|
|
333
|
+
} else {
|
|
334
|
+
await record("platform egress hosts: appended to an allowlist", async () => {
|
|
335
|
+
const allow = await observe(plain) ?? [];
|
|
336
|
+
for (const host of [...SPEC_ALLOW, ...PLATFORM_EGRESS_HOSTS])
|
|
337
|
+
check(allow.includes(host), `allowlist ${JSON.stringify(allow)} lacks ${host}`);
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
} finally {
|
|
341
|
+
await withoutPlatform.handle?.onSandboxDelete({ reason: "conformance" }).catch(() => void 0);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
await record("platform environment: reserved names refused", async () => {
|
|
345
|
+
const started = await startFromProvider(kit, provider, {
|
|
346
|
+
environmentOptions: platform.environmentOptions({
|
|
347
|
+
env: { HTTPS_PROXY: "http://spec.example.com" }
|
|
348
|
+
}),
|
|
349
|
+
ownBinding: true
|
|
350
|
+
}).then(
|
|
351
|
+
(handle) => handle,
|
|
352
|
+
() => null
|
|
353
|
+
);
|
|
354
|
+
if (started == null) return;
|
|
355
|
+
await started.onSandboxDelete({ reason: "conformance" }).catch(() => void 0);
|
|
356
|
+
throw new Error("a spec setting HTTPS_PROXY started");
|
|
357
|
+
});
|
|
358
|
+
};
|
|
217
359
|
const runSandboxConformance = async (args) => {
|
|
218
360
|
const timeoutMs = args.timeoutMs ?? 3e4;
|
|
219
361
|
const cases = [];
|
|
@@ -312,6 +454,21 @@ const runSandboxConformance = async (args) => {
|
|
|
312
454
|
}
|
|
313
455
|
await target.removePath({ path: root, recursive: true, force: true }).catch(() => void 0);
|
|
314
456
|
await started.handle?.onSandboxDelete({ reason: "conformance" }).catch(() => void 0);
|
|
457
|
+
if (args.platform != null && args.provider != null) {
|
|
458
|
+
await runPlatformCases({
|
|
459
|
+
kit: args,
|
|
460
|
+
provider: args.provider,
|
|
461
|
+
platform: args.platform,
|
|
462
|
+
record,
|
|
463
|
+
skip: (name, detail) => cases.push({
|
|
464
|
+
name,
|
|
465
|
+
status: ConformanceCaseStatus.Skipped,
|
|
466
|
+
durationMs: 0,
|
|
467
|
+
error: null,
|
|
468
|
+
detail
|
|
469
|
+
})
|
|
470
|
+
});
|
|
471
|
+
}
|
|
315
472
|
return { passed: cases.every((entry) => entry.status !== ConformanceCaseStatus.Failed), cases };
|
|
316
473
|
};
|
|
317
474
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/conformance/sandbox-kit.ts"],
|
|
4
|
-
"sourcesContent": ["import type { JsonValue } from \"../json.mjs\";\nimport { SandboxAccess } from \"../manifest.mjs\";\nimport { readAllBytes } from \"../sandbox/bytes.mjs\";\nimport { streamToString } from \"../sandbox/convenience.mjs\";\nimport { createInMemoryHandleNetwork } from \"../sandbox/testing.mjs\";\nimport {\n noSandboxActingUser,\n noSandboxGuides,\n noSandboxRepositories,\n noSandboxVariables,\n SandboxEntryType,\n type AnySandboxProviderIface,\n type NetworkSandboxSessionIface,\n type SandboxPrepareContextIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n} from \"../sandbox/types.mjs\";\nimport { HandleRpcErrorCode, isHandleRpcError } from \"../sandbox/wire.mjs\";\nimport { ConformanceCaseStatus, type ConformanceCaseResultIface } from \"./harness-kit.mjs\";\n\n// Sandbox conformance: files, streams with\n// multi-megabyte content, ranged reads, process I/O and kill, run directly on\n// the handle and again through the handle RPC (client and server over an\n// in-memory connection), plus the server's read-only access policy. Commands\n// used: echo, cat, sleep and `exit` under `shell: true`.\n\nexport interface RunSandboxConformanceArgsIface {\n // Either a started handle, or a provider the kit prepares and starts.\n handle?: NetworkSandboxSessionIface;\n provider?: AnySandboxProviderIface;\n environmentOptions?: JsonValue;\n openOptions?: JsonValue;\n prepareContext?: Partial<SandboxPrepareContextIface>;\n startContext?: Partial<SandboxStartContextIface>;\n // Also run the cases through the handle RPC (default true).\n viaWire?: boolean;\n largeFileBytes?: number;\n timeoutMs?: number;\n}\n\nexport interface SandboxConformanceReportIface {\n passed: boolean;\n cases: ConformanceCaseResultIface[];\n}\n\ninterface StartedProviderIface {\n handle: SandboxProviderHandleIface<NetworkSandboxSessionIface> | null;\n}\n\nconst check = (condition: boolean, message: string) => {\n if (!condition) throw new Error(message);\n};\n\nconst patternBytes = (size: number, seed: number): Uint8Array => {\n const bytes = new Uint8Array(size);\n let state = seed >>> 0;\n for (let i = 0; i < size; i += 1) {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n bytes[i] = state >>> 24;\n }\n return bytes;\n};\n\nconst chunked = (bytes: Uint8Array, chunk: number): ReadableStream<Uint8Array> => {\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= bytes.byteLength) {\n controller.close();\n return;\n }\n controller.enqueue(bytes.slice(offset, offset + chunk));\n offset += chunk;\n },\n });\n};\n\nconst sameBytes = (a: Uint8Array, b: Uint8Array) =>\n a.byteLength === b.byteLength && a.every((value, i) => value === b[i]);\n\nconst withTimeout = async <T>(promise: Promise<T>, ms: number, what: string): Promise<T> => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms} ms`)), ms);\n }),\n ]);\n } finally {\n if (timer != null) clearTimeout(timer);\n }\n};\n\ntype SandboxCase = {\n name: string;\n run: (sandbox: NetworkSandboxSessionIface, root: string) => Promise<string | void>;\n};\n\nconst sandboxCases = (largeFileBytes: number): SandboxCase[] => [\n {\n name: 'describe',\n run: async (sandbox) => {\n check(sandbox.id.length > 0, 'empty id');\n check(\n sandbox.defaultWorkingDirectory.startsWith('/'),\n 'defaultWorkingDirectory is not absolute',\n );\n check(\n sandbox.resolvePath('a/b') === `${sandbox.defaultWorkingDirectory.replace(/\\/$/, '')}/a/b`,\n 'resolvePath',\n );\n },\n },\n {\n name: 'text files',\n run: async (sandbox, root) => {\n const path = `${root}/nested/dir/a.txt`;\n await sandbox.writeTextFile({ path, content: 'first' });\n await sandbox.writeTextFile({ path, content: 'h\u00E9llo\\n' });\n check((await sandbox.readTextFile({ path })) === 'h\u00E9llo\\n', 'text round trip');\n check(\n (await sandbox.readTextFile({ path: `${root}/missing.txt` })) == null,\n 'missing text file is not null',\n );\n check(\n (await sandbox.readFile({ path: `${root}/missing.txt` })) == null,\n 'missing file stream is not null',\n );\n },\n },\n {\n name: 'ranged reads',\n run: async (sandbox, root) => {\n const path = `${root}/lines.txt`;\n await sandbox.writeTextFile({ path, content: 'l1\\nl2\\nl3\\nl4\\n' });\n check(\n (await sandbox.readTextFile({ path, startLine: 2, endLine: 3 })) === 'l2\\nl3\\n',\n 'lines 2-3',\n );\n check(\n (await sandbox.readTextFile({ path, startLine: 4, endLine: 99 })) === 'l4\\n',\n 'endLine past EOF',\n );\n },\n },\n {\n name: 'multi-megabyte streams',\n run: async (sandbox, root) => {\n const path = `${root}/large.bin`;\n const content = patternBytes(largeFileBytes, largeFileBytes);\n await sandbox.writeFile({ path, content: chunked(content, 300_000) });\n const stream = await sandbox.readFile({ path });\n check(stream != null, 'large file not found');\n if (stream == null) return;\n check(sameBytes(await readAllBytes(stream), content), 'streamed bytes differ');\n const binary = await sandbox.readBinaryFile({ path });\n check(binary != null && sameBytes(binary, content), 'readBinaryFile differs');\n const small = patternBytes(1000, 7);\n await sandbox.writeBinaryFile({ path: `${root}/small.bin`, content: small });\n const back = await sandbox.readBinaryFile({ path: `${root}/small.bin` });\n check(back != null && sameBytes(back, small), 'binary round trip');\n return `${largeFileBytes} bytes`;\n },\n },\n {\n name: 'stat, readDir, removePath',\n run: async (sandbox, root) => {\n await sandbox.writeTextFile({ path: `${root}/tree/x.txt`, content: 'xyz' });\n await sandbox.writeTextFile({ path: `${root}/tree/sub/y.txt`, content: 'y' });\n const stat = await sandbox.stat({ path: `${root}/tree/x.txt` });\n check(stat?.type === SandboxEntryType.File && stat.size === 3, 'file stat');\n check(\n (await sandbox.stat({ path: `${root}/tree` }))?.type === SandboxEntryType.Directory,\n 'directory stat',\n );\n check(\n (await sandbox.stat({ path: `${root}/tree/none` })) == null,\n 'missing stat is not null',\n );\n const names = (await sandbox.readDir({ path: `${root}/tree` }))\n .map((entry) => entry.name)\n .sort();\n check(\n JSON.stringify(names) === JSON.stringify(['sub', 'x.txt']),\n `readDir returned ${names.join(',')}`,\n );\n await sandbox.removePath({ path: `${root}/tree/none`, force: true });\n await sandbox.removePath({ path: `${root}/tree`, recursive: true });\n check(\n (await sandbox.stat({ path: `${root}/tree/x.txt` })) == null,\n 'recursive remove left files',\n );\n },\n },\n {\n name: 'process output and exit codes',\n run: async (sandbox) => {\n const echo = await sandbox.run({ command: 'echo', args: ['hello', 'world'] });\n check(\n echo.exitCode === 0 && echo.stdout === 'hello world\\n',\n `echo: ${JSON.stringify(echo)}`,\n );\n const shell = await sandbox.run({ command: 'echo out; echo err >&2; exit 3', shell: true });\n check(\n shell.exitCode === 3 && shell.stdout === 'out\\n' && shell.stderr === 'err\\n',\n `shell: ${JSON.stringify(shell)}`,\n );\n },\n },\n {\n name: 'process stdin',\n run: async (sandbox) => {\n const piped = await sandbox.run({ command: 'cat', stdin: 'from stdin' });\n check(piped.stdout === 'from stdin', `run stdin: ${JSON.stringify(piped)}`);\n const cat = await sandbox.spawn({ command: 'cat' });\n const output = streamToString(cat.stdout);\n await cat.write('a');\n await cat.write('b', { end: true });\n check((await output) === 'ab', 'spawned cat echoed wrong data');\n check((await cat.wait()).exitCode === 0, 'cat exit code');\n },\n },\n {\n name: 'process kill',\n run: async (sandbox) => {\n const sleeper = await sandbox.spawn({ command: 'sleep', args: ['30'] });\n await sleeper.kill();\n const result = await withTimeout(sleeper.wait(), 5_000, 'wait after kill');\n check(result.exitCode !== 0, 'killed process exited 0');\n },\n },\n];\n\nconst startFromProvider = async (\n args: RunSandboxConformanceArgsIface,\n provider: AnySandboxProviderIface,\n): Promise<SandboxProviderHandleIface<NetworkSandboxSessionIface>> => {\n const implementation = provider.definition.environment(args.environmentOptions);\n const prepareContext: SandboxPrepareContextIface = {\n files: {},\n resources: {},\n sourceRevision: 'conformance',\n storagePath: '/tmp/final-conformance',\n organizationId: 'conformance',\n guides: noSandboxGuides,\n actingUser: noSandboxActingUser,\n ...args.prepareContext,\n };\n const artifact = await implementation.prepare(prepareContext);\n const startContext: SandboxStartContextIface = {\n session: {\n id: crypto.randomUUID(),\n organizationId: 'conformance',\n conversationId: null,\n definitionId: 'conformance',\n bindingId: crypto.randomUUID(),\n target: 'conformance',\n },\n storagePath: '/tmp/final-conformance',\n guides: noSandboxGuides,\n variables: noSandboxVariables,\n repositories: noSandboxRepositories,\n actingUser: noSandboxActingUser,\n ...args.startContext,\n };\n const { handle } = await implementation.start(startContext, args.openOptions, artifact);\n return handle;\n};\n\nexport const runSandboxConformance = async (\n args: RunSandboxConformanceArgsIface,\n): Promise<SandboxConformanceReportIface> => {\n const timeoutMs = args.timeoutMs ?? 30_000;\n const cases: ConformanceCaseResultIface[] = [];\n const record = async (name: string, run: () => Promise<string | void>) => {\n const started = Date.now();\n try {\n const detail = await withTimeout(run(), timeoutMs, name);\n cases.push({\n name,\n status: ConformanceCaseStatus.Passed,\n durationMs: Date.now() - started,\n error: null,\n detail: detail ?? null,\n });\n } catch (error) {\n cases.push({\n name,\n status: ConformanceCaseStatus.Failed,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n detail: null,\n });\n }\n };\n\n // A holder, so the assignment inside the closure is visible to the narrowing.\n const started: StartedProviderIface = { handle: null };\n let sandbox = args.handle ?? null;\n if (sandbox == null) {\n if (args.provider == null)\n throw new Error('runSandboxConformance needs a handle or a provider');\n const provider = args.provider;\n await record('provider start', async () => {\n started.handle = await startFromProvider(args, provider);\n });\n sandbox = started.handle?.sandbox ?? null;\n }\n if (sandbox == null) return { passed: false, cases };\n const target = sandbox;\n\n const root = target.resolvePath(`conformance-${crypto.randomUUID().slice(0, 8)}`);\n const list = sandboxCases(args.largeFileBytes ?? 5 * 1024 * 1024);\n for (const entry of list) await record(entry.name, () => entry.run(target, root));\n\n if (args.viaWire !== false) {\n const network = createInMemoryHandleNetwork();\n network.serve({ url: 'mem://conformance', sandbox: target });\n network.serve({\n url: 'mem://conformance-read',\n sandbox: target,\n access: { mode: SandboxAccess.Read, lifecycle: false },\n });\n const client = await network.connect({ url: 'mem://conformance', token: 'conformance' });\n try {\n const wireRoot = `${root}-wire`;\n for (const entry of list)\n await record(`handle rpc: ${entry.name}`, () => entry.run(client, wireRoot));\n await record('handle rpc: read-only access policy', async () => {\n const readOnly = await network.connect({\n url: 'mem://conformance-read',\n token: 'conformance',\n });\n try {\n await target.writeTextFile({ path: `${root}/ro.txt`, content: 'visible' });\n check(\n (await readOnly.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'read failed on a read binding',\n );\n const attempts: [string, Promise<unknown>][] = [\n [\n 'writeTextFile',\n readOnly.writeTextFile({ path: `${root}/ro.txt`, content: 'changed' }),\n ],\n ['run', readOnly.run({ command: 'echo' })],\n ['spawn', readOnly.spawn({ command: 'echo' })],\n ['removePath', readOnly.removePath({ path: `${root}/ro.txt` })],\n ];\n for (const [what, attempt] of attempts) {\n const error = await attempt.then(\n () => null,\n (cause: unknown) => cause,\n );\n check(\n isHandleRpcError(error) && error.code === HandleRpcErrorCode.Forbidden,\n `${what} was not rejected`,\n );\n }\n check(\n (await target.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'a read binding changed the file',\n );\n } finally {\n readOnly.close();\n }\n });\n } finally {\n client.close();\n await target\n .removePath({ path: `${root}-wire`, recursive: true, force: true })\n .catch(() => undefined);\n }\n }\n\n await target.removePath({ path: root, recursive: true, force: true }).catch(() => undefined);\n await started.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n return { passed: cases.every((entry) => entry.status !== Con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AAI,EAAE,SAAS,OAAO,CAAC,CAAC;AAAA,YACzC,CAAC,SAAS,SAAS,MAAM,EAAE,SAAS,OAAO,CAAC,CAAC;AAAA,YAC7C,CAAC,cAAc,SAAS,WAAW,EAAE,MAAM,GAAG,IAAI,UAAU,CAAC,CAAC;AAAA,UAChE;AACA,qBAAW,CAAC,MAAM,OAAO,KAAK,UAAU;AACtC,kBAAM,QAAQ,MAAM,QAAQ;AAAA,cAC1B,MAAM;AAAA,cACN,CAAC,UAAmB;AAAA,YACtB;AACA;AAAA,cACE,iBAAiB,KAAK,KAAK,MAAM,SAAS,mBAAmB;AAAA,cAC7D,GAAG,IAAI;AAAA,YACT;AAAA,UACF;AACA;AAAA,YACG,MAAM,OAAO,aAAa,EAAE,MAAM,GAAG,IAAI,UAAU,CAAC,MAAO;AAAA,YAC5D;AAAA,UACF;AAAA,QACF,UAAE;AACA,mBAAS,MAAM;AAAA,QACjB;AAAA,MACF,CAAC;AAAA,IACH,UAAE;AACA,aAAO,MAAM;AACb,YAAM,OACH,WAAW,EAAE,MAAM,GAAG,IAAI,SAAS,WAAW,MAAM,OAAO,KAAK,CAAC,EACjE,MAAM,MAAM,MAAS;AAAA,IAC1B;AAAA,EACF;AAEA,QAAM,OAAO,WAAW,EAAE,MAAM,MAAM,WAAW,MAAM,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AAC3F,QAAM,QAAQ,QAAQ,gBAAgB,EAAE,QAAQ,cAAc,CAAC,EAAE,MAAM,MAAM,MAAS;AACtF,SAAO,EAAE,QAAQ,MAAM,MAAM,CAAC,UAAU,MAAM,WAAW,sBAAsB,MAAM,GAAG,MAAM;AAChG;",
|
|
4
|
+
"sourcesContent": ["import type { JsonValue } from \"../json.mjs\";\nimport { SandboxAccess } from \"../manifest.mjs\";\nimport { readAllBytes } from \"../sandbox/bytes.mjs\";\nimport { streamToString } from \"../sandbox/convenience.mjs\";\nimport { createInMemoryHandleNetwork } from \"../sandbox/testing.mjs\";\nimport {\n noSandboxActingUser,\n noSandboxGuides,\n noSandboxRepositories,\n noSandboxVariables,\n SandboxEntryType,\n type AnySandboxProviderIface,\n type NetworkSandboxSessionIface,\n type SandboxPrepareContextIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n} from \"../sandbox/types.mjs\";\nimport { HandleRpcErrorCode, isHandleRpcError } from \"../sandbox/wire.mjs\";\nimport { ConformanceCaseStatus, type ConformanceCaseResultIface } from \"./harness-kit.mjs\";\n\n// Sandbox conformance: files, streams with\n// multi-megabyte content, ranged reads, process I/O and kill, run directly on\n// the handle and again through the handle RPC (client and server over an\n// in-memory connection), plus the server's read-only access policy. Commands\n// used: echo, cat, sleep and `exit` under `shell: true`, and printenv for the\n// platform environment cases.\n\nexport interface RunSandboxConformanceArgsIface {\n // Either a started handle, or a provider the kit prepares and starts.\n handle?: NetworkSandboxSessionIface;\n provider?: AnySandboxProviderIface;\n environmentOptions?: JsonValue;\n openOptions?: JsonValue;\n prepareContext?: Partial<SandboxPrepareContextIface>;\n startContext?: Partial<SandboxStartContextIface>;\n // Also run the cases through the handle RPC (default true).\n viaWire?: boolean;\n largeFileBytes?: number;\n timeoutMs?: number;\n // Also run the platform environment cases, on sandboxes of their own (needs `provider`).\n platform?: SandboxPlatformConformanceIface;\n}\n\n// How the platform environment cases declare a spec for the provider under test.\nexport interface SandboxPlatformConformanceIface {\n // Environment options whose spec sets `env` as plain variables for every\n // process and, when `allow` is given, an allowlist egress policy of those hosts.\n environmentOptions(args: { env: Record<string, string>; allow?: string[] }): JsonValue;\n // The allowlist the provider gave its backend for this sandbox. Absent: the\n // egress hosts case is skipped.\n observedAllowlist?(sandbox: NetworkSandboxSessionIface): Promise<readonly string[] | null>;\n}\n\nexport interface SandboxConformanceReportIface {\n passed: boolean;\n cases: ConformanceCaseResultIface[];\n}\n\ninterface StartedProviderIface {\n handle: SandboxProviderHandleIface<NetworkSandboxSessionIface> | null;\n}\n\nconst check = (condition: boolean, message: string) => {\n if (!condition) throw new Error(message);\n};\n\nconst patternBytes = (size: number, seed: number): Uint8Array => {\n const bytes = new Uint8Array(size);\n let state = seed >>> 0;\n for (let i = 0; i < size; i += 1) {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n bytes[i] = state >>> 24;\n }\n return bytes;\n};\n\nconst chunked = (bytes: Uint8Array, chunk: number): ReadableStream<Uint8Array> => {\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= bytes.byteLength) {\n controller.close();\n return;\n }\n controller.enqueue(bytes.slice(offset, offset + chunk));\n offset += chunk;\n },\n });\n};\n\nconst sameBytes = (a: Uint8Array, b: Uint8Array) =>\n a.byteLength === b.byteLength && a.every((value, i) => value === b[i]);\n\nconst withTimeout = async <T>(promise: Promise<T>, ms: number, what: string): Promise<T> => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms} ms`)), ms);\n }),\n ]);\n } finally {\n if (timer != null) clearTimeout(timer);\n }\n};\n\ntype SandboxCase = {\n name: string;\n run: (sandbox: NetworkSandboxSessionIface, root: string) => Promise<string | void>;\n};\n\nconst sandboxCases = (largeFileBytes: number): SandboxCase[] => [\n {\n name: 'describe',\n run: async (sandbox) => {\n check(sandbox.id.length > 0, 'empty id');\n check(\n sandbox.defaultWorkingDirectory.startsWith('/'),\n 'defaultWorkingDirectory is not absolute',\n );\n check(\n sandbox.resolvePath('a/b') === `${sandbox.defaultWorkingDirectory.replace(/\\/$/, '')}/a/b`,\n 'resolvePath',\n );\n },\n },\n {\n name: 'text files',\n run: async (sandbox, root) => {\n const path = `${root}/nested/dir/a.txt`;\n await sandbox.writeTextFile({ path, content: 'first' });\n await sandbox.writeTextFile({ path, content: 'h\u00E9llo\\n' });\n check((await sandbox.readTextFile({ path })) === 'h\u00E9llo\\n', 'text round trip');\n check(\n (await sandbox.readTextFile({ path: `${root}/missing.txt` })) == null,\n 'missing text file is not null',\n );\n check(\n (await sandbox.readFile({ path: `${root}/missing.txt` })) == null,\n 'missing file stream is not null',\n );\n },\n },\n {\n name: 'ranged reads',\n run: async (sandbox, root) => {\n const path = `${root}/lines.txt`;\n await sandbox.writeTextFile({ path, content: 'l1\\nl2\\nl3\\nl4\\n' });\n check(\n (await sandbox.readTextFile({ path, startLine: 2, endLine: 3 })) === 'l2\\nl3\\n',\n 'lines 2-3',\n );\n check(\n (await sandbox.readTextFile({ path, startLine: 4, endLine: 99 })) === 'l4\\n',\n 'endLine past EOF',\n );\n },\n },\n {\n name: 'multi-megabyte streams',\n run: async (sandbox, root) => {\n const path = `${root}/large.bin`;\n const content = patternBytes(largeFileBytes, largeFileBytes);\n await sandbox.writeFile({ path, content: chunked(content, 300_000) });\n const stream = await sandbox.readFile({ path });\n check(stream != null, 'large file not found');\n if (stream == null) return;\n check(sameBytes(await readAllBytes(stream), content), 'streamed bytes differ');\n const binary = await sandbox.readBinaryFile({ path });\n check(binary != null && sameBytes(binary, content), 'readBinaryFile differs');\n const small = patternBytes(1000, 7);\n await sandbox.writeBinaryFile({ path: `${root}/small.bin`, content: small });\n const back = await sandbox.readBinaryFile({ path: `${root}/small.bin` });\n check(back != null && sameBytes(back, small), 'binary round trip');\n return `${largeFileBytes} bytes`;\n },\n },\n {\n name: 'stat, readDir, removePath',\n run: async (sandbox, root) => {\n await sandbox.writeTextFile({ path: `${root}/tree/x.txt`, content: 'xyz' });\n await sandbox.writeTextFile({ path: `${root}/tree/sub/y.txt`, content: 'y' });\n const stat = await sandbox.stat({ path: `${root}/tree/x.txt` });\n check(stat?.type === SandboxEntryType.File && stat.size === 3, 'file stat');\n check(\n (await sandbox.stat({ path: `${root}/tree` }))?.type === SandboxEntryType.Directory,\n 'directory stat',\n );\n check(\n (await sandbox.stat({ path: `${root}/tree/none` })) == null,\n 'missing stat is not null',\n );\n const names = (await sandbox.readDir({ path: `${root}/tree` }))\n .map((entry) => entry.name)\n .sort();\n check(\n JSON.stringify(names) === JSON.stringify(['sub', 'x.txt']),\n `readDir returned ${names.join(',')}`,\n );\n await sandbox.removePath({ path: `${root}/tree/none`, force: true });\n await sandbox.removePath({ path: `${root}/tree`, recursive: true });\n check(\n (await sandbox.stat({ path: `${root}/tree/x.txt` })) == null,\n 'recursive remove left files',\n );\n },\n },\n {\n name: 'process output and exit codes',\n run: async (sandbox) => {\n const echo = await sandbox.run({ command: 'echo', args: ['hello', 'world'] });\n check(\n echo.exitCode === 0 && echo.stdout === 'hello world\\n',\n `echo: ${JSON.stringify(echo)}`,\n );\n const shell = await sandbox.run({ command: 'echo out; echo err >&2; exit 3', shell: true });\n check(\n shell.exitCode === 3 && shell.stdout === 'out\\n' && shell.stderr === 'err\\n',\n `shell: ${JSON.stringify(shell)}`,\n );\n },\n },\n {\n name: 'process stdin',\n run: async (sandbox) => {\n const piped = await sandbox.run({ command: 'cat', stdin: 'from stdin' });\n check(piped.stdout === 'from stdin', `run stdin: ${JSON.stringify(piped)}`);\n const cat = await sandbox.spawn({ command: 'cat' });\n const output = streamToString(cat.stdout);\n await cat.write('a');\n await cat.write('b', { end: true });\n check((await output) === 'ab', 'spawned cat echoed wrong data');\n check((await cat.wait()).exitCode === 0, 'cat exit code');\n },\n },\n {\n name: 'process kill',\n run: async (sandbox) => {\n const sleeper = await sandbox.spawn({ command: 'sleep', args: ['30'] });\n await sleeper.kill();\n const result = await withTimeout(sleeper.wait(), 5_000, 'wait after kill');\n check(result.exitCode !== 0, 'killed process exited 0');\n },\n },\n];\n\nconst startFromProvider = async (\n args: RunSandboxConformanceArgsIface,\n provider: AnySandboxProviderIface,\n overrides: {\n environmentOptions?: JsonValue;\n startContext?: Partial<SandboxStartContextIface>;\n // A binding (and so a sandbox) of its own, whatever session the caller's context names.\n ownBinding?: boolean;\n } = {},\n): Promise<SandboxProviderHandleIface<NetworkSandboxSessionIface>> => {\n const implementation = provider.definition.environment(\n overrides.environmentOptions ?? args.environmentOptions,\n );\n const prepareContext: SandboxPrepareContextIface = {\n files: {},\n resources: {},\n sourceRevision: 'conformance',\n storagePath: '/tmp/final-conformance',\n organizationId: 'conformance',\n guides: noSandboxGuides,\n actingUser: noSandboxActingUser,\n ...args.prepareContext,\n };\n const artifact = await implementation.prepare(prepareContext);\n const startContext: SandboxStartContextIface = {\n session: {\n id: crypto.randomUUID(),\n organizationId: 'conformance',\n conversationId: null,\n definitionId: 'conformance',\n bindingId: crypto.randomUUID(),\n target: 'conformance',\n },\n storagePath: '/tmp/final-conformance',\n guides: noSandboxGuides,\n variables: noSandboxVariables,\n repositories: noSandboxRepositories,\n actingUser: noSandboxActingUser,\n ...args.startContext,\n ...overrides.startContext,\n };\n if (overrides.ownBinding === true) {\n startContext.session = {\n ...startContext.session,\n id: crypto.randomUUID(),\n bindingId: crypto.randomUUID(),\n conversationId: null,\n };\n }\n const { handle } = await implementation.start(startContext, args.openOptions, artifact);\n return handle;\n};\n\nconst PLATFORM_VARIABLE = 'FINAL_CONFORMANCE_PLATFORM';\nconst SPEC_VARIABLE = 'FINAL_CONFORMANCE_SPEC';\nconst SHARED_VARIABLE = 'FINAL_CONFORMANCE_SHARED';\nconst SPEC_ENV = { [SPEC_VARIABLE]: 'spec', [SHARED_VARIABLE]: 'spec' };\nconst SPEC_ALLOW = ['conformance.example.com'];\nconst PLATFORM_EGRESS_HOSTS = ['egress.conformance.example.com'];\n\n// A variable as a spawned process sees it; null when unset.\nconst variableIn = async (\n sandbox: NetworkSandboxSessionIface,\n name: string,\n): Promise<string | null> => {\n const process = await sandbox.spawn({ command: 'printenv', args: [name] });\n const [stdout, { exitCode }] = await Promise.all([\n streamToString(process.stdout),\n process.wait(),\n ]);\n return exitCode === 0 ? stdout.replace(/\\n$/, '') : null;\n};\n\nconst expectVariables = async (\n sandbox: NetworkSandboxSessionIface,\n expected: Record<string, string | null>,\n) => {\n for (const [name, value] of Object.entries(expected)) {\n const actual = await variableIn(sandbox, name);\n check(\n actual === value,\n `${name} is ${JSON.stringify(actual)}, expected ${JSON.stringify(value)}`,\n );\n }\n};\n\ntype RecordCase = (name: string, run: () => Promise<string | void>) => Promise<void>;\n\n// The start context's platformFiles are written before any process runs;\n// platformEnvironment reaches every process, read again for each one and over\n// the spec's env; platformEgressHosts join an allowlist;\n// a spec naming a platform variable is refused.\nconst runPlatformCases = async (args: {\n kit: RunSandboxConformanceArgsIface;\n provider: AnySandboxProviderIface;\n platform: SandboxPlatformConformanceIface;\n record: RecordCase;\n skip: (name: string, detail: string) => void;\n}) => {\n const { kit, provider, platform, record } = args;\n let platformValues: Record<string, string> = {\n [PLATFORM_VARIABLE]: 'first',\n [SHARED_VARIABLE]: 'platform',\n };\n const filePath = `/tmp/final-conformance-${crypto.randomUUID().slice(0, 8)}/platform/ca.pem`;\n const order: string[] = [];\n const withPlatform: StartedProviderIface = { handle: null };\n await record('platform environment: provider start', async () => {\n withPlatform.handle = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV }),\n startContext: {\n platformFiles: async () => {\n order.push('files');\n return { [filePath]: 'conformance CA\\n' };\n },\n platformEnvironment: async () => {\n order.push('environment');\n return { ...platformValues };\n },\n },\n ownBinding: true,\n });\n });\n const sandbox = withPlatform.handle?.sandbox;\n if (sandbox != null) {\n try {\n await record('platform files: written before any process', async () => {\n check(\n order.indexOf('files') === 0,\n `platformEnvironment was read before platformFiles: ${order.join(', ')}`,\n );\n const content = await sandbox.readTextFile({ path: filePath });\n check(content === 'conformance CA\\n', `${filePath} holds ${JSON.stringify(content)}`);\n });\n await record('platform environment: reaches spawned processes', async () => {\n await expectVariables(sandbox, { [PLATFORM_VARIABLE]: 'first' });\n const run = await sandbox.run({ command: 'printenv', args: [PLATFORM_VARIABLE] });\n check(run.stdout === 'first\\n', `run saw ${JSON.stringify(run.stdout)}`);\n });\n await record('platform environment: read again for every process', async () => {\n platformValues = { ...platformValues, [PLATFORM_VARIABLE]: 'second' };\n await expectVariables(sandbox, { [PLATFORM_VARIABLE]: 'second' });\n });\n await record('platform environment: overrides the spec env', async () => {\n await expectVariables(sandbox, { [SHARED_VARIABLE]: 'platform', [SPEC_VARIABLE]: 'spec' });\n });\n await record('platform environment: {} leaves the spec env', async () => {\n platformValues = {};\n await expectVariables(sandbox, {\n [PLATFORM_VARIABLE]: null,\n [SHARED_VARIABLE]: 'spec',\n [SPEC_VARIABLE]: 'spec',\n });\n });\n } finally {\n await withPlatform.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n }\n }\n\n const withoutPlatform: StartedProviderIface = { handle: null };\n await record('platform environment: provider start without it', async () => {\n withoutPlatform.handle = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),\n startContext: { platformEnvironment: undefined, platformEgressHosts: PLATFORM_EGRESS_HOSTS },\n ownBinding: true,\n });\n });\n const plain = withoutPlatform.handle?.sandbox;\n if (plain != null) {\n try {\n await record('platform environment: absent leaves the spec env', () =>\n expectVariables(plain, {\n [PLATFORM_VARIABLE]: null,\n [SHARED_VARIABLE]: 'spec',\n [SPEC_VARIABLE]: 'spec',\n }),\n );\n const observe = platform.observedAllowlist;\n if (observe == null) {\n args.skip('platform egress hosts: appended to an allowlist', 'no observedAllowlist');\n } else {\n await record('platform egress hosts: appended to an allowlist', async () => {\n const allow = (await observe(plain)) ?? [];\n for (const host of [...SPEC_ALLOW, ...PLATFORM_EGRESS_HOSTS])\n check(allow.includes(host), `allowlist ${JSON.stringify(allow)} lacks ${host}`);\n });\n }\n } finally {\n await withoutPlatform.handle\n ?.onSandboxDelete({ reason: 'conformance' })\n .catch(() => undefined);\n }\n }\n\n await record('platform environment: reserved names refused', async () => {\n const started = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({\n env: { HTTPS_PROXY: 'http://spec.example.com' },\n }),\n ownBinding: true,\n }).then(\n (handle) => handle,\n () => null,\n );\n if (started == null) return;\n await started.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n throw new Error('a spec setting HTTPS_PROXY started');\n });\n};\n\nexport const runSandboxConformance = async (\n args: RunSandboxConformanceArgsIface,\n): Promise<SandboxConformanceReportIface> => {\n const timeoutMs = args.timeoutMs ?? 30_000;\n const cases: ConformanceCaseResultIface[] = [];\n const record: RecordCase = async (name, run) => {\n const started = Date.now();\n try {\n const detail = await withTimeout(run(), timeoutMs, name);\n cases.push({\n name,\n status: ConformanceCaseStatus.Passed,\n durationMs: Date.now() - started,\n error: null,\n detail: detail ?? null,\n });\n } catch (error) {\n cases.push({\n name,\n status: ConformanceCaseStatus.Failed,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n detail: null,\n });\n }\n };\n\n // A holder, so the assignment inside the closure is visible to the narrowing.\n const started: StartedProviderIface = { handle: null };\n let sandbox = args.handle ?? null;\n if (sandbox == null) {\n if (args.provider == null)\n throw new Error('runSandboxConformance needs a handle or a provider');\n const provider = args.provider;\n await record('provider start', async () => {\n started.handle = await startFromProvider(args, provider);\n });\n sandbox = started.handle?.sandbox ?? null;\n }\n if (sandbox == null) return { passed: false, cases };\n const target = sandbox;\n\n const root = target.resolvePath(`conformance-${crypto.randomUUID().slice(0, 8)}`);\n const list = sandboxCases(args.largeFileBytes ?? 5 * 1024 * 1024);\n for (const entry of list) await record(entry.name, () => entry.run(target, root));\n\n if (args.viaWire !== false) {\n const network = createInMemoryHandleNetwork();\n network.serve({ url: 'mem://conformance', sandbox: target });\n network.serve({\n url: 'mem://conformance-read',\n sandbox: target,\n access: { mode: SandboxAccess.Read, lifecycle: false },\n });\n const client = await network.connect({ url: 'mem://conformance', token: 'conformance' });\n try {\n const wireRoot = `${root}-wire`;\n for (const entry of list)\n await record(`handle rpc: ${entry.name}`, () => entry.run(client, wireRoot));\n await record('handle rpc: read-only access policy', async () => {\n const readOnly = await network.connect({\n url: 'mem://conformance-read',\n token: 'conformance',\n });\n try {\n await target.writeTextFile({ path: `${root}/ro.txt`, content: 'visible' });\n check(\n (await readOnly.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'read failed on a read binding',\n );\n const attempts: [string, Promise<unknown>][] = [\n [\n 'writeTextFile',\n readOnly.writeTextFile({ path: `${root}/ro.txt`, content: 'changed' }),\n ],\n ['run', readOnly.run({ command: 'echo' })],\n ['spawn', readOnly.spawn({ command: 'echo' })],\n ['removePath', readOnly.removePath({ path: `${root}/ro.txt` })],\n ];\n for (const [what, attempt] of attempts) {\n const error = await attempt.then(\n () => null,\n (cause: unknown) => cause,\n );\n check(\n isHandleRpcError(error) && error.code === HandleRpcErrorCode.Forbidden,\n `${what} was not rejected`,\n );\n }\n check(\n (await target.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'a read binding changed the file',\n );\n } finally {\n readOnly.close();\n }\n });\n } finally {\n client.close();\n await target\n .removePath({ path: `${root}-wire`, recursive: true, force: true })\n .catch(() => undefined);\n }\n }\n\n await target.removePath({ path: root, recursive: true, force: true }).catch(() => undefined);\n await started.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n\n if (args.platform != null && args.provider != null) {\n await runPlatformCases({\n kit: args,\n provider: args.provider,\n platform: args.platform,\n record,\n skip: (name, detail) =>\n cases.push({\n name,\n status: ConformanceCaseStatus.Skipped,\n durationMs: 0,\n error: null,\n detail,\n }),\n });\n }\n return { passed: cases.every((entry) => entry.status !== ConformanceCaseStatus.Failed), cases };\n};\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,mCAAmC;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AACP,SAAS,oBAAoB,wBAAwB;AACrD,SAAS,6BAA8D;AA4CvE,MAAM,QAAQ,CAAC,WAAoB,YAAoB;AACrD,MAAI,CAAC,UAAW,OAAM,IAAI,MAAM,OAAO;AACzC;AAEA,MAAM,eAAe,CAAC,MAAc,SAA6B;AAC/D,QAAM,QAAQ,IAAI,WAAW,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MAAS;AAC3F,QAAM,QAAQ,QAAQ,gBAAgB,EAAE,QAAQ,cAAc,CAAC,EAAE,MAAM,MAAM,MAAS;AAEtF,MAAI,KAAK,YAAY,QAAQ,KAAK,YAAY,MAAM;AAClD,UAAM,iBAAiB;AAAA,MACrB,KAAK;AAAA,MACL,UAAU,KAAK;AAAA,MACf,UAAU,KAAK;AAAA,MACf;AAAA,MACA,MAAM,CAAC,MAAM,WACX,MAAM,KAAK;AAAA,QACT;AAAA,QACA,QAAQ,sBAAsB;AAAA,QAC9B,YAAY;AAAA,QACZ,OAAO;AAAA,QACP;AAAA,MACF,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AACA,SAAO,EAAE,QAAQ,MAAM,MAAM,CAAC,UAAU,MAAM,WAAW,sBAAsB,MAAM,GAAG,MAAM;AAChG;",
|
|
6
6
|
"names": ["started"]
|
|
7
7
|
}
|
package/dist/modules/harness.mjs
CHANGED
|
@@ -83,7 +83,8 @@ const harnessDescriptionSchema = z.object({
|
|
|
83
83
|
nativeToolPolicy: z.boolean().optional(),
|
|
84
84
|
// Defers and searches MCP tools itself (a harness-native tool search): the
|
|
85
85
|
// host lists every exposed tool, ignoring connections' `tools.load`, and
|
|
86
|
-
// adds no search of its own. Absent: the host
|
|
86
|
+
// adds no search of its own. Absent: the host lists what `load` (or, without
|
|
87
|
+
// it, HOSTING.md's defaults) leaves listed and serves search for the rest.
|
|
87
88
|
deferredToolSearch: z.boolean().optional()
|
|
88
89
|
}),
|
|
89
90
|
promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/harness.ts"],
|
|
4
|
-
"sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n // Defers and searches MCP tools itself (a harness-native tool search): the\n // host lists every exposed tool, ignoring connections' `tools.load`, and\n // adds no search of its own. Absent: the host applies `load` and serves search.\n deferredToolSearch: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n bindings?: HostedBindingsIface;\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
|
|
5
|
-
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,iBAAiB,wBAA8C;AACxE,SAAS,oBAAoB,+BAA+B;AAG5D,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,gBAAgB,uBAAwD;AACjF,SAAS,WAAW,yBAA2C;AAC/D,SAAS,yBAAyB,kBAAkB;AAG7C,MAAM,wBAAwB;AAO9B,IAAK,eAAL,kBAAKA,kBAAL;AACL,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAOL,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,SAAM;AACN,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAOL,IAAK,oBAAL,kBAAKC,uBAAL;AAEL,EAAAA,mBAAA,WAAQ;AAER,EAAAA,mBAAA,qBAAkB;AAElB,EAAAA,mBAAA,eAAY;AANF,SAAAA;AAAA,GAAA;AAUL,IAAK,cAAL,kBAAKC,iBAAL;AACL,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,SAAM;AAFI,SAAAA;AAAA,GAAA;AAKL,IAAK,0BAAL,kBAAKC,6BAAL;AACL,EAAAA,yBAAA,aAAU;AACV,EAAAA,yBAAA,YAAS;AAFC,SAAAA;AAAA,GAAA;AAUL,IAAK,oBAAL,kBAAKC,uBAAL;AAEL,EAAAA,mBAAA,gBAA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AE,SAAS;AAAA;AAAA;AAAA;AAAA,
|
|
4
|
+
"sourcesContent": ["import type { McpServer } from '@agentclientprotocol/sdk/experimental/v2';\nimport * as z from 'zod';\nimport { CredentialRoute, routeGrantSchema, type RouteGrantIface } from \"./credential-routes.mjs\";\nimport { CredentialDelivery, InferenceCredentialKind } from \"./credentials.mjs\";\nimport type { JsonSchema, JsonValue } from \"./json.mjs\";\nimport type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport { jsonObjectSchema, jsonSchemaSchema } from \"./json.mjs\";\nimport { BaseCapability, InstructionRole, type ResolvedAgentManifestIface } from \"./manifest.mjs\";\nimport { bundleRef, providerRefSchema, type ProviderRef } from \"./provider-ref.mjs\";\nimport { referencedSharedSchemas, SCHEMA_IDS } from \"./schemas.mjs\";\n\n// Placeholder export name the compiler replaces with the defining module's path.\nexport const PENDING_BUNDLE_EXPORT = '<pending>';\n\n// A harness is a specific ACP agent program together with how to reach it. Hosting is part of what a harness is, so there is no\n// engine parameter: \"Pi on Final's serverless runtime\" and \"Pi on a server you\n// run\" are two harnesses. The hosting half is deliberately small; everything\n// about what the agent does goes over ACP v2.\n\nexport enum AcpTransport {\n Relay = 'relay',\n Ws = 'ws',\n Http = 'http',\n Stdio = 'stdio',\n}\n\nexport enum McpTransportKind {\n Acp = 'acp',\n Http = 'http',\n Stdio = 'stdio',\n}\n\n// How a harness provides one base capability.\nexport enum BaseToolProvision {\n // Routed to the declared sandbox target.\n Bound = 'bound',\n // Native on the harness's host and switchable through its own allow-lists.\n HostDisableable = 'host-disableable',\n // Native on the harness's host and not switchable.\n HostFixed = 'host-fixed',\n}\n\n// SDK wires a harness speaks to reach a bound sandbox target.\nexport enum SandboxWire {\n HandleRpc = 'handle-rpc',\n Mcp = 'mcp',\n}\n\nexport enum UserInstructionDelivery {\n History = 'history',\n System = 'system',\n}\n\n// Who operates the place a harness's credentials land. Every\n// harness, Final's included, gets the same grant forms; a subscription goes to\n// a third-party harness only when its owner allowed third-party harnesses.\n// Only installed provider packages may declare first-party; a bundle-declared\n// harness is third-party whatever it declares.\nexport enum HarnessTrustClass {\n // The provider operates the harness on infrastructure it runs (Final's serverless harnesses).\n FirstParty = 'first-party',\n // Someone else's host or program (remote hosts, external ACP agents, local processes).\n ThirdParty = 'third-party',\n}\n\n// What an accepted session/prompt does while the session is running. Both are valid; refusing one is a conformance failure.\nexport enum PromptWhileRunning {\n // Joins the running work: the model sees it at its next step.\n Inject = 'inject',\n // Runs after the current work goes idle; dropped by session/cancel if not started.\n Queue = 'queue',\n}\n\n// Defaults for a description that does not declare the hosting contract's\n// newer fields (bundle harnesses, older registrations): the session service\n// then assumes nothing survives a dropped connection and that a prompt while\n// running waits for idle.\nexport const DEFAULT_PROMPT_WHILE_RUNNING = PromptWhileRunning.Queue;\nexport const DEFAULT_SESSION_SURVIVES_DISCONNECT = false;\n\nexport const baseToolDeclarationSchema = z.object({\n provision: z.nativeEnum(BaseToolProvision),\n nativeTools: z.array(z.string()),\n});\n\nexport const harnessDescriptionSchema = z.object({\n // Everything configurable about this harness (model, reasoning, credentials,\n // permission mode, instructions, skills, cwd, ...). JSON Schema so Build can\n // render it; may $ref the shared final://schemas/* fragments.\n configSchema: jsonSchemaSchema,\n // Absent: user fragments enter history. System-only programs declare their conversion.\n userInstructionDelivery: z.nativeEnum(UserInstructionDelivery).optional(),\n acp: z.object({\n transports: z.array(z.nativeEnum(AcpTransport)).min(1),\n mcp: z.array(z.nativeEnum(McpTransportKind)),\n }),\n // A capability missing here is unavailable on this harness.\n baseTools: z.partialRecord(z.nativeEnum(BaseCapability), baseToolDeclarationSchema),\n consumes: z.array(z.nativeEnum(SandboxWire)),\n inference: z.object({\n vendors: z.array(z.string()),\n kinds: z.array(z.nativeEnum(InferenceCredentialKind)),\n delivery: z.nativeEnum(CredentialDelivery),\n }),\n // Absent: third-party.\n trust: z.nativeEnum(HarnessTrustClass).optional(),\n supports: z.object({\n observe: z.boolean(),\n resumeReplay: z.boolean(),\n fork: z.boolean(),\n // Renders _meta[\"final.ai\"].author itself; otherwise the channel prepends\n // the author's name to the text.\n authorMeta: z.boolean(),\n // Explicit false: native toolPolicy cannot be enforced by this adapter's public surface.\n nativeToolPolicy: z.boolean().optional(),\n // Defers and searches MCP tools itself (a harness-native tool search): the\n // host lists every exposed tool, ignoring connections' `tools.load`, and\n // adds no search of its own. Absent: the host lists what `load` (or, without\n // it, HOSTING.md's defaults) leaves listed and serves search for the rest.\n deferredToolSearch: z.boolean().optional(),\n }),\n promptWhileRunning: z.nativeEnum(PromptWhileRunning).default(DEFAULT_PROMPT_WHILE_RUNNING),\n // Keeps the session, its running work and its open requests across a dropped\n // connection, buffers updates for replay, and re-raises the open requests\n // with the same JSON-RPC ids on the next session/resume. False:\n // open turns end `harness_state_lost` after a reconnect.\n sessionSurvivesDisconnect: z.boolean().default(DEFAULT_SESSION_SURVIVES_DISCONNECT),\n});\n\nexport type BaseToolDeclarationIface = z.infer<typeof baseToolDeclarationSchema>;\nexport type HarnessDescriptionIface = z.infer<typeof harnessDescriptionSchema>;\n\nexport const deliveredHarnessConfig = (args: {\n config: JsonValue;\n description: HarnessDescriptionIface;\n}): JsonValue => {\n if (args.description.userInstructionDelivery !== UserInstructionDelivery.System)\n return args.config;\n const config = jsonObjectSchema.safeParse(args.config);\n if (!config.success) return args.config;\n const fields = referencedSharedSchemas(args.description.configSchema);\n const field =\n Object.entries(fields).find(([, schema]) => schema === SCHEMA_IDS.instructions)?.[0] ??\n 'instructions';\n const instructions = config.data[field];\n if (!Array.isArray(instructions)) return args.config;\n return {\n ...config.data,\n [field]: instructions.map((value) => {\n const fragment = jsonObjectSchema.safeParse(value);\n return fragment.success && fragment.data['role'] === InstructionRole.User\n ? { ...fragment.data, role: InstructionRole.System }\n : value;\n }),\n };\n};\n\nexport const harnessSessionRefSchema = z.object({\n harness: providerRefSchema,\n // Opaque to the session service; the harness's own id for the session.\n harnessSessionRef: z.string().min(1),\n // Bumped whenever the harness loses state; a mismatch on resume means the\n // session service must re-seed with session/new.\n generation: z.number().int().nonnegative(),\n});\n\nexport type HarnessSessionRefIface = z.infer<typeof harnessSessionRefSchema>;\n\n// Route-scoped, short-lived grants: credential-routes.ts.\nexport {\n credentialRefreshRequestSchema,\n CredentialRoute,\n routeGrantSchema,\n type CredentialRefreshRequestIface,\n type RouteGrantIface,\n} from \"./credential-routes.mjs\";\n\nexport interface CredentialGrantIface {\n // Base URL of the broker routes (`<base>/model`, `<base>/refresh`, ...).\n brokerUrl: string;\n grants: RouteGrantIface[];\n // What the model grant resolved to, for harnesses that hand credentials over\n // at open (delivery 'at-open'). Null for per-request harnesses.\n atOpen: AtOpenModelCredentialIface | null;\n // How to renew this grant; null only when it carries no route grant.\n refresh: CredentialGrantRefreshIface | null;\n}\n\n// Renewal is pulled, never pushed. Per-request harnesses fetch\n// `<brokerUrl>/model` on every request. At-open harnesses (or their host)\n// POST `url` with `authorization: Bearer <token>` and a\n// `credentialRefreshRequestSchema` body before `expiresAt` and once after a\n// vendor 401; the answer is the grant's next generation (a\n// `credentialRefreshResultSchema` body with its own `refresh`), which replaces\n// this one. The broker resolves the policy again for it, so a disconnected\n// credential falls through; a revoked grant (every open revokes the previous\n// open's grants) or a closed harness session is refused (401).\nexport interface CredentialGrantRefreshIface {\n // `<brokerUrl>/refresh`.\n url: string;\n // One of this grant's own route grants (the model route's).\n token: string;\n harnessSessionId: string;\n // When `token` expires; a refresh after it is refused.\n expiresAt: string;\n}\n\nexport interface AtOpenModelCredentialIface {\n vendor: string;\n kind: InferenceCredentialKind;\n // Base URL and bearer for an OpenAI- or Anthropic-compatible endpoint (the\n // platform proxy, a corporate gateway) or the vendor itself.\n baseUrl: string | null;\n apiKey: string | null;\n // Subscription material for Final-managed harnesses only (Claude setup token,\n // Codex app-server chatgptAuthTokens); renewed through the grant's refresh route.\n subscription: { format: 'claude-setup-token' | 'chatgpt-auth-tokens'; value: string } | null;\n fingerprint: string;\n}\n\nexport const atOpenModelCredentialSchema = z.object({\n vendor: z.string(),\n kind: z.nativeEnum(InferenceCredentialKind),\n baseUrl: z.string().min(1).nullable(),\n apiKey: z.string().min(1).nullable(),\n subscription: z\n .object({\n format: z.union([z.literal('claude-setup-token'), z.literal('chatgpt-auth-tokens')]),\n value: z.string().min(1),\n })\n .nullable(),\n fingerprint: z.string(),\n}) satisfies z.ZodType<AtOpenModelCredentialIface>;\n\nexport const credentialGrantRefreshSchema = z.object({\n url: z.string().min(1),\n token: z.string().min(1),\n harnessSessionId: z.string().min(1),\n expiresAt: z.string(),\n}) satisfies z.ZodType<CredentialGrantRefreshIface>;\n\nexport const credentialGrantSchema = z.object({\n brokerUrl: z.string().min(1),\n grants: z.array(routeGrantSchema),\n atOpen: atOpenModelCredentialSchema.nullable(),\n refresh: credentialGrantRefreshSchema.nullable(),\n}) satisfies z.ZodType<CredentialGrantIface>;\n\n// An `http` MCP server entry the harness was handed in `session/new`\n// (`mcpServers`), with fresh headers. Same name and url; the harness swaps the\n// headers of the entry with that url.\nexport interface RenewedMcpServerIface {\n name: string;\n url: string;\n headers: { name: string; value: string }[];\n}\n\n// What a refresh answers: the grant's next generation, plus fresh copies of the\n// other short-lived material the harness was handed at open. Renewing the\n// `mcp` route renews the session's `http` MCP server headers; renewing\n// `sandbox` renews the bound sandbox targets' endpoint tokens.\nexport interface CredentialRefreshResultIface extends CredentialGrantIface {\n mcpServers: RenewedMcpServerIface[];\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n}\n\nconst endpointTokenSchema = z.object({\n url: z.string().min(1),\n token: z.string(),\n expiresAt: z.string(),\n});\n\nexport const sandboxTargetEndpointSchema = z.object({\n target: z.string().min(1),\n bindingId: z.string().min(1),\n capabilities: z.array(z.string()),\n rpc: endpointTokenSchema.nullable(),\n mcp: endpointTokenSchema.nullable(),\n}) satisfies z.ZodType<SandboxTargetEndpointIface>;\n\nexport const renewedMcpServerSchema = z.object({\n name: z.string().min(1),\n url: z.string().min(1),\n headers: z.array(z.object({ name: z.string().min(1), value: z.string() })),\n}) satisfies z.ZodType<RenewedMcpServerIface>;\n\n// Absent renewals parse as none, so an answer without them still parses.\nexport const credentialRefreshResultSchema = credentialGrantSchema.extend({\n mcpServers: z.array(renewedMcpServerSchema).default([]),\n sandboxes: z.record(z.string(), sandboxTargetEndpointSchema).default({}),\n}) satisfies z.ZodType<CredentialRefreshResultIface, unknown>;\n\n// The refresh descriptor for a set of route grants: authenticated by the model\n// grant (else the first), due when that token expires.\nexport const grantRefreshFor = (args: {\n brokerUrl: string;\n harnessSessionId: string;\n grants: readonly RouteGrantIface[];\n}): CredentialGrantRefreshIface | null => {\n const grant =\n args.grants.find((candidate) => candidate.route === CredentialRoute.Model) ?? args.grants[0];\n if (grant == null) return null;\n return {\n url: `${args.brokerUrl.replace(/\\/+$/, '')}/refresh`,\n token: grant.token,\n harnessSessionId: args.harnessSessionId,\n expiresAt: grant.expiresAt,\n };\n};\n\nexport interface SecretReaderIface {\n get(name: string): Promise<string | null>;\n}\n\nexport interface TraceContextIface {\n traceparent: string | null;\n tracestate: string | null;\n}\n\n// A bound sandbox target as the session service hands it to a harness: a stable\n// per-binding address that starts the sandbox on the first tool call. Never a lease, a data-plane token for a live VM, or provider code.\nexport interface SandboxTargetEndpointIface {\n target: string;\n bindingId: string;\n capabilities: string[];\n rpc: { url: string; token: string; expiresAt: string } | null;\n mcp: { url: string; token: string; expiresAt: string } | null;\n}\n\nexport interface HarnessSessionContextIface {\n bindings?: HostedBindingsIface;\n sessionId: string;\n organizationId: string;\n definitionId: string;\n revisionId: string;\n // Public base URL of the session service for this session (MCP over HTTP,\n // sandbox endpoints, the broker).\n sessionServiceUrl: string;\n // The region of the session service serving the session and its sandbox\n // bindings, so a harness can run near it; null when unknown.\n sessionServiceRegion?: string | null;\n}\n\n// Lifecycle signals a harness implementation may report about the runtime\n// hosting a session (invocations, metering, traces). Informational: the\n// session service records them (agent.harness_invocations, Tinybird) and never\n// depends on them for correctness.\nexport interface HarnessObserverIface {\n // The runtime accepted the invocation request (its response began).\n invocationAccepted?(event: { invocationRef: string; at: string }): void;\n invocationStarted?(event: {\n invocationRef: string;\n at: string;\n bootMs: number | null;\n // The runtime's deployed version (Workers version id, commit), for rollouts.\n versionId?: string | null;\n commitSha?: string | null;\n }): void;\n invocationKeepalive?(event: { invocationRef: string; at: string; activeWork: number }): void;\n invocationEnded?(event: {\n invocationRef: string;\n at: string;\n reason: string;\n error: string | null;\n metering: Record<string, number>;\n }): void;\n trace?(event: { name: string; at: string; fields: Record<string, JsonValue> }): void;\n}\n\nexport interface OpenHarnessSessionArgsIface {\n session: HarnessSessionContextIface;\n // The session service's id for this harness session (agent.harness_sessions);\n // implementations key their runtime state and route grants by it.\n harnessSessionId: string;\n // Hosting may authorize the child endpoint to fork this source through ACP.\n forkSource?: { ref: HarnessSessionRefIface; acpSessionId: string };\n observer?: HarnessObserverIface;\n // The binding's config, validated against configSchema, dynamic slots resolved.\n config: JsonValue;\n manifest: ResolvedAgentManifestIface;\n // Already materialized ACP MCP server entries: authored tools, connections\n // (Final's MCP server among them), sandbox MCP projections where applicable.\n mcpServers: McpServer[];\n // Declared base capabilities with the target endpoint each is bound to.\n baseTools: Partial<Record<BaseCapability, SandboxTargetEndpointIface>>;\n sandboxes: Record<string, SandboxTargetEndpointIface>;\n credentials: CredentialGrantIface;\n secrets: SecretReaderIface;\n trace: TraceContextIface;\n}\n\nexport interface ResumeHarnessSessionArgsIface extends OpenHarnessSessionArgsIface {\n ref: HarnessSessionRefIface;\n // Last log seq the session service holds from this harness session; the\n // harness replays anything newer after session/resume.\n lastSeq: number;\n}\n\n// Resolved only in memory; refs/manifests retain secret names, never TLS keys.\nexport interface HarnessClientTlsIface {\n cert: string;\n key: string;\n ca?: string;\n}\n\nexport type HarnessEndpointIface =\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Ws;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Http;\n url: string;\n headers: Record<string, string>;\n resolveHeaders?: () => Promise<Record<string, string>>;\n tls?: HarnessClientTlsIface;\n }\n // websocket-gateway relay channel (Final-managed harnesses).\n | { ref: HarnessSessionRefIface; transport: AcpTransport.Relay; channel: string; token: string }\n // Local development, CI and conformance only.\n | {\n ref: HarnessSessionRefIface;\n transport: AcpTransport.Stdio;\n command: string;\n args: string[];\n env: Record<string, string>;\n };\n\nexport interface HarnessHealthIface {\n ok: boolean;\n detail?: string;\n checkedAt: string;\n}\n\n// The binding a description is asked for: its config (validated against the\n// configSchema of the binding-free description) and the definition's secrets.\nexport interface DescribeHarnessArgsIface {\n config: JsonValue;\n secrets: SecretReaderIface;\n}\n\nexport interface HarnessIface {\n // Without a binding: what Build renders before one exists (configSchema,\n // declared capabilities). With one: the description of that binding, which a\n // harness reaching an arbitrary agent derives from the agent itself (e.g. its\n // `initialize`). Every harness implements both; most ignore the binding.\n describe(binding?: DescribeHarnessArgsIface): Promise<HarnessDescriptionIface>;\n open(args: OpenHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n resume(args: ResumeHarnessSessionArgsIface): Promise<HarnessEndpointIface>;\n park(ref: HarnessSessionRefIface): Promise<void>;\n // Graceful by default: the program's state is durable (resumable) before it\n // stops, bounded by the implementation's timeout, then forced. `force` skips\n // the wait; the session service passes it when the program did not settle\n // ACP `session/close` within its bound.\n close(ref: HarnessSessionRefIface, opts?: CloseHarnessSessionOptsIface): Promise<void>;\n health(\n ref: HarnessSessionRefIface,\n context?: DescribeHarnessArgsIface,\n ): Promise<HarnessHealthIface>;\n}\n\nexport interface CloseHarnessSessionOptsIface {\n force?: boolean;\n // As with health, retained refs can resolve current client TLS without storing keys in the ref.\n context?: DescribeHarnessArgsIface;\n}\n\n// What an installed harness module exports: the implementation plus an\n// authoring helper that builds the manifest binding.\nexport interface HarnessModuleIface<Config> {\n ref: ProviderRef;\n harness: HarnessIface;\n binding: (config: Config) => { harness: ProviderRef; config: JsonValue };\n}\n\n// Custom harnesses in a definition's bundle. Calling the result\n// with a config yields the manifest binding; the implementation is resolved\n// from the bundle by export name.\nexport interface DefinedHarnessBindingIface {\n harness: ProviderRef;\n config: JsonValue;\n definedHarness: true;\n}\n\nexport interface DefinedHarnessIface<Config> extends HarnessIface {\n (config: Config): DefinedHarnessBindingIface;\n}\n\nexport const defineHarness = <Config extends JsonValue = JsonValue>(\n implementation: HarnessIface,\n): DefinedHarnessIface<Config> => {\n // The export name is unknown here; the compiler rewrites `bundle:<pending>`\n // to the module path that exported this harness.\n const binding = (config: Config): DefinedHarnessBindingIface => ({\n harness: bundleRef(PENDING_BUNDLE_EXPORT),\n config,\n definedHarness: true,\n });\n return Object.assign(binding, implementation);\n};\n\nexport const describeConfigSchema = (description: HarnessDescriptionIface): JsonSchema =>\n description.configSchema;\n"],
|
|
5
|
+
"mappings": "AACA,YAAY,OAAO;AACnB,SAAS,iBAAiB,wBAA8C;AACxE,SAAS,oBAAoB,+BAA+B;AAG5D,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,gBAAgB,uBAAwD;AACjF,SAAS,WAAW,yBAA2C;AAC/D,SAAS,yBAAyB,kBAAkB;AAG7C,MAAM,wBAAwB;AAO9B,IAAK,eAAL,kBAAKA,kBAAL;AACL,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAOL,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,SAAM;AACN,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAOL,IAAK,oBAAL,kBAAKC,uBAAL;AAEL,EAAAA,mBAAA,WAAQ;AAER,EAAAA,mBAAA,qBAAkB;AAElB,EAAAA,mBAAA,eAAY;AANF,SAAAA;AAAA,GAAA;AAUL,IAAK,cAAL,kBAAKC,iBAAL;AACL,EAAAA,aAAA,eAAY;AACZ,EAA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;AAEO,MAAM,uBAAuB,CAAC,gBACnC,YAAY;",
|
|
6
6
|
"names": ["AcpTransport", "McpTransportKind", "BaseToolProvision", "SandboxWire", "UserInstructionDelivery", "HarnessTrustClass", "PromptWhileRunning", "CredentialRoute", "routeGrantSchema"]
|
|
7
7
|
}
|
|
@@ -17,6 +17,7 @@ export interface CreateMemorySandboxArgsIface {
|
|
|
17
17
|
screen?: NetworkSandboxSessionIface['screen'];
|
|
18
18
|
localMcp?: () => Promise<SandboxMcpEndpoint[]>;
|
|
19
19
|
networkPolicy?: boolean;
|
|
20
|
+
baseEnv?: () => Promise<Record<string, string>>;
|
|
20
21
|
now?: () => Date;
|
|
21
22
|
}
|
|
22
23
|
export declare const createMemorySandbox: (args?: CreateMemorySandboxArgsIface) => MemorySandboxIface;
|
|
@@ -6,8 +6,11 @@ import { normalizePosixPath, posixDirname, resolvePosixPath } from "./paths.mjs"
|
|
|
6
6
|
import {
|
|
7
7
|
defineSandboxProvider,
|
|
8
8
|
NetworkPolicy,
|
|
9
|
+
PLATFORM_ENVIRONMENT_NAMES,
|
|
10
|
+
platformProcessEnvironment,
|
|
9
11
|
PortProtocol,
|
|
10
|
-
SandboxEntryType
|
|
12
|
+
SandboxEntryType,
|
|
13
|
+
writePlatformFiles
|
|
11
14
|
} from "./types.mjs";
|
|
12
15
|
const fsError = (code, message) => Object.assign(new Error(`${code}: ${message}`), { code });
|
|
13
16
|
const abortableSleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
@@ -114,6 +117,7 @@ const createMemorySandbox = (args = {}) => {
|
|
|
114
117
|
};
|
|
115
118
|
};
|
|
116
119
|
const spawn = async (options) => {
|
|
120
|
+
const env = { ...await args.baseEnv?.(), ...options.env };
|
|
117
121
|
const controller = new AbortController();
|
|
118
122
|
let killedWith = null;
|
|
119
123
|
const outputs = { stdout: null, stderr: null };
|
|
@@ -166,6 +170,7 @@ const createMemorySandbox = (args = {}) => {
|
|
|
166
170
|
signal: controller.signal
|
|
167
171
|
},
|
|
168
172
|
cwd: options.cwd == null ? cwd : resolve(options.cwd),
|
|
173
|
+
env,
|
|
169
174
|
sleep: abortableSleep
|
|
170
175
|
};
|
|
171
176
|
const timeout = options.timeoutMs == null ? null : setTimeout(() => {
|
|
@@ -365,7 +370,9 @@ const memorySandboxTextFiles = async (sandbox, root = "/") => {
|
|
|
365
370
|
const memoryEnvironmentSchema = z.object({
|
|
366
371
|
files: z.record(z.string(), z.string()).optional(),
|
|
367
372
|
cwd: z.string().optional(),
|
|
368
|
-
ports: z.array(z.number().int()).optional()
|
|
373
|
+
ports: z.array(z.number().int()).optional(),
|
|
374
|
+
// Plain variables for every process, under the platform's.
|
|
375
|
+
env: z.record(z.string(), z.string()).optional()
|
|
369
376
|
}).nullable().optional();
|
|
370
377
|
const fingerprint = (value) => {
|
|
371
378
|
let hash = 2166136261;
|
|
@@ -390,20 +397,28 @@ const memorySandboxProvider = defineSandboxProvider({
|
|
|
390
397
|
cwd: options.cwd ?? "/workspace",
|
|
391
398
|
ports: options.ports ?? []
|
|
392
399
|
});
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
400
|
+
const specEnv = options.env ?? {};
|
|
401
|
+
const open = async (ctx, bindingId, artifact) => {
|
|
402
|
+
for (const name of Object.keys(specEnv))
|
|
403
|
+
if (PLATFORM_ENVIRONMENT_NAMES.has(name)) throw new Error(`${name} is reserved`);
|
|
404
|
+
const sandbox = createMemorySandbox({
|
|
405
|
+
id: bindingId,
|
|
406
|
+
files: artifact.files,
|
|
407
|
+
cwd: artifact.cwd,
|
|
408
|
+
ports: artifact.ports,
|
|
409
|
+
baseEnv: platformProcessEnvironment(ctx, specEnv)
|
|
410
|
+
});
|
|
411
|
+
await writePlatformFiles(ctx, sandbox);
|
|
412
|
+
return sandbox;
|
|
413
|
+
};
|
|
399
414
|
return {
|
|
400
415
|
artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,
|
|
401
416
|
prepare: async (ctx) => artifactFor(ctx.files),
|
|
402
417
|
start: async (ctx, _openOptions, artifact) => ({
|
|
403
|
-
handle: memoryHandle(open(ctx.session.bindingId, artifact)),
|
|
418
|
+
handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),
|
|
404
419
|
state: { id: ctx.session.bindingId }
|
|
405
420
|
}),
|
|
406
|
-
resume: async (
|
|
421
|
+
resume: async (ctx, artifact, state) => memoryHandle(await open(ctx, state.id, artifact)),
|
|
407
422
|
park: async (_ctx, _artifact, state) => state
|
|
408
423
|
};
|
|
409
424
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/memory-sandbox.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { runMemoryArgv, runMemoryScript, type MemoryShellFsIface } from \"./memory-shell.mjs\";\nimport { normalizePosixPath, posixDirname, resolvePosixPath } from \"./paths.mjs\";\nimport {\n defineSandboxProvider,\n NetworkPolicy,\n PortProtocol,\n SandboxEntryType,\n type DirEntryIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderHandleIface,\n type StatIface,\n} from \"./types.mjs\";\n\n// An in-memory reference sandbox: a virtual filesystem plus a tiny command\n// interpreter (memory-shell.ts). Used by tests and the conformance kit, and as\n// the smallest complete example of the sandbox contract.\n\nexport interface MemorySandboxIface extends NetworkSandboxSessionIface {\n readonly networkPolicy: NetworkPolicyIface;\n readonly stopped: boolean;\n}\n\nexport interface CreateMemorySandboxArgsIface {\n id?: string;\n files?: Record<string, string | Uint8Array>;\n cwd?: string;\n ports?: number[];\n portUrl?: (args: { port: number; protocol: PortProtocol }) => string;\n // Optional capabilities; present only when given.\n computerUse?: () => Promise<SandboxMcpEndpoint>;\n screen?: NetworkSandboxSessionIface['screen'];\n localMcp?: () => Promise<SandboxMcpEndpoint[]>;\n networkPolicy?: boolean;\n now?: () => Date;\n}\n\ntype MemoryEntry =\n | { type: 'file'; data: Uint8Array; modifiedAt: Date }\n | { type: 'directory'; modifiedAt: Date };\n\ninterface ProcessOutputsIface {\n stdout: ReadableStreamDefaultController<Uint8Array> | null;\n stderr: ReadableStreamDefaultController<Uint8Array> | null;\n}\n\nconst fsError = (code: string, message: string) =>\n Object.assign(new Error(`${code}: ${message}`), { code });\n\nconst abortableSleep = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\nconst signalExitCode = (signal: string | undefined): number => {\n if (signal === 'SIGKILL' || signal === 'KILL' || signal === '9') return 137;\n if (signal === 'SIGINT' || signal === 'INT') return 130;\n return 143;\n};\n\nexport const createMemorySandbox = (\n args: CreateMemorySandboxArgsIface = {},\n): MemorySandboxIface => {\n const id = args.id ?? `memory-${crypto.randomUUID()}`;\n const cwd = normalizePosixPath(args.cwd ?? '/workspace');\n const now = args.now ?? (() => new Date());\n const entries = new Map<string, MemoryEntry>();\n const processes = new Set<SandboxProcessIface>();\n let networkPolicy: NetworkPolicyIface = { mode: NetworkPolicy.AllowAll };\n let stopped = false;\n\n const resolve = (path: string) => resolvePosixPath(cwd, path);\n\n const ensureDirectory = (path: string) => {\n const normalized = normalizePosixPath(path);\n const existing = entries.get(normalized);\n if (existing?.type === 'directory') return;\n if (existing?.type === 'file') throw fsError('ENOTDIR', `${normalized} is a file`);\n if (normalized !== '/') ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'directory', modifiedAt: now() });\n };\n\n const putFile = (path: string, data: Uint8Array) => {\n const normalized = normalizePosixPath(path);\n if (entries.get(normalized)?.type === 'directory')\n throw fsError('EISDIR', `${normalized} is a directory`);\n ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'file', data, modifiedAt: now() });\n };\n\n const children = (path: string): string[] => {\n const prefix = path === '/' ? '/' : `${path}/`;\n const names: string[] = [];\n for (const key of entries.keys()) {\n if (key !== path && key.startsWith(prefix) && !key.slice(prefix.length).includes('/')) {\n names.push(key.slice(prefix.length));\n }\n }\n return names.sort();\n };\n\n ensureDirectory('/');\n ensureDirectory(cwd);\n for (const [path, content] of Object.entries(args.files ?? {})) {\n putFile(resolve(path), content instanceof Uint8Array ? content : utf8Encode(content));\n }\n\n const shellFs: MemoryShellFsIface = {\n readFile: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry?.type === 'file' ? entry.data : null;\n },\n writeFile: (path, data, options) => {\n const entry = entries.get(normalizePosixPath(path));\n if (options.append && entry?.type === 'file') {\n const merged = new Uint8Array(entry.data.byteLength + data.byteLength);\n merged.set(entry.data, 0);\n merged.set(data, entry.data.byteLength);\n putFile(path, merged);\n return;\n }\n putFile(path, data);\n },\n kind: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry == null ? null : entry.type;\n },\n list: (path) => {\n const normalized = normalizePosixPath(path);\n return entries.get(normalized)?.type === 'directory' ? children(normalized) : null;\n },\n mkdir: (path, options) => {\n const normalized = normalizePosixPath(path);\n if (!options.parents && entries.get(posixDirname(normalized))?.type !== 'directory') {\n throw fsError('ENOENT', 'No such file or directory');\n }\n if (!options.parents && entries.has(normalized)) throw fsError('EEXIST', 'File exists');\n ensureDirectory(normalized);\n },\n };\n\n const statOf = (path: string): StatIface | null => {\n const entry = entries.get(path);\n if (entry == null) return null;\n return {\n path,\n type: entry.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: entry.type === 'file' ? entry.data.byteLength : 0,\n modifiedAt: entry.modifiedAt.toISOString(),\n mode: entry.type === 'file' ? 0o644 : 0o755,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const controller = new AbortController();\n let killedWith: string | null = null;\n const outputs: ProcessOutputsIface = { stdout: null, stderr: null };\n const stdout = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stdout = c;\n },\n });\n const stderr = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stderr = c;\n },\n });\n let self: SandboxProcessIface | null = null;\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (options.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (options.stdin instanceof ReadableStream) {\n stdinSource = options.stdin;\n } else {\n const bytes = utf8Encode(options.stdin);\n stdinSource = new ReadableStream<Uint8Array>({\n start: (c) => {\n if (bytes.byteLength > 0) c.enqueue(bytes);\n c.close();\n },\n });\n }\n const stdinReader = stdinSource.getReader();\n const abortPromise = new Promise<null>((resolveAbort) =>\n controller.signal.addEventListener('abort', () => resolveAbort(null), { once: true }),\n );\n const readStdin = async (): Promise<Uint8Array | null> => {\n const result = await Promise.race([stdinReader.read(), abortPromise]);\n if (result == null) throw controller.signal.reason;\n return result.done ? null : result.value;\n };\n const emit = (\n target: ReadableStreamDefaultController<Uint8Array> | null,\n bytes: Uint8Array,\n ) => {\n if (bytes.byteLength > 0) target?.enqueue(bytes.slice());\n };\n const context = {\n fs: shellFs,\n io: {\n readStdin,\n stdout: (bytes: Uint8Array) => emit(outputs.stdout, bytes),\n stderr: (bytes: Uint8Array) => emit(outputs.stderr, bytes),\n signal: controller.signal,\n },\n cwd: options.cwd == null ? cwd : resolve(options.cwd),\n sleep: abortableSleep,\n };\n const timeout =\n options.timeoutMs == null\n ? null\n : setTimeout(() => {\n killedWith = 'timeout';\n controller.abort(new Error('timed out'));\n }, options.timeoutMs);\n const onAbortSignal = () => {\n killedWith ??= 'SIGTERM';\n controller.abort(new Error('aborted'));\n };\n options.abortSignal?.addEventListener('abort', onAbortSignal, { once: true });\n const exited = (async (): Promise<{ exitCode: number }> => {\n let exitCode: number;\n try {\n if (context.fs.kind(context.cwd) !== 'directory') {\n context.io.stderr(utf8Encode(`cd: ${context.cwd}: No such file or directory\\n`));\n exitCode = 1;\n } else if (options.shell === true) {\n const script = [options.command, ...(options.args ?? [])].join(' ');\n exitCode = await runMemoryScript({ ...context, script });\n } else {\n exitCode = await runMemoryArgv({\n ...context,\n argv: [options.command, ...(options.args ?? [])],\n });\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n context.io.stderr(\n utf8Encode(`${error instanceof Error ? error.message : String(error)}\\n`),\n );\n exitCode = 1;\n } else {\n exitCode = killedWith === 'timeout' ? 124 : signalExitCode(killedWith ?? undefined);\n }\n }\n if (timeout != null) clearTimeout(timeout);\n options.abortSignal?.removeEventListener('abort', onAbortSignal);\n stdinReader.cancel().catch(() => undefined);\n outputs.stdout?.close();\n outputs.stderr?.close();\n if (self != null) processes.delete(self);\n return { exitCode };\n })();\n const child: SandboxProcessIface = {\n pid: null,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n const bytes = data instanceof Uint8Array ? data : utf8Encode(data);\n if (bytes.byteLength > 0) await stdinWriter.write(bytes);\n if (writeOptions?.end === true) await stdinWriter.close();\n },\n wait: () => exited,\n kill: async (signal) => {\n killedWith ??= signal ?? 'SIGTERM';\n controller.abort(new Error(`killed (${signal ?? 'SIGTERM'})`));\n await exited;\n },\n };\n self = child;\n processes.add(child);\n return child;\n };\n\n const sandbox: MemorySandboxIface = {\n id,\n defaultWorkingDirectory: cwd,\n ports: args.ports ?? [],\n get description() {\n return `In-memory sandbox ${id}. Working directory ${cwd}. Commands: echo, cat, ls, pwd, cd, true, false, sleep, exit, mkdir, sh -c.`;\n },\n get networkPolicy() {\n return networkPolicy;\n },\n get stopped() {\n return stopped;\n },\n readFile: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) return null;\n if (entry.type === 'directory') throw fsError('EISDIR', `${path} is a directory`);\n const data = entry.data;\n const chunkBytes = 64 * 1024;\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= data.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(data.byteLength, offset + chunkBytes);\n controller.enqueue(data.slice(offset, end));\n offset = end;\n },\n });\n },\n readBinaryFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile: async (options) => {\n const data = await readAllBytes(options.content);\n putFile(resolve(options.path), data);\n },\n writeBinaryFile: async (options) => {\n putFile(resolve(options.path), options.content.slice());\n },\n writeTextFile: async (options) => {\n putFile(resolve(options.path), encodeSandboxText(options.content, options.encoding));\n },\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options) => statOf(resolve(options.path)),\n readDir: async (options): Promise<DirEntryIface[]> => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) throw fsError('ENOENT', `${path}: No such file or directory`);\n if (entry.type !== 'directory') throw fsError('ENOTDIR', `${path} is not a directory`);\n return children(path).map((name) => {\n const childPath = path === '/' ? `/${name}` : `${path}/${name}`;\n const child = entries.get(childPath);\n return {\n name,\n path: childPath,\n type: child?.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: child?.type === 'file' ? child.data.byteLength : null,\n };\n });\n },\n resolvePath: resolve,\n removePath: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) {\n if (options.force === true) return;\n throw fsError('ENOENT', `${path}: No such file or directory`);\n }\n if (path === '/') throw fsError('EPERM', 'refusing to remove /');\n if (entry.type === 'directory') {\n const prefix = `${path}/`;\n const nested = [...entries.keys()].filter((key) => key.startsWith(prefix));\n if (nested.length > 0 && options.recursive !== true)\n throw fsError('ENOTEMPTY', `${path}: Directory not empty`);\n for (const key of nested) entries.delete(key);\n }\n entries.delete(path);\n },\n getPortEndpoint: async (options) => {\n const protocol = options.protocol ?? PortProtocol.Http;\n return {\n url:\n args.portUrl?.({ port: options.port, protocol }) ??\n `${protocol}://127.0.0.1:${options.port}`,\n };\n },\n getPortUrl: async (options) => (await sandbox.getPortEndpoint(options)).url,\n stop: async () => {\n stopped = true;\n await Promise.all([...processes].map((child) => child.kill()));\n },\n destroy: async () => {\n await sandbox.stop();\n entries.clear();\n ensureDirectory('/');\n },\n };\n if (args.networkPolicy === true) {\n sandbox.setNetworkPolicy = async (policy) => {\n networkPolicy = policy;\n };\n }\n if (args.computerUse != null) sandbox.computerUse = args.computerUse;\n if (args.screen != null) sandbox.screen = args.screen;\n if (args.localMcp != null) sandbox.localMcp = args.localMcp;\n return sandbox;\n};\n\n// Every file of a memory sandbox as path \u2192 base64-free UTF-8 text (binary\n// files are skipped); handy for assertions.\nexport const memorySandboxTextFiles = async (\n sandbox: NetworkSandboxSessionIface,\n root = '/',\n): Promise<Record<string, string>> => {\n const out: Record<string, string> = {};\n const walk = async (path: string) => {\n for (const entry of await sandbox.readDir({ path })) {\n if (entry.type === SandboxEntryType.Directory) await walk(entry.path);\n else {\n const text = await sandbox.readTextFile({ path: entry.path });\n if (text != null) out[entry.path] = text;\n }\n }\n };\n await walk(root);\n return out;\n};\n\nconst memoryEnvironmentSchema = z\n .object({\n files: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n ports: z.array(z.number().int()).optional(),\n })\n .nullable()\n .optional();\n\nexport type MemorySandboxArtifact = { files: Record<string, string>; cwd: string; ports: number[] };\nexport type MemorySandboxState = { id: string };\n\nconst fingerprint = (value: string): string => {\n // FNV-1a, enough for a content key in an example provider.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n};\n\nconst memoryHandle = (\n sandbox: MemorySandboxIface,\n): SandboxProviderHandleIface<MemorySandboxIface> => ({\n sandbox,\n onSandboxStop: () => sandbox.stop(),\n onSandboxDelete: () => sandbox.destroy(),\n onRuntimeShutdown: () => sandbox.stop(),\n});\n\n// Example provider over the memory sandbox. Ephemeral: `resume` starts again\n// from the prepared artifact, so files written before a park are lost.\nexport const memorySandboxProvider = defineSandboxProvider<\n JsonValue,\n JsonValue,\n MemorySandboxArtifact,\n MemorySandboxState,\n MemorySandboxIface\n>({\n name: 'memory',\n environment: (rawOptions) => {\n const options = memoryEnvironmentSchema.parse(rawOptions) ?? {};\n const artifactFor = (files: Record<string, string>): MemorySandboxArtifact => ({\n files: { ...options.files, ...files },\n cwd: options.cwd ?? '/workspace',\n ports: options.ports ?? [],\n });\n const open = (bindingId: string, artifact: MemorySandboxArtifact) =>\n createMemorySandbox({\n id: bindingId,\n files: artifact.files,\n cwd: artifact.cwd,\n ports: artifact.ports,\n });\n return {\n artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,\n prepare: async (ctx) => artifactFor(ctx.files),\n start: async (ctx, _openOptions, artifact) => ({\n handle: memoryHandle(open(ctx.session.bindingId, artifact)),\n state: { id: ctx.session.bindingId },\n }),\n resume: async (_ctx, artifact, state) => memoryHandle(open(state.id, artifact)),\n park: async (_ctx, _artifact, state) => state,\n };\n },\n});\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,mBAAmB,cAAc,kBAAkB;AAC5D,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,eAAe,uBAAgD;AACxE,SAAS,oBAAoB,cAAc,wBAAwB;AACnE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OASK;AAkCP,MAAM,UAAU,CAAC,MAA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IAAI,KAAK,CAAC,CAAC,CAAC;AAAA,MACzF,SAAS,OAAO,QAAQ,YAAY,IAAI,KAAK;AAAA,MAC7C,OAAO,OAAO,KAAK,cAAc,cAAc;AAAA,QAC7C,QAAQ,aAAa,KAAK,IAAI,QAAQ,WAAW,QAAQ,CAAC;AAAA,QAC1D,OAAO,EAAE,IAAI,IAAI,QAAQ,UAAU;AAAA,MACrC;AAAA,MACA,QAAQ,OAAO,MAAM,UAAU,UAAU,aAAa,KAAK,MAAM,IAAI,QAAQ,CAAC;AAAA,MAC9E,MAAM,OAAO,MAAM,WAAW,UAAU;AAAA,IAC1C;AAAA,EACF;AACF,CAAC;",
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { runMemoryArgv, runMemoryScript, type MemoryShellFsIface } from \"./memory-shell.mjs\";\nimport { normalizePosixPath, posixDirname, resolvePosixPath } from \"./paths.mjs\";\nimport {\n defineSandboxProvider,\n NetworkPolicy,\n PLATFORM_ENVIRONMENT_NAMES,\n platformProcessEnvironment,\n PortProtocol,\n SandboxEntryType,\n writePlatformFiles,\n type DirEntryIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n type StatIface,\n} from \"./types.mjs\";\n\n// An in-memory reference sandbox: a virtual filesystem plus a tiny command\n// interpreter (memory-shell.ts). Used by tests and the conformance kit, and as\n// the smallest complete example of the sandbox contract.\n\nexport interface MemorySandboxIface extends NetworkSandboxSessionIface {\n readonly networkPolicy: NetworkPolicyIface;\n readonly stopped: boolean;\n}\n\nexport interface CreateMemorySandboxArgsIface {\n id?: string;\n files?: Record<string, string | Uint8Array>;\n cwd?: string;\n ports?: number[];\n portUrl?: (args: { port: number; protocol: PortProtocol }) => string;\n // Optional capabilities; present only when given.\n computerUse?: () => Promise<SandboxMcpEndpoint>;\n screen?: NetworkSandboxSessionIface['screen'];\n localMcp?: () => Promise<SandboxMcpEndpoint[]>;\n networkPolicy?: boolean;\n // Every process's environment, under per-call env; read again for each process.\n baseEnv?: () => Promise<Record<string, string>>;\n now?: () => Date;\n}\n\ntype MemoryEntry =\n | { type: 'file'; data: Uint8Array; modifiedAt: Date }\n | { type: 'directory'; modifiedAt: Date };\n\ninterface ProcessOutputsIface {\n stdout: ReadableStreamDefaultController<Uint8Array> | null;\n stderr: ReadableStreamDefaultController<Uint8Array> | null;\n}\n\nconst fsError = (code: string, message: string) =>\n Object.assign(new Error(`${code}: ${message}`), { code });\n\nconst abortableSleep = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\nconst signalExitCode = (signal: string | undefined): number => {\n if (signal === 'SIGKILL' || signal === 'KILL' || signal === '9') return 137;\n if (signal === 'SIGINT' || signal === 'INT') return 130;\n return 143;\n};\n\nexport const createMemorySandbox = (\n args: CreateMemorySandboxArgsIface = {},\n): MemorySandboxIface => {\n const id = args.id ?? `memory-${crypto.randomUUID()}`;\n const cwd = normalizePosixPath(args.cwd ?? '/workspace');\n const now = args.now ?? (() => new Date());\n const entries = new Map<string, MemoryEntry>();\n const processes = new Set<SandboxProcessIface>();\n let networkPolicy: NetworkPolicyIface = { mode: NetworkPolicy.AllowAll };\n let stopped = false;\n\n const resolve = (path: string) => resolvePosixPath(cwd, path);\n\n const ensureDirectory = (path: string) => {\n const normalized = normalizePosixPath(path);\n const existing = entries.get(normalized);\n if (existing?.type === 'directory') return;\n if (existing?.type === 'file') throw fsError('ENOTDIR', `${normalized} is a file`);\n if (normalized !== '/') ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'directory', modifiedAt: now() });\n };\n\n const putFile = (path: string, data: Uint8Array) => {\n const normalized = normalizePosixPath(path);\n if (entries.get(normalized)?.type === 'directory')\n throw fsError('EISDIR', `${normalized} is a directory`);\n ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'file', data, modifiedAt: now() });\n };\n\n const children = (path: string): string[] => {\n const prefix = path === '/' ? '/' : `${path}/`;\n const names: string[] = [];\n for (const key of entries.keys()) {\n if (key !== path && key.startsWith(prefix) && !key.slice(prefix.length).includes('/')) {\n names.push(key.slice(prefix.length));\n }\n }\n return names.sort();\n };\n\n ensureDirectory('/');\n ensureDirectory(cwd);\n for (const [path, content] of Object.entries(args.files ?? {})) {\n putFile(resolve(path), content instanceof Uint8Array ? content : utf8Encode(content));\n }\n\n const shellFs: MemoryShellFsIface = {\n readFile: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry?.type === 'file' ? entry.data : null;\n },\n writeFile: (path, data, options) => {\n const entry = entries.get(normalizePosixPath(path));\n if (options.append && entry?.type === 'file') {\n const merged = new Uint8Array(entry.data.byteLength + data.byteLength);\n merged.set(entry.data, 0);\n merged.set(data, entry.data.byteLength);\n putFile(path, merged);\n return;\n }\n putFile(path, data);\n },\n kind: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry == null ? null : entry.type;\n },\n list: (path) => {\n const normalized = normalizePosixPath(path);\n return entries.get(normalized)?.type === 'directory' ? children(normalized) : null;\n },\n mkdir: (path, options) => {\n const normalized = normalizePosixPath(path);\n if (!options.parents && entries.get(posixDirname(normalized))?.type !== 'directory') {\n throw fsError('ENOENT', 'No such file or directory');\n }\n if (!options.parents && entries.has(normalized)) throw fsError('EEXIST', 'File exists');\n ensureDirectory(normalized);\n },\n };\n\n const statOf = (path: string): StatIface | null => {\n const entry = entries.get(path);\n if (entry == null) return null;\n return {\n path,\n type: entry.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: entry.type === 'file' ? entry.data.byteLength : 0,\n modifiedAt: entry.modifiedAt.toISOString(),\n mode: entry.type === 'file' ? 0o644 : 0o755,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const env = { ...(await args.baseEnv?.()), ...options.env };\n const controller = new AbortController();\n let killedWith: string | null = null;\n const outputs: ProcessOutputsIface = { stdout: null, stderr: null };\n const stdout = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stdout = c;\n },\n });\n const stderr = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stderr = c;\n },\n });\n let self: SandboxProcessIface | null = null;\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (options.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (options.stdin instanceof ReadableStream) {\n stdinSource = options.stdin;\n } else {\n const bytes = utf8Encode(options.stdin);\n stdinSource = new ReadableStream<Uint8Array>({\n start: (c) => {\n if (bytes.byteLength > 0) c.enqueue(bytes);\n c.close();\n },\n });\n }\n const stdinReader = stdinSource.getReader();\n const abortPromise = new Promise<null>((resolveAbort) =>\n controller.signal.addEventListener('abort', () => resolveAbort(null), { once: true }),\n );\n const readStdin = async (): Promise<Uint8Array | null> => {\n const result = await Promise.race([stdinReader.read(), abortPromise]);\n if (result == null) throw controller.signal.reason;\n return result.done ? null : result.value;\n };\n const emit = (\n target: ReadableStreamDefaultController<Uint8Array> | null,\n bytes: Uint8Array,\n ) => {\n if (bytes.byteLength > 0) target?.enqueue(bytes.slice());\n };\n const context = {\n fs: shellFs,\n io: {\n readStdin,\n stdout: (bytes: Uint8Array) => emit(outputs.stdout, bytes),\n stderr: (bytes: Uint8Array) => emit(outputs.stderr, bytes),\n signal: controller.signal,\n },\n cwd: options.cwd == null ? cwd : resolve(options.cwd),\n env,\n sleep: abortableSleep,\n };\n const timeout =\n options.timeoutMs == null\n ? null\n : setTimeout(() => {\n killedWith = 'timeout';\n controller.abort(new Error('timed out'));\n }, options.timeoutMs);\n const onAbortSignal = () => {\n killedWith ??= 'SIGTERM';\n controller.abort(new Error('aborted'));\n };\n options.abortSignal?.addEventListener('abort', onAbortSignal, { once: true });\n const exited = (async (): Promise<{ exitCode: number }> => {\n let exitCode: number;\n try {\n if (context.fs.kind(context.cwd) !== 'directory') {\n context.io.stderr(utf8Encode(`cd: ${context.cwd}: No such file or directory\\n`));\n exitCode = 1;\n } else if (options.shell === true) {\n const script = [options.command, ...(options.args ?? [])].join(' ');\n exitCode = await runMemoryScript({ ...context, script });\n } else {\n exitCode = await runMemoryArgv({\n ...context,\n argv: [options.command, ...(options.args ?? [])],\n });\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n context.io.stderr(\n utf8Encode(`${error instanceof Error ? error.message : String(error)}\\n`),\n );\n exitCode = 1;\n } else {\n exitCode = killedWith === 'timeout' ? 124 : signalExitCode(killedWith ?? undefined);\n }\n }\n if (timeout != null) clearTimeout(timeout);\n options.abortSignal?.removeEventListener('abort', onAbortSignal);\n stdinReader.cancel().catch(() => undefined);\n outputs.stdout?.close();\n outputs.stderr?.close();\n if (self != null) processes.delete(self);\n return { exitCode };\n })();\n const child: SandboxProcessIface = {\n pid: null,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n const bytes = data instanceof Uint8Array ? data : utf8Encode(data);\n if (bytes.byteLength > 0) await stdinWriter.write(bytes);\n if (writeOptions?.end === true) await stdinWriter.close();\n },\n wait: () => exited,\n kill: async (signal) => {\n killedWith ??= signal ?? 'SIGTERM';\n controller.abort(new Error(`killed (${signal ?? 'SIGTERM'})`));\n await exited;\n },\n };\n self = child;\n processes.add(child);\n return child;\n };\n\n const sandbox: MemorySandboxIface = {\n id,\n defaultWorkingDirectory: cwd,\n ports: args.ports ?? [],\n get description() {\n return `In-memory sandbox ${id}. Working directory ${cwd}. Commands: echo, cat, ls, pwd, cd, true, false, sleep, exit, mkdir, sh -c.`;\n },\n get networkPolicy() {\n return networkPolicy;\n },\n get stopped() {\n return stopped;\n },\n readFile: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) return null;\n if (entry.type === 'directory') throw fsError('EISDIR', `${path} is a directory`);\n const data = entry.data;\n const chunkBytes = 64 * 1024;\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= data.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(data.byteLength, offset + chunkBytes);\n controller.enqueue(data.slice(offset, end));\n offset = end;\n },\n });\n },\n readBinaryFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile: async (options) => {\n const data = await readAllBytes(options.content);\n putFile(resolve(options.path), data);\n },\n writeBinaryFile: async (options) => {\n putFile(resolve(options.path), options.content.slice());\n },\n writeTextFile: async (options) => {\n putFile(resolve(options.path), encodeSandboxText(options.content, options.encoding));\n },\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options) => statOf(resolve(options.path)),\n readDir: async (options): Promise<DirEntryIface[]> => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) throw fsError('ENOENT', `${path}: No such file or directory`);\n if (entry.type !== 'directory') throw fsError('ENOTDIR', `${path} is not a directory`);\n return children(path).map((name) => {\n const childPath = path === '/' ? `/${name}` : `${path}/${name}`;\n const child = entries.get(childPath);\n return {\n name,\n path: childPath,\n type: child?.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: child?.type === 'file' ? child.data.byteLength : null,\n };\n });\n },\n resolvePath: resolve,\n removePath: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) {\n if (options.force === true) return;\n throw fsError('ENOENT', `${path}: No such file or directory`);\n }\n if (path === '/') throw fsError('EPERM', 'refusing to remove /');\n if (entry.type === 'directory') {\n const prefix = `${path}/`;\n const nested = [...entries.keys()].filter((key) => key.startsWith(prefix));\n if (nested.length > 0 && options.recursive !== true)\n throw fsError('ENOTEMPTY', `${path}: Directory not empty`);\n for (const key of nested) entries.delete(key);\n }\n entries.delete(path);\n },\n getPortEndpoint: async (options) => {\n const protocol = options.protocol ?? PortProtocol.Http;\n return {\n url:\n args.portUrl?.({ port: options.port, protocol }) ??\n `${protocol}://127.0.0.1:${options.port}`,\n };\n },\n getPortUrl: async (options) => (await sandbox.getPortEndpoint(options)).url,\n stop: async () => {\n stopped = true;\n await Promise.all([...processes].map((child) => child.kill()));\n },\n destroy: async () => {\n await sandbox.stop();\n entries.clear();\n ensureDirectory('/');\n },\n };\n if (args.networkPolicy === true) {\n sandbox.setNetworkPolicy = async (policy) => {\n networkPolicy = policy;\n };\n }\n if (args.computerUse != null) sandbox.computerUse = args.computerUse;\n if (args.screen != null) sandbox.screen = args.screen;\n if (args.localMcp != null) sandbox.localMcp = args.localMcp;\n return sandbox;\n};\n\n// Every file of a memory sandbox as path \u2192 base64-free UTF-8 text (binary\n// files are skipped); handy for assertions.\nexport const memorySandboxTextFiles = async (\n sandbox: NetworkSandboxSessionIface,\n root = '/',\n): Promise<Record<string, string>> => {\n const out: Record<string, string> = {};\n const walk = async (path: string) => {\n for (const entry of await sandbox.readDir({ path })) {\n if (entry.type === SandboxEntryType.Directory) await walk(entry.path);\n else {\n const text = await sandbox.readTextFile({ path: entry.path });\n if (text != null) out[entry.path] = text;\n }\n }\n };\n await walk(root);\n return out;\n};\n\nconst memoryEnvironmentSchema = z\n .object({\n files: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n ports: z.array(z.number().int()).optional(),\n // Plain variables for every process, under the platform's.\n env: z.record(z.string(), z.string()).optional(),\n })\n .nullable()\n .optional();\n\nexport type MemorySandboxArtifact = { files: Record<string, string>; cwd: string; ports: number[] };\nexport type MemorySandboxState = { id: string };\n\nconst fingerprint = (value: string): string => {\n // FNV-1a, enough for a content key in an example provider.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n};\n\nconst memoryHandle = (\n sandbox: MemorySandboxIface,\n): SandboxProviderHandleIface<MemorySandboxIface> => ({\n sandbox,\n onSandboxStop: () => sandbox.stop(),\n onSandboxDelete: () => sandbox.destroy(),\n onRuntimeShutdown: () => sandbox.stop(),\n});\n\n// Example provider over the memory sandbox. Ephemeral: `resume` starts again\n// from the prepared artifact, so files written before a park are lost.\nexport const memorySandboxProvider = defineSandboxProvider<\n JsonValue,\n JsonValue,\n MemorySandboxArtifact,\n MemorySandboxState,\n MemorySandboxIface\n>({\n name: 'memory',\n environment: (rawOptions) => {\n const options = memoryEnvironmentSchema.parse(rawOptions) ?? {};\n const artifactFor = (files: Record<string, string>): MemorySandboxArtifact => ({\n files: { ...options.files, ...files },\n cwd: options.cwd ?? '/workspace',\n ports: options.ports ?? [],\n });\n const specEnv = options.env ?? {};\n const open = async (\n ctx: SandboxStartContextIface,\n bindingId: string,\n artifact: MemorySandboxArtifact,\n ) => {\n for (const name of Object.keys(specEnv))\n if (PLATFORM_ENVIRONMENT_NAMES.has(name)) throw new Error(`${name} is reserved`);\n const sandbox = createMemorySandbox({\n id: bindingId,\n files: artifact.files,\n cwd: artifact.cwd,\n ports: artifact.ports,\n baseEnv: platformProcessEnvironment(ctx, specEnv),\n });\n await writePlatformFiles(ctx, sandbox);\n return sandbox;\n };\n return {\n artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,\n prepare: async (ctx) => artifactFor(ctx.files),\n start: async (ctx, _openOptions, artifact) => ({\n handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),\n state: { id: ctx.session.bindingId },\n }),\n resume: async (ctx, artifact, state) => memoryHandle(await open(ctx, state.id, artifact)),\n park: async (_ctx, _artifact, state) => state,\n };\n },\n});\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,mBAAmB,cAAc,kBAAkB;AAC5D,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,eAAe,uBAAgD;AACxE,SAAS,oBAAoB,cAAc,wBAAwB;AACnE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAUK;AAoCP,MAAM,UAAU,CAAC,MAAc,YAC7B,OAAO,OAAO,IAAI,MAAM,GAAG,IAAI,KAAK,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC;AAE1D,MAAM,iBAAiB,CAAC,IAAY,WAClC,IAAI,QAAc,CAAC,SAAS,WAAW;AACrC,MAAI,OAAO,SAAS;AAClB,WAAO,OAAO,MAAM;AACpB;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,MAAM;AAC7B,WAAO,oBAAoB,SAAS,OAAO;AAC3C,YAAQ;AAAA,EACV,GAAG,EAAE;AACL,QAAM,UAAU,MAAM;AACpB,iBAAa,KAAK;AAClB,WAAO,OAAO,MAAM;AAAA,EACtB;AACA,SAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;AAC1D,CAAC;AAEH,MAAM,iBAAiB,CAAC,WAAuC;AAC7D,MAAI,WAAW,aAAa,WAAW,UAAU,WAAW,IAAK,QAAO;AACxE,MAAI,WAAW,YAAY,WAAW,MAAO,QAAO;AACpD,SAAO;AACT;AAEO,MAAM,sBAAsB,CACjC,OAAqC,CAAC,MACf;AACvB,QAAM,KAAK,KAAK,MAAM,UAAU,OAAO,WAAW,CAAC;AACnD,QAAM,MAAM,mBAAmB,KAAK,OAAO,YAAY;AACvD,QAAM,MAAM,KAAK,QAAQ,MAAM,oBAAI,KAAK;AACxC,QAAM,UAAU,oBAAI,IA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A,EACF;AACF,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -19,6 +19,7 @@ export interface MemoryShellContextIface {
|
|
|
19
19
|
fs: MemoryShellFsIface;
|
|
20
20
|
io: MemoryShellIoIface;
|
|
21
21
|
cwd: string;
|
|
22
|
+
env?: Record<string, string>;
|
|
22
23
|
sleep: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
23
24
|
}
|
|
24
25
|
export declare const runMemoryScript: (args: MemoryShellContextIface & {
|
|
@@ -189,6 +189,20 @@ const runCommand = async (context, command) => {
|
|
|
189
189
|
context.cwd = path;
|
|
190
190
|
return 0;
|
|
191
191
|
}
|
|
192
|
+
case "printenv": {
|
|
193
|
+
const env = context.env ?? {};
|
|
194
|
+
if (args.length === 0) {
|
|
195
|
+
for (const [key, value] of Object.entries(env)) out(line(`${key}=${value}`));
|
|
196
|
+
return 0;
|
|
197
|
+
}
|
|
198
|
+
let status2 = 0;
|
|
199
|
+
for (const arg of args) {
|
|
200
|
+
const value = Object.hasOwn(env, arg) ? env[arg] : void 0;
|
|
201
|
+
if (value == null) status2 = 1;
|
|
202
|
+
else out(line(value));
|
|
203
|
+
}
|
|
204
|
+
return status2;
|
|
205
|
+
}
|
|
192
206
|
case "true":
|
|
193
207
|
return 0;
|
|
194
208
|
case "false":
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/memory-shell.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport { utf8Encode } from \"./bytes.mjs\";\nimport { posixBasename, resolvePosixPath } from \"./paths.mjs\";\n\n// A tiny command interpreter for the in-memory reference sandbox: enough of a\n// shell for tests and the conformance kit. Supports `;`, `&&`, `||`, newlines,\n// single and double quotes, `> file`, `>> file`, `>&2`, and the commands echo,\n// cat, ls, pwd, cd, true, false, sleep, exit, mkdir and `sh -c` / `bash -c`.\n\nexport interface MemoryShellFsIface {\n readFile(path: string): Uint8Array | null;\n writeFile(path: string, data: Uint8Array, options: { append: boolean }): void;\n kind(path: string): 'file' | 'directory' | null;\n list(path: string): string[] | null;\n mkdir(path: string, options: { parents: boolean }): void;\n}\n\nexport interface MemoryShellIoIface {\n // Next stdin chunk, or null at end of input.\n readStdin: () => Promise<Uint8Array | null>;\n stdout: (bytes: Uint8Array) => void;\n stderr: (bytes: Uint8Array) => void;\n signal: AbortSignal;\n}\n\nexport interface MemoryShellContextIface {\n fs: MemoryShellFsIface;\n io: MemoryShellIoIface;\n cwd: string;\n sleep: (ms: number, signal: AbortSignal) => Promise<void>;\n}\n\ntype Token = { kind: 'word'; value: string } | { kind: 'op'; value: string };\n\ninterface CommandIface {\n argv: string[];\n stdoutTo: { path: string; append: boolean } | 'stderr' | null;\n}\n\ninterface StepIface {\n connector: ';' | '&&' | '||';\n command: CommandIface;\n}\n\n// `exit N` unwinds the script as an error carrying the status.\ninterface ExitRequestIface extends Error {\n code: number;\n}\n\nconst EXIT_REQUEST = 'MemoryShellExit';\nconst exitFieldsSchema = z.object({ code: z.number() });\n\nconst exitRequest = (code: number): ExitRequestIface =>\n Object.assign(new Error(`exit ${code}`), { name: EXIT_REQUEST, code });\n\nconst isExitRequest = (cause: unknown): cause is ExitRequestIface =>\n cause instanceof Error &&\n cause.name === EXIT_REQUEST &&\n exitFieldsSchema.safeParse(cause).success;\n\nconst tokenize = (script: string): Token[] => {\n const tokens: Token[] = [];\n let word: string | null = null;\n const flush = () => {\n if (word != null) tokens.push({ kind: 'word', value: word });\n word = null;\n };\n for (let i = 0; i < script.length; i += 1) {\n const char = script[i] ?? '';\n if (char === \"'\") {\n const end = script.indexOf(\"'\", i + 1);\n const stop = end < 0 ? script.length : end;\n word = (word ?? '') + script.slice(i + 1, stop);\n i = stop;\n continue;\n }\n if (char === '\"') {\n let value = '';\n let j = i + 1;\n for (; j < script.length && script[j] !== '\"'; j += 1) {\n if (script[j] === '\\\\' && j + 1 < script.length) {\n j += 1;\n }\n value += script[j] ?? '';\n }\n word = (word ?? '') + value;\n i = j;\n continue;\n }\n if (char === '\\\\' && i + 1 < script.length) {\n word = (word ?? '') + (script[i + 1] ?? '');\n i += 1;\n continue;\n }\n if (char === ' ' || char === '\\t') {\n flush();\n continue;\n }\n if (char === '\\n' || char === ';') {\n flush();\n tokens.push({ kind: 'op', value: ';' });\n continue;\n }\n if (char === '&' && script[i + 1] === '&') {\n flush();\n tokens.push({ kind: 'op', value: '&&' });\n i += 1;\n continue;\n }\n if (char === '|' && script[i + 1] === '|') {\n flush();\n tokens.push({ kind: 'op', value: '||' });\n i += 1;\n continue;\n }\n if (char === '>') {\n flush();\n if (script.startsWith('>&2', i)) {\n tokens.push({ kind: 'op', value: '>&2' });\n i += 2;\n } else if (script[i + 1] === '>') {\n tokens.push({ kind: 'op', value: '>>' });\n i += 1;\n } else {\n tokens.push({ kind: 'op', value: '>' });\n }\n continue;\n }\n if (char === '#' && word == null) {\n const end = script.indexOf('\\n', i);\n i = end < 0 ? script.length : end - 1;\n continue;\n }\n word = (word ?? '') + char;\n }\n flush();\n return tokens;\n};\n\nconst parse = (script: string): StepIface[] => {\n const steps: StepIface[] = [];\n let connector: StepIface['connector'] = ';';\n let command: CommandIface = { argv: [], stdoutTo: null };\n const push = () => {\n if (command.argv.length > 0) steps.push({ connector, command });\n command = { argv: [], stdoutTo: null };\n };\n const tokens = tokenize(script);\n for (let i = 0; i < tokens.length; i += 1) {\n const token = tokens[i];\n if (token == null) continue;\n if (token.kind === 'word') {\n command.argv.push(token.value);\n continue;\n }\n if (token.value === '>&2') {\n command.stdoutTo = 'stderr';\n continue;\n }\n if (token.value === '>' || token.value === '>>') {\n const target = tokens[i + 1];\n if (target?.kind === 'word') {\n command.stdoutTo = { path: target.value, append: token.value === '>>' };\n i += 1;\n }\n continue;\n }\n push();\n connector = token.value === '&&' ? '&&' : token.value === '||' ? '||' : ';';\n }\n push();\n return steps;\n};\n\nconst line = (text: string) => utf8Encode(`${text}\\n`);\n\nconst runCommand = async (\n context: MemoryShellContextIface,\n command: CommandIface,\n): Promise<number> => {\n const [name, ...args] = command.argv;\n const captured: Uint8Array[] = [];\n const out = (bytes: Uint8Array) => {\n if (command.stdoutTo == null) context.io.stdout(bytes);\n else if (command.stdoutTo === 'stderr') context.io.stderr(bytes);\n else captured.push(bytes);\n };\n const err = (text: string) => context.io.stderr(line(text));\n const status = await (async (): Promise<number> => {\n switch (name) {\n case 'echo': {\n const noNewline = args[0] === '-n';\n const text = (noNewline ? args.slice(1) : args).join(' ');\n out(utf8Encode(noNewline ? text : `${text}\\n`));\n return 0;\n }\n case 'cat': {\n if (args.length === 0) {\n for (;;) {\n const chunk = await context.io.readStdin();\n if (chunk == null) return 0;\n out(chunk);\n }\n }\n let status = 0;\n for (const arg of args) {\n const path = resolvePosixPath(context.cwd, arg);\n const data = context.fs.readFile(path);\n if (data == null) {\n err(\n `cat: ${arg}: ${context.fs.kind(path) === 'directory' ? 'Is a directory' : 'No such file or directory'}`,\n );\n status = 1;\n } else {\n out(data);\n }\n }\n return status;\n }\n case 'ls': {\n const targets = args.filter((arg) => !arg.startsWith('-'));\n let status = 0;\n for (const arg of targets.length === 0 ? ['.'] : targets) {\n const path = resolvePosixPath(context.cwd, arg);\n const kind = context.fs.kind(path);\n if (kind == null) {\n err(`ls: cannot access '${arg}': No such file or directory`);\n status = 2;\n } else if (kind === 'file') {\n out(line(posixBasename(path)));\n } else {\n for (const entry of context.fs.list(path) ?? []) out(line(entry));\n }\n }\n return status;\n }\n case 'pwd':\n out(line(context.cwd));\n return 0;\n case 'cd': {\n const path = resolvePosixPath(context.cwd, args[0] ?? '/');\n if (context.fs.kind(path) !== 'directory') {\n err(`cd: ${args[0] ?? '/'}: No such file or directory`);\n return 1;\n }\n context.cwd = path;\n return 0;\n }\n case 'true':\n return 0;\n case 'false':\n return 1;\n case 'sleep': {\n const seconds = Number(args[0] ?? '0');\n if (!Number.isFinite(seconds) || seconds < 0) {\n err(`sleep: invalid time interval '${args[0] ?? ''}'`);\n return 1;\n }\n await context.sleep(seconds * 1000, context.io.signal);\n return 0;\n }\n case 'exit': {\n const code = Number(args[0] ?? '0');\n throw exitRequest(Number.isInteger(code) ? code & 0xff : 2);\n }\n case 'mkdir': {\n const parents = args.includes('-p');\n for (const arg of args.filter((value) => !value.startsWith('-'))) {\n try {\n context.fs.mkdir(resolvePosixPath(context.cwd, arg), { parents });\n } catch (error) {\n err(\n `mkdir: cannot create directory '${arg}': ${error instanceof Error ? error.message : 'error'}`,\n );\n return 1;\n }\n }\n return 0;\n }\n case 'sh':\n case 'bash': {\n const flag = args.indexOf('-c');\n const script = flag >= 0 ? args[flag + 1] : undefined;\n if (script == null) {\n err(`${name}: interactive shells are not supported by the memory sandbox`);\n return 127;\n }\n return runMemoryScript({ ...context, script });\n }\n default:\n err(`${name ?? ''}: command not found`);\n return 127;\n }\n })();\n if (command.stdoutTo != null && command.stdoutTo !== 'stderr') {\n const path = resolvePosixPath(context.cwd, command.stdoutTo.path);\n const total = captured.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const data = new Uint8Array(total);\n let offset = 0;\n for (const chunk of captured) {\n data.set(chunk, offset);\n offset += chunk.byteLength;\n }\n context.fs.writeFile(path, data, { append: command.stdoutTo.append });\n }\n return status;\n};\n\n// Runs a script; resolves with its exit status. Aborting the signal stops it\n// between commands and inside `sleep` and stdin reads (the caller maps the\n// abort to a signal exit status).\nexport const runMemoryScript = async (\n args: MemoryShellContextIface & { script: string },\n): Promise<number> => {\n let status = 0;\n try {\n for (const step of parse(args.script)) {\n args.io.signal.throwIfAborted();\n if (step.connector === '&&' && status !== 0) continue;\n if (step.connector === '||' && status === 0) continue;\n status = await runCommand(args, step.command);\n }\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n return status;\n};\n\nexport const runMemoryArgv = async (\n args: MemoryShellContextIface & { argv: string[] },\n): Promise<number> => {\n try {\n return await runCommand(args, { argv: args.argv, stdoutTo: null });\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n};\n"],
|
|
5
|
-
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,kBAAkB;AAC3B,SAAS,eAAe,wBAAwB;
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport { utf8Encode } from \"./bytes.mjs\";\nimport { posixBasename, resolvePosixPath } from \"./paths.mjs\";\n\n// A tiny command interpreter for the in-memory reference sandbox: enough of a\n// shell for tests and the conformance kit. Supports `;`, `&&`, `||`, newlines,\n// single and double quotes, `> file`, `>> file`, `>&2`, and the commands echo,\n// cat, ls, pwd, cd, true, false, sleep, exit, mkdir, printenv and `sh -c` / `bash -c`.\n\nexport interface MemoryShellFsIface {\n readFile(path: string): Uint8Array | null;\n writeFile(path: string, data: Uint8Array, options: { append: boolean }): void;\n kind(path: string): 'file' | 'directory' | null;\n list(path: string): string[] | null;\n mkdir(path: string, options: { parents: boolean }): void;\n}\n\nexport interface MemoryShellIoIface {\n // Next stdin chunk, or null at end of input.\n readStdin: () => Promise<Uint8Array | null>;\n stdout: (bytes: Uint8Array) => void;\n stderr: (bytes: Uint8Array) => void;\n signal: AbortSignal;\n}\n\nexport interface MemoryShellContextIface {\n fs: MemoryShellFsIface;\n io: MemoryShellIoIface;\n cwd: string;\n // The process's environment, which only printenv reads (no `$` expansion).\n env?: Record<string, string>;\n sleep: (ms: number, signal: AbortSignal) => Promise<void>;\n}\n\ntype Token = { kind: 'word'; value: string } | { kind: 'op'; value: string };\n\ninterface CommandIface {\n argv: string[];\n stdoutTo: { path: string; append: boolean } | 'stderr' | null;\n}\n\ninterface StepIface {\n connector: ';' | '&&' | '||';\n command: CommandIface;\n}\n\n// `exit N` unwinds the script as an error carrying the status.\ninterface ExitRequestIface extends Error {\n code: number;\n}\n\nconst EXIT_REQUEST = 'MemoryShellExit';\nconst exitFieldsSchema = z.object({ code: z.number() });\n\nconst exitRequest = (code: number): ExitRequestIface =>\n Object.assign(new Error(`exit ${code}`), { name: EXIT_REQUEST, code });\n\nconst isExitRequest = (cause: unknown): cause is ExitRequestIface =>\n cause instanceof Error &&\n cause.name === EXIT_REQUEST &&\n exitFieldsSchema.safeParse(cause).success;\n\nconst tokenize = (script: string): Token[] => {\n const tokens: Token[] = [];\n let word: string | null = null;\n const flush = () => {\n if (word != null) tokens.push({ kind: 'word', value: word });\n word = null;\n };\n for (let i = 0; i < script.length; i += 1) {\n const char = script[i] ?? '';\n if (char === \"'\") {\n const end = script.indexOf(\"'\", i + 1);\n const stop = end < 0 ? script.length : end;\n word = (word ?? '') + script.slice(i + 1, stop);\n i = stop;\n continue;\n }\n if (char === '\"') {\n let value = '';\n let j = i + 1;\n for (; j < script.length && script[j] !== '\"'; j += 1) {\n if (script[j] === '\\\\' && j + 1 < script.length) {\n j += 1;\n }\n value += script[j] ?? '';\n }\n word = (word ?? '') + value;\n i = j;\n continue;\n }\n if (char === '\\\\' && i + 1 < script.length) {\n word = (word ?? '') + (script[i + 1] ?? '');\n i += 1;\n continue;\n }\n if (char === ' ' || char === '\\t') {\n flush();\n continue;\n }\n if (char === '\\n' || char === ';') {\n flush();\n tokens.push({ kind: 'op', value: ';' });\n continue;\n }\n if (char === '&' && script[i + 1] === '&') {\n flush();\n tokens.push({ kind: 'op', value: '&&' });\n i += 1;\n continue;\n }\n if (char === '|' && script[i + 1] === '|') {\n flush();\n tokens.push({ kind: 'op', value: '||' });\n i += 1;\n continue;\n }\n if (char === '>') {\n flush();\n if (script.startsWith('>&2', i)) {\n tokens.push({ kind: 'op', value: '>&2' });\n i += 2;\n } else if (script[i + 1] === '>') {\n tokens.push({ kind: 'op', value: '>>' });\n i += 1;\n } else {\n tokens.push({ kind: 'op', value: '>' });\n }\n continue;\n }\n if (char === '#' && word == null) {\n const end = script.indexOf('\\n', i);\n i = end < 0 ? script.length : end - 1;\n continue;\n }\n word = (word ?? '') + char;\n }\n flush();\n return tokens;\n};\n\nconst parse = (script: string): StepIface[] => {\n const steps: StepIface[] = [];\n let connector: StepIface['connector'] = ';';\n let command: CommandIface = { argv: [], stdoutTo: null };\n const push = () => {\n if (command.argv.length > 0) steps.push({ connector, command });\n command = { argv: [], stdoutTo: null };\n };\n const tokens = tokenize(script);\n for (let i = 0; i < tokens.length; i += 1) {\n const token = tokens[i];\n if (token == null) continue;\n if (token.kind === 'word') {\n command.argv.push(token.value);\n continue;\n }\n if (token.value === '>&2') {\n command.stdoutTo = 'stderr';\n continue;\n }\n if (token.value === '>' || token.value === '>>') {\n const target = tokens[i + 1];\n if (target?.kind === 'word') {\n command.stdoutTo = { path: target.value, append: token.value === '>>' };\n i += 1;\n }\n continue;\n }\n push();\n connector = token.value === '&&' ? '&&' : token.value === '||' ? '||' : ';';\n }\n push();\n return steps;\n};\n\nconst line = (text: string) => utf8Encode(`${text}\\n`);\n\nconst runCommand = async (\n context: MemoryShellContextIface,\n command: CommandIface,\n): Promise<number> => {\n const [name, ...args] = command.argv;\n const captured: Uint8Array[] = [];\n const out = (bytes: Uint8Array) => {\n if (command.stdoutTo == null) context.io.stdout(bytes);\n else if (command.stdoutTo === 'stderr') context.io.stderr(bytes);\n else captured.push(bytes);\n };\n const err = (text: string) => context.io.stderr(line(text));\n const status = await (async (): Promise<number> => {\n switch (name) {\n case 'echo': {\n const noNewline = args[0] === '-n';\n const text = (noNewline ? args.slice(1) : args).join(' ');\n out(utf8Encode(noNewline ? text : `${text}\\n`));\n return 0;\n }\n case 'cat': {\n if (args.length === 0) {\n for (;;) {\n const chunk = await context.io.readStdin();\n if (chunk == null) return 0;\n out(chunk);\n }\n }\n let status = 0;\n for (const arg of args) {\n const path = resolvePosixPath(context.cwd, arg);\n const data = context.fs.readFile(path);\n if (data == null) {\n err(\n `cat: ${arg}: ${context.fs.kind(path) === 'directory' ? 'Is a directory' : 'No such file or directory'}`,\n );\n status = 1;\n } else {\n out(data);\n }\n }\n return status;\n }\n case 'ls': {\n const targets = args.filter((arg) => !arg.startsWith('-'));\n let status = 0;\n for (const arg of targets.length === 0 ? ['.'] : targets) {\n const path = resolvePosixPath(context.cwd, arg);\n const kind = context.fs.kind(path);\n if (kind == null) {\n err(`ls: cannot access '${arg}': No such file or directory`);\n status = 2;\n } else if (kind === 'file') {\n out(line(posixBasename(path)));\n } else {\n for (const entry of context.fs.list(path) ?? []) out(line(entry));\n }\n }\n return status;\n }\n case 'pwd':\n out(line(context.cwd));\n return 0;\n case 'cd': {\n const path = resolvePosixPath(context.cwd, args[0] ?? '/');\n if (context.fs.kind(path) !== 'directory') {\n err(`cd: ${args[0] ?? '/'}: No such file or directory`);\n return 1;\n }\n context.cwd = path;\n return 0;\n }\n case 'printenv': {\n const env = context.env ?? {};\n if (args.length === 0) {\n for (const [key, value] of Object.entries(env)) out(line(`${key}=${value}`));\n return 0;\n }\n let status = 0;\n for (const arg of args) {\n const value = Object.hasOwn(env, arg) ? env[arg] : undefined;\n if (value == null) status = 1;\n else out(line(value));\n }\n return status;\n }\n case 'true':\n return 0;\n case 'false':\n return 1;\n case 'sleep': {\n const seconds = Number(args[0] ?? '0');\n if (!Number.isFinite(seconds) || seconds < 0) {\n err(`sleep: invalid time interval '${args[0] ?? ''}'`);\n return 1;\n }\n await context.sleep(seconds * 1000, context.io.signal);\n return 0;\n }\n case 'exit': {\n const code = Number(args[0] ?? '0');\n throw exitRequest(Number.isInteger(code) ? code & 0xff : 2);\n }\n case 'mkdir': {\n const parents = args.includes('-p');\n for (const arg of args.filter((value) => !value.startsWith('-'))) {\n try {\n context.fs.mkdir(resolvePosixPath(context.cwd, arg), { parents });\n } catch (error) {\n err(\n `mkdir: cannot create directory '${arg}': ${error instanceof Error ? error.message : 'error'}`,\n );\n return 1;\n }\n }\n return 0;\n }\n case 'sh':\n case 'bash': {\n const flag = args.indexOf('-c');\n const script = flag >= 0 ? args[flag + 1] : undefined;\n if (script == null) {\n err(`${name}: interactive shells are not supported by the memory sandbox`);\n return 127;\n }\n return runMemoryScript({ ...context, script });\n }\n default:\n err(`${name ?? ''}: command not found`);\n return 127;\n }\n })();\n if (command.stdoutTo != null && command.stdoutTo !== 'stderr') {\n const path = resolvePosixPath(context.cwd, command.stdoutTo.path);\n const total = captured.reduce((sum, chunk) => sum + chunk.byteLength, 0);\n const data = new Uint8Array(total);\n let offset = 0;\n for (const chunk of captured) {\n data.set(chunk, offset);\n offset += chunk.byteLength;\n }\n context.fs.writeFile(path, data, { append: command.stdoutTo.append });\n }\n return status;\n};\n\n// Runs a script; resolves with its exit status. Aborting the signal stops it\n// between commands and inside `sleep` and stdin reads (the caller maps the\n// abort to a signal exit status).\nexport const runMemoryScript = async (\n args: MemoryShellContextIface & { script: string },\n): Promise<number> => {\n let status = 0;\n try {\n for (const step of parse(args.script)) {\n args.io.signal.throwIfAborted();\n if (step.connector === '&&' && status !== 0) continue;\n if (step.connector === '||' && status === 0) continue;\n status = await runCommand(args, step.command);\n }\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n return status;\n};\n\nexport const runMemoryArgv = async (\n args: MemoryShellContextIface & { argv: string[] },\n): Promise<number> => {\n try {\n return await runCommand(args, { argv: args.argv, stdoutTo: null });\n } catch (error) {\n if (isExitRequest(error)) return error.code;\n throw error;\n }\n};\n"],
|
|
5
|
+
"mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,kBAAkB;AAC3B,SAAS,eAAe,wBAAwB;AAiDhD,MAAM,eAAe;AACrB,MAAM,mBAAmB,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;AAEtD,MAAM,cAAc,CAAC,SACnB,OAAO,OAAO,IAAI,MAAM,QAAQ,IAAI,EAAE,GAAG,EAAE,MAAM,cAAc,KAAK,CAAC;AAEvE,MAAM,gBAAgB,CAAC,UACrB,iBAAiB,SACjB,MAAM,SAAS,gBACf,iBAAiB,UAAU,KAAK,EAAE;AAEpC,MAAM,WAAW,CAAC,WAA4B;AAC5C,QAAM,SAAkB,CAAC;AACzB,MAAI,OAAsB;AAC1B,QAAM,QAAQ,MAAM;AAClB,QAAI,QAAQ,KAAM,QAAO,KAAK,EAAE,MAAM,QA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,MAAI;AACF,WAAO,MAAM,WAAW,MAAM,EAAE,MAAM,KAAK,MAAM,UAAU,KAAK,CAAC;AAAA,EACnE,SAAS,OAAO;AACd,QAAI,cAAc,KAAK,EAAG,QAAO,MAAM;AACvC,UAAM;AAAA,EACR;AACF;",
|
|
6
6
|
"names": ["status"]
|
|
7
7
|
}
|
|
@@ -291,7 +291,14 @@ export interface SandboxStartContextIface {
|
|
|
291
291
|
variables: SandboxVariablesIface;
|
|
292
292
|
repositories: SandboxRepositoriesIface;
|
|
293
293
|
actingUser: SandboxActingUserIface;
|
|
294
|
-
|
|
294
|
+
platformEnvironment?: () => Promise<Record<string, string>>;
|
|
295
|
+
platformEgressHosts?: string[];
|
|
296
|
+
platformFiles?: () => Promise<Record<string, string>>;
|
|
297
|
+
}
|
|
298
|
+
export declare const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string>;
|
|
299
|
+
export declare const platformProcessEnvironment: (ctx: Pick<SandboxStartContextIface, "platformEnvironment">, specEnv: Record<string, string>) => (() => Promise<Record<string, string>>);
|
|
300
|
+
export declare const writePlatformFiles: (ctx: Pick<SandboxStartContextIface, "platformFiles">, sandbox: Pick<SandboxSessionIface, "writeTextFile">) => Promise<void>;
|
|
301
|
+
export declare const withPlatformEgressHosts: (ctx: Pick<SandboxStartContextIface, "platformEgressHosts">, policy: NetworkPolicyIface) => NetworkPolicyIface;
|
|
295
302
|
export declare enum SandboxSessionEndReason {
|
|
296
303
|
Completed = "completed",
|
|
297
304
|
Expired = "expired",
|
|
@@ -39,6 +39,33 @@ const noSandboxRepositories = {
|
|
|
39
39
|
};
|
|
40
40
|
const noSandboxVariables = { get: async () => null };
|
|
41
41
|
const noSandboxActingUser = { current: async () => null };
|
|
42
|
+
const PLATFORM_ENVIRONMENT_NAMES = /* @__PURE__ */ new Set([
|
|
43
|
+
"HTTPS_PROXY",
|
|
44
|
+
"HTTP_PROXY",
|
|
45
|
+
"NO_PROXY",
|
|
46
|
+
"NODE_USE_ENV_PROXY",
|
|
47
|
+
"SSL_CERT_FILE",
|
|
48
|
+
"CURL_CA_BUNDLE",
|
|
49
|
+
"REQUESTS_CA_BUNDLE",
|
|
50
|
+
"GIT_SSL_CAINFO",
|
|
51
|
+
"CARGO_HTTP_CAINFO",
|
|
52
|
+
"DENO_CERT",
|
|
53
|
+
"NODE_EXTRA_CA_CERTS",
|
|
54
|
+
"FINAL_EGRESS_URL",
|
|
55
|
+
"FINAL_EGRESS_TOKEN",
|
|
56
|
+
"GH_TOKEN",
|
|
57
|
+
"GITHUB_TOKEN"
|
|
58
|
+
]);
|
|
59
|
+
const platformProcessEnvironment = (ctx, specEnv) => async () => ({ ...specEnv, ...await ctx.platformEnvironment?.() });
|
|
60
|
+
const writePlatformFiles = async (ctx, sandbox) => {
|
|
61
|
+
for (const [path, content] of Object.entries(await ctx.platformFiles?.() ?? {}))
|
|
62
|
+
await sandbox.writeTextFile({ path, content });
|
|
63
|
+
};
|
|
64
|
+
const withPlatformEgressHosts = (ctx, policy) => {
|
|
65
|
+
const hosts = ctx.platformEgressHosts ?? [];
|
|
66
|
+
if (policy.mode !== "allowlist" /* Allowlist */ || hosts.length === 0) return policy;
|
|
67
|
+
return { ...policy, allow: [.../* @__PURE__ */ new Set([...policy.allow ?? [], ...hosts])] };
|
|
68
|
+
};
|
|
42
69
|
var SandboxSessionEndReason = /* @__PURE__ */ ((SandboxSessionEndReason2) => {
|
|
43
70
|
SandboxSessionEndReason2["Completed"] = "completed";
|
|
44
71
|
SandboxSessionEndReason2["Expired"] = "expired";
|
|
@@ -70,6 +97,7 @@ var SandboxEventKind = /* @__PURE__ */ ((SandboxEventKind2) => {
|
|
|
70
97
|
})(SandboxEventKind || {});
|
|
71
98
|
export {
|
|
72
99
|
NetworkPolicy,
|
|
100
|
+
PLATFORM_ENVIRONMENT_NAMES,
|
|
73
101
|
PortProtocol,
|
|
74
102
|
SandboxCapability,
|
|
75
103
|
SandboxEntryType,
|
|
@@ -81,6 +109,9 @@ export {
|
|
|
81
109
|
noSandboxActingUser,
|
|
82
110
|
noSandboxGuides,
|
|
83
111
|
noSandboxRepositories,
|
|
84
|
-
noSandboxVariables
|
|
112
|
+
noSandboxVariables,
|
|
113
|
+
platformProcessEnvironment,
|
|
114
|
+
withPlatformEgressHosts,
|
|
115
|
+
writePlatformFiles
|
|
85
116
|
};
|
|
86
117
|
//# sourceMappingURL=types.mjs.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/sandbox/types.ts"],
|
|
4
|
-
"sourcesContent": ["import type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../manifest.mjs\";\nimport type { SandboxEditorRequestIface, SandboxEditorResultIface } from \"./editor.mjs\";\nimport { awaitableOpenRequest, type AwaitableSandboxOpenRequestIface } from \"./open-scope.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport enum SandboxEntryType {\n File = 'file',\n Directory = 'directory',\n Symlink = 'symlink',\n Other = 'other',\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum NetworkPolicy {\n AllowAll = 'allow-all',\n DenyAll = 'deny-all',\n Allowlist = 'allowlist',\n}\n\nexport interface NetworkPolicyIface {\n mode: NetworkPolicy;\n allow?: string[];\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the session service) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Capabilities a started sandbox advertises (and the handle RPC exposes).\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n}\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// A saved computer setup guide version: Build's versioned build-\n// and start-time inputs for a sandbox, as the session service serves them.\nexport interface SandboxGuideVersionIface {\n guideId: string;\n versionId: string;\n slug: string;\n title: string;\n number: number;\n image: string;\n // `.final/sandbox-template.yaml` v2 as JSON.\n templateConfig: JsonValue;\n // The start-time parameters this version defaults to.\n defaultParameters: JsonValue;\n instructionsMarkdown: string | null;\n // A ready build from the guide's provider, reusable independently of workspace seeds.\n preparedArtifact?: { providerRef: string; key: string; artifact: JsonValue };\n}\n\n// The organization's computer setup guides, read through the session service.\n// Every provider gets the same reader; a provider whose\n// environments name no guide never calls it.\nexport interface SandboxGuidesIface {\n get(args: { ref: string; version: number | 'latest' }): Promise<SandboxGuideVersionIface | null>;\n // The organization's default guide; null when it has none.\n default(): Promise<SandboxGuideVersionIface | null>;\n}\n\n// Where to clone a repository from, with a short-lived read credential that\n// must reach only the clone process (never a repository's git config).\nexport interface SandboxRepositoryCloneSourceIface {\n url: string;\n // Checked out after the clone; null keeps the default branch.\n ref: string | null;\n // An HTTP Authorization header value for the clone, or null.\n authorization: string | null;\n}\n\n// Repository credentials for the repositories an environment names (a Code\n// Storage id, a GitHub owner/name), resolved by the session service for the\n// session's organization only. Null: not a repository it can resolve.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\n// Reads a named organization variable (managed in Build) for the session's\n// organization. Values are injected into the sandbox only, never stored in a\n// manifest, a state or the log.\nexport interface SandboxVariablesIface {\n get(name: string): Promise<string | null>;\n}\n\nexport const noSandboxGuides: SandboxGuidesIface = {\n get: async () => null,\n default: async () => null,\n};\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\nexport const noSandboxVariables: SandboxVariablesIface = { get: async () => null };\n\n// The user a session acts for: the author of its running turn, else its owner,\n// else the user whose Home its conversation is. A call a person makes through\n// the platform's sandbox viewer acts for that person instead. Null when it acts\n// for no user (a turn nobody prompted in a shared conversation) and outside any\n// session (a guide build). Read on each call, because it changes between turns\n// and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n actingUser: SandboxActingUserIface;\n}\n\n// What an environment's hooks are given before anything starts.\nexport interface SandboxEnvironmentContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n guides: SandboxGuidesIface;\n}\n\n// Scoped by the host to this organization and provider. Providers can retain\n// reusable intermediate artifacts independently of a revision's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\nexport interface SandboxPrepareContextIface {\n bindings?: HostedBindingsIface;\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Agent revisions supply workspace-relative seeds; setup-guide builds supply\n // guide.json and optional instructions.md. Resources name workspace, skills or guide.\n // Model instructions remain harness config.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n organizationId: string;\n // The guide inputs (build-time) an environment names, resolved by the platform.\n guides: SandboxGuidesIface;\n // Who the session the artifact is prepared for acts for, for environments that\n // name a backend resource relative to that user; the key must then name it.\n actingUser: SandboxActingUserIface;\n log?: (message: string) => void;\n}\n\nexport interface SandboxStartContextIface {\n bindings?: HostedBindingsIface;\n /** Passive recovery only: never wake, create, seed, or restart backend services. */\n passive?: boolean;\n preparation?: SandboxPreparationSourceIface;\n session: {\n id: string;\n organizationId: string;\n conversationId: string | null;\n definitionId: string;\n bindingId: string;\n target: string;\n };\n storagePath: string;\n // Start-time inputs: guides, the variables to inject, repository credentials.\n guides: SandboxGuidesIface;\n variables: SandboxVariablesIface;\n repositories: SandboxRepositoriesIface;\n actingUser: SandboxActingUserIface;\n}\n\nexport enum SandboxSessionEndReason {\n Completed = 'completed',\n Expired = 'expired',\n Failed = 'failed',\n}\n\n// How long an environment's sandbox outlives a session: `session`\n// keeps it for the session's life; `conversation` gives every session in the\n// conversation one shared sandbox per target, surviving session resets;\n// `ephemeral` discards it when released.\nexport enum SandboxWorkspace {\n Session = 'session',\n Conversation = 'conversation',\n Ephemeral = 'ephemeral',\n}\n\nexport interface SandboxProviderImplementationIface<\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The workspace this environment declares, read before anything starts so the\n // session service knows which sessions share a binding. Absent or null: session.\n workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;\n // The capabilities this environment's sandboxes offer, read before anything\n // starts through the backend's own API. Absent or null: unknown\n // until started; local MCP is then not projected.\n capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // The hosted MCP servers' tool catalogs the backend can give without starting\n // a sandbox (from its own records), so the MCP projection lists them from the\n // first `tools/list`. The projection checks a server's catalog against the\n // live server when a call first opens that server (servers a session never\n // uses stay closed) and announces a change with\n // `notifications/tools/list_changed`.\n //\n // Trade-off: a catalog left unknown (absent hook, null, or a null field) can\n // only be learned from the live sandbox, so the first `tools/list` that finds\n // it unknown starts the sandbox in the background, at session start rather\n // than on the first tool call. Otherwise those tools would never be listed,\n // and nothing would ever call them. Providers that can give the catalog keep\n // attach lazy.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without starting/resuming a sandbox. Null means the backend\n // is live or offers no snapshot. An unavailable sleeping snapshot must throw,\n // never fall through to a read that wakes it. Pin subsequent ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without opening, resuming or extending a sandbox.\n // Stop requires execute access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { bindingId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for this provider's existing workspace. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the session service caches artifacts in\n // agent.sandbox_artifacts and calls prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // session service can place the harness near it; null when unknown.\n start(\n ctx: SandboxStartContextIface,\n options: OpenOptions | undefined,\n artifact: Artifact,\n ): Promise<{ handle: SandboxProviderHandleIface<S>; state: State; region?: string | null }>;\n resume(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Reconnect to an already running backend after host restart for a read-only viewer.\n // Absent: viewers can use a retained live handle but cannot trigger resume.\n resumePassive?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Park: pause or stop the sandbox, returning the state resume needs.\n park?(ctx: SandboxStartContextIface, artifact: Artifact, state: State): Promise<State>;\n onSessionEnd?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n options: { reason: SandboxSessionEndReason },\n ): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The session service records it with each\n // binding and refuses to resume a state written under another version (the\n // next call starts the sandbox again instead).\n stateProtocolVersion?: number;\n environment(\n options?: EnvOptions,\n ): SandboxProviderImplementationIface<OpenOptions, Artifact, State, S>;\n}\n\n// A defined provider: the definition plus authoring sugar. `environment(opts)`\n// returns an environment whose `.open(openOptions)` records a sandbox binding\n// target when authored, and is what the session service drives at run time.\nexport interface SandboxProviderIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>;\n readonly name: string;\n environment(options?: EnvOptions): AwaitableSandboxEnvironmentIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly options: EnvOptions | undefined;\n // Provider-authored notices shown by the compiler and Build before publication.\n readonly authoringWarnings?: readonly string[];\n // Authoring: records the open options (access, ...) for this target.\n open(options?: OpenOptions): SandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\n// An environment whose open request a sandbox.ts selector can await to get\n// the live session (open-scope.ts); what defineSandboxProvider and the\n// installed helpers return.\nexport interface AwaitableSandboxEnvironmentIface<\n EnvOptions,\n OpenOptions,\n> extends SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n open(options?: OpenOptions): AwaitableSandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxOpenRequestIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly environmentOptions: EnvOptions | undefined;\n readonly openOptions: OpenOptions | undefined;\n readonly authoringWarnings?: readonly string[];\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, OpenOptions, Artifact, State, S> => ({\n definition,\n name: definition.name,\n environment: (options) => ({\n providerName: definition.name,\n options,\n open: (openOptions) =>\n awaitableOpenRequest({\n providerName: definition.name,\n environmentOptions: options,\n openOptions,\n }),\n }),\n});\n\n// Erased form the session service stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
|
|
5
|
-
"mappings": "AAQA,SAAS,4BAAmE;AAoCrE,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;
|
|
4
|
+
"sourcesContent": ["import type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../manifest.mjs\";\nimport type { SandboxEditorRequestIface, SandboxEditorResultIface } from \"./editor.mjs\";\nimport { awaitableOpenRequest, type AwaitableSandboxOpenRequestIface } from \"./open-scope.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport enum SandboxEntryType {\n File = 'file',\n Directory = 'directory',\n Symlink = 'symlink',\n Other = 'other',\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n // Writes create missing parent directories.\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum NetworkPolicy {\n AllowAll = 'allow-all',\n DenyAll = 'deny-all',\n Allowlist = 'allowlist',\n}\n\nexport interface NetworkPolicyIface {\n mode: NetworkPolicy;\n allow?: string[];\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the session service) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Capabilities a started sandbox advertises (and the handle RPC exposes).\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n}\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// A saved computer setup guide version: Build's versioned build-\n// and start-time inputs for a sandbox, as the session service serves them.\nexport interface SandboxGuideVersionIface {\n guideId: string;\n versionId: string;\n slug: string;\n title: string;\n number: number;\n image: string;\n // `.final/sandbox-template.yaml` v2 as JSON.\n templateConfig: JsonValue;\n // The start-time parameters this version defaults to.\n defaultParameters: JsonValue;\n instructionsMarkdown: string | null;\n // A ready build from the guide's provider, reusable independently of workspace seeds.\n preparedArtifact?: { providerRef: string; key: string; artifact: JsonValue };\n}\n\n// The organization's computer setup guides, read through the session service.\n// Every provider gets the same reader; a provider whose\n// environments name no guide never calls it.\nexport interface SandboxGuidesIface {\n get(args: { ref: string; version: number | 'latest' }): Promise<SandboxGuideVersionIface | null>;\n // The organization's default guide; null when it has none.\n default(): Promise<SandboxGuideVersionIface | null>;\n}\n\n// Where to clone a repository from, with a short-lived read credential that\n// must reach only the clone process (never a repository's git config).\nexport interface SandboxRepositoryCloneSourceIface {\n url: string;\n // Checked out after the clone; null keeps the default branch.\n ref: string | null;\n // An HTTP Authorization header value for the clone, or null.\n authorization: string | null;\n}\n\n// Repository credentials for the repositories an environment names (a Code\n// Storage id, a GitHub owner/name), resolved by the session service for the\n// session's organization only. Null: not a repository it can resolve.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\n// Reads a named organization variable (managed in Build) for the session's\n// organization. Values are injected into the sandbox only, never stored in a\n// manifest, a state or the log.\nexport interface SandboxVariablesIface {\n get(name: string): Promise<string | null>;\n}\n\nexport const noSandboxGuides: SandboxGuidesIface = {\n get: async () => null,\n default: async () => null,\n};\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\nexport const noSandboxVariables: SandboxVariablesIface = { get: async () => null };\n\n// The user a session acts for: the author of its running turn, else its owner,\n// else the user whose Home its conversation is. A call a person makes through\n// the platform's sandbox viewer acts for that person instead. Null when it acts\n// for no user (a turn nobody prompted in a shared conversation) and outside any\n// session (a guide build). Read on each call, because it changes between turns\n// and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n actingUser: SandboxActingUserIface;\n}\n\n// What an environment's hooks are given before anything starts.\nexport interface SandboxEnvironmentContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n guides: SandboxGuidesIface;\n}\n\n// Scoped by the host to this organization and provider. Providers can retain\n// reusable intermediate artifacts independently of a revision's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\nexport interface SandboxPrepareContextIface {\n bindings?: HostedBindingsIface;\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Agent revisions supply workspace-relative seeds; setup-guide builds supply\n // guide.json and optional instructions.md. Resources name workspace, skills or guide.\n // Model instructions remain harness config.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n organizationId: string;\n // The guide inputs (build-time) an environment names, resolved by the platform.\n guides: SandboxGuidesIface;\n // Who the session the artifact is prepared for acts for, for environments that\n // name a backend resource relative to that user; the key must then name it.\n actingUser: SandboxActingUserIface;\n log?: (message: string) => void;\n}\n\nexport interface SandboxStartContextIface {\n bindings?: HostedBindingsIface;\n /** Passive recovery only: never wake, create, seed, or restart backend services. */\n passive?: boolean;\n preparation?: SandboxPreparationSourceIface;\n session: {\n id: string;\n organizationId: string;\n conversationId: string | null;\n definitionId: string;\n bindingId: string;\n target: string;\n };\n storagePath: string;\n // Start-time inputs: guides, the variables to inject, repository credentials.\n guides: SandboxGuidesIface;\n variables: SandboxVariablesIface;\n repositories: SandboxRepositoriesIface;\n actingUser: SandboxActingUserIface;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, and one placeholder per bound secret. Evaluated\n // again for every spawn/run, never once per session: a secret bound\n // mid-session must reach the next command. May resolve to {} (no proxy\n // configured, or not ready yet). Platform values override the spec's env.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, to append\n // to any allowlist-mode network policy the spec declares.\n platformEgressHosts?: string[];\n // Files the platform needs in the sandbox before any clone, setup step or\n // service runs: written right after the sandbox exists, on start and resume.\n // Paths are absolute; missing parent directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. A spec that sets one (as a plain\n// value or an organization variable) is refused at start.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n 'GH_TOKEN',\n 'GITHUB_TOKEN',\n]);\n\n// A process's base environment: the spec's variables under the platform's,\n// read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxStartContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that now exists, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxStartContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxStartContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\n};\n\nexport enum SandboxSessionEndReason {\n Completed = 'completed',\n Expired = 'expired',\n Failed = 'failed',\n}\n\n// How long an environment's sandbox outlives a session: `session`\n// keeps it for the session's life; `conversation` gives every session in the\n// conversation one shared sandbox per target, surviving session resets;\n// `ephemeral` discards it when released.\nexport enum SandboxWorkspace {\n Session = 'session',\n Conversation = 'conversation',\n Ephemeral = 'ephemeral',\n}\n\nexport interface SandboxProviderImplementationIface<\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The workspace this environment declares, read before anything starts so the\n // session service knows which sessions share a binding. Absent or null: session.\n workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;\n // The capabilities this environment's sandboxes offer, read before anything\n // starts through the backend's own API. Absent or null: unknown\n // until started; local MCP is then not projected.\n capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // The hosted MCP servers' tool catalogs the backend can give without starting\n // a sandbox (from its own records), so the MCP projection lists them from the\n // first `tools/list`. The projection checks a server's catalog against the\n // live server when a call first opens that server (servers a session never\n // uses stay closed) and announces a change with\n // `notifications/tools/list_changed`.\n //\n // Trade-off: a catalog left unknown (absent hook, null, or a null field) can\n // only be learned from the live sandbox, so the first `tools/list` that finds\n // it unknown starts the sandbox in the background, at session start rather\n // than on the first tool call. Otherwise those tools would never be listed,\n // and nothing would ever call them. Providers that can give the catalog keep\n // attach lazy.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without starting/resuming a sandbox. Null means the backend\n // is live or offers no snapshot. An unavailable sleeping snapshot must throw,\n // never fall through to a read that wakes it. Pin subsequent ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without opening, resuming or extending a sandbox.\n // Stop requires execute access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { bindingId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for this provider's existing workspace. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the session service caches artifacts in\n // agent.sandbox_artifacts and calls prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // session service can place the harness near it; null when unknown.\n start(\n ctx: SandboxStartContextIface,\n options: OpenOptions | undefined,\n artifact: Artifact,\n ): Promise<{ handle: SandboxProviderHandleIface<S>; state: State; region?: string | null }>;\n resume(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Reconnect to an already running backend after host restart for a read-only viewer.\n // Absent: viewers can use a retained live handle but cannot trigger resume.\n resumePassive?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Park: pause or stop the sandbox, returning the state resume needs.\n park?(ctx: SandboxStartContextIface, artifact: Artifact, state: State): Promise<State>;\n onSessionEnd?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n options: { reason: SandboxSessionEndReason },\n ): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The session service records it with each\n // binding and refuses to resume a state written under another version (the\n // next call starts the sandbox again instead).\n stateProtocolVersion?: number;\n environment(\n options?: EnvOptions,\n ): SandboxProviderImplementationIface<OpenOptions, Artifact, State, S>;\n}\n\n// A defined provider: the definition plus authoring sugar. `environment(opts)`\n// returns an environment whose `.open(openOptions)` records a sandbox binding\n// target when authored, and is what the session service drives at run time.\nexport interface SandboxProviderIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>;\n readonly name: string;\n environment(options?: EnvOptions): AwaitableSandboxEnvironmentIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly options: EnvOptions | undefined;\n // Provider-authored notices shown by the compiler and Build before publication.\n readonly authoringWarnings?: readonly string[];\n // Authoring: records the open options (access, ...) for this target.\n open(options?: OpenOptions): SandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\n// An environment whose open request a sandbox.ts selector can await to get\n// the live session (open-scope.ts); what defineSandboxProvider and the\n// installed helpers return.\nexport interface AwaitableSandboxEnvironmentIface<\n EnvOptions,\n OpenOptions,\n> extends SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n open(options?: OpenOptions): AwaitableSandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxOpenRequestIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly environmentOptions: EnvOptions | undefined;\n readonly openOptions: OpenOptions | undefined;\n readonly authoringWarnings?: readonly string[];\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, OpenOptions, Artifact, State, S> => ({\n definition,\n name: definition.name,\n environment: (options) => ({\n providerName: definition.name,\n options,\n open: (openOptions) =>\n awaitableOpenRequest({\n providerName: definition.name,\n environmentOptions: options,\n openOptions,\n }),\n }),\n});\n\n// Erased form the session service stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
|
|
5
|
+
"mappings": "AAQA,SAAS,4BAAmE;AAoCrE,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAmEL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,cAAW;AACX,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,eAAY;AAHF,SAAAA;AAAA,GAAA;AAWL,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AAyCL,MAAM,uBAAuB,CAClC,aACwC,aAAa;AAgChD,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,WA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,yBAAA,eAAY;AACZ,EAAAA,yBAAA,aAAU;AACV,EAAAA,yBAAA,YAAS;AAHC,SAAAA;AAAA,GAAA;AAUL,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,kBAAe;AACf,EAAAA,kBAAA,eAAY;AAHF,SAAAA;AAAA,GAAA;AAmJL,MAAM,wBAAwB,CAOnC,gBACuE;AAAA,EACvE;AAAA,EACA,MAAM,WAAW;AAAA,EACjB,aAAa,CAAC,aAAa;AAAA,IACzB,cAAc,WAAW;AAAA,IACzB;AAAA,IACA,MAAM,CAAC,gBACL,qBAAqB;AAAA,MACnB,cAAc,WAAW;AAAA,MACzB,oBAAoB;AAAA,MACpB;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAYO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
|
|
6
6
|
"names": ["SandboxEntryType", "NetworkPolicy", "PortProtocol", "SandboxCapability", "SandboxSessionEndReason", "SandboxWorkspace", "SandboxEventKind"]
|
|
7
7
|
}
|
package/dist/modules/schemas.mjs
CHANGED
|
@@ -42,7 +42,7 @@ const SHARED_SCHEMAS = {
|
|
|
42
42
|
[SCHEMA_IDS.modelPicker]: {
|
|
43
43
|
$id: SCHEMA_IDS.modelPicker,
|
|
44
44
|
title: "Model",
|
|
45
|
-
// The harness
|
|
45
|
+
// The harness or hosting platform supplies reference constraints and picker choices.
|
|
46
46
|
type: "string",
|
|
47
47
|
"x-final-widget": "model-picker"
|
|
48
48
|
},
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/schemas.ts"],
|
|
4
|
-
"sourcesContent": ["import * as z from 'zod';\nimport type { JsonSchema } from \"./json.mjs\";\n\n// Shared JSON Schema fragments harness config schemas may $ref so Build renders\n// the familiar pickers. A harness with none of these\n// fields leaves them out.\n\nexport const SCHEMA_IDS = {\n modelPicker: 'final://schemas/model-picker',\n credentialPolicy: 'final://schemas/credential-policy',\n permissionMode: 'final://schemas/permission-mode',\n instructions: 'final://schemas/instructions',\n skills: 'final://schemas/skills',\n reasoning: 'final://schemas/reasoning',\n secretRef: 'final://schemas/secret-ref',\n} as const;\n\nconst dynamicSlotJsonSchema: JsonSchema = {\n type: 'object',\n required: ['$dynamic'],\n properties: {\n $dynamic: {\n type: 'object',\n required: ['resolver', 'events'],\n properties: {\n resolver: { type: 'string' },\n events: { type: 'array', items: { enum: ['session.started', 'turn.started'] } },\n description: { type: 'string' },\n preview: { type: 'string' },\n },\n },\n },\n};\n\nconst credentialNodeJsonSchema: JsonSchema = {\n type: 'object',\n required: ['kind'],\n properties: {\n kind: { enum: ['subscription', 'api-key', 'platform', 'harness-owned', 'custom'] },\n owner: { enum: ['payer', 'organization'] },\n vendor: { type: 'string' },\n pin: { type: 'string' },\n secret: { type: 'string' },\n baseUrl: { type: 'string', format: 'uri' },\n budget: { type: 'string' },\n resolver: { type: 'string' },\n },\n};\n\nexport const SHARED_SCHEMAS = {\n [SCHEMA_IDS.modelPicker]: {\n $id: SCHEMA_IDS.modelPicker,\n title: 'Model',\n // The harness
|
|
4
|
+
"sourcesContent": ["import * as z from 'zod';\nimport type { JsonSchema } from \"./json.mjs\";\n\n// Shared JSON Schema fragments harness config schemas may $ref so Build renders\n// the familiar pickers. A harness with none of these\n// fields leaves them out.\n\nexport const SCHEMA_IDS = {\n modelPicker: 'final://schemas/model-picker',\n credentialPolicy: 'final://schemas/credential-policy',\n permissionMode: 'final://schemas/permission-mode',\n instructions: 'final://schemas/instructions',\n skills: 'final://schemas/skills',\n reasoning: 'final://schemas/reasoning',\n secretRef: 'final://schemas/secret-ref',\n} as const;\n\nconst dynamicSlotJsonSchema: JsonSchema = {\n type: 'object',\n required: ['$dynamic'],\n properties: {\n $dynamic: {\n type: 'object',\n required: ['resolver', 'events'],\n properties: {\n resolver: { type: 'string' },\n events: { type: 'array', items: { enum: ['session.started', 'turn.started'] } },\n description: { type: 'string' },\n preview: { type: 'string' },\n },\n },\n },\n};\n\nconst credentialNodeJsonSchema: JsonSchema = {\n type: 'object',\n required: ['kind'],\n properties: {\n kind: { enum: ['subscription', 'api-key', 'platform', 'harness-owned', 'custom'] },\n owner: { enum: ['payer', 'organization'] },\n vendor: { type: 'string' },\n pin: { type: 'string' },\n secret: { type: 'string' },\n baseUrl: { type: 'string', format: 'uri' },\n budget: { type: 'string' },\n resolver: { type: 'string' },\n },\n};\n\nexport const SHARED_SCHEMAS = {\n [SCHEMA_IDS.modelPicker]: {\n $id: SCHEMA_IDS.modelPicker,\n title: 'Model',\n // The harness or hosting platform supplies reference constraints and picker choices.\n type: 'string',\n 'x-final-widget': 'model-picker',\n },\n [SCHEMA_IDS.reasoning]: {\n $id: SCHEMA_IDS.reasoning,\n title: 'Reasoning',\n enum: ['none', 'minimal', 'low', 'medium', 'high', 'max'],\n 'x-final-widget': 'reasoning-picker',\n },\n [SCHEMA_IDS.credentialPolicy]: {\n $id: SCHEMA_IDS.credentialPolicy,\n title: 'Credentials',\n type: 'object',\n required: ['payer', 'tryInOrder'],\n properties: {\n payer: { enum: ['agent-owner', 'organization', 'prompting-user', 'conversation-owner'] },\n tryInOrder: { type: 'array', minItems: 1, items: credentialNodeJsonSchema },\n },\n 'x-final-widget': 'credential-policy',\n },\n [SCHEMA_IDS.permissionMode]: {\n $id: SCHEMA_IDS.permissionMode,\n title: 'Permission mode',\n // The harness supplies the enum of its own modes.\n type: 'string',\n 'x-final-widget': 'permission-mode',\n },\n [SCHEMA_IDS.instructions]: {\n $id: SCHEMA_IDS.instructions,\n title: 'Instructions',\n type: 'array',\n items: {\n anyOf: [\n {\n type: 'object',\n required: ['role', 'content'],\n properties: {\n role: { enum: ['system', 'user'] },\n content: { type: 'string' },\n source: { type: 'string' },\n },\n },\n dynamicSlotJsonSchema,\n ],\n },\n 'x-final-widget': 'instructions',\n },\n [SCHEMA_IDS.skills]: {\n $id: SCHEMA_IDS.skills,\n title: 'Skills',\n type: 'array',\n items: {\n anyOf: [\n {\n type: 'object',\n required: ['key', 'files'],\n properties: {\n key: { type: 'string' },\n description: { type: 'string' },\n files: {\n type: 'array',\n items: {\n type: 'object',\n required: ['path', 'content'],\n properties: { path: { type: 'string' }, content: { type: 'string' } },\n },\n },\n },\n },\n dynamicSlotJsonSchema,\n ],\n },\n 'x-final-widget': 'skills',\n },\n [SCHEMA_IDS.secretRef]: {\n $id: SCHEMA_IDS.secretRef,\n title: 'Secret',\n type: 'object',\n required: ['secretKey'],\n properties: { secretKey: { type: 'string' } },\n 'x-final-widget': 'secret-picker',\n },\n} satisfies Record<string, JsonSchema>;\n\n// Which shared fragments a config schema references at its top level, e.g.\n// to decide whether the directory's instructions/skills apply to a harness.\nconst fieldRefSchema = z.object({ $ref: z.string().startsWith('final://schemas/') });\nconst propertiesSchema = z.object({ properties: z.record(z.string(), z.json()) });\n\nexport interface SharedSchemaReferencesIface {\n [field: string]: string;\n}\n\nexport const referencedSharedSchemas = (configSchema: JsonSchema): SharedSchemaReferencesIface => {\n const parsed = propertiesSchema.safeParse(configSchema);\n const out: SharedSchemaReferencesIface = {};\n if (!parsed.success) return out;\n for (const [field, fieldSchema] of Object.entries(parsed.data.properties)) {\n const ref = fieldRefSchema.safeParse(fieldSchema);\n if (ref.success) out[field] = ref.data.$ref;\n }\n return out;\n};\n"],
|
|
5
5
|
"mappings": "AAAA,YAAY,OAAO;AAOZ,MAAM,aAAa;AAAA,EACxB,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,WAAW;AACb;AAEA,MAAM,wBAAoC;AAAA,EACxC,MAAM;AAAA,EACN,UAAU,CAAC,UAAU;AAAA,EACrB,YAAY;AAAA,IACV,UAAU;AAAA,MACR,MAAM;AAAA,MACN,UAAU,CAAC,YAAY,QAAQ;AAAA,MAC/B,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MACF;AAAA,IACF;AAAA,IACA,kBAAkB;AAAA,EACpB;AAAA,EACA,CAAC,WAAW,SAAS,GAAG;AAAA,IACtB,KAAK,WAAW;AAAA,IAChB,OAAO;AAAA,IACP,MAAM;AAAA,IACN,UAAU,CAAC,WAAW;AAAA,IACtB,YAAY,EAAE,WAAW,EAAE,MAAM,SAAS,EAAE;AAAA,IAC5C,kBAAkB;AAAA,EACpB;AACF;AAIA,MAAM,iBAAiB,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,kBAAkB,EAAE,CAAC;AACnF,MAAM,mBAAmB,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC,EAAE,CAAC;AAMzE,MAAM,0BAA0B,CAAC,iBAA0D;AAChG,QAAM,SAAS,iBAAiB,UAAU,YAAY;AACtD,QAAM,MAAmC,CAAC;AAC1C,MAAI,CAAC,OAAO,QAAS,QAAO;AAC5B,aAAW,CAAC,OAAO,WAAW,KAAK,OAAO,QAAQ,OAAO,KAAK,UAAU,GAAG;AACzE,UAAM,MAAM,eAAe,UAAU,WAAW;AAChD,QAAI,IAAI,QAAS,KAAI,KAAK,IAAI,IAAI,KAAK;AAAA,EACzC;AACA,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@finalai/agent-provider",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Provider contracts for the agent stack: harnesses, sandboxes (handle, wire, MCP projection), channels, credential policies, and the conformance kit.",
|
|
6
6
|
"license": "Apache-2.0",
|