@finalai/agent-provider 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/HOSTING.md +334 -245
  2. package/README.md +93 -14
  3. package/dist/modules/canonical-json.d.mts +4 -0
  4. package/dist/modules/canonical-json.mjs +33 -0
  5. package/dist/modules/canonical-json.mjs.map +7 -0
  6. package/dist/modules/channel.d.mts +9 -3
  7. package/dist/modules/channel.mjs.map +2 -2
  8. package/dist/modules/code-host/host.d.mts +10 -0
  9. package/dist/modules/code-host/host.mjs +88 -0
  10. package/dist/modules/code-host/host.mjs.map +7 -0
  11. package/dist/modules/code-host/in-process.d.mts +24 -0
  12. package/dist/modules/code-host/in-process.mjs +89 -0
  13. package/dist/modules/code-host/in-process.mjs.map +7 -0
  14. package/dist/modules/code-host/index.d.mts +4 -0
  15. package/dist/modules/code-host/index.mjs +5 -0
  16. package/dist/modules/code-host/index.mjs.map +7 -0
  17. package/dist/modules/code-host/serverless.d.mts +63 -0
  18. package/dist/modules/code-host/serverless.mjs +27 -0
  19. package/dist/modules/code-host/serverless.mjs.map +7 -0
  20. package/dist/modules/code-host/types.d.mts +152 -0
  21. package/dist/modules/code-host/types.mjs +85 -0
  22. package/dist/modules/code-host/types.mjs.map +7 -0
  23. package/dist/modules/conformance/agent.mjs +72 -6
  24. package/dist/modules/conformance/agent.mjs.map +2 -2
  25. package/dist/modules/conformance/harness-kit.d.mts +9 -2
  26. package/dist/modules/conformance/harness-kit.mjs +224 -63
  27. package/dist/modules/conformance/harness-kit.mjs.map +3 -3
  28. package/dist/modules/conformance/local-harness.d.mts +1 -4
  29. package/dist/modules/conformance/local-harness.mjs +21 -22
  30. package/dist/modules/conformance/local-harness.mjs.map +2 -2
  31. package/dist/modules/conformance/protocol.d.mts +1 -0
  32. package/dist/modules/conformance/protocol.mjs +2 -0
  33. package/dist/modules/conformance/protocol.mjs.map +2 -2
  34. package/dist/modules/conformance/sandbox-kit.d.mts +12 -4
  35. package/dist/modules/conformance/sandbox-kit.mjs +189 -103
  36. package/dist/modules/conformance/sandbox-kit.mjs.map +2 -2
  37. package/dist/modules/conformance/scripted-model/chat-completions.mjs +1 -0
  38. package/dist/modules/conformance/scripted-model/chat-completions.mjs.map +2 -2
  39. package/dist/modules/conformance/scripted-model/directives.d.mts +3 -0
  40. package/dist/modules/conformance/scripted-model/directives.mjs +26 -10
  41. package/dist/modules/conformance/scripted-model/directives.mjs.map +2 -2
  42. package/dist/modules/conformance/scripted-model/messages.mjs +1 -0
  43. package/dist/modules/conformance/scripted-model/messages.mjs.map +2 -2
  44. package/dist/modules/conformance/scripted-model/responses.mjs +2 -0
  45. package/dist/modules/conformance/scripted-model/responses.mjs.map +2 -2
  46. package/dist/modules/conformance/stdio.d.mts +21 -0
  47. package/dist/modules/conformance/stdio.mjs +158 -0
  48. package/dist/modules/conformance/stdio.mjs.map +7 -0
  49. package/dist/modules/credential-routes.d.mts +2 -0
  50. package/dist/modules/credential-routes.mjs +2 -0
  51. package/dist/modules/credential-routes.mjs.map +2 -2
  52. package/dist/modules/document.d.mts +376 -0
  53. package/dist/modules/document.mjs +208 -0
  54. package/dist/modules/document.mjs.map +7 -0
  55. package/dist/modules/harness-configuration.d.mts +16 -0
  56. package/dist/modules/harness-configuration.mjs +83 -0
  57. package/dist/modules/harness-configuration.mjs.map +7 -0
  58. package/dist/modules/harness-definition.d.mts +280 -0
  59. package/dist/modules/harness-definition.mjs +430 -0
  60. package/dist/modules/harness-definition.mjs.map +7 -0
  61. package/dist/modules/harness-provider.d.mts +197 -0
  62. package/dist/modules/harness-provider.mjs +108 -0
  63. package/dist/modules/harness-provider.mjs.map +7 -0
  64. package/dist/modules/harness-requirements.d.mts +19 -0
  65. package/dist/modules/harness-requirements.mjs +40 -0
  66. package/dist/modules/harness-requirements.mjs.map +7 -0
  67. package/dist/modules/harness-start.d.mts +33 -0
  68. package/dist/modules/harness-start.mjs +107 -0
  69. package/dist/modules/harness-start.mjs.map +7 -0
  70. package/dist/modules/harness.d.mts +84 -109
  71. package/dist/modules/harness.mjs +56 -111
  72. package/dist/modules/harness.mjs.map +3 -3
  73. package/dist/modules/identity.d.mts +1 -0
  74. package/dist/modules/identity.mjs +2 -0
  75. package/dist/modules/identity.mjs.map +7 -0
  76. package/dist/modules/index.d.mts +12 -6
  77. package/dist/modules/index.mjs +12 -6
  78. package/dist/modules/index.mjs.map +2 -2
  79. package/dist/modules/inference.d.mts +35 -0
  80. package/dist/modules/inference.mjs +74 -0
  81. package/dist/modules/inference.mjs.map +7 -0
  82. package/dist/modules/local-channel-context.mjs +3 -1
  83. package/dist/modules/local-channel-context.mjs.map +2 -2
  84. package/dist/modules/requirements-check.d.mts +30 -0
  85. package/dist/modules/requirements-check.mjs +164 -0
  86. package/dist/modules/requirements-check.mjs.map +7 -0
  87. package/dist/modules/room-surface.d.mts +0 -5
  88. package/dist/modules/room-surface.mjs.map +2 -2
  89. package/dist/modules/sandbox/client.d.mts +3 -0
  90. package/dist/modules/sandbox/client.mjs +101 -18
  91. package/dist/modules/sandbox/client.mjs.map +2 -2
  92. package/dist/modules/sandbox/grant.d.mts +78 -0
  93. package/dist/modules/sandbox/grant.mjs +134 -0
  94. package/dist/modules/sandbox/grant.mjs.map +7 -0
  95. package/dist/modules/sandbox/index.d.mts +3 -3
  96. package/dist/modules/sandbox/index.mjs +4 -5
  97. package/dist/modules/sandbox/index.mjs.map +2 -2
  98. package/dist/modules/sandbox/mcp-hosted.d.mts +1 -1
  99. package/dist/modules/sandbox/mcp-hosted.mjs +4 -7
  100. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  101. package/dist/modules/sandbox/mcp.d.mts +4 -2
  102. package/dist/modules/sandbox/mcp.mjs +14 -7
  103. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  104. package/dist/modules/sandbox/memory-sandbox.d.mts +2 -1
  105. package/dist/modules/sandbox/memory-sandbox.mjs +71 -41
  106. package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
  107. package/dist/modules/sandbox/networking.d.mts +7 -7
  108. package/dist/modules/sandbox/networking.mjs +16 -9
  109. package/dist/modules/sandbox/networking.mjs.map +2 -2
  110. package/dist/modules/sandbox/remote/adapter.d.mts +30 -0
  111. package/dist/modules/sandbox/remote/adapter.mjs +381 -0
  112. package/dist/modules/sandbox/remote/adapter.mjs.map +7 -0
  113. package/dist/modules/sandbox/remote/errors.d.mts +10 -0
  114. package/dist/modules/sandbox/remote/errors.mjs +62 -0
  115. package/dist/modules/sandbox/remote/errors.mjs.map +7 -0
  116. package/dist/modules/sandbox/remote/index.d.mts +5 -0
  117. package/dist/modules/sandbox/remote/index.mjs +6 -0
  118. package/dist/modules/sandbox/remote/index.mjs.map +7 -0
  119. package/dist/modules/sandbox/remote/ndjson.d.mts +6 -0
  120. package/dist/modules/sandbox/remote/ndjson.mjs +80 -0
  121. package/dist/modules/sandbox/remote/ndjson.mjs.map +7 -0
  122. package/dist/modules/sandbox/remote/platform-api.d.mts +8 -0
  123. package/dist/modules/sandbox/remote/platform-api.mjs +15 -0
  124. package/dist/modules/sandbox/remote/platform-api.mjs.map +7 -0
  125. package/dist/modules/sandbox/remote/preamble.d.mts +7 -0
  126. package/dist/modules/sandbox/remote/preamble.mjs +51 -0
  127. package/dist/modules/sandbox/remote/preamble.mjs.map +7 -0
  128. package/dist/modules/sandbox/remote/serve.d.mts +34 -0
  129. package/dist/modules/sandbox/remote/serve.mjs +519 -0
  130. package/dist/modules/sandbox/remote/serve.mjs.map +7 -0
  131. package/dist/modules/sandbox/remote/testing.d.mts +34 -0
  132. package/dist/modules/sandbox/remote/testing.mjs +275 -0
  133. package/dist/modules/sandbox/remote/testing.mjs.map +7 -0
  134. package/dist/modules/sandbox/seeds.d.mts +2 -2
  135. package/dist/modules/sandbox/seeds.mjs +2 -2
  136. package/dist/modules/sandbox/seeds.mjs.map +2 -2
  137. package/dist/modules/sandbox/server.d.mts +4 -6
  138. package/dist/modules/sandbox/server.mjs +93 -49
  139. package/dist/modules/sandbox/server.mjs.map +2 -2
  140. package/dist/modules/sandbox/setup/apply.d.mts +41 -0
  141. package/dist/modules/sandbox/setup/apply.mjs +204 -0
  142. package/dist/modules/sandbox/setup/apply.mjs.map +7 -0
  143. package/dist/modules/sandbox/setup/describe.d.mts +10 -0
  144. package/dist/modules/sandbox/setup/describe.mjs +62 -0
  145. package/dist/modules/sandbox/setup/describe.mjs.map +7 -0
  146. package/dist/modules/sandbox/setup/index.d.mts +6 -0
  147. package/dist/modules/sandbox/setup/index.mjs +17 -0
  148. package/dist/modules/sandbox/setup/index.mjs.map +7 -0
  149. package/dist/modules/sandbox/setup/paths.d.mts +8 -0
  150. package/dist/modules/sandbox/setup/paths.mjs +18 -0
  151. package/dist/modules/sandbox/setup/paths.mjs.map +7 -0
  152. package/dist/modules/sandbox/setup/schema.d.mts +42 -0
  153. package/dist/modules/sandbox/setup/schema.mjs +58 -0
  154. package/dist/modules/sandbox/setup/schema.mjs.map +7 -0
  155. package/dist/modules/sandbox/tool-policy.d.mts +1 -1
  156. package/dist/modules/sandbox/tool-policy.mjs +1 -1
  157. package/dist/modules/sandbox/tool-policy.mjs.map +2 -2
  158. package/dist/modules/sandbox/types.d.mts +117 -130
  159. package/dist/modules/sandbox/types.mjs +46 -50
  160. package/dist/modules/sandbox/types.mjs.map +3 -3
  161. package/dist/modules/sandbox/wire.d.mts +93 -6
  162. package/dist/modules/sandbox/wire.mjs +61 -38
  163. package/dist/modules/sandbox/wire.mjs.map +2 -2
  164. package/dist/modules/schemas.d.mts +5 -76
  165. package/dist/modules/schemas.mjs +18 -85
  166. package/dist/modules/schemas.mjs.map +2 -2
  167. package/dist/modules/tool-annotations.d.mts +15 -6
  168. package/dist/modules/tool-annotations.mjs +9 -3
  169. package/dist/modules/tool-annotations.mjs.map +2 -2
  170. package/dist/modules/tool-descriptor.d.mts +16 -0
  171. package/dist/modules/tool-descriptor.mjs +19 -0
  172. package/dist/modules/tool-descriptor.mjs.map +7 -0
  173. package/dist/modules/tool-patterns.d.mts +7 -7
  174. package/dist/modules/tool-patterns.mjs +10 -9
  175. package/dist/modules/tool-patterns.mjs.map +2 -2
  176. package/package.json +86 -36
  177. package/dist/modules/credentials.d.mts +0 -206
  178. package/dist/modules/credentials.mjs +0 -207
  179. package/dist/modules/credentials.mjs.map +0 -7
  180. package/dist/modules/dynamic.d.mts +0 -40
  181. package/dist/modules/dynamic.mjs +0 -79
  182. package/dist/modules/dynamic.mjs.map +0 -7
  183. package/dist/modules/hosted-bindings.d.mts +0 -15
  184. package/dist/modules/hosted-bindings.mjs +0 -21
  185. package/dist/modules/hosted-bindings.mjs.map +0 -7
  186. package/dist/modules/manifest.d.mts +0 -787
  187. package/dist/modules/manifest.mjs +0 -320
  188. package/dist/modules/manifest.mjs.map +0 -7
  189. package/dist/modules/provider-ref.d.mts +0 -29
  190. package/dist/modules/provider-ref.mjs +0 -55
  191. package/dist/modules/provider-ref.mjs.map +0 -7
  192. package/dist/modules/sandbox/open-scope-node.d.mts +0 -4
  193. package/dist/modules/sandbox/open-scope-node.mjs +0 -19
  194. package/dist/modules/sandbox/open-scope-node.mjs.map +0 -7
  195. package/dist/modules/sandbox/open-scope.d.mts +0 -16
  196. package/dist/modules/sandbox/open-scope.mjs +0 -66
  197. package/dist/modules/sandbox/open-scope.mjs.map +0 -7
  198. package/dist/modules/sandbox/workspace-identity.d.mts +0 -5
  199. package/dist/modules/sandbox/workspace-identity.mjs +0 -14
  200. package/dist/modules/sandbox/workspace-identity.mjs.map +0 -7
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/requirements-check.ts"],
4
+ "sourcesContent": ["import {\n Capability,\n capabilityAccessCovers,\n DEFAULT_CAPABILITY_ACCESS as FULL_ACCESS,\n type CapabilityAccess,\n} from '@finalai/agent-protocol';\nimport {\n HarnessComputeStatus,\n RequirementKind,\n RequirementProblem,\n type ResolvedProvideDocumentIface,\n} from '@finalai/agent-protocol/agent-platform';\nimport { computeRequirementsOf, inProcessCodeOf, type AgentDocumentIface } from \"./document.mjs\";\nimport { harnessUnsuitability, type HarnessSuitabilityArgsIface } from \"./harness-requirements.mjs\";\n\n// One check, run by every call that can start work: every requirement not\n// marked optional is provided and suitable, or nothing starts. The platform\n// runs it with what it knows about each provided resource; the SDK runs the\n// same function before sending so a caller sees the same list either way.\n\nexport interface UnmetIface {\n kind: RequirementKind;\n name: string;\n description: string | null;\n problem: RequirementProblem;\n detail: string | null;\n}\n\n// What the checker knows about one provided sandbox.\nexport interface ProvidedSandboxIface {\n // Capabilities the sandbox's provider serves, with the most access it grants.\n capabilities: Partial<Record<Capability, CapabilityAccess>>;\n}\n\n// What the check needs to know about the harness the settings name: its\n// definition composed with its adapter and environment (harnessCheckInputOf,\n// ./harness-definition.ts).\nexport interface HarnessCheckInputIface extends Omit<HarnessSuitabilityArgsIface, 'document'> {\n // Per capability: whether the harness serves it natively on the machine it\n // runs on, drives a provided sandbox, or cannot use it. Absent: sandbox.\n compute: Partial<Record<Capability, HarnessComputeStatus>>;\n // The sandbox the harness runs in; its native capabilities are that\n // sandbox's, so only it may be provided for them. Null: it runs at a URL,\n // whose machine serves them.\n environment?: string | null;\n // It runs in the sandbox provided for `shell`, and none was.\n awaitsEnvironment?: boolean;\n // Per native capability, the access levels below full the harness can\n // hold the model to. Absent: it can enforce any.\n enforces?: Partial<Record<Capability, readonly CapabilityAccess[]>>;\n // Why the harness, its adapter and its environment do not compose.\n problems?: readonly string[];\n}\n\nexport interface RequirementsCheckArgsIface {\n document: AgentDocumentIface;\n provide: ResolvedProvideDocumentIface;\n // Null when no harness was provided or its name is unknown.\n harness: HarnessCheckInputIface | null;\n // Looked up by id; null for an id that names nothing in the session's project.\n sandbox: (id: string) => ProvidedSandboxIface | null;\n integrationExists: (id: string) => boolean;\n // Whether a connected client holds the in-process code; absent means none does.\n inProcessCodeAvailable?: boolean;\n}\n\nconst describe = (text: string | undefined): string | null => text ?? null;\n\nexport const unmetRequirements = (args: RequirementsCheckArgsIface): UnmetIface[] => {\n const { document, provide } = args;\n const unmet: UnmetIface[] = [];\n\n if (provide.harness == null || args.harness == null) {\n unmet.push({\n kind: RequirementKind.Harness,\n name: 'harness',\n description: null,\n problem:\n provide.harness == null ? RequirementProblem.NotProvided : RequirementProblem.NotFound,\n detail: provide.harness == null ? null : `Unknown harness ${provide.harness.harness}`,\n });\n } else {\n const unsuitable = harnessUnsuitability({ ...args.harness, document });\n const details: string[] = [...(args.harness.problems ?? [])];\n if (unsuitable != null) {\n if (unsuitable.missingFeatures.length > 0)\n details.push(`does not support ${unsuitable.missingFeatures.join(', ')}`);\n if (unsuitable.permission != null)\n details.push(\n `runs at ${unsuitable.permission.offered}, above the agent's ceiling of ${unsuitable.permission.ceiling}`,\n );\n }\n if (details.length > 0)\n unmet.push({\n kind: RequirementKind.Harness,\n name: 'harness',\n description: null,\n problem: RequirementProblem.Unsuitable,\n detail: `${provide.harness.harness} ${details.join('; ')}`,\n });\n }\n const harnessName = provide.harness?.harness ?? 'The harness';\n\n // A harness placed by `shell` runs nowhere until a sandbox provides it.\n if (args.harness?.awaitsEnvironment === true)\n unmet.push({\n kind: RequirementKind.Compute,\n name: Capability.Shell,\n description: null,\n problem: RequirementProblem.NotProvided,\n detail: `${harnessName} runs in the sandbox provided for shell`,\n });\n\n const compute = provide.compute ?? {};\n const files = compute[Capability.Files];\n const shell = compute[Capability.Shell];\n if (files != null && shell != null && files !== shell)\n unmet.push({\n kind: RequirementKind.Compute,\n name: Capability.Shell,\n description: null,\n problem: RequirementProblem.DifferentSandboxes,\n detail: '`files` and `shell` must be provided by the same sandbox',\n });\n\n const insufficientAccess = (\n capability: Capability,\n sandboxId: string,\n required: CapabilityAccess,\n ): string | null => {\n const sandbox = args.sandbox(sandboxId);\n if (sandbox == null) return null;\n const granted = sandbox.capabilities[capability];\n if (granted == null) return `Sandbox ${sandboxId} does not offer ${capability}`;\n if (!capabilityAccessCovers(granted, required))\n return `Sandbox ${sandboxId} grants ${granted}; the agent requires ${required}`;\n return null;\n };\n\n for (const [capability, requirement] of computeRequirementsOf(document)) {\n const sandboxId = compute[capability];\n const description = describe(requirement.description);\n const served = args.harness?.compute[capability];\n const fail = (problem: RequirementProblem, detail: string | null): void => {\n unmet.push({ kind: RequirementKind.Compute, name: capability, description, problem, detail });\n };\n if (served === HarnessComputeStatus.Unavailable) {\n if (sandboxId != null || !requirement.optional)\n fail(RequirementProblem.Unsuitable, `${harnessName} cannot use ${capability}`);\n continue;\n }\n if (served === HarnessComputeStatus.Harness) {\n if (args.harness?.awaitsEnvironment === true) continue;\n const environment = args.harness?.environment ?? null;\n if (sandboxId != null && sandboxId !== environment) {\n fail(\n RequirementProblem.Unsuitable,\n environment == null\n ? `${harnessName} uses ${capability} on its own machine and cannot use a provided sandbox for it`\n : `${harnessName} uses ${capability} natively in sandbox ${environment}; provide that sandbox for it`,\n );\n continue;\n }\n if (environment != null) {\n if (args.sandbox(environment) == null) {\n fail(RequirementProblem.NotFound, `No sandbox ${environment} in this project`);\n continue;\n }\n const access = insufficientAccess(capability, environment, requirement.access);\n if (access != null) {\n fail(RequirementProblem.Unsuitable, access);\n continue;\n }\n }\n // Its own tools bypass any sandbox grant: anything below full access\n // must be a level the harness itself can hold the model to.\n const enforced = args.harness?.enforces?.[capability];\n const full = capabilityAccessCovers(requirement.access, FULL_ACCESS[capability]);\n if (enforced != null && !full && !enforced.includes(requirement.access))\n fail(\n RequirementProblem.Unsuitable,\n `${harnessName} cannot hold ${capability} to ${requirement.access} with its own tools`,\n );\n continue;\n }\n if (sandboxId == null) {\n if (!requirement.optional) fail(RequirementProblem.NotProvided, null);\n continue;\n }\n if (args.sandbox(sandboxId) == null) {\n fail(RequirementProblem.NotFound, `No sandbox ${sandboxId} in this project`);\n continue;\n }\n const access = insufficientAccess(capability, sandboxId, requirement.access);\n if (access != null) fail(RequirementProblem.Unsuitable, access);\n }\n\n const integrations = provide.integrations ?? {};\n for (const [slot, requirement] of Object.entries(document.require.integrations)) {\n const integrationId = integrations[slot];\n if (integrationId == null) {\n if (!requirement.optional)\n unmet.push({\n kind: RequirementKind.Integration,\n name: slot,\n description: requirement.description,\n problem: RequirementProblem.NotProvided,\n detail: null,\n });\n continue;\n }\n if (!args.integrationExists(integrationId))\n unmet.push({\n kind: RequirementKind.Integration,\n name: slot,\n description: requirement.description,\n problem: RequirementProblem.NotFound,\n detail: `No integration ${integrationId} in this project`,\n });\n }\n\n if (args.inProcessCodeAvailable !== true)\n for (const name of inProcessCodeOf(document))\n unmet.push({\n kind: RequirementKind.Code,\n name,\n description: null,\n problem: RequirementProblem.CodeUnavailable,\n detail: `${name} only runs in the process that holds its code`,\n });\n\n return unmet;\n};\n"],
5
+ "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA,6BAA6B;AAAA,OAExB;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,uBAAuB,uBAAgD;AAChF,SAAS,4BAA8D;AAqDvE,MAAM,WAAW,CAAC,SAA4C,QAAQ;AAE/D,MAAM,oBAAoB,CAAC,SAAmD;AACnF,QAAM,EAAE,UAAU,QAAQ,IAAI;AAC9B,QAAM,QAAsB,CAAC;AAE7B,MAAI,QAAQ,WAAW,QAAQ,KAAK,WAAW,MAAM;AACnD,UAAM,KAAK;AAAA,MACT,MAAM,gBAAgB;AAAA,MACtB,MAAM;AAAA,MACN,aAAa;AAAA,MACb,SACE,QAAQ,WAAW,OAAO,mBAAmB,cAAc,mBAAmB;AAAA,MAChF,QAAQ,QAAQ,WAAW,OAAO,OAAO,mBAAmB,QAAQ,QAAQ,OAAO;AAAA,IACrF,CAAC;AAAA,EACH,OAAO;AACL,UAAM,aAAa,qBAAqB,EAAE,GAAG,KAAK,SAAS,SAAS,CAAC;AACrE,UAAM,UAAoB,CAAC,GAAI,KAAK,QAAQ,YAAY,CAAC,CAAE;AAC3D,QAAI,cAAc,MAAM;AACtB,UAAI,WAAW,gBAAgB,SAAS;AACtC,gBAAQ,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access"]
7
+ }
@@ -1,4 +1,3 @@
1
- import type { HostedBindingsIface } from "./hosted-bindings.mjs";
2
1
  import type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';
3
2
  import type { SessionUpdateKind } from '@finalai/acp-session';
4
3
  import * as z from 'zod';
@@ -158,7 +157,6 @@ export interface PromptArgsIface {
158
157
  waitForAcceptance?: boolean;
159
158
  channelBinding?: {
160
159
  id: string;
161
- revisionId: string;
162
160
  };
163
161
  auth?: RoomAuthIface | null;
164
162
  title?: string;
@@ -249,7 +247,6 @@ export interface RoomPlatformIface {
249
247
  export interface RoomInputResponseIface {
250
248
  channelBinding?: {
251
249
  id: string;
252
- revisionId: string;
253
250
  };
254
251
  auth?: RoomAuthIface | null;
255
252
  participantId: string;
@@ -259,7 +256,6 @@ export interface RoomInputResponseIface {
259
256
  userId: string | null;
260
257
  }
261
258
  export interface RoomReceiveContextIface {
262
- bindings?: HostedBindingsIface;
263
259
  platform: RoomPlatformIface;
264
260
  organizationId: string;
265
261
  definitionId: string | null;
@@ -279,7 +275,6 @@ export interface RoomReceiveContextIface {
279
275
  requestedDelivery?: Delivery;
280
276
  }
281
277
  export interface ProjectionContextIface<State = JsonValue> {
282
- bindings?: HostedBindingsIface;
283
278
  sessionId?: string;
284
279
  platform: RoomPlatformIface;
285
280
  config: JsonObject;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/room-surface.ts"],
4
- "sourcesContent": ["import type { HostedBindingsIface } from \"./hosted-bindings.mjs\";\nimport type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';\nimport type { SessionUpdateKind } from '@finalai/acp-session';\nimport * as z from 'zod';\nimport type { ChannelTurnStateIface } from \"./channel.mjs\";\nimport { jsonObjectSchema, jsonValueSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { SemanticChannelEventKind } from \"./semantic-events.mjs\";\n\n// Contracts for customizing Final chats. Admission callbacks receive the\n// current message and members; renderers and events can post room output.\n// External transports use the separate scoped channel contract.\n\nexport enum RoomPrincipalType {\n User = 'user',\n Service = 'service',\n}\n\n// Who a room input or response came from, as vouched for by its authenticator.\nexport interface RoomAuthIface extends JsonObject {\n principalId: string;\n principalType: RoomPrincipalType | `${RoomPrincipalType}`;\n authenticator: string;\n // `displayName` (a string) when the principal is named; see principalDisplayName.\n attributes: JsonObject;\n}\n\nexport const roomAuthSchema = z.object({\n principalId: z.string().min(1),\n principalType: z.nativeEnum(RoomPrincipalType),\n authenticator: z.string().min(1),\n // How the agent and the people reading its reply name the principal.\n displayName: z.string().min(1).max(200).optional(),\n attributes: jsonObjectSchema.default({}),\n});\n\n// How a principal is named to the agent and in captions: its `displayName`, else its id.\nexport const principalDisplayName = (auth: RoomAuthIface): string => {\n const name = auth['displayName'];\n return typeof name === 'string' && name.length > 0 ? name : auth.principalId;\n};\n\nexport enum ConversationKind {\n Direct = 'direct',\n Group = 'group',\n}\n\nexport enum ParticipantKind {\n User = 'user',\n Agent = 'agent',\n}\n\nexport enum RoutingMode {\n Mention = 'mention',\n All = 'all',\n Default = 'default',\n}\n\nexport enum TurnPolicy {\n Steer = 'steer',\n Queue = 'queue',\n}\n\nexport enum Delivery {\n Prompt = 'prompt',\n Observe = 'observe',\n}\n\nexport enum MessageKind {\n Message = 'message',\n Card = 'card',\n}\n\nexport enum CardKind {\n Elicitation = 'elicitation',\n Permission = 'permission',\n Notice = 'notice',\n}\n\nexport interface ParticipantIface {\n id: string;\n kind: ParticipantKind;\n displayName: string;\n userId: string | null;\n definitionId: string | null;\n routingMode: RoutingMode | null;\n sessionId: string | null;\n // Whether the agent's harness supports _final/session/observe and renders\n // _meta[\"final.ai\"].author; null for non-agents.\n supportsObserve: boolean | null;\n rendersAuthorMeta: boolean | null;\n left: boolean;\n}\n\nexport const roomReceiveResultSchema = z.union([\n z.object({ conversationId: z.string().min(1) }),\n z.object({ sessionId: z.string().min(1) }),\n z.null(),\n]);\nexport type RoomReceiveResult = z.infer<typeof roomReceiveResultSchema>;\n\nexport interface ConversationRefIface {\n conversationId: string;\n}\n\nexport interface ConversationIface extends ConversationRefIface {\n organizationId: string;\n kind: ConversationKind;\n title: string | null;\n isHome: boolean;\n turnPolicy: TurnPolicy;\n}\n\nexport interface MessageRefIface {\n messageId: string;\n seq: number;\n}\n\nexport interface ConversationMessageIface extends MessageRefIface {\n conversationId: string;\n authorParticipantId: string;\n kind: MessageKind;\n body: string;\n content: ContentBlock[];\n replyToMessageId: string | null;\n threadRootId: string | null;\n // Earlier messages of the conversation the author quoted, in order.\n quotedMessageIds: string[];\n // Agent participant ids explicitly mentioned in the message.\n mentionedParticipantIds: string[];\n // Number of agent-authored hops that led to this message (0 for humans).\n hopDepth: number;\n // The originating agent for a tool-posted message, including linked conversations.\n agentAuthorDefinitionId?: string | null;\n createdAt: string;\n}\n\nexport interface RouteArgsIface {\n conversation: ConversationIface;\n message: ConversationMessageIface;\n participants: ParticipantIface[];\n agentParticipantId?: string;\n}\n\nexport interface RouteDecisionIface {\n participantId: string;\n delivery: Delivery;\n}\n\nexport interface PostMessageArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind?: MessageKind;\n content: ContentBlock[];\n replyToMessageId?: string | null;\n threadRootId?: string | null;\n quotedMessageIds?: string[];\n clientMessageId?: string | null;\n mentionedParticipantIds?: string[];\n attachmentIds?: string[];\n hopDepth?: number;\n // A tool or linked-conversation event carries the turn that produced it.\n originTurnId?: string | null;\n // Projection provenance for agent replies.\n source?: { turnId: string; fromSeq: number; toSeq: number } | null;\n}\n\nexport const roomMessageInputSchema = z.object({\n conversationId: z.string().min(1),\n authorParticipantId: z.string().min(1),\n kind: z.nativeEnum(MessageKind).default(MessageKind.Message),\n content: z.array(jsonObjectSchema).min(1),\n clientMessageId: z.string().min(1).nullish(),\n replyToMessageId: z.string().min(1).nullish(),\n threadRootId: z.string().min(1).nullish(),\n quotedMessageIds: z.array(z.string().min(1)).default([]),\n mentionedParticipantIds: z.array(z.string().min(1)).default([]),\n});\n\nexport interface CardArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind: CardKind;\n decisionId: string | null;\n // Generic cards only: a title, body, options, and entity links (a Goal is an\n // entity link, not a card kind).\n state: JsonObject;\n entityLinks: {\n kind: string;\n id: string;\n title?: string;\n url?: string;\n description?: string;\n imageUrl?: string;\n }[];\n}\n\nexport interface PromptArgsIface {\n waitForAcceptance?: boolean;\n channelBinding?: { id: string; revisionId: string };\n auth?: RoomAuthIface | null;\n title?: string;\n participantId: string;\n content: ContentBlock[];\n turnPolicy: TurnPolicy;\n replyExpected: boolean;\n idempotencyKey: string;\n // Who prompted (for payer resolution and decision audience).\n authorParticipantId: string;\n audienceParticipantIds: string[];\n sourceMessageId: string;\n}\n\nexport interface ObserveArgsIface {\n participantId: string;\n content: ContentBlock[];\n idempotencyKey: string;\n}\n\n// Operations available while customizing a Final chat.\nexport interface RoomPlatformIface {\n conversations: {\n get(conversationId: string): Promise<ConversationIface | null>;\n createAttachmentUpload?(args: {\n conversationId: string;\n name: string;\n contentType: string;\n sizeBytes: number;\n }): Promise<{\n attachmentId: string;\n uploadUrl: string;\n method: string;\n headers: Record<string, string>;\n expiresAt: string;\n }>;\n getAttachmentUrl?(args: {\n conversationId: string;\n attachmentId: string;\n }): Promise<{ attachmentId: string; url: string; expiresAt: string }>;\n // Dispatch a stored reply to each recipient's binding; each channel owns routing.\n dispatchMessage?(args: {\n conversationId: string;\n messageId: string;\n participantId?: string;\n requestedDelivery?: Delivery;\n }): Promise<void>;\n participants(conversationId: string): Promise<ParticipantIface[]>;\n postMessage(args: PostMessageArgsIface): Promise<ConversationMessageIface>;\n updateMessage(args: {\n messageId: string;\n content: ContentBlock[];\n final: boolean;\n }): Promise<void>;\n postCard(args: CardArgsIface): Promise<ConversationMessageIface>;\n updateCard(args: { messageId: string; state: JsonObject }): Promise<void>;\n recentMessages(args: {\n conversationId: string;\n limit: number;\n beforeSeq?: number;\n afterSeq?: number;\n }): Promise<ConversationMessageIface[]>;\n // Messages of the conversation by id, however old (reply, thread and quote\n // context outside the recent window); unknown and deleted ones are absent.\n getMessages(args: {\n conversationId: string;\n messageIds: string[];\n }): Promise<ConversationMessageIface[]>;\n };\n sessions: {\n prompt(\n args: PromptArgsIface,\n ): Promise<{ messageId: string; sessionId?: string; turnId?: string }>;\n observe(args: ObserveArgsIface): Promise<void>;\n cancel(args: {\n participantId: string;\n reason?: string;\n throughMessageSeq?: number;\n }): Promise<void>;\n respond?(args: RoomInputResponseIface): Promise<{ resolved: boolean }>;\n };\n log(message: string, details?: Record<string, JsonValue>): void;\n}\n\nexport interface RoomInputResponseIface {\n channelBinding?: { id: string; revisionId: string };\n auth?: RoomAuthIface | null;\n participantId: string;\n decisionId: string;\n outcome: JsonValue;\n actorParticipantId: string;\n userId: string | null;\n}\n\nexport interface RoomReceiveContextIface {\n bindings?: HostedBindingsIface;\n platform: RoomPlatformIface;\n organizationId: string;\n definitionId: string | null;\n bindingId: string | null;\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\n // A stored, authenticated delivery to one agent in a shared conversation.\n agentParticipantId?: string;\n message?: ConversationMessageIface;\n conversation?: ConversationIface;\n participants?: readonly ParticipantIface[];\n response?: RoomInputResponseIface;\n conversationId?: string;\n cancelReason?: string;\n // Preserve this boundary when forwarding a retryable conversation Stop.\n cancelThroughMessageSeq?: number;\n requestedDelivery?: Delivery;\n}\n\nexport interface ProjectionContextIface<State = JsonValue> {\n bindings?: HostedBindingsIface;\n sessionId?: string;\n platform: RoomPlatformIface;\n // The binding's config and the agent's secrets (manifest.secrets), as receive gets them:\n // a channel posts its replies back to its own service with them.\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\n conversation: ConversationIface | null;\n agentParticipant: ParticipantIface | null;\n turn: { id: string; promptMessageId: string | null; authorParticipantId: string | null };\n seq: number;\n state: ChannelTurnStateIface<State>;\n}\n\nexport enum DecisionEventKind {\n Created = 'decision.created',\n Resolved = 'decision.resolved',\n}\n\nexport type AcpUpdateKind = SessionUpdate['sessionUpdate'];\n// The update kinds ACP v2 names; AcpUpdateKind also admits any other string.\nexport type KnownAcpUpdateKind = `${SessionUpdateKind}`;\n\nexport type RoomEventKind = AcpUpdateKind | `${DecisionEventKind}` | `${SemanticChannelEventKind}`;\n\nexport interface RoomEventIface {\n type: string;\n data: JsonValue;\n seq: number;\n}\n\nexport type RoomEventHandler<State = JsonValue> = (\n event: RoomEventIface,\n ctx: ProjectionContextIface<State>,\n) => Promise<void>;\n\nexport enum DecisionKind {\n Permission = 'permission',\n Elicitation = 'elicitation',\n}\n\n// `data` of a decision.created event: an ACP session/request_permission or\n// elicitation/create request awaiting its audience.\nexport const decisionCreatedDataSchema = z.object({\n decisionId: z.string().min(1),\n kind: z.nativeEnum(DecisionKind),\n audienceParticipantIds: z.array(z.string()),\n request: jsonValueSchema,\n});\n\nexport type DecisionCreatedDataIface = z.infer<typeof decisionCreatedDataSchema>;\n\n// `data` of a decision.resolved event: the answer (or cancellation) as recorded,\n// and the principal a channel answered as (null for Final rooms and expiries).\nexport const decisionResolvedDataSchema = z.object({\n decisionId: z.string().min(1),\n outcome: jsonValueSchema,\n respondedBy: roomAuthSchema.nullable().default(null),\n});\n\nexport type DecisionResolvedDataIface = z.infer<typeof decisionResolvedDataSchema>;\n\n// The visible-output updates `project` receives. After them, the\n// turn's projection ends with one ACP v2 idle `state_update` (turnEndUpdate).\n// Thought, tool, plan and every other update, other state updates included,\n// reach a channel only through an `events` handler for its kind.\nexport const PROJECTED_UPDATE_KINDS: ReadonlySet<AcpUpdateKind> = new Set<AcpUpdateKind>([\n 'agent_message_chunk',\n 'agent_message',\n]);\n\nconst turnEndSchema = z.looseObject({\n sessionUpdate: z.literal('state_update'),\n state: z.literal('idle'),\n stopReason: z.string().nullish(),\n _meta: z\n .looseObject({ 'final.ai': z.looseObject({ stopReason: z.string().nullish() }).nullish() })\n .nullish(),\n});\n\n// The stop reason when the update ends the turn (an idle state_update); null otherwise.\nexport const turnEndOf = (update: SessionUpdate): { stopReason: string | null } | null => {\n const parsed = turnEndSchema.safeParse(update);\n if (!parsed.success) return null;\n return {\n stopReason: parsed.data.stopReason ?? parsed.data._meta?.['final.ai']?.stopReason ?? null,\n };\n};\n\n// The idle state_update that ends a turn, as `project` receives it. A stop\n// reason outside ACP's known set rides in `_meta[\"final.ai\"]` (the SDK types\n// only received values as unknown variants).\nexport const turnEndUpdate = (stopReason: string | null): SessionUpdate => {\n switch (stopReason) {\n case null:\n return { sessionUpdate: 'state_update', state: 'idle' };\n case 'end_turn':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'end_turn' };\n case 'max_tokens':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_tokens' };\n case 'max_turn_requests':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_turn_requests' };\n case 'refusal':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'refusal' };\n case 'cancelled':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'cancelled' };\n default:\n return {\n sessionUpdate: 'state_update',\n state: 'idle',\n _meta: { 'final.ai': { stopReason } },\n };\n }\n};\n\n// The Final chat admission, routing and rendering extension.\nexport interface RoomSurfaceDefinitionIface<Inbound, State = undefined> {\n config?: JsonObject;\n configure?: (config: JsonObject) => RoomSurfaceDefinitionIface<Inbound, State>;\n respond?(\n input: RoomInputResponseIface,\n ctx: RoomReceiveContextIface,\n ): Promise<{ resolved: boolean }>;\n cancel?(ctx: RoomReceiveContextIface): Promise<{ accepted: boolean }>;\n // Inserts the input into its conversation and routes it. Returns where it went.\n receive(input: Inbound, ctx: RoomReceiveContextIface): Promise<RoomReceiveResult>;\n // Pure: who gets this message, and how. The channel applies it\n // to what it posts, from receive and project.\n route(args: RouteArgsIface): RouteDecisionIface[] | Promise<RouteDecisionIface[]>;\n turnPolicy: TurnPolicy;\n // ACP update \u2192 visible message / card. Called with a turn's\n // PROJECTED_UPDATE_KINDS updates in seq order, then its idle state_update.\n project(update: SessionUpdate, ctx: ProjectionContextIface<State>): Promise<void>;\n events?: Partial<Record<RoomEventKind, RoomEventHandler<State>>>;\n}\n\nexport const defineRoomSurface = <Inbound, State = undefined>(\n definition: RoomSurfaceDefinitionIface<Inbound, State>,\n): RoomSurfaceDefinitionIface<Inbound, State> => definition;\n"],
5
- "mappings": "AAGA,YAAY,OAAO;AAEnB,SAAS,kBAAkB,uBAAwD;AAO5E,IAAK,oBAAL,kBAAKA,uBAAL;AACL,EAAAA,mBAAA,UAAO;AACP,EAAAA,mBAAA,aAAU;AAFA,SAAAA;AAAA,GAAA;AAcL,MAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC7B,eAAe,EAAE,WAAW,iBAAiB;AAAA,EAC7C,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA;AAAA,EAE/B,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAAA,EACjD,YAAY,iBAAiB,QAAQ,CAAC,CAAC;AACzC,CAAC;AAGM,MAAM,uBAAuB,CAAC,SAAgC;AACnE,QAAM,OAAO,KAAK,aAAa;AAC/B,SAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO,KAAK;AACnE;AAEO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,YAAS;AACT,EAAAA,kBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAKL,IAAK,kBAAL,kBAAKC,qBAAL;AACL,EAAAA,iBAAA,UAAO;AACP,EAAAA,iBAAA,WAAQ;AAFE,SAAAA;AAAA,GAAA;AAKL,IAAK,cAAL,kBAAKC,iBAAL;AACL,EAAAA,aAAA,aAAU;AACV,EAAAA,aAAA,SAAM;AACN,EAAAA,aAAA,aAAU;AAHA,SAAAA;AAAA,GAAA;AAML,IAAK,aAAL,kBAAKC,gBAAL;AACL,EAAAA,YAAA,WAAQ;AACR,EAAAA,YAAA,WAAQ;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IAClB,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,OAAO;AAAA,IACxD,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,WAAW;AAAA,IAChF,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,aAAa;AAAA,IAClF,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,oBAAoB;AAAA,IACzF,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,UAAU;AAAA,IAC/E,KAAK;AACH,aAAO,EAAE,eAAe,gBAAgB,OAAO,QAAQ,YAAY,YAAY;AAAA,IACjF;AACE,aAAO;AAAA,QACL,eAAe;AAAA,QACf,OAAO;AAAA,QACP,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE;AAAA,MACtC;AAAA,EACJ;AACF;AAuBO,MAAM,oBAAoB,CAC/B,eAC+C;",
4
+ "sourcesContent": ["import type { ContentBlock, SessionUpdate } from '@agentclientprotocol/sdk/experimental/v2';\nimport type { SessionUpdateKind } from '@finalai/acp-session';\nimport * as z from 'zod';\nimport type { ChannelTurnStateIface } from \"./channel.mjs\";\nimport { jsonObjectSchema, jsonValueSchema, type JsonObject, type JsonValue } from \"./json.mjs\";\nimport type { SemanticChannelEventKind } from \"./semantic-events.mjs\";\n\n// Contracts for customizing Final chats. Admission callbacks receive the\n// current message and members; renderers and events can post room output.\n// External transports use the separate scoped channel contract.\n\nexport enum RoomPrincipalType {\n User = 'user',\n Service = 'service',\n}\n\n// Who a room input or response came from, as vouched for by its authenticator.\nexport interface RoomAuthIface extends JsonObject {\n principalId: string;\n principalType: RoomPrincipalType | `${RoomPrincipalType}`;\n authenticator: string;\n // `displayName` (a string) when the principal is named; see principalDisplayName.\n attributes: JsonObject;\n}\n\nexport const roomAuthSchema = z.object({\n principalId: z.string().min(1),\n principalType: z.nativeEnum(RoomPrincipalType),\n authenticator: z.string().min(1),\n // How the agent and the people reading its reply name the principal.\n displayName: z.string().min(1).max(200).optional(),\n attributes: jsonObjectSchema.default({}),\n});\n\n// How a principal is named to the agent and in captions: its `displayName`, else its id.\nexport const principalDisplayName = (auth: RoomAuthIface): string => {\n const name = auth['displayName'];\n return typeof name === 'string' && name.length > 0 ? name : auth.principalId;\n};\n\nexport enum ConversationKind {\n Direct = 'direct',\n Group = 'group',\n}\n\nexport enum ParticipantKind {\n User = 'user',\n Agent = 'agent',\n}\n\nexport enum RoutingMode {\n Mention = 'mention',\n All = 'all',\n Default = 'default',\n}\n\nexport enum TurnPolicy {\n Steer = 'steer',\n Queue = 'queue',\n}\n\nexport enum Delivery {\n Prompt = 'prompt',\n Observe = 'observe',\n}\n\nexport enum MessageKind {\n Message = 'message',\n Card = 'card',\n}\n\nexport enum CardKind {\n Elicitation = 'elicitation',\n Permission = 'permission',\n Notice = 'notice',\n}\n\nexport interface ParticipantIface {\n id: string;\n kind: ParticipantKind;\n displayName: string;\n userId: string | null;\n definitionId: string | null;\n routingMode: RoutingMode | null;\n sessionId: string | null;\n // Whether the agent's harness supports _final/session/observe and renders\n // _meta[\"final.ai\"].author; null for non-agents.\n supportsObserve: boolean | null;\n rendersAuthorMeta: boolean | null;\n left: boolean;\n}\n\nexport const roomReceiveResultSchema = z.union([\n z.object({ conversationId: z.string().min(1) }),\n z.object({ sessionId: z.string().min(1) }),\n z.null(),\n]);\nexport type RoomReceiveResult = z.infer<typeof roomReceiveResultSchema>;\n\nexport interface ConversationRefIface {\n conversationId: string;\n}\n\nexport interface ConversationIface extends ConversationRefIface {\n organizationId: string;\n kind: ConversationKind;\n title: string | null;\n isHome: boolean;\n turnPolicy: TurnPolicy;\n}\n\nexport interface MessageRefIface {\n messageId: string;\n seq: number;\n}\n\nexport interface ConversationMessageIface extends MessageRefIface {\n conversationId: string;\n authorParticipantId: string;\n kind: MessageKind;\n body: string;\n content: ContentBlock[];\n replyToMessageId: string | null;\n threadRootId: string | null;\n // Earlier messages of the conversation the author quoted, in order.\n quotedMessageIds: string[];\n // Agent participant ids explicitly mentioned in the message.\n mentionedParticipantIds: string[];\n // Number of agent-authored hops that led to this message (0 for humans).\n hopDepth: number;\n // The originating agent for a tool-posted message, including linked conversations.\n agentAuthorDefinitionId?: string | null;\n createdAt: string;\n}\n\nexport interface RouteArgsIface {\n conversation: ConversationIface;\n message: ConversationMessageIface;\n participants: ParticipantIface[];\n agentParticipantId?: string;\n}\n\nexport interface RouteDecisionIface {\n participantId: string;\n delivery: Delivery;\n}\n\nexport interface PostMessageArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind?: MessageKind;\n content: ContentBlock[];\n replyToMessageId?: string | null;\n threadRootId?: string | null;\n quotedMessageIds?: string[];\n clientMessageId?: string | null;\n mentionedParticipantIds?: string[];\n attachmentIds?: string[];\n hopDepth?: number;\n // A tool or linked-conversation event carries the turn that produced it.\n originTurnId?: string | null;\n // Projection provenance for agent replies.\n source?: { turnId: string; fromSeq: number; toSeq: number } | null;\n}\n\nexport const roomMessageInputSchema = z.object({\n conversationId: z.string().min(1),\n authorParticipantId: z.string().min(1),\n kind: z.nativeEnum(MessageKind).default(MessageKind.Message),\n content: z.array(jsonObjectSchema).min(1),\n clientMessageId: z.string().min(1).nullish(),\n replyToMessageId: z.string().min(1).nullish(),\n threadRootId: z.string().min(1).nullish(),\n quotedMessageIds: z.array(z.string().min(1)).default([]),\n mentionedParticipantIds: z.array(z.string().min(1)).default([]),\n});\n\nexport interface CardArgsIface {\n conversationId: string;\n authorParticipantId: string;\n kind: CardKind;\n decisionId: string | null;\n // Generic cards only: a title, body, options, and entity links (a Final Task is an\n // entity link, not a card kind).\n state: JsonObject;\n entityLinks: {\n kind: string;\n id: string;\n title?: string;\n url?: string;\n description?: string;\n imageUrl?: string;\n }[];\n}\n\nexport interface PromptArgsIface {\n waitForAcceptance?: boolean;\n channelBinding?: { id: string };\n auth?: RoomAuthIface | null;\n title?: string;\n participantId: string;\n content: ContentBlock[];\n turnPolicy: TurnPolicy;\n replyExpected: boolean;\n idempotencyKey: string;\n // Who prompted (for inference resolution and decision audience).\n authorParticipantId: string;\n audienceParticipantIds: string[];\n sourceMessageId: string;\n}\n\nexport interface ObserveArgsIface {\n participantId: string;\n content: ContentBlock[];\n idempotencyKey: string;\n}\n\n// Operations available while customizing a Final chat.\nexport interface RoomPlatformIface {\n conversations: {\n get(conversationId: string): Promise<ConversationIface | null>;\n createAttachmentUpload?(args: {\n conversationId: string;\n name: string;\n contentType: string;\n sizeBytes: number;\n }): Promise<{\n attachmentId: string;\n uploadUrl: string;\n method: string;\n headers: Record<string, string>;\n expiresAt: string;\n }>;\n getAttachmentUrl?(args: {\n conversationId: string;\n attachmentId: string;\n }): Promise<{ attachmentId: string; url: string; expiresAt: string }>;\n // Dispatch a stored reply to each recipient's binding; each channel owns routing.\n dispatchMessage?(args: {\n conversationId: string;\n messageId: string;\n participantId?: string;\n requestedDelivery?: Delivery;\n }): Promise<void>;\n participants(conversationId: string): Promise<ParticipantIface[]>;\n postMessage(args: PostMessageArgsIface): Promise<ConversationMessageIface>;\n updateMessage(args: {\n messageId: string;\n content: ContentBlock[];\n final: boolean;\n }): Promise<void>;\n postCard(args: CardArgsIface): Promise<ConversationMessageIface>;\n updateCard(args: { messageId: string; state: JsonObject }): Promise<void>;\n recentMessages(args: {\n conversationId: string;\n limit: number;\n beforeSeq?: number;\n afterSeq?: number;\n }): Promise<ConversationMessageIface[]>;\n // Messages of the conversation by id, however old (reply, thread and quote\n // context outside the recent window); unknown and deleted ones are absent.\n getMessages(args: {\n conversationId: string;\n messageIds: string[];\n }): Promise<ConversationMessageIface[]>;\n };\n sessions: {\n prompt(\n args: PromptArgsIface,\n ): Promise<{ messageId: string; sessionId?: string; turnId?: string }>;\n observe(args: ObserveArgsIface): Promise<void>;\n cancel(args: {\n participantId: string;\n reason?: string;\n throughMessageSeq?: number;\n }): Promise<void>;\n respond?(args: RoomInputResponseIface): Promise<{ resolved: boolean }>;\n };\n log(message: string, details?: Record<string, JsonValue>): void;\n}\n\nexport interface RoomInputResponseIface {\n channelBinding?: { id: string };\n auth?: RoomAuthIface | null;\n participantId: string;\n decisionId: string;\n outcome: JsonValue;\n actorParticipantId: string;\n userId: string | null;\n}\n\nexport interface RoomReceiveContextIface {\n platform: RoomPlatformIface;\n organizationId: string;\n definitionId: string | null;\n bindingId: string | null;\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\n // A stored, authenticated delivery to one agent in a shared conversation.\n agentParticipantId?: string;\n message?: ConversationMessageIface;\n conversation?: ConversationIface;\n participants?: readonly ParticipantIface[];\n response?: RoomInputResponseIface;\n conversationId?: string;\n cancelReason?: string;\n // Preserve this boundary when forwarding a retryable conversation Stop.\n cancelThroughMessageSeq?: number;\n requestedDelivery?: Delivery;\n}\n\nexport interface ProjectionContextIface<State = JsonValue> {\n sessionId?: string;\n platform: RoomPlatformIface;\n // The binding's config and the agent's secrets (manifest.secrets), as receive gets them:\n // a channel posts its replies back to its own service with them.\n config: JsonObject;\n secrets: { get(name: string): Promise<string | null> };\n conversation: ConversationIface | null;\n agentParticipant: ParticipantIface | null;\n turn: { id: string; promptMessageId: string | null; authorParticipantId: string | null };\n seq: number;\n state: ChannelTurnStateIface<State>;\n}\n\nexport enum DecisionEventKind {\n Created = 'decision.created',\n Resolved = 'decision.resolved',\n}\n\nexport type AcpUpdateKind = SessionUpdate['sessionUpdate'];\n// The update kinds ACP v2 names; AcpUpdateKind also admits any other string.\nexport type KnownAcpUpdateKind = `${SessionUpdateKind}`;\n\nexport type RoomEventKind = AcpUpdateKind | `${DecisionEventKind}` | `${SemanticChannelEventKind}`;\n\nexport interface RoomEventIface {\n type: string;\n data: JsonValue;\n seq: number;\n}\n\nexport type RoomEventHandler<State = JsonValue> = (\n event: RoomEventIface,\n ctx: ProjectionContextIface<State>,\n) => Promise<void>;\n\nexport enum DecisionKind {\n Permission = 'permission',\n Elicitation = 'elicitation',\n}\n\n// `data` of a decision.created event: an ACP session/request_permission or\n// elicitation/create request awaiting its audience.\nexport const decisionCreatedDataSchema = z.object({\n decisionId: z.string().min(1),\n kind: z.nativeEnum(DecisionKind),\n audienceParticipantIds: z.array(z.string()),\n request: jsonValueSchema,\n});\n\nexport type DecisionCreatedDataIface = z.infer<typeof decisionCreatedDataSchema>;\n\n// `data` of a decision.resolved event: the answer (or cancellation) as recorded,\n// and the principal a channel answered as (null for Final rooms and expiries).\nexport const decisionResolvedDataSchema = z.object({\n decisionId: z.string().min(1),\n outcome: jsonValueSchema,\n respondedBy: roomAuthSchema.nullable().default(null),\n});\n\nexport type DecisionResolvedDataIface = z.infer<typeof decisionResolvedDataSchema>;\n\n// The visible-output updates `project` receives. After them, the\n// turn's projection ends with one ACP v2 idle `state_update` (turnEndUpdate).\n// Thought, tool, plan and every other update, other state updates included,\n// reach a channel only through an `events` handler for its kind.\nexport const PROJECTED_UPDATE_KINDS: ReadonlySet<AcpUpdateKind> = new Set<AcpUpdateKind>([\n 'agent_message_chunk',\n 'agent_message',\n]);\n\nconst turnEndSchema = z.looseObject({\n sessionUpdate: z.literal('state_update'),\n state: z.literal('idle'),\n stopReason: z.string().nullish(),\n _meta: z\n .looseObject({ 'final.ai': z.looseObject({ stopReason: z.string().nullish() }).nullish() })\n .nullish(),\n});\n\n// The stop reason when the update ends the turn (an idle state_update); null otherwise.\nexport const turnEndOf = (update: SessionUpdate): { stopReason: string | null } | null => {\n const parsed = turnEndSchema.safeParse(update);\n if (!parsed.success) return null;\n return {\n stopReason: parsed.data.stopReason ?? parsed.data._meta?.['final.ai']?.stopReason ?? null,\n };\n};\n\n// The idle state_update that ends a turn, as `project` receives it. A stop\n// reason outside ACP's known set rides in `_meta[\"final.ai\"]` (the SDK types\n// only received values as unknown variants).\nexport const turnEndUpdate = (stopReason: string | null): SessionUpdate => {\n switch (stopReason) {\n case null:\n return { sessionUpdate: 'state_update', state: 'idle' };\n case 'end_turn':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'end_turn' };\n case 'max_tokens':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_tokens' };\n case 'max_turn_requests':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'max_turn_requests' };\n case 'refusal':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'refusal' };\n case 'cancelled':\n return { sessionUpdate: 'state_update', state: 'idle', stopReason: 'cancelled' };\n default:\n return {\n sessionUpdate: 'state_update',\n state: 'idle',\n _meta: { 'final.ai': { stopReason } },\n };\n }\n};\n\n// The Final chat admission, routing and rendering extension.\nexport interface RoomSurfaceDefinitionIface<Inbound, State = undefined> {\n config?: JsonObject;\n configure?: (config: JsonObject) => RoomSurfaceDefinitionIface<Inbound, State>;\n respond?(\n input: RoomInputResponseIface,\n ctx: RoomReceiveContextIface,\n ): Promise<{ resolved: boolean }>;\n cancel?(ctx: RoomReceiveContextIface): Promise<{ accepted: boolean }>;\n // Inserts the input into its conversation and routes it. Returns where it went.\n receive(input: Inbound, ctx: RoomReceiveContextIface): Promise<RoomReceiveResult>;\n // Pure: who gets this message, and how. The channel applies it\n // to what it posts, from receive and project.\n route(args: RouteArgsIface): RouteDecisionIface[] | Promise<RouteDecisionIface[]>;\n turnPolicy: TurnPolicy;\n // ACP update \u2192 visible message / card. Called with a turn's\n // PROJECTED_UPDATE_KINDS updates in seq order, then its idle state_update.\n project(update: SessionUpdate, ctx: ProjectionContextIface<State>): Promise<void>;\n events?: Partial<Record<RoomEventKind, RoomEventHandler<State>>>;\n}\n\nexport const defineRoomSurface = <Inbound, State = undefined>(\n definition: RoomSurfaceDefinitionIface<Inbound, State>,\n): RoomSurfaceDefinitionIface<Inbound, State> => definition;\n"],
5
+ "mappings": "AAEA,YAAY,OAAO;AAEnB,SAAS,kBAAkB,uBAAwD;AAO5E,IAAK,oBAAL,kBAAKA,uBAAL;AACL,EAAAA,mBAAA,UAAO;AACP,EAAAA,mBAAA,aAAU;AAFA,SAAAA;AAAA,GAAA;AAcL,MAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,aA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,gBAAgB,OAAO,QAAQ,YAAY,YAAY;AAAA,IACjF;AACE,aAAO;AAAA,QACL,eAAe;AAAA,QACf,OAAO;AAAA,QACP,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE;AAAA,MACtC;AAAA,EACJ;AACF;AAuBO,MAAM,oBAAoB,CAC/B,eAC+C;",
6
6
  "names": ["RoomPrincipalType", "ConversationKind", "ParticipantKind", "RoutingMode", "TurnPolicy", "Delivery", "MessageKind", "CardKind", "DecisionEventKind", "DecisionKind"]
7
7
  }
@@ -40,6 +40,9 @@ export interface ConnectSandboxClientArgsIface {
40
40
  maxDelayMs?: number;
41
41
  };
42
42
  refreshMarginMs?: number;
43
+ identity?: (args: {
44
+ renew: boolean;
45
+ }) => Promise<string>;
43
46
  clientInfo?: {
44
47
  name: string;
45
48
  version: string;
@@ -3,6 +3,7 @@ import { readTextFileStream, runCollect } from "./convenience.mjs";
3
3
  import { resolvePosixPath } from "./paths.mjs";
4
4
  import { createRpcPeer } from "./rpc-peer.mjs";
5
5
  import {
6
+ isSandboxWorkerEndpoint,
6
7
  SandboxCapability
7
8
  } from "./types.mjs";
8
9
  import {
@@ -96,6 +97,36 @@ const connectSandboxClient = async (args) => {
96
97
  if (current === connection) current = null;
97
98
  await getConnection();
98
99
  };
100
+ const syncIdentity = (connection, renew) => {
101
+ const identity = args.identity;
102
+ if (identity == null) return Promise.resolve();
103
+ const run = connection.identitySync.then(async () => {
104
+ const assertion = await identity({ renew });
105
+ if (assertion === connection.identity || connection.peer.isClosed()) return;
106
+ const raw = await connection.peer.request(HandleRpcMethod.IdentityRefresh, { assertion });
107
+ connection.identity = assertion;
108
+ scheduleIdentityRenewal(
109
+ connection,
110
+ parseHandleRpcResult(HandleRpcMethod.IdentityRefresh, raw).expiresAt
111
+ );
112
+ });
113
+ connection.identitySync = run.catch(() => void 0);
114
+ return run;
115
+ };
116
+ const scheduleIdentityRenewal = (connection, expiresAt) => {
117
+ if (connection.identityTimer != null) clearTimeout(connection.identityTimer);
118
+ connection.identityTimer = null;
119
+ if (expiresAt == null || args.identity == null || closedByUser) return;
120
+ const remaining = Date.parse(expiresAt) - now();
121
+ if (Number.isNaN(remaining)) return;
122
+ const delay = Math.max(0, Math.min(remaining - refreshMarginMs, remaining / 2));
123
+ connection.identityTimer = setTimeout(
124
+ () => {
125
+ void syncIdentity(connection, true).catch(() => void 0);
126
+ },
127
+ Math.min(2147483647, delay)
128
+ );
129
+ };
99
130
  const initialize = async (target) => {
100
131
  const channel = await openChannel({ url: target.url, token: target.token });
101
132
  let connection = null;
@@ -104,19 +135,31 @@ const connectSandboxClient = async (args) => {
104
135
  binary,
105
136
  onClose: () => {
106
137
  if (connection == null) return;
138
+ if (connection.identityTimer != null) clearTimeout(connection.identityTimer);
107
139
  live.delete(connection);
108
140
  if (current === connection) current = null;
109
141
  }
110
142
  });
111
143
  try {
144
+ const identity = args.identity == null ? null : await args.identity({ renew: false });
112
145
  const raw = await peer.request(HandleRpcMethod.Initialize, {
113
146
  handleRpcVersion: HANDLE_RPC_VERSION,
114
147
  token: target.token,
148
+ ...identity == null ? {} : { identity },
115
149
  client: args.clientInfo
116
150
  });
117
151
  const info = handleRpcMethodSchemas[HandleRpcMethod.Initialize].result.parse(raw);
118
- connection = { peer, target, info, nextStreamId: 1 };
152
+ connection = {
153
+ peer,
154
+ target,
155
+ info,
156
+ nextStreamId: 1,
157
+ identity,
158
+ identitySync: Promise.resolve(),
159
+ identityTimer: null
160
+ };
119
161
  live.add(connection);
162
+ if (identity != null) scheduleIdentityRenewal(connection, info.expiresAt);
120
163
  return connection;
121
164
  } catch (error) {
122
165
  peer.close(HandleRpcCloseCode.Normal, "initialize failed");
@@ -158,13 +201,18 @@ const connectSandboxClient = async (args) => {
158
201
  }
159
202
  }
160
203
  };
161
- const getConnection = () => {
204
+ const liveConnection = () => {
162
205
  if (current != null && !current.peer.isClosed()) return Promise.resolve(current);
163
206
  connecting ??= establish().finally(() => {
164
207
  connecting = null;
165
208
  });
166
209
  return connecting;
167
210
  };
211
+ const getConnection = async () => {
212
+ const connection = await liveConnection();
213
+ await syncIdentity(connection, false);
214
+ return connection;
215
+ };
168
216
  const requestOn = async (connection, method, params, options) => {
169
217
  const raw = await connection.peer.request(method, params, { signal: options?.signal });
170
218
  return parseHandleRpcResult(method, raw);
@@ -293,7 +341,7 @@ const connectSandboxClient = async (args) => {
293
341
  kill
294
342
  };
295
343
  };
296
- const spawn = async (options) => {
344
+ const startProcess = async (args2) => {
297
345
  const connection = await getConnection();
298
346
  const processId = randomId();
299
347
  const stdoutStreamId = allocateStreamId(connection);
@@ -303,27 +351,21 @@ const connectSandboxClient = async (args) => {
303
351
  const stderr = connection.peer.streams.openIncoming(stderrStreamId);
304
352
  let stdinWriter = null;
305
353
  let stdinSource;
306
- if (options.stdin == null) {
354
+ if (args2.stdin == null) {
307
355
  const pipe = new TransformStream();
308
356
  stdinWriter = pipe.writable.getWriter();
309
357
  stdinSource = pipe.readable;
310
- } else if (options.stdin instanceof ReadableStream) {
311
- stdinSource = options.stdin;
358
+ } else if (args2.stdin instanceof ReadableStream) {
359
+ stdinSource = args2.stdin;
312
360
  } else {
313
- stdinSource = bytesToStream(utf8Encode(options.stdin));
361
+ stdinSource = bytesToStream(utf8Encode(args2.stdin));
314
362
  }
315
363
  connection.peer.streams.openOutgoing(stdinStreamId, stdinSource).catch(() => void 0);
316
- const durable = options.durable === true && connection.info.capabilities.includes(SandboxCapability.DurableProcesses);
364
+ const durable = args2.durable === true && connection.info.capabilities.includes(SandboxCapability.DurableProcesses);
317
365
  let result;
318
366
  try {
319
- result = await requestOn(connection, HandleRpcMethod.Spawn, {
367
+ result = await args2.request(connection, {
320
368
  processId,
321
- command: options.command,
322
- args: options.args,
323
- cwd: options.cwd,
324
- env: options.env,
325
- shell: options.shell,
326
- timeoutMs: options.timeoutMs,
327
369
  stdinStreamId,
328
370
  stdoutStreamId,
329
371
  stderrStreamId,
@@ -332,16 +374,22 @@ const connectSandboxClient = async (args) => {
332
374
  } catch (error) {
333
375
  connection.peer.streams.discardIncoming(stdoutStreamId);
334
376
  connection.peer.streams.discardIncoming(stderrStreamId);
335
- connection.peer.streams.abortOutgoing(stdinStreamId, "spawn failed");
377
+ connection.peer.streams.abortOutgoing(stdinStreamId, "start failed");
336
378
  throw error;
337
379
  }
380
+ if ("endpoint" in result) {
381
+ connection.peer.streams.discardIncoming(stdoutStreamId);
382
+ connection.peer.streams.discardIncoming(stderrStreamId);
383
+ connection.peer.streams.abortOutgoing(stdinStreamId, "worker endpoint");
384
+ return { endpoint: result.endpoint };
385
+ }
338
386
  const ref = result.ref ?? null;
339
387
  const controls = processControls({
340
388
  connection,
341
389
  processId,
342
390
  durable: ref != null,
343
391
  streamIds: [stdoutStreamId, stderrStreamId],
344
- abortSignal: options.abortSignal
392
+ abortSignal: args2.abortSignal
345
393
  });
346
394
  return {
347
395
  pid: result.pid,
@@ -350,7 +398,7 @@ const connectSandboxClient = async (args) => {
350
398
  stderr,
351
399
  write: async (data, writeOptions) => {
352
400
  if (stdinWriter == null) throw new Error("stdin was provided at spawn");
353
- if (ref != null) options.abortSignal?.throwIfAborted();
401
+ if (ref != null) args2.abortSignal?.throwIfAborted();
354
402
  const bytes = data instanceof Uint8Array ? data : utf8Encode(data);
355
403
  if (bytes.byteLength > 0) await stdinWriter.write(bytes);
356
404
  if (writeOptions?.end === true) await stdinWriter.close();
@@ -358,6 +406,40 @@ const connectSandboxClient = async (args) => {
358
406
  ...controls
359
407
  };
360
408
  };
409
+ const spawn = async (options) => {
410
+ const started = await startProcess({
411
+ stdin: options.stdin,
412
+ durable: options.durable,
413
+ abortSignal: options.abortSignal,
414
+ request: (connection, streams) => requestOn(connection, HandleRpcMethod.Spawn, {
415
+ command: options.command,
416
+ args: options.args,
417
+ cwd: options.cwd,
418
+ env: options.env,
419
+ shell: options.shell,
420
+ timeoutMs: options.timeoutMs,
421
+ ...streams
422
+ })
423
+ });
424
+ if (isSandboxWorkerEndpoint(started))
425
+ throw handleRpcError({
426
+ code: HandleRpcErrorCode.InvalidRequest,
427
+ message: "sandbox/spawn answered with an endpoint"
428
+ });
429
+ return started;
430
+ };
431
+ const startWorker = (options) => startProcess({
432
+ stdin: void 0,
433
+ durable: options.durable,
434
+ abortSignal: options.abortSignal,
435
+ request: (connection, streams) => requestOn(connection, HandleRpcMethod.StartWorker, {
436
+ program: options.program,
437
+ env: options.env,
438
+ input: options.input,
439
+ ...options.identity == null ? {} : { identity: options.identity },
440
+ ...streams
441
+ })
442
+ });
361
443
  const attachProcess = async (options) => {
362
444
  const connection = await getConnection();
363
445
  const processId = randomId();
@@ -561,6 +643,7 @@ const connectSandboxClient = async (args) => {
561
643
  }
562
644
  if (capabilities.includes(SandboxCapability.DurableProcesses))
563
645
  client.attachProcess = attachProcess;
646
+ if (capabilities.includes(SandboxCapability.Workers)) client.startWorker = startWorker;
564
647
  if (capabilities.includes(SandboxCapability.ComputerUse)) {
565
648
  client.computerUse = async () => {
566
649
  const { connection, result } = await callOnConnection(HandleRpcMethod.ComputerUse, {});
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/client.ts"],
4
- "sourcesContent": ["import { bytesToBase64, bytesToStream, encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { resolvePosixPath } from \"./paths.mjs\";\nimport { createRpcPeer, type RpcPeerIface } from \"./rpc-peer.mjs\";\nimport {\n SandboxCapability,\n type AbortableIface,\n type DirEntryIface,\n type McpChannelIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxAttachedProcessIface,\n type SandboxAttachProcessOptionsIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type ScreenSessionIface,\n type StatIface,\n} from \"./types.mjs\";\nimport {\n frameChannelFromWebSocket,\n HANDLE_RPC_IDEMPOTENT_METHODS,\n HANDLE_RPC_VERSION,\n handleRpcClientProtocols,\n HandleRpcCloseCode,\n handleRpcError,\n HandleRpcErrorCode,\n HandleRpcMethod,\n handleRpcMethodSchemas,\n isHandleRpcError,\n MAX_INLINE_WRITE_BYTES,\n parseHandleRpcResult,\n type FrameChannelIface,\n type HandleRpcParams,\n type HandleRpcResult,\n type InitializeResultIface,\n type WebSocketConstructorIface,\n} from \"./wire.mjs\";\n\n// NetworkSandboxSessionIface implemented purely over the handle RPC: no\n// provider code, only the wire. Works wherever a WebSocket exists (Workers,\n// browsers, Node 22+) or over any frame channel through `openChannel`.\n\nexport interface SandboxClientIface extends NetworkSandboxSessionIface {\n readonly confinedFiles: boolean;\n readonly providerHooks: boolean;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n readonly capabilities: readonly SandboxCapability[];\n // A byte range of a file, streamed; null when the file does not exist.\n readFileRange(options: {\n path: string;\n root?: string;\n offset: number;\n length?: number;\n abortSignal?: AbortSignal;\n }): Promise<ReadableStream<Uint8Array> | null>;\n // Closes every connection and fails in-flight calls.\n close(): void;\n}\n\nexport interface SandboxClientCredentialIface {\n token: string;\n expiresAt: string | null;\n // A new stable endpoint URL, when the issuer moved it.\n url?: string;\n}\n\nexport interface ConnectSandboxClientArgsIface {\n // The session service's stable per-binding address; the first call to reach\n // it attaches the sandbox, and every call is served there.\n url: string;\n token: string;\n expiresAt?: string | null;\n // Defaults to the global WebSocket.\n WebSocket?: WebSocketConstructorIface;\n // Replaces WebSocket dialing entirely (relays, tests).\n openChannel?: (target: { url: string; token: string }) => Promise<FrameChannelIface>;\n // Returns a fresh credential for the stable endpoint (`url`), e.g. from the\n // broker's `sandbox` route.\n refreshToken?: () => Promise<SandboxClientCredentialIface>;\n // Send stream chunks as binary frames (default true).\n binary?: boolean;\n reconnect?: { attempts?: number; baseDelayMs?: number; maxDelayMs?: number };\n // How long before expiry to refresh the credential (default 60 s).\n refreshMarginMs?: number;\n clientInfo?: { name: string; version: string };\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n randomId?: () => string;\n}\n\ninterface TargetIface {\n url: string;\n token: string;\n expiresAt: string | null;\n}\n\ninterface ConnectionIface {\n peer: RpcPeerIface;\n target: TargetIface;\n info: InitializeResultIface;\n nextStreamId: number;\n}\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nconst defaultOpenChannel =\n (WebSocketImpl: WebSocketConstructorIface | undefined) =>\n async (target: { url: string; token: string }): Promise<FrameChannelIface> => {\n const Impl = WebSocketImpl ?? globalThis.WebSocket;\n if (Impl == null)\n throw new Error('no WebSocket implementation available; pass WebSocket or openChannel');\n const { channel, opened } = frameChannelFromWebSocket(\n new Impl(target.url, handleRpcClientProtocols(target.token)),\n );\n await opened;\n return channel;\n };\n\nconst isRetryable = (cause: unknown): boolean => isHandleRpcError(cause) && cause.retryable;\n\nexport const connectSandboxClient = async (\n args: ConnectSandboxClientArgsIface,\n): Promise<SandboxClientIface> => {\n const now = args.now ?? Date.now;\n const sleep = args.sleep ?? defaultSleep;\n const randomId = args.randomId ?? (() => crypto.randomUUID());\n const openChannel = args.openChannel ?? defaultOpenChannel(args.WebSocket);\n const attempts = args.reconnect?.attempts ?? 5;\n const baseDelayMs = args.reconnect?.baseDelayMs ?? 100;\n const maxDelayMs = args.reconnect?.maxDelayMs ?? 5_000;\n const refreshMarginMs = args.refreshMarginMs ?? 60_000;\n const binary = args.binary ?? true;\n\n let origin: TargetIface = {\n url: args.url,\n token: args.token,\n expiresAt: args.expiresAt ?? null,\n };\n let current: ConnectionIface | null = null;\n let connecting: Promise<ConnectionIface> | null = null;\n let closedByUser = false;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n const live = new Set<ConnectionIface>();\n let lastInfo: InitializeResultIface | null = null;\n\n const refreshOrigin = async (): Promise<boolean> => {\n if (args.refreshToken == null) return false;\n const fresh = await args.refreshToken();\n origin = {\n url: fresh.url ?? origin.url,\n token: fresh.token,\n expiresAt: fresh.expiresAt,\n };\n return true;\n };\n\n const scheduleRefresh = (connection: ConnectionIface) => {\n if (refreshTimer != null) clearTimeout(refreshTimer);\n refreshTimer = null;\n const expiresAt = connection.info.expiresAt ?? connection.target.expiresAt;\n if (expiresAt == null || args.refreshToken == null || closedByUser) return;\n const remaining = Date.parse(expiresAt) - now();\n if (Number.isNaN(remaining)) return;\n const delay = Math.max(0, Math.min(remaining - refreshMarginMs, remaining / 2));\n refreshTimer = setTimeout(\n () => {\n void refreshConnection(connection).catch(() => undefined);\n },\n Math.min(2_147_483_647, delay),\n );\n };\n\n // The connection takes the new token in place; in-flight calls continue.\n // A moved endpoint (a new `url`) is dialed fresh instead, and in-flight\n // calls finish on the old connection.\n const refreshConnection = async (connection: ConnectionIface) => {\n if (closedByUser || connection.peer.isClosed()) return;\n await refreshOrigin();\n if (origin.url === connection.target.url) {\n const result = await requestOn(connection, HandleRpcMethod.AuthRefresh, {\n token: origin.token,\n });\n connection.target = {\n ...connection.target,\n token: origin.token,\n expiresAt: result.expiresAt,\n };\n connection.info = { ...connection.info, expiresAt: result.expiresAt };\n scheduleRefresh(connection);\n return;\n }\n if (current === connection) current = null;\n await getConnection();\n };\n\n const initialize = async (target: TargetIface): Promise<ConnectionIface> => {\n const channel = await openChannel({ url: target.url, token: target.token });\n let connection: ConnectionIface | null = null;\n const peer = createRpcPeer({\n channel,\n binary,\n onClose: () => {\n if (connection == null) return;\n live.delete(connection);\n if (current === connection) current = null;\n },\n });\n try {\n const raw = await peer.request(HandleRpcMethod.Initialize, {\n handleRpcVersion: HANDLE_RPC_VERSION,\n token: target.token,\n client: args.clientInfo,\n });\n const info = handleRpcMethodSchemas[HandleRpcMethod.Initialize].result.parse(raw);\n connection = { peer, target, info, nextStreamId: 1 };\n live.add(connection);\n return connection;\n } catch (error) {\n peer.close(HandleRpcCloseCode.Normal, 'initialize failed');\n throw error;\n }\n };\n\n const establish = async (): Promise<ConnectionIface> => {\n let failures = 0;\n let refreshed = false;\n for (;;) {\n if (closedByUser)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'client closed',\n });\n try {\n const connection = await initialize(origin);\n current = connection;\n lastInfo = connection.info;\n scheduleRefresh(connection);\n return connection;\n } catch (error) {\n if (closedByUser) throw error;\n const unauthorized =\n isHandleRpcError(error) && error.code === HandleRpcErrorCode.Unauthorized;\n if (unauthorized && !refreshed && (await refreshOrigin().catch(() => false))) {\n refreshed = true;\n continue;\n }\n if (unauthorized) throw error;\n failures += 1;\n if (failures >= attempts) {\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: `could not connect to the sandbox: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n });\n }\n await sleep(Math.min(maxDelayMs, baseDelayMs * 2 ** (failures - 1)));\n }\n }\n };\n\n const getConnection = (): Promise<ConnectionIface> => {\n if (current != null && !current.peer.isClosed()) return Promise.resolve(current);\n connecting ??= establish().finally(() => {\n connecting = null;\n });\n return connecting;\n };\n\n const requestOn = async <M extends HandleRpcMethod>(\n connection: ConnectionIface,\n method: M,\n params: HandleRpcParams<M>,\n options?: { signal?: AbortSignal },\n ): Promise<HandleRpcResult<M>> => {\n const raw = await connection.peer.request(method, params, { signal: options?.signal });\n return parseHandleRpcResult(method, raw);\n };\n\n const callOnConnection = async <M extends HandleRpcMethod>(\n method: M,\n params: HandleRpcParams<M>,\n options?: { signal?: AbortSignal },\n ): Promise<{ connection: ConnectionIface; result: HandleRpcResult<M> }> => {\n const idempotent = HANDLE_RPC_IDEMPOTENT_METHODS.includes(method);\n for (let attempt = 0; ; attempt += 1) {\n const connection = await getConnection();\n try {\n return { connection, result: await requestOn(connection, method, params, options) };\n } catch (error) {\n if (attempt === 0 && idempotent && isRetryable(error)) continue;\n throw error;\n }\n }\n };\n\n const call = async <M extends HandleRpcMethod>(\n method: M,\n params: HandleRpcParams<M>,\n options?: { signal?: AbortSignal },\n ): Promise<HandleRpcResult<M>> => (await callOnConnection(method, params, options)).result;\n\n const allocateStreamId = (connection: ConnectionIface): number => {\n const id = connection.nextStreamId;\n connection.nextStreamId += 1;\n return id;\n };\n\n const first = await getConnection();\n const describe = (): InitializeResultIface => current?.info ?? lastInfo ?? first.info;\n\n const readFile = async (options: {\n path: string;\n root?: string;\n offset?: number;\n length?: number;\n abortSignal?: AbortSignal;\n }) => {\n const connection = await getConnection();\n const streamId = allocateStreamId(connection);\n const stream = connection.peer.streams.openIncoming(streamId);\n try {\n const result = await requestOn(\n connection,\n HandleRpcMethod.ReadFile,\n {\n path: options.path,\n root: options.root,\n streamId,\n offset: options.offset,\n length: options.length,\n },\n { signal: options.abortSignal },\n );\n if (!result.found) {\n connection.peer.streams.discardIncoming(streamId);\n return null;\n }\n } catch (error) {\n connection.peer.streams.discardIncoming(streamId);\n throw error;\n }\n options.abortSignal?.addEventListener(\n 'abort',\n () => connection.peer.streams.cancelIncoming(streamId, 'aborted'),\n {\n once: true,\n },\n );\n return stream;\n };\n\n const writeFile = async (options: {\n path: string;\n content: ReadableStream<Uint8Array>;\n abortSignal?: AbortSignal;\n }) => {\n const connection = await getConnection();\n const streamId = allocateStreamId(connection);\n const sending = connection.peer.streams.openOutgoing(streamId, options.content);\n sending.catch(() => undefined);\n try {\n await requestOn(\n connection,\n HandleRpcMethod.WriteFile,\n { path: options.path, streamId },\n { signal: options.abortSignal },\n );\n } catch (error) {\n connection.peer.streams.abortOutgoing(streamId, 'request failed');\n throw error;\n }\n };\n\n const writeBinaryFile = async (options: {\n path: string;\n content: Uint8Array;\n abortSignal?: AbortSignal;\n }) => {\n if (options.content.byteLength > MAX_INLINE_WRITE_BYTES) {\n await writeFile({\n path: options.path,\n content: bytesToStream(options.content),\n abortSignal: options.abortSignal,\n });\n return;\n }\n await call(\n HandleRpcMethod.WriteFile,\n { path: options.path, contentBase64: bytesToBase64(options.content) },\n { signal: options.abortSignal },\n );\n };\n\n // process/wait and process/kill for a served process. Aborting `abortSignal`\n // kills an ordinary process; a durable one is detached instead (process/detach):\n // its streams fail here and stop on the server, and it keeps running.\n const processControls = (args: {\n connection: ConnectionIface;\n processId: string;\n durable: boolean;\n streamIds: number[];\n abortSignal?: AbortSignal;\n }): Pick<SandboxProcessIface, 'wait' | 'kill'> => {\n const { connection, processId } = args;\n let waiting: Promise<{ exitCode: number }> | null = null;\n const kill = async (signal?: string) => {\n try {\n await requestOn(connection, HandleRpcMethod.ProcessKill, { processId, signal });\n } catch (error) {\n // Already exited and reaped, or the connection (and so the process) is gone.\n if (\n isHandleRpcError(error) &&\n (error.code === HandleRpcErrorCode.NotFound || error.retryable)\n )\n return;\n throw error;\n }\n };\n const onAbort = () => {\n if (!args.durable) {\n void kill().catch(() => undefined);\n return;\n }\n for (const streamId of args.streamIds)\n connection.peer.streams.cancelIncoming(streamId, 'process handle detached');\n // Best effort: a closed connection already released it on the server.\n void requestOn(connection, HandleRpcMethod.ProcessDetach, { processId }).catch(\n () => undefined,\n );\n };\n args.abortSignal?.addEventListener('abort', onAbort, { once: true });\n if (args.abortSignal?.aborted === true) onAbort();\n return {\n wait: () => {\n waiting ??= requestOn(\n connection,\n HandleRpcMethod.ProcessWait,\n { processId },\n { signal: args.abortSignal },\n );\n return waiting;\n },\n kill,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const connection = await getConnection();\n const processId = randomId();\n const stdoutStreamId = allocateStreamId(connection);\n const stderrStreamId = allocateStreamId(connection);\n const stdinStreamId = allocateStreamId(connection);\n const stdout = connection.peer.streams.openIncoming(stdoutStreamId);\n const stderr = connection.peer.streams.openIncoming(stderrStreamId);\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 stdinSource = bytesToStream(utf8Encode(options.stdin));\n }\n connection.peer.streams.openOutgoing(stdinStreamId, stdinSource).catch(() => undefined);\n // Servers without the capability would ignore it; older ones do not know it.\n const durable =\n options.durable === true &&\n connection.info.capabilities.includes(SandboxCapability.DurableProcesses);\n let result: HandleRpcResult<HandleRpcMethod.Spawn>;\n try {\n result = await requestOn(connection, HandleRpcMethod.Spawn, {\n processId,\n command: options.command,\n args: options.args,\n cwd: options.cwd,\n env: options.env,\n shell: options.shell,\n timeoutMs: options.timeoutMs,\n stdinStreamId,\n stdoutStreamId,\n stderrStreamId,\n ...(durable ? { durable: true } : {}),\n });\n } catch (error) {\n connection.peer.streams.discardIncoming(stdoutStreamId);\n connection.peer.streams.discardIncoming(stderrStreamId);\n connection.peer.streams.abortOutgoing(stdinStreamId, 'spawn failed');\n throw error;\n }\n const ref = result.ref ?? null;\n const controls = processControls({\n connection,\n processId,\n durable: ref != null,\n streamIds: [stdoutStreamId, stderrStreamId],\n abortSignal: options.abortSignal,\n });\n return {\n pid: result.pid,\n ref,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n // A detached handle is done with the process.\n if (ref != null) options.abortSignal?.throwIfAborted();\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 ...controls,\n };\n };\n\n const attachProcess = async (\n options: SandboxAttachProcessOptionsIface,\n ): Promise<SandboxAttachedProcessIface | null> => {\n const connection = await getConnection();\n const processId = randomId();\n const stdoutStreamId = allocateStreamId(connection);\n const stderrStreamId = allocateStreamId(connection);\n const stdout = connection.peer.streams.openIncoming(stdoutStreamId);\n const stderr = connection.peer.streams.openIncoming(stderrStreamId);\n const discard = () => {\n connection.peer.streams.discardIncoming(stdoutStreamId);\n connection.peer.streams.discardIncoming(stderrStreamId);\n };\n let result: HandleRpcResult<HandleRpcMethod.ProcessAttach>;\n try {\n result = await requestOn(\n connection,\n HandleRpcMethod.ProcessAttach,\n {\n processId,\n ref: options.ref,\n stdoutOffset: options.stdoutOffset,\n stderrOffset: options.stderrOffset,\n stdoutStreamId,\n stderrStreamId,\n },\n { signal: options.abortSignal },\n );\n } catch (error) {\n discard();\n // The server may have attached it before the cancellation reached it.\n void requestOn(connection, HandleRpcMethod.ProcessDetach, { processId }).catch(\n () => undefined,\n );\n throw error;\n }\n if (!result.found) {\n discard();\n return null;\n }\n return {\n ref: options.ref,\n stdoutOffset: result.stdoutOffset,\n stderrOffset: result.stderrOffset,\n stdout,\n stderr,\n ...processControls({\n connection,\n processId,\n durable: true,\n streamIds: [stdoutStreamId, stderrStreamId],\n abortSignal: options.abortSignal,\n }),\n };\n };\n\n const client: SandboxClientIface = {\n get id() {\n return describe().id;\n },\n get defaultWorkingDirectory() {\n return describe().defaultWorkingDirectory;\n },\n get ports() {\n return describe().ports;\n },\n get description() {\n return describe().description;\n },\n get capabilities() {\n return describe().capabilities;\n },\n confinedFiles: describe().confinedFiles === true,\n providerHooks: describe().providerHooks === true,\n onRuntimeShutdown: async () => {\n await call(HandleRpcMethod.OnRuntimeShutdown, {});\n },\n onSandboxStop: async () => {\n await call(HandleRpcMethod.OnSandboxStop, {});\n },\n onSandboxDelete: async (options) => {\n await call(HandleRpcMethod.OnSandboxDelete, options ?? {});\n },\n readFile: (options) => readFile(options),\n readFileRange: readFile,\n readBinaryFile: async (options) => {\n const stream = await readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const { abortSignal: _abortSignal, ...params } = options;\n const parsed = handleRpcMethodSchemas[HandleRpcMethod.ReadTextFile].params.safeParse(params);\n if (!parsed.success)\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: parsed.error.message,\n });\n const stream = await readFile({ path: options.path, abortSignal: options.abortSignal });\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile,\n writeBinaryFile,\n writeTextFile: async (options) =>\n writeBinaryFile({\n path: options.path,\n content: encodeSandboxText(options.content, options.encoding),\n abortSignal: options.abortSignal,\n }),\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options): Promise<StatIface | null> =>\n (\n await call(\n HandleRpcMethod.Stat,\n { path: options.path, root: options.root },\n { signal: options.abortSignal },\n )\n ).stat,\n readDir: async (options): Promise<DirEntryIface[]> =>\n (\n await call(\n HandleRpcMethod.ReadDir,\n { path: options.path, root: options.root },\n { signal: options.abortSignal },\n )\n ).entries,\n resolvePath: (path) => resolvePosixPath(describe().defaultWorkingDirectory, path),\n removePath: async (options) => {\n const { abortSignal, ...params } = options;\n await call(HandleRpcMethod.RemovePath, params, { signal: abortSignal });\n },\n getPortEndpoint: (options) => call(HandleRpcMethod.GetPortEndpoint, options),\n getPortUrl: async (options) => (await call(HandleRpcMethod.GetPortEndpoint, options)).url,\n stop: async () => {\n await call(HandleRpcMethod.Stop, {});\n },\n destroy: async () => {\n await call(HandleRpcMethod.Destroy, {});\n },\n close: () => {\n closedByUser = true;\n if (refreshTimer != null) clearTimeout(refreshTimer);\n for (const connection of live)\n connection.peer.close(HandleRpcCloseCode.Normal, 'client closed');\n live.clear();\n current = null;\n },\n };\n\n const mcpEndpoint = (\n connection: ConnectionIface,\n endpoint: HandleRpcResult<HandleRpcMethod.ComputerUse>,\n ): SandboxMcpEndpoint => {\n if ('url' in endpoint) return endpoint;\n return {\n name: endpoint.name,\n connect: async (options?: AbortableIface): Promise<McpChannelIface> => {\n const opened = await requestOn(\n connection,\n HandleRpcMethod.McpOpen,\n { endpointKey: endpoint.endpointKey },\n { signal: options?.abortSignal },\n );\n let closed = false;\n const requireOpen = (): void => {\n if (closed)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'MCP channel closed',\n });\n };\n const channel: McpChannelIface = {\n send: async (message, sendOptions) => {\n requireOpen();\n await requestOn(\n connection,\n HandleRpcMethod.McpSend,\n { channelId: opened.channelId, message },\n { signal: sendOptions?.abortSignal },\n );\n },\n receive: async (receiveOptions) => {\n requireOpen();\n return (\n await requestOn(\n connection,\n HandleRpcMethod.McpReceive,\n { channelId: opened.channelId },\n { signal: receiveOptions?.abortSignal },\n )\n ).messages;\n },\n close: async () => {\n if (closed) return;\n closed = true;\n if (!connection.peer.isClosed())\n await requestOn(connection, HandleRpcMethod.McpClose, {\n channelId: opened.channelId,\n });\n },\n };\n if (options?.abortSignal?.aborted === true) {\n await channel.close().catch(() => undefined);\n options.abortSignal.throwIfAborted();\n }\n return channel;\n },\n };\n };\n\n const capabilities = first.info.capabilities;\n if (capabilities.includes(SandboxCapability.NetworkPolicy)) {\n client.setNetworkPolicy = async (policy: NetworkPolicyIface) => {\n await call(HandleRpcMethod.SetNetworkPolicy, policy);\n };\n }\n if (capabilities.includes(SandboxCapability.Egress)) {\n client.egress = (request) => call(HandleRpcMethod.Egress, request);\n }\n if (capabilities.includes(SandboxCapability.DurableProcesses))\n client.attachProcess = attachProcess;\n if (capabilities.includes(SandboxCapability.ComputerUse)) {\n client.computerUse = async (): Promise<SandboxMcpEndpoint> => {\n const { connection, result } = await callOnConnection(HandleRpcMethod.ComputerUse, {});\n return mcpEndpoint(connection, result);\n };\n }\n if (capabilities.includes(SandboxCapability.Screen)) {\n client.screen = (options): Promise<ScreenSessionIface> =>\n call(HandleRpcMethod.Screen, options ?? {});\n }\n if (capabilities.includes(SandboxCapability.LocalMcp)) {\n client.localMcp = async (): Promise<SandboxMcpEndpoint[]> => {\n const { connection, result } = await callOnConnection(HandleRpcMethod.LocalMcp, {});\n return result.endpoints.map((endpoint) => mcpEndpoint(connection, endpoint));\n };\n }\n return client;\n};\n"],
5
- "mappings": "AAAA,SAAS,eAAe,eAAe,mBAAmB,cAAc,kBAAkB;AAC1F,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,wBAAwB;AACjC,SAAS,qBAAwC;AACjD;AAAA,EACE;AAAA,OAaK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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UAAU,IAAI,CAAC,aAAa,YAAY,YAAY,QAAQ,CAAC;AAAA,IAC7E;AAAA,EACF;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import { bytesToBase64, bytesToStream, encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { resolvePosixPath } from \"./paths.mjs\";\nimport { createRpcPeer, type RpcPeerIface } from \"./rpc-peer.mjs\";\nimport {\n isSandboxWorkerEndpoint,\n SandboxCapability,\n type AbortableIface,\n type DirEntryIface,\n type McpChannelIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxAttachedProcessIface,\n type SandboxAttachProcessOptionsIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxWorkerOptionsIface,\n type SandboxWorkerStartType,\n type ScreenSessionIface,\n type StatIface,\n} from \"./types.mjs\";\nimport {\n frameChannelFromWebSocket,\n HANDLE_RPC_IDEMPOTENT_METHODS,\n HANDLE_RPC_VERSION,\n handleRpcClientProtocols,\n HandleRpcCloseCode,\n handleRpcError,\n HandleRpcErrorCode,\n HandleRpcMethod,\n handleRpcMethodSchemas,\n isHandleRpcError,\n MAX_INLINE_WRITE_BYTES,\n parseHandleRpcResult,\n type FrameChannelIface,\n type HandleRpcParams,\n type HandleRpcResult,\n type InitializeResultIface,\n type WebSocketConstructorIface,\n} from \"./wire.mjs\";\n\n// NetworkSandboxSessionIface implemented purely over the handle RPC: no\n// provider code, only the wire. Works wherever a WebSocket exists (Workers,\n// browsers, Node 22+) or over any frame channel through `openChannel`.\n\nexport interface SandboxClientIface extends NetworkSandboxSessionIface {\n readonly confinedFiles: boolean;\n readonly providerHooks: boolean;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n readonly capabilities: readonly SandboxCapability[];\n // A byte range of a file, streamed; null when the file does not exist.\n readFileRange(options: {\n path: string;\n root?: string;\n offset: number;\n length?: number;\n abortSignal?: AbortSignal;\n }): Promise<ReadableStream<Uint8Array> | null>;\n // Closes every connection and fails in-flight calls.\n close(): void;\n}\n\nexport interface SandboxClientCredentialIface {\n token: string;\n expiresAt: string | null;\n // A new stable endpoint URL, when the issuer moved it.\n url?: string;\n}\n\nexport interface ConnectSandboxClientArgsIface {\n // The session service's stable per-binding address; the first call to reach\n // it attaches the sandbox, and every call is served there.\n url: string;\n token: string;\n expiresAt?: string | null;\n // Defaults to the global WebSocket.\n WebSocket?: WebSocketConstructorIface;\n // Replaces WebSocket dialing entirely (relays, tests).\n openChannel?: (target: { url: string; token: string }) => Promise<FrameChannelIface>;\n // Returns a fresh credential for the stable endpoint (`url`), e.g. from the\n // broker's `sandbox` route.\n refreshToken?: () => Promise<SandboxClientCredentialIface>;\n // Send stream chunks as binary frames (default true).\n binary?: boolean;\n reconnect?: { attempts?: number; baseDelayMs?: number; maxDelayMs?: number };\n // How long before expiry to refresh the credential (default 60 s).\n refreshMarginMs?: number;\n // On a sandbox provider's attach socket: the platform-identity assertion the\n // connection presents, sent in `initialize`. Asked again before every call;\n // when the answer changed, `identity/refresh` goes out first. `renew` asks\n // for a new one before the one in force expires.\n identity?: (args: { renew: boolean }) => Promise<string>;\n clientInfo?: { name: string; version: string };\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n randomId?: () => string;\n}\n\ninterface TargetIface {\n url: string;\n token: string;\n expiresAt: string | null;\n}\n\ninterface ConnectionIface {\n peer: RpcPeerIface;\n target: TargetIface;\n info: InitializeResultIface;\n nextStreamId: number;\n // The assertion in force (`identity`), and the last identity sync, which calls wait on.\n identity: string | null;\n identitySync: Promise<void>;\n identityTimer: ReturnType<typeof setTimeout> | null;\n}\n\nconst defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\nconst defaultOpenChannel =\n (WebSocketImpl: WebSocketConstructorIface | undefined) =>\n async (target: { url: string; token: string }): Promise<FrameChannelIface> => {\n const Impl = WebSocketImpl ?? globalThis.WebSocket;\n if (Impl == null)\n throw new Error('no WebSocket implementation available; pass WebSocket or openChannel');\n const { channel, opened } = frameChannelFromWebSocket(\n new Impl(target.url, handleRpcClientProtocols(target.token)),\n );\n await opened;\n return channel;\n };\n\nconst isRetryable = (cause: unknown): boolean => isHandleRpcError(cause) && cause.retryable;\n\nexport const connectSandboxClient = async (\n args: ConnectSandboxClientArgsIface,\n): Promise<SandboxClientIface> => {\n const now = args.now ?? Date.now;\n const sleep = args.sleep ?? defaultSleep;\n const randomId = args.randomId ?? (() => crypto.randomUUID());\n const openChannel = args.openChannel ?? defaultOpenChannel(args.WebSocket);\n const attempts = args.reconnect?.attempts ?? 5;\n const baseDelayMs = args.reconnect?.baseDelayMs ?? 100;\n const maxDelayMs = args.reconnect?.maxDelayMs ?? 5_000;\n const refreshMarginMs = args.refreshMarginMs ?? 60_000;\n const binary = args.binary ?? true;\n\n let origin: TargetIface = {\n url: args.url,\n token: args.token,\n expiresAt: args.expiresAt ?? null,\n };\n let current: ConnectionIface | null = null;\n let connecting: Promise<ConnectionIface> | null = null;\n let closedByUser = false;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n const live = new Set<ConnectionIface>();\n let lastInfo: InitializeResultIface | null = null;\n\n const refreshOrigin = async (): Promise<boolean> => {\n if (args.refreshToken == null) return false;\n const fresh = await args.refreshToken();\n origin = {\n url: fresh.url ?? origin.url,\n token: fresh.token,\n expiresAt: fresh.expiresAt,\n };\n return true;\n };\n\n const scheduleRefresh = (connection: ConnectionIface) => {\n if (refreshTimer != null) clearTimeout(refreshTimer);\n refreshTimer = null;\n const expiresAt = connection.info.expiresAt ?? connection.target.expiresAt;\n if (expiresAt == null || args.refreshToken == null || closedByUser) return;\n const remaining = Date.parse(expiresAt) - now();\n if (Number.isNaN(remaining)) return;\n const delay = Math.max(0, Math.min(remaining - refreshMarginMs, remaining / 2));\n refreshTimer = setTimeout(\n () => {\n void refreshConnection(connection).catch(() => undefined);\n },\n Math.min(2_147_483_647, delay),\n );\n };\n\n // The connection takes the new token in place; in-flight calls continue.\n // A moved endpoint (a new `url`) is dialed fresh instead, and in-flight\n // calls finish on the old connection.\n const refreshConnection = async (connection: ConnectionIface) => {\n if (closedByUser || connection.peer.isClosed()) return;\n await refreshOrigin();\n if (origin.url === connection.target.url) {\n const result = await requestOn(connection, HandleRpcMethod.AuthRefresh, {\n token: origin.token,\n });\n connection.target = {\n ...connection.target,\n token: origin.token,\n expiresAt: result.expiresAt,\n };\n connection.info = { ...connection.info, expiresAt: result.expiresAt };\n scheduleRefresh(connection);\n return;\n }\n if (current === connection) current = null;\n await getConnection();\n };\n\n // Sends `identity/refresh` when the assertion the caller hands out changed\n // (or, with `renew`, for a new one), one sync at a time per connection.\n // Calls on a process or MCP channel already open reuse the identity in force.\n const syncIdentity = (connection: ConnectionIface, renew: boolean): Promise<void> => {\n const identity = args.identity;\n if (identity == null) return Promise.resolve();\n const run = connection.identitySync.then(async () => {\n const assertion = await identity({ renew });\n if (assertion === connection.identity || connection.peer.isClosed()) return;\n const raw = await connection.peer.request(HandleRpcMethod.IdentityRefresh, { assertion });\n connection.identity = assertion;\n scheduleIdentityRenewal(\n connection,\n parseHandleRpcResult(HandleRpcMethod.IdentityRefresh, raw).expiresAt,\n );\n });\n connection.identitySync = run.catch(() => undefined);\n return run;\n };\n\n const scheduleIdentityRenewal = (connection: ConnectionIface, expiresAt: string | null) => {\n if (connection.identityTimer != null) clearTimeout(connection.identityTimer);\n connection.identityTimer = null;\n if (expiresAt == null || args.identity == null || closedByUser) return;\n const remaining = Date.parse(expiresAt) - now();\n if (Number.isNaN(remaining)) return;\n const delay = Math.max(0, Math.min(remaining - refreshMarginMs, remaining / 2));\n connection.identityTimer = setTimeout(\n () => {\n void syncIdentity(connection, true).catch(() => undefined);\n },\n Math.min(2_147_483_647, delay),\n );\n };\n\n const initialize = async (target: TargetIface): Promise<ConnectionIface> => {\n const channel = await openChannel({ url: target.url, token: target.token });\n let connection: ConnectionIface | null = null;\n const peer = createRpcPeer({\n channel,\n binary,\n onClose: () => {\n if (connection == null) return;\n if (connection.identityTimer != null) clearTimeout(connection.identityTimer);\n live.delete(connection);\n if (current === connection) current = null;\n },\n });\n try {\n const identity = args.identity == null ? null : await args.identity({ renew: false });\n const raw = await peer.request(HandleRpcMethod.Initialize, {\n handleRpcVersion: HANDLE_RPC_VERSION,\n token: target.token,\n ...(identity == null ? {} : { identity }),\n client: args.clientInfo,\n });\n const info = handleRpcMethodSchemas[HandleRpcMethod.Initialize].result.parse(raw);\n connection = {\n peer,\n target,\n info,\n nextStreamId: 1,\n identity,\n identitySync: Promise.resolve(),\n identityTimer: null,\n };\n live.add(connection);\n if (identity != null) scheduleIdentityRenewal(connection, info.expiresAt);\n return connection;\n } catch (error) {\n peer.close(HandleRpcCloseCode.Normal, 'initialize failed');\n throw error;\n }\n };\n\n const establish = async (): Promise<ConnectionIface> => {\n let failures = 0;\n let refreshed = false;\n for (;;) {\n if (closedByUser)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'client closed',\n });\n try {\n const connection = await initialize(origin);\n current = connection;\n lastInfo = connection.info;\n scheduleRefresh(connection);\n return connection;\n } catch (error) {\n if (closedByUser) throw error;\n const unauthorized =\n isHandleRpcError(error) && error.code === HandleRpcErrorCode.Unauthorized;\n if (unauthorized && !refreshed && (await refreshOrigin().catch(() => false))) {\n refreshed = true;\n continue;\n }\n if (unauthorized) throw error;\n failures += 1;\n if (failures >= attempts) {\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: `could not connect to the sandbox: ${error instanceof Error ? error.message : String(error)}`,\n retryable: true,\n });\n }\n await sleep(Math.min(maxDelayMs, baseDelayMs * 2 ** (failures - 1)));\n }\n }\n };\n\n const liveConnection = (): Promise<ConnectionIface> => {\n if (current != null && !current.peer.isClosed()) return Promise.resolve(current);\n connecting ??= establish().finally(() => {\n connecting = null;\n });\n return connecting;\n };\n\n // The connection for the next call, its identity brought up to date first\n // (before the call opens any stream, so stream chunks never precede it).\n const getConnection = async (): Promise<ConnectionIface> => {\n const connection = await liveConnection();\n await syncIdentity(connection, false);\n return connection;\n };\n\n const requestOn = async <M extends HandleRpcMethod>(\n connection: ConnectionIface,\n method: M,\n params: HandleRpcParams<M>,\n options?: { signal?: AbortSignal },\n ): Promise<HandleRpcResult<M>> => {\n const raw = await connection.peer.request(method, params, { signal: options?.signal });\n return parseHandleRpcResult(method, raw);\n };\n\n const callOnConnection = async <M extends HandleRpcMethod>(\n method: M,\n params: HandleRpcParams<M>,\n options?: { signal?: AbortSignal },\n ): Promise<{ connection: ConnectionIface; result: HandleRpcResult<M> }> => {\n const idempotent = HANDLE_RPC_IDEMPOTENT_METHODS.includes(method);\n for (let attempt = 0; ; attempt += 1) {\n const connection = await getConnection();\n try {\n return { connection, result: await requestOn(connection, method, params, options) };\n } catch (error) {\n if (attempt === 0 && idempotent && isRetryable(error)) continue;\n throw error;\n }\n }\n };\n\n const call = async <M extends HandleRpcMethod>(\n method: M,\n params: HandleRpcParams<M>,\n options?: { signal?: AbortSignal },\n ): Promise<HandleRpcResult<M>> => (await callOnConnection(method, params, options)).result;\n\n const allocateStreamId = (connection: ConnectionIface): number => {\n const id = connection.nextStreamId;\n connection.nextStreamId += 1;\n return id;\n };\n\n const first = await getConnection();\n const describe = (): InitializeResultIface => current?.info ?? lastInfo ?? first.info;\n\n const readFile = async (options: {\n path: string;\n root?: string;\n offset?: number;\n length?: number;\n abortSignal?: AbortSignal;\n }) => {\n const connection = await getConnection();\n const streamId = allocateStreamId(connection);\n const stream = connection.peer.streams.openIncoming(streamId);\n try {\n const result = await requestOn(\n connection,\n HandleRpcMethod.ReadFile,\n {\n path: options.path,\n root: options.root,\n streamId,\n offset: options.offset,\n length: options.length,\n },\n { signal: options.abortSignal },\n );\n if (!result.found) {\n connection.peer.streams.discardIncoming(streamId);\n return null;\n }\n } catch (error) {\n connection.peer.streams.discardIncoming(streamId);\n throw error;\n }\n options.abortSignal?.addEventListener(\n 'abort',\n () => connection.peer.streams.cancelIncoming(streamId, 'aborted'),\n {\n once: true,\n },\n );\n return stream;\n };\n\n const writeFile = async (options: {\n path: string;\n content: ReadableStream<Uint8Array>;\n abortSignal?: AbortSignal;\n }) => {\n const connection = await getConnection();\n const streamId = allocateStreamId(connection);\n const sending = connection.peer.streams.openOutgoing(streamId, options.content);\n sending.catch(() => undefined);\n try {\n await requestOn(\n connection,\n HandleRpcMethod.WriteFile,\n { path: options.path, streamId },\n { signal: options.abortSignal },\n );\n } catch (error) {\n connection.peer.streams.abortOutgoing(streamId, 'request failed');\n throw error;\n }\n };\n\n const writeBinaryFile = async (options: {\n path: string;\n content: Uint8Array;\n abortSignal?: AbortSignal;\n }) => {\n if (options.content.byteLength > MAX_INLINE_WRITE_BYTES) {\n await writeFile({\n path: options.path,\n content: bytesToStream(options.content),\n abortSignal: options.abortSignal,\n });\n return;\n }\n await call(\n HandleRpcMethod.WriteFile,\n { path: options.path, contentBase64: bytesToBase64(options.content) },\n { signal: options.abortSignal },\n );\n };\n\n // process/wait and process/kill for a served process. Aborting `abortSignal`\n // kills an ordinary process; a durable one is detached instead (process/detach):\n // its streams fail here and stop on the server, and it keeps running.\n const processControls = (args: {\n connection: ConnectionIface;\n processId: string;\n durable: boolean;\n streamIds: number[];\n abortSignal?: AbortSignal;\n }): Pick<SandboxProcessIface, 'wait' | 'kill'> => {\n const { connection, processId } = args;\n let waiting: Promise<{ exitCode: number }> | null = null;\n const kill = async (signal?: string) => {\n try {\n await requestOn(connection, HandleRpcMethod.ProcessKill, { processId, signal });\n } catch (error) {\n // Already exited and reaped, or the connection (and so the process) is gone.\n if (\n isHandleRpcError(error) &&\n (error.code === HandleRpcErrorCode.NotFound || error.retryable)\n )\n return;\n throw error;\n }\n };\n const onAbort = () => {\n if (!args.durable) {\n void kill().catch(() => undefined);\n return;\n }\n for (const streamId of args.streamIds)\n connection.peer.streams.cancelIncoming(streamId, 'process handle detached');\n // Best effort: a closed connection already released it on the server.\n void requestOn(connection, HandleRpcMethod.ProcessDetach, { processId }).catch(\n () => undefined,\n );\n };\n args.abortSignal?.addEventListener('abort', onAbort, { once: true });\n if (args.abortSignal?.aborted === true) onAbort();\n return {\n wait: () => {\n waiting ??= requestOn(\n connection,\n HandleRpcMethod.ProcessWait,\n { processId },\n { signal: args.abortSignal },\n );\n return waiting;\n },\n kill,\n };\n };\n\n // A served process: `sandbox/spawn` or `sandbox/startWorker`, with the\n // streams and controls they share.\n const startProcess = async (args: {\n stdin: ReadableStream<Uint8Array> | string | undefined;\n durable: boolean | undefined;\n abortSignal: AbortSignal | undefined;\n request: (\n connection: ConnectionIface,\n streams: {\n processId: string;\n stdinStreamId: number;\n stdoutStreamId: number;\n stderrStreamId: number;\n durable?: true;\n },\n ) => Promise<HandleRpcResult<HandleRpcMethod.StartWorker>>;\n }): Promise<SandboxWorkerStartType> => {\n const connection = await getConnection();\n const processId = randomId();\n const stdoutStreamId = allocateStreamId(connection);\n const stderrStreamId = allocateStreamId(connection);\n const stdinStreamId = allocateStreamId(connection);\n const stdout = connection.peer.streams.openIncoming(stdoutStreamId);\n const stderr = connection.peer.streams.openIncoming(stderrStreamId);\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (args.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (args.stdin instanceof ReadableStream) {\n stdinSource = args.stdin;\n } else {\n stdinSource = bytesToStream(utf8Encode(args.stdin));\n }\n connection.peer.streams.openOutgoing(stdinStreamId, stdinSource).catch(() => undefined);\n // Servers without the capability would ignore it; older ones do not know it.\n const durable =\n args.durable === true &&\n connection.info.capabilities.includes(SandboxCapability.DurableProcesses);\n let result: HandleRpcResult<HandleRpcMethod.StartWorker>;\n try {\n result = await args.request(connection, {\n processId,\n stdinStreamId,\n stdoutStreamId,\n stderrStreamId,\n ...(durable ? { durable: true } : {}),\n });\n } catch (error) {\n connection.peer.streams.discardIncoming(stdoutStreamId);\n connection.peer.streams.discardIncoming(stderrStreamId);\n connection.peer.streams.abortOutgoing(stdinStreamId, 'start failed');\n throw error;\n }\n // A worker program serving its own endpoint: its streams carry nothing.\n if ('endpoint' in result) {\n connection.peer.streams.discardIncoming(stdoutStreamId);\n connection.peer.streams.discardIncoming(stderrStreamId);\n connection.peer.streams.abortOutgoing(stdinStreamId, 'worker endpoint');\n return { endpoint: result.endpoint };\n }\n const ref = result.ref ?? null;\n const controls = processControls({\n connection,\n processId,\n durable: ref != null,\n streamIds: [stdoutStreamId, stderrStreamId],\n abortSignal: args.abortSignal,\n });\n return {\n pid: result.pid,\n ref,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n // A detached handle is done with the process.\n if (ref != null) args.abortSignal?.throwIfAborted();\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 ...controls,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const started = await startProcess({\n stdin: options.stdin,\n durable: options.durable,\n abortSignal: options.abortSignal,\n request: (connection, streams) =>\n requestOn(connection, HandleRpcMethod.Spawn, {\n command: options.command,\n args: options.args,\n cwd: options.cwd,\n env: options.env,\n shell: options.shell,\n timeoutMs: options.timeoutMs,\n ...streams,\n }),\n });\n if (isSandboxWorkerEndpoint(started))\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidRequest,\n message: 'sandbox/spawn answered with an endpoint',\n });\n return started;\n };\n\n const startWorker = (options: SandboxWorkerOptionsIface): Promise<SandboxWorkerStartType> =>\n startProcess({\n stdin: undefined,\n durable: options.durable,\n abortSignal: options.abortSignal,\n request: (connection, streams) =>\n requestOn(connection, HandleRpcMethod.StartWorker, {\n program: options.program,\n env: options.env,\n input: options.input,\n ...(options.identity == null ? {} : { identity: options.identity }),\n ...streams,\n }),\n });\n\n const attachProcess = async (\n options: SandboxAttachProcessOptionsIface,\n ): Promise<SandboxAttachedProcessIface | null> => {\n const connection = await getConnection();\n const processId = randomId();\n const stdoutStreamId = allocateStreamId(connection);\n const stderrStreamId = allocateStreamId(connection);\n const stdout = connection.peer.streams.openIncoming(stdoutStreamId);\n const stderr = connection.peer.streams.openIncoming(stderrStreamId);\n const discard = () => {\n connection.peer.streams.discardIncoming(stdoutStreamId);\n connection.peer.streams.discardIncoming(stderrStreamId);\n };\n let result: HandleRpcResult<HandleRpcMethod.ProcessAttach>;\n try {\n result = await requestOn(\n connection,\n HandleRpcMethod.ProcessAttach,\n {\n processId,\n ref: options.ref,\n stdoutOffset: options.stdoutOffset,\n stderrOffset: options.stderrOffset,\n stdoutStreamId,\n stderrStreamId,\n },\n { signal: options.abortSignal },\n );\n } catch (error) {\n discard();\n // The server may have attached it before the cancellation reached it.\n void requestOn(connection, HandleRpcMethod.ProcessDetach, { processId }).catch(\n () => undefined,\n );\n throw error;\n }\n if (!result.found) {\n discard();\n return null;\n }\n return {\n ref: options.ref,\n stdoutOffset: result.stdoutOffset,\n stderrOffset: result.stderrOffset,\n stdout,\n stderr,\n ...processControls({\n connection,\n processId,\n durable: true,\n streamIds: [stdoutStreamId, stderrStreamId],\n abortSignal: options.abortSignal,\n }),\n };\n };\n\n const client: SandboxClientIface = {\n get id() {\n return describe().id;\n },\n get defaultWorkingDirectory() {\n return describe().defaultWorkingDirectory;\n },\n get ports() {\n return describe().ports;\n },\n get description() {\n return describe().description;\n },\n get capabilities() {\n return describe().capabilities;\n },\n confinedFiles: describe().confinedFiles === true,\n providerHooks: describe().providerHooks === true,\n onRuntimeShutdown: async () => {\n await call(HandleRpcMethod.OnRuntimeShutdown, {});\n },\n onSandboxStop: async () => {\n await call(HandleRpcMethod.OnSandboxStop, {});\n },\n onSandboxDelete: async (options) => {\n await call(HandleRpcMethod.OnSandboxDelete, options ?? {});\n },\n readFile: (options) => readFile(options),\n readFileRange: readFile,\n readBinaryFile: async (options) => {\n const stream = await readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const { abortSignal: _abortSignal, ...params } = options;\n const parsed = handleRpcMethodSchemas[HandleRpcMethod.ReadTextFile].params.safeParse(params);\n if (!parsed.success)\n throw handleRpcError({\n code: HandleRpcErrorCode.InvalidParams,\n message: parsed.error.message,\n });\n const stream = await readFile({ path: options.path, abortSignal: options.abortSignal });\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile,\n writeBinaryFile,\n writeTextFile: async (options) =>\n writeBinaryFile({\n path: options.path,\n content: encodeSandboxText(options.content, options.encoding),\n abortSignal: options.abortSignal,\n }),\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options): Promise<StatIface | null> =>\n (\n await call(\n HandleRpcMethod.Stat,\n { path: options.path, root: options.root },\n { signal: options.abortSignal },\n )\n ).stat,\n readDir: async (options): Promise<DirEntryIface[]> =>\n (\n await call(\n HandleRpcMethod.ReadDir,\n { path: options.path, root: options.root },\n { signal: options.abortSignal },\n )\n ).entries,\n resolvePath: (path) => resolvePosixPath(describe().defaultWorkingDirectory, path),\n removePath: async (options) => {\n const { abortSignal, ...params } = options;\n await call(HandleRpcMethod.RemovePath, params, { signal: abortSignal });\n },\n getPortEndpoint: (options) => call(HandleRpcMethod.GetPortEndpoint, options),\n getPortUrl: async (options) => (await call(HandleRpcMethod.GetPortEndpoint, options)).url,\n stop: async () => {\n await call(HandleRpcMethod.Stop, {});\n },\n destroy: async () => {\n await call(HandleRpcMethod.Destroy, {});\n },\n close: () => {\n closedByUser = true;\n if (refreshTimer != null) clearTimeout(refreshTimer);\n for (const connection of live)\n connection.peer.close(HandleRpcCloseCode.Normal, 'client closed');\n live.clear();\n current = null;\n },\n };\n\n const mcpEndpoint = (\n connection: ConnectionIface,\n endpoint: HandleRpcResult<HandleRpcMethod.ComputerUse>,\n ): SandboxMcpEndpoint => {\n if ('url' in endpoint) return endpoint;\n return {\n name: endpoint.name,\n connect: async (options?: AbortableIface): Promise<McpChannelIface> => {\n const opened = await requestOn(\n connection,\n HandleRpcMethod.McpOpen,\n { endpointKey: endpoint.endpointKey },\n { signal: options?.abortSignal },\n );\n let closed = false;\n const requireOpen = (): void => {\n if (closed)\n throw handleRpcError({\n code: HandleRpcErrorCode.ConnectionClosed,\n message: 'MCP channel closed',\n });\n };\n const channel: McpChannelIface = {\n send: async (message, sendOptions) => {\n requireOpen();\n await requestOn(\n connection,\n HandleRpcMethod.McpSend,\n { channelId: opened.channelId, message },\n { signal: sendOptions?.abortSignal },\n );\n },\n receive: async (receiveOptions) => {\n requireOpen();\n return (\n await requestOn(\n connection,\n HandleRpcMethod.McpReceive,\n { channelId: opened.channelId },\n { signal: receiveOptions?.abortSignal },\n )\n ).messages;\n },\n close: async () => {\n if (closed) return;\n closed = true;\n if (!connection.peer.isClosed())\n await requestOn(connection, HandleRpcMethod.McpClose, {\n channelId: opened.channelId,\n });\n },\n };\n if (options?.abortSignal?.aborted === true) {\n await channel.close().catch(() => undefined);\n options.abortSignal.throwIfAborted();\n }\n return channel;\n },\n };\n };\n\n const capabilities = first.info.capabilities;\n if (capabilities.includes(SandboxCapability.NetworkPolicy)) {\n client.setNetworkPolicy = async (policy: NetworkPolicyIface) => {\n await call(HandleRpcMethod.SetNetworkPolicy, policy);\n };\n }\n if (capabilities.includes(SandboxCapability.Egress)) {\n client.egress = (request) => call(HandleRpcMethod.Egress, request);\n }\n if (capabilities.includes(SandboxCapability.DurableProcesses))\n client.attachProcess = attachProcess;\n if (capabilities.includes(SandboxCapability.Workers)) client.startWorker = startWorker;\n if (capabilities.includes(SandboxCapability.ComputerUse)) {\n client.computerUse = async (): Promise<SandboxMcpEndpoint> => {\n const { connection, result } = await callOnConnection(HandleRpcMethod.ComputerUse, {});\n return mcpEndpoint(connection, result);\n };\n }\n if (capabilities.includes(SandboxCapability.Screen)) {\n client.screen = (options): Promise<ScreenSessionIface> =>\n call(HandleRpcMethod.Screen, options ?? {});\n }\n if (capabilities.includes(SandboxCapability.LocalMcp)) {\n client.localMcp = async (): Promise<SandboxMcpEndpoint[]> => {\n const { connection, result } = await callOnConnection(HandleRpcMethod.LocalMcp, {});\n return result.endpoints.map((endpoint) => mcpEndpoint(connection, endpoint));\n };\n }\n return client;\n};\n"],
5
+ "mappings": "AAAA,SAAS,eAAe,eAAe,mBAAmB,cAAc,kBAAkB;AAC1F,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,wBAAwB;AACjC,SAAS,qBAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OAeK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AA8EP,MAAM,eAAe,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAE3F,MAAM,qBACJ,CAAC,kBACD,OAAO,WAAuE;AAC5E,QAAM,OAAO,iBAAiB,WAAW;AACzC,MAAI,QAAQ;AACV,UAAM,IAAI,MAAM,sEAAsE;AACxF,QAAM,EAAE,SAAS,OAAO,IAAI;AAAA,IAC1B,IAAI,KAAK,OAAO,KAAK,yBAAyB,OAAO,KAAK,CAAC;AAAA,EAC7D;AACA,QAAM;AACN,SAAO;AACT;AAEF,MAAM,cAAc,CAAC,UAA4B,iBAAiB,KAAK,KAAK,MAAM;AAE3E,MAAM,uBAAuB,OAClC,SACgC;AAChC,QAAM,MAAM,KAAK,OAAO,KAAK;AAC7B,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,WAAW,KAAK,aAAa,MAAM,OAAO,WAAW;AAC3D,QAAM,cAAc,KAAK,eAAe,mBAAmB,KAAK,SAAS;AACzE,QAAM,WAAW,KAAK,WAAW,YAAY;AAC7C,QAAM,cAAc,KAAK,WAAW,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