@finalai/agent-provider 0.1.4 → 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/agent.mjs +8 -4
- package/dist/modules/conformance/agent.mjs.map +2 -2
- 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
|
@@ -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 !== 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;AA+BvE,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,IAAI;AACjC,MAAI,QAAQ,SAAS;AACrB,WAAS,IAAI,GAAG,IAAI,MAAM,KAAK,GAAG;AAChC,YAAS,KAAK,KAAK,OAAO,OAAO,IAAI,eAAgB;AACrD,UAAM,CAAC,IAAI,UAAU;AAAA,EACvB;AACA,SAAO;AACT;AAEA,MAAM,UAAU,CAAC,OAAmB,UAA8C;AAChF,MAAI,SAAS;AACb,SAAO,IAAI,eAA2B;AAAA,IACpC,MAAM,CAAC,eAAe;AACpB,UAAI,UAAU,MAAM,YAAY;AAC9B,mBAAW,MAAM;AACjB;AAAA,MACF;AACA,iBAAW,QAAQ,MAAM,M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O,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 !== Conform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F;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;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;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,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,IAC3B,OAAO,EAAE,MAAM,EAAE,WAAW,uBAAuB,CAAC;AAAA,IACpD,UAAU,EAAE,WAAW,kBAAkB;AAAA,EAC3C,CAAC;AAAA;AAAA,EAED,OAAO,EAAE,WAAW,iBAAiB,EAAE,SAAS;AAAA,EAChD,UAAU,EAAE,OAAO;AAAA,IACjB,SAAS,EAAE,QAAQ;AAAA,IACnB,cAAc,EAAE,QAAQ;AAAA,IACxB,MAAM,EAAE,QAAQ;AAAA;AAAA;AAAA,IAGhB,YAAY,EAAE,QAAQ;AAAA;AAAA,IAEtB,kBAAkB,EAAE,QAAQ,EAAE,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;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AAgB,KAAK,KAAK,KAAK,OAAO,CAAC;AAC7F,MAAI,SAAS,KAAM,QAAO;AAC1B,SAAO;AAAA,IACL,KAAK,GAAG,KAAK,UAAU,QAAQ,QAAQ,EAAE,CAAC;AAAA,IAC1C,OAAO,MAAM;AAAA,IACb,kBAAkB,KAAK;AAAA,IACvB,WAAW,MAAM;AAAA,EACnB;AACF;AAyLO,MAAM,gBAAgB,CAC3B,mBACgC;AAGhC,QAAM,UAAU,CAAC,YAAgD;AAAA,IAC/D,SAAS,UAAU,qBAAqB;AAAA,IACxC;AAAA,IACA,gBAAgB;AAAA,EAClB;AACA,SAAO,OAAO,OAAO,SAAS,cAAc;AAC9C;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,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;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,MAAM,UAAU,KAAK,CAAC;AAC9D,UAAM,cAAc,CAAC,WAA0D;AAAA,MAC7E,OAAO,EAAE,GAAG,QAAQ,OAAO,GAAG,MAAM;AAAA,MACpC,KAAK,QAAQ,OAAO;AAAA,MACpB,OAAO,QAAQ,SAAS,CAAC;AAAA,IAC3B;AACA,UAAM,OAAO,CAAC,WAAmB,aAC/B,oBAAoB;AAAA,MAClB,IAAI;AAAA,MACJ,OAAO,SAAS;AAAA,MAChB,KAAK,SAAS;AAAA,MACd,OAAO,SAAS;AAAA,IAClB,CAAC;AACH,WAAO;AAAA,MACL,aAAa,OAAO,QAAQ,UAAU,YAAY,KAAK,UAAU,YAAY,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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U,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC;AAAA,MACzF,SAAS,OAAO,QAAQ,YAAY,IAAI,KAAK;AAAA,MAC7C,OAAO,OAAO,KAAK,cAAc,cAAc;AAAA,QAC7C,QAAQ,aAAa,MAAM,KAAK,KAAK,IAAI,QAAQ,WAAW,QAAQ,CAAC;AAAA,QACrE,OAAO,EAAE,IAAI,IAAI,QAAQ,UAAU;AAAA,MACrC;AAAA,MACA,QAAQ,OAAO,KAAK,UAAU,UAAU,aAAa,MAAM,KAAK,KAAK,MAAM,IAAI,QAAQ,CAAC;AAAA,MACxF,MAAM,OAAO,MAAM,WAAW,UAAU;AAAA,IAC1C;AAAA,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":
|