@syntropika/tembra-sdk 0.2.1 → 0.3.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 (241) hide show
  1. package/README.md +43 -17
  2. package/dist/authoring/types.d.ts +64 -3
  3. package/dist/authoring/wit.d.ts +6 -0
  4. package/dist/bridge/commands.d.ts +1190 -0
  5. package/dist/bridge/identifiers.d.ts +2 -0
  6. package/dist/bridge/kernel.d.ts +18 -107
  7. package/dist/bridge/protocol.d.ts +3 -138
  8. package/dist/browser.d.ts +14 -1
  9. package/dist/browser.js +141 -3298
  10. package/dist/chunks/browser-b8jamxw2.js +3399 -0
  11. package/dist/chunks/execution-nsqc6nrt.js +1419 -0
  12. package/dist/chunks/index-01zk0xqx.js +160 -0
  13. package/dist/chunks/index-3fjdfdfd.js +152 -0
  14. package/dist/chunks/index-aaymjn7v.js +787 -0
  15. package/dist/chunks/index-c1w7z9hx.js +356 -0
  16. package/dist/chunks/index-h8t0n42q.js +738 -0
  17. package/dist/chunks/index-hfds9mzp.js +308 -0
  18. package/dist/chunks/index-kr4x67wt.js +177 -0
  19. package/dist/chunks/index-kr6bnh34.js +117 -0
  20. package/dist/chunks/index-kyt9dj0a.js +1421 -0
  21. package/dist/chunks/index-n1wxzc9w.js +830 -0
  22. package/dist/chunks/index-pvac426d.js +74 -0
  23. package/dist/chunks/index-smyds5ce.js +3234 -0
  24. package/dist/chunks/index-sse8aapb.js +121 -0
  25. package/dist/chunks/index-v6heph77.js +643 -0
  26. package/dist/chunks/index-xrdvnv37.js +3448 -0
  27. package/dist/chunks/index-za4mg94e.js +26 -0
  28. package/dist/chunks/index-zkqmnjj8.js +167 -0
  29. package/dist/coordinator.js +9 -500
  30. package/dist/error.d.ts +2 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/guest.d.ts +173 -0
  33. package/dist/guest.js +26 -0
  34. package/dist/host.d.ts +36 -30
  35. package/dist/host.js +37 -3276
  36. package/dist/http/bytes.d.ts +8 -0
  37. package/dist/http/events.d.ts +7 -0
  38. package/dist/http.d.ts +45 -0
  39. package/dist/http.js +291 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +49 -862
  42. package/dist/infrastructure/rpc/client.d.ts +2 -1
  43. package/dist/infrastructure/rpc/resources.d.ts +28 -0
  44. package/dist/interpreter/abi.d.ts +54 -0
  45. package/dist/interpreter/acquire.d.ts +18 -0
  46. package/dist/interpreter/browser-network.d.ts +52 -0
  47. package/dist/interpreter/browser-port.d.ts +55 -0
  48. package/dist/interpreter/browser.d.ts +79 -0
  49. package/dist/interpreter/cli.d.ts +5 -0
  50. package/dist/interpreter/codec.d.ts +42 -0
  51. package/dist/interpreter/component/execution.d.ts +42 -0
  52. package/dist/interpreter/component/host.d.ts +69 -0
  53. package/dist/interpreter/component/instance.d.ts +40 -0
  54. package/dist/interpreter/component/kernel.d.ts +120 -0
  55. package/dist/interpreter/component/names.d.ts +5 -0
  56. package/dist/interpreter/component/port.d.ts +85 -0
  57. package/dist/interpreter/component/prepared.d.ts +97 -0
  58. package/dist/interpreter/component/resources.d.ts +45 -0
  59. package/dist/interpreter/component/revision.d.ts +87 -0
  60. package/dist/interpreter/component/scope.d.ts +116 -0
  61. package/dist/interpreter/component/streams.d.ts +28 -0
  62. package/dist/interpreter/component/values.d.ts +79 -0
  63. package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
  64. package/dist/interpreter/component/wasi-host.d.ts +64 -0
  65. package/dist/interpreter/component/wasi-http.d.ts +33 -0
  66. package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
  67. package/dist/interpreter/component/wasi.d.ts +41 -0
  68. package/dist/interpreter/core.d.ts +64 -0
  69. package/dist/interpreter/fetch-http-provider.d.ts +17 -0
  70. package/dist/interpreter/filesystem/contract.d.ts +85 -0
  71. package/dist/interpreter/filesystem/memory.d.ts +3 -0
  72. package/dist/interpreter/filesystem/opfs.d.ts +3 -0
  73. package/dist/interpreter/filesystem/scope.d.ts +35 -0
  74. package/dist/interpreter/filesystem.d.ts +8 -0
  75. package/dist/interpreter/gate.d.ts +6 -0
  76. package/dist/interpreter/host-protocol.d.ts +100 -0
  77. package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
  78. package/dist/interpreter/http-ingress.d.ts +96 -0
  79. package/dist/interpreter/http-provider.d.ts +85 -0
  80. package/dist/interpreter/io.d.ts +20 -0
  81. package/dist/interpreter/mobile.d.ts +149 -0
  82. package/dist/interpreter/native-ingress.d.ts +95 -0
  83. package/dist/interpreter/node-port.d.ts +25 -0
  84. package/dist/interpreter/node.d.ts +36 -0
  85. package/dist/interpreter/revision.d.ts +64 -0
  86. package/dist/interpreter/scope.d.ts +89 -0
  87. package/dist/interpreter/socket-addresses.d.ts +50 -0
  88. package/dist/interpreter/socket-provider.d.ts +110 -0
  89. package/dist/interpreter/standard-cli.d.ts +34 -0
  90. package/dist/interpreter/standard-codec.d.ts +96 -0
  91. package/dist/interpreter/standard-filesystem.d.ts +47 -0
  92. package/dist/interpreter/standard-host.d.ts +71 -0
  93. package/dist/interpreter/standard-http-values.d.ts +159 -0
  94. package/dist/interpreter/standard-http.d.ts +9 -0
  95. package/dist/interpreter/standard-ingress.d.ts +63 -0
  96. package/dist/interpreter/standard-sockets.d.ts +177 -0
  97. package/dist/interpreter/standard-streams.d.ts +218 -0
  98. package/dist/interpreter/standard-system.d.ts +35 -0
  99. package/dist/interpreter/standard-utf8.d.ts +4 -0
  100. package/dist/interpreter/standard.d.ts +18 -0
  101. package/dist/interpreter/types.d.ts +152 -0
  102. package/dist/interpreter/wit-shape.d.ts +92 -0
  103. package/dist/manager.js +5 -332
  104. package/dist/msgpack.js +9 -615
  105. package/dist/node.d.ts +8 -1
  106. package/dist/node.js +248 -3287
  107. package/dist/rpc.js +196 -699
  108. package/dist/runtime/adapters.d.ts +120 -0
  109. package/dist/runtime/adapters.js +38 -0
  110. package/dist/runtime/calls.d.ts +9 -3
  111. package/dist/runtime/lifecycle.d.ts +3 -1
  112. package/dist/runtime/orbs.d.ts +5 -4
  113. package/dist/runtime/references.d.ts +27 -1
  114. package/dist/runtime/reload.d.ts +5 -3
  115. package/dist/runtime/scopes.d.ts +1 -1
  116. package/dist/runtime/signals.d.ts +4 -0
  117. package/dist/runtime/wit-client.d.ts +38 -0
  118. package/dist/telemetry.js +4 -25
  119. package/dist/tooling/build.d.ts +2 -2
  120. package/dist/tooling/client-resources.d.ts +23 -0
  121. package/dist/tooling/client.d.ts +10 -0
  122. package/dist/tooling/component-glue.d.ts +17 -0
  123. package/dist/tooling/component.d.ts +11 -0
  124. package/dist/tooling/index.d.ts +3 -1
  125. package/dist/tooling/index.js +1155 -102
  126. package/dist/tooling/resolver.d.ts +4 -4
  127. package/dist/tooling/typecheck.d.ts +2 -1
  128. package/dist/tooling/types.d.ts +27 -12
  129. package/dist/tooling/wit.d.ts +9 -0
  130. package/dist/wasi/wasi-clocks-types.d.ts +2 -0
  131. package/dist/wasi/wasi-http-client.d.ts +5 -0
  132. package/dist/wasi/wasi-http-types.d.ts +285 -0
  133. package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
  134. package/dist/wasi/wasi-sockets-types.d.ts +146 -0
  135. package/package.json +62 -35
  136. package/src/authoring/declaration.ts +1 -1
  137. package/src/authoring/types.ts +53 -3
  138. package/src/authoring/wit.ts +15 -0
  139. package/src/bridge/commands.ts +1105 -0
  140. package/src/bridge/identifiers.ts +2 -0
  141. package/src/bridge/kernel.ts +56 -98
  142. package/src/bridge/protocol.ts +3 -142
  143. package/src/browser.ts +90 -6
  144. package/src/context-key.ts +4 -7
  145. package/src/error.ts +1 -1
  146. package/src/errors.ts +7 -0
  147. package/src/guest.ts +327 -0
  148. package/src/host.ts +128 -23
  149. package/src/http/bytes.ts +87 -0
  150. package/src/http/events.ts +34 -0
  151. package/src/http.ts +272 -0
  152. package/src/index.ts +3 -0
  153. package/src/infrastructure/rpc/client.ts +136 -17
  154. package/src/infrastructure/rpc/resources.ts +123 -0
  155. package/src/interpreter/abi.ts +69 -0
  156. package/src/interpreter/acquire.ts +58 -0
  157. package/src/interpreter/browser-network.ts +170 -0
  158. package/src/interpreter/browser-port.ts +425 -0
  159. package/src/interpreter/browser.ts +340 -0
  160. package/src/interpreter/cli.ts +30 -0
  161. package/src/interpreter/codec.ts +298 -0
  162. package/src/interpreter/component/execution.ts +264 -0
  163. package/src/interpreter/component/host.ts +409 -0
  164. package/src/interpreter/component/instance.ts +138 -0
  165. package/src/interpreter/component/kernel.ts +611 -0
  166. package/src/interpreter/component/names.ts +13 -0
  167. package/src/interpreter/component/port.ts +598 -0
  168. package/src/interpreter/component/prepared.ts +194 -0
  169. package/src/interpreter/component/resources.ts +345 -0
  170. package/src/interpreter/component/revision.ts +702 -0
  171. package/src/interpreter/component/scope.ts +447 -0
  172. package/src/interpreter/component/streams.ts +180 -0
  173. package/src/interpreter/component/values.ts +254 -0
  174. package/src/interpreter/component/wasi-filesystem.ts +472 -0
  175. package/src/interpreter/component/wasi-host.ts +197 -0
  176. package/src/interpreter/component/wasi-http.ts +939 -0
  177. package/src/interpreter/component/wasi-sockets.ts +958 -0
  178. package/src/interpreter/component/wasi.ts +238 -0
  179. package/src/interpreter/core.ts +386 -0
  180. package/src/interpreter/fetch-http-provider.ts +98 -0
  181. package/src/interpreter/filesystem/contract.ts +138 -0
  182. package/src/interpreter/filesystem/memory.ts +180 -0
  183. package/src/interpreter/filesystem/opfs.ts +294 -0
  184. package/src/interpreter/filesystem/scope.ts +390 -0
  185. package/src/interpreter/filesystem.ts +20 -0
  186. package/src/interpreter/gate.ts +55 -0
  187. package/src/interpreter/host-protocol.ts +242 -0
  188. package/src/interpreter/http-ingress-fetch.ts +133 -0
  189. package/src/interpreter/http-ingress.ts +203 -0
  190. package/src/interpreter/http-provider.ts +105 -0
  191. package/src/interpreter/io.ts +66 -0
  192. package/src/interpreter/mobile.ts +385 -0
  193. package/src/interpreter/native-ingress.ts +550 -0
  194. package/src/interpreter/node-port.ts +218 -0
  195. package/src/interpreter/node.ts +114 -0
  196. package/src/interpreter/revision.ts +450 -0
  197. package/src/interpreter/scope.ts +453 -0
  198. package/src/interpreter/socket-addresses.ts +246 -0
  199. package/src/interpreter/socket-provider.ts +126 -0
  200. package/src/interpreter/standard-cli.ts +184 -0
  201. package/src/interpreter/standard-codec.ts +403 -0
  202. package/src/interpreter/standard-filesystem.ts +545 -0
  203. package/src/interpreter/standard-host.ts +840 -0
  204. package/src/interpreter/standard-http-values.ts +624 -0
  205. package/src/interpreter/standard-http.ts +622 -0
  206. package/src/interpreter/standard-ingress.ts +344 -0
  207. package/src/interpreter/standard-sockets.ts +847 -0
  208. package/src/interpreter/standard-streams.ts +710 -0
  209. package/src/interpreter/standard-system.ts +182 -0
  210. package/src/interpreter/standard-utf8.ts +72 -0
  211. package/src/interpreter/standard.ts +283 -0
  212. package/src/interpreter/types.ts +163 -0
  213. package/src/interpreter/wit-shape.ts +175 -0
  214. package/src/node.ts +43 -14
  215. package/src/runtime/activities.ts +6 -6
  216. package/src/runtime/adapters.ts +314 -0
  217. package/src/runtime/calls.ts +218 -56
  218. package/src/runtime/context.ts +7 -7
  219. package/src/runtime/lifecycle.ts +36 -17
  220. package/src/runtime/orbs.ts +81 -39
  221. package/src/runtime/programs.ts +16 -8
  222. package/src/runtime/references.ts +128 -11
  223. package/src/runtime/reload.ts +71 -30
  224. package/src/runtime/resources.ts +2 -2
  225. package/src/runtime/scopes.ts +17 -17
  226. package/src/runtime/session.ts +3 -1
  227. package/src/runtime/signals.ts +31 -0
  228. package/src/runtime/wit-client.ts +228 -0
  229. package/src/tooling/build.ts +152 -54
  230. package/src/tooling/client-resources.ts +74 -0
  231. package/src/tooling/client.ts +531 -0
  232. package/src/tooling/component-glue.ts +288 -0
  233. package/src/tooling/component.ts +225 -0
  234. package/src/tooling/index.ts +3 -7
  235. package/src/tooling/resolver.ts +42 -25
  236. package/src/tooling/typecheck.ts +59 -4
  237. package/src/tooling/types.ts +27 -12
  238. package/src/tooling/wit.ts +188 -0
  239. package/dist/embedded.d.ts +0 -1
  240. package/dist/embedded.js +0 -1
  241. package/src/embedded.ts +0 -293
@@ -0,0 +1,450 @@
1
+ import type { Description, ReferenceBinding } from "./types.ts";
2
+ import type { Declaration } from "../authoring/declaration.ts";
3
+ import type {
4
+ OrbDefinition,
5
+ ServiceDefinition,
6
+ HookDefinition,
7
+ Contribution,
8
+ } from "../authoring/types.ts";
9
+ import { series, waterfall, bail } from "../authoring/hooks.ts";
10
+ import { KernelOp } from "../bridge/protocol.ts";
11
+ import {
12
+ declareFactory,
13
+ bindCaptured,
14
+ signature,
15
+ signatures,
16
+ validateEnvironment,
17
+ admitFactory,
18
+ disposeOrb,
19
+ isolatedRevision,
20
+ releaseEnvironment,
21
+ type AdaptedOrb,
22
+ type AdaptedService,
23
+ } from "#tembra-adapters";
24
+ import { Context } from "../runtime/context.ts";
25
+ import type { Environment } from "../runtime/records.ts";
26
+
27
+ import { check, encode, packet, checkedResult, VALUE_LIMIT, type Encoded } from "./codec.ts";
28
+ import { HTTP_HANDLER, IngressExchange } from "./http-ingress.ts";
29
+ import { Gate } from "./gate.ts";
30
+ import { Scope } from "./scope.ts";
31
+ import {
32
+ query,
33
+ type ContractPort,
34
+ type ExportedInterface,
35
+ type HookBinding,
36
+ type CheckedImplementation,
37
+ type InstallationPlan,
38
+ type InterpreterPort,
39
+ type ExecutionScope,
40
+ } from "./types.ts";
41
+ import { lift, shapes, type Signature, type WitFunction, type WitTypes } from "./wit-shape.ts";
42
+
43
+ /** The contract's `describe` answer, as far as this adapter reads it. */
44
+ type Described = WitTypes & {
45
+ references: Readonly<Record<string, ReferenceBinding>>;
46
+ imports: { binding: string; functions?: Record<string, WitFunction> }[];
47
+ exports: { binding: string; contract?: string; functions?: Record<string, WitFunction> }[];
48
+ };
49
+
50
+ /**
51
+ * Build the interpreter Load's exported-function table from the prepared contract, exactly as the
52
+ * native host does (`adapter::exported_functions`): every function of an exported interface with
53
+ * an identity, under the export slot `bind` returns for it. The incoming HTTP handler is served
54
+ * only through `ingress`, so it has no id.
55
+ */
56
+ export function exportedFunctions(
57
+ description: {
58
+ readonly javascriptNames: Readonly<Record<string, string>>;
59
+ readonly exports: readonly {
60
+ readonly contract?: string | null;
61
+ readonly functions?: Readonly<Record<string, unknown>>;
62
+ }[];
63
+ },
64
+ contract: Pick<ContractPort, "bind">,
65
+ ): ExportedInterface[] {
66
+ const names = description.javascriptNames;
67
+ const spelling = (name: string) => {
68
+ const spelled = names[name];
69
+ if (spelled === undefined) throw new Error(`Missing WIT JavaScript name for ${name}`);
70
+ return spelled;
71
+ };
72
+ return description.exports.flatMap((item) => {
73
+ const identity = item.contract;
74
+ const functions = Object.keys(item.functions ?? {});
75
+ if (!identity || !functions.length || identity === HTTP_HANDLER) return [];
76
+ return [
77
+ {
78
+ interface: identity,
79
+ service: spelling(identity.split("/").at(-1)!.split("@")[0]!),
80
+ functions: functions.map(
81
+ (name) => [contract.bind(identity, name, true), spelling(name)] as const,
82
+ ),
83
+ },
84
+ ];
85
+ });
86
+ }
87
+
88
+ /**
89
+ * One definition per hook a checked implementation declares, composed as it declares: shared by
90
+ * source revisions and prepared components, so a hook composes alike whatever declared it.
91
+ */
92
+ export function declaredHooks(bindings: readonly HookBinding[]): Record<string, HookDefinition> {
93
+ const hooks: Record<string, HookDefinition> = {};
94
+ for (const binding of bindings) {
95
+ const hook =
96
+ binding.composition === "series"
97
+ ? series()
98
+ : binding.composition === "bail"
99
+ ? bail()
100
+ : waterfall();
101
+ hooks[binding.name] = Object.assign(hook, { [signature]: binding.signature });
102
+ }
103
+ return hooks;
104
+ }
105
+
106
+ /** One isolated revision translates callbacks into ordinary SDK declarations and calls. */
107
+ export class Revision {
108
+ readonly gate = new Gate();
109
+ readonly imports = new Map<string, string>();
110
+ /** Checked reference views use the Orb table, shared by the compiled Store. */
111
+ readonly views = new Map<string, ReferenceBinding>();
112
+ readonly importSignatures = new Map<string, string>();
113
+ readonly importMethods = new Map<string, Map<string, { name: string; slot: number }>>();
114
+ readonly hooks = new Map<string, HookBinding>();
115
+ /** Where WIT `u64`/`s64` occur in each bound slot's arguments and result. */
116
+ readonly signatures = new Map<number, Signature>();
117
+ readonly scopes = new Map<number, Scope>();
118
+ active = false;
119
+ #closed = false;
120
+
121
+ /** Both transports share the resolved Rust contract; the SDK remains the sole lifecycle adapter. */
122
+ constructor(
123
+ readonly port: InterpreterPort,
124
+ readonly contract: ContractPort,
125
+ readonly timeout: number,
126
+ ) {}
127
+
128
+ /** Run pure synchronous guest work only while its enclosing factory owns admission. */
129
+ private async declare(command: string, scope: ExecutionScope): Promise<unknown> {
130
+ this.active = true;
131
+ try {
132
+ return await this.port.declare(command, scope);
133
+ } finally {
134
+ scope.cancel();
135
+ this.active = false;
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Run same-revision resource callbacks and decode their reply after physical settlement.
141
+ * Cross-revision methods use executeText and check the original bytes before decoding.
142
+ */
143
+ async execute(command: string, scope: ExecutionScope): Promise<unknown> {
144
+ return JSON.parse(await this.executeText(command, scope));
145
+ }
146
+
147
+ /** Retain the original reply until its prepared result signature has checked the bytes. */
148
+ private async executeText(command: string, scope: ExecutionScope): Promise<string> {
149
+ const release = await this.gate.enter(undefined, scope.signal);
150
+ this.active = true;
151
+ try {
152
+ scope.check();
153
+ return await this.port.execute(command, scope);
154
+ } finally {
155
+ scope.cancel();
156
+ this.active = false;
157
+ release();
158
+ }
159
+ }
160
+
161
+ /**
162
+ * The host-local incoming HTTP service. It has no contract signature, so no WIT dependency can
163
+ * bind it, and its method accepts only an exchange issued by `Host.handleHttp`. One request is
164
+ * one callback of this revision: it holds the gate until the response delivery ended.
165
+ */
166
+ private ingress(
167
+ contract: string,
168
+ description: { javascriptNames: Record<string, string> },
169
+ create: (service: string) => (declaration: Declaration) => Promise<Scope>,
170
+ ): ServiceDefinition {
171
+ if (contract !== HTTP_HANDLER) throw new Error(`Unsupported incoming HTTP export ${contract}`);
172
+ const service = description.javascriptNames["handler"];
173
+ const method = description.javascriptNames["handle"];
174
+ if (!service || !method) throw new Error("Missing prepared incoming HTTP handler names");
175
+ const declared = (JSON.parse(this.port.description()) as Description).services[service];
176
+ if (!declared?.methods.includes(method))
177
+ throw new Error(`The Orb exports ${HTTP_HANDLER} without a ${service}.${method} handler`);
178
+ return {
179
+ [declareFactory]: create(service),
180
+ lifetime: declared.lifetime,
181
+ linger: declared.linger,
182
+ [admitFactory]: () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2))),
183
+ methods: {
184
+ handle: async (environment: Scope, context: Context, value: unknown): Promise<void> => {
185
+ const exchange = IngressExchange.claim(value);
186
+ if (!this.port.ingress)
187
+ throw new Error("This host does not serve incoming HTTP for source Orbs yet");
188
+ const entered = new Context(
189
+ context.session,
190
+ context.root,
191
+ context.invocation,
192
+ context.session.kernel.command(KernelOp.EnterExecution, {
193
+ call: context.invocation!.id,
194
+ context: context.frame || undefined,
195
+ }),
196
+ );
197
+ const scope = environment.exchange({ context: entered });
198
+ const release = await this.gate.enter(undefined, scope.signal);
199
+ this.active = true;
200
+ try {
201
+ scope.check();
202
+ await this.port.ingress(
203
+ { environment: environment.id, service, method },
204
+ exchange,
205
+ scope,
206
+ );
207
+ } finally {
208
+ scope.cancel();
209
+ this.active = false;
210
+ release();
211
+ }
212
+ },
213
+ },
214
+ } as AdaptedService;
215
+ }
216
+
217
+ /** Build callback definitions from WIT rather than asking consumers to repeat service metadata. */
218
+ definition(
219
+ identity: Pick<OrbDefinition, "name" | "apiVersion">,
220
+ installation: InstallationPlan,
221
+ ): OrbDefinition {
222
+ const { importServices: imports } = installation;
223
+ const checked = query<CheckedImplementation>(this.contract, {
224
+ kind: "implementation",
225
+ name: identity.name,
226
+ apiVersion: identity.apiVersion,
227
+ value: JSON.parse(this.port.description()) as Description,
228
+ bindings: installation.bindings,
229
+ });
230
+ const { plan } = checked;
231
+ const description = query<Described>(this.contract, { kind: "describe" });
232
+ const compile = shapes(description);
233
+ const names = description.javascriptNames;
234
+ /**
235
+ * The callback of the exported hook interface `contract`. Hook and contribution bindings carry
236
+ * that full interface identity (the contract's own resolver chose it), so it is looked up as is.
237
+ */
238
+ const callback = (contract: string, method: string): WitFunction => {
239
+ const exported = description.exports.find((item) => item.contract === contract);
240
+ const found = Object.entries(exported?.functions ?? {}).find(
241
+ ([name]) => names[name] === method,
242
+ );
243
+ if (!found) throw new Error(`Missing prepared signature for ${contract}#${method}`);
244
+ return found[1];
245
+ };
246
+ for (const hook of checked.hooks.hooks) {
247
+ this.hooks.set(hook.alias, hook);
248
+ this.signatures.set(hook.slot, compile(callback(hook.name, hook.method)));
249
+ }
250
+ for (const [binding, service] of Object.entries(imports)) {
251
+ if (checked.hooks.contributions.some((contribution) => contribution.binding === binding))
252
+ continue;
253
+ this.imports.set(binding, service);
254
+ const provider = installation.bindings[binding];
255
+ const requirement =
256
+ provider?.kind === "orb"
257
+ ? plan.orb.requires.find((item) => item.orb === provider.name)
258
+ : undefined;
259
+ const signature =
260
+ requirement && Object.hasOwn(requirement.signatures, service)
261
+ ? requirement.signatures[service]
262
+ : undefined;
263
+ if (signature) this.importSignatures.set(binding, signature);
264
+ const selected = description.imports.find((item) => item.binding === binding);
265
+ if (!selected?.functions) throw new Error("Missing prepared import signatures");
266
+ const view = description.references[binding];
267
+ if (view) this.views.set(binding, view);
268
+ const methods = new Map<string, { name: string; slot: number }>();
269
+ for (const [name, fn] of Object.entries(selected.functions)) {
270
+ if (view?.acquire === name) continue;
271
+ const spelling = description.javascriptNames[name];
272
+ if (!spelling || methods.has(spelling)) throw new Error("Ambiguous prepared import method");
273
+ const slot = this.contract.bind(binding, name, false);
274
+ this.signatures.set(slot, compile(view ? { ...fn, params: fn.params.slice(1) } : fn));
275
+ methods.set(spelling, { name: view?.methods[name] ?? name, slot });
276
+ }
277
+ this.importMethods.set(binding, methods);
278
+ }
279
+ let rootScope: Scope | undefined;
280
+ const create = (service: string | null) => async (declaration: Declaration) => {
281
+ const scope = new Scope(this, declaration, service);
282
+ if (service === null) rootScope = scope;
283
+ this.scopes.set(scope.id, scope);
284
+ await this.declare(
285
+ JSON.stringify({ kind: "create", environment: scope.id, service }),
286
+ scope.exchange({ declaration }),
287
+ );
288
+ return scope;
289
+ };
290
+ const services: Record<string, ServiceDefinition> = {};
291
+ for (const service of checked.services) {
292
+ const { interface: binding, alias } = service;
293
+ const exported = description.exports.find((item) => item.binding === binding)?.functions;
294
+ services[service.name] = {
295
+ [signature]: service.signature,
296
+ [declareFactory]: create(alias),
297
+ lifetime: service.lifetime,
298
+ linger: service.linger,
299
+ [admitFactory]: () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2))),
300
+ methods: Object.fromEntries(
301
+ Object.keys(service.methods).map((method) => {
302
+ // The guest selects the method by this export slot through its Load table.
303
+ const slot = this.contract.bind(binding, method, true);
304
+ const fn = exported?.[method];
305
+ if (!fn) throw new Error(`Missing prepared signature for ${binding}#${method}`);
306
+ const shape = compile(fn);
307
+ this.signatures.set(slot, shape);
308
+ const invoke = async (
309
+ environment: Scope,
310
+ context: Context,
311
+ input: Encoded,
312
+ ): Promise<Encoded> => {
313
+ const entered = new Context(
314
+ context.session,
315
+ context.root,
316
+ context.invocation,
317
+ context.session.kernel.command(KernelOp.EnterExecution, {
318
+ call: context.invocation!.id,
319
+ context: context.frame || undefined,
320
+ }),
321
+ );
322
+ const text = await this.executeText(
323
+ packet(
324
+ { kind: "invoke", environment: environment.id, function: slot },
325
+ "args",
326
+ input,
327
+ ),
328
+ environment.exchange({ context: entered }),
329
+ );
330
+ return checkedResult(this.contract, slot, text);
331
+ };
332
+ return [
333
+ method,
334
+ bindCaptured(
335
+ async (environment: Scope, context: Context, ...args: unknown[]) => {
336
+ // Host values are captured once, with WIT 64-bit positions typed in the walk.
337
+ const input = check(
338
+ this.contract,
339
+ slot,
340
+ true,
341
+ encode(args, VALUE_LIMIT, shape.params),
342
+ );
343
+ const text = (await invoke(environment, context, input)).text;
344
+ return lift(shape.result, JSON.parse(text));
345
+ },
346
+ service.signature,
347
+ invoke,
348
+ ),
349
+ ];
350
+ }),
351
+ ),
352
+ } as AdaptedService;
353
+ }
354
+ // Service names are kernel-global, `<orb>::<interface>` like the contract's own services.
355
+ if (plan.ingress)
356
+ services[`${identity.name}::${HTTP_HANDLER}`] = this.ingress(
357
+ plan.ingress,
358
+ description,
359
+ create,
360
+ );
361
+ const hooks = declaredHooks(checked.hooks.hooks);
362
+ const contributes: Record<string, Record<string, Contribution>> = {};
363
+ for (const binding of checked.hooks.contributions) {
364
+ const shape = compile(callback(binding.name, binding.method));
365
+ this.signatures.set(binding.slot, shape);
366
+ (contributes[binding.target] ??= {})[binding.name] = {
367
+ priority: binding.priority,
368
+ handle: async (context, input) => {
369
+ if (!rootScope || this.scopes.get(rootScope.id) !== rootScope)
370
+ throw new Error("Contribution Orb scope is unavailable");
371
+ const entered = new Context(
372
+ context.session,
373
+ context.root,
374
+ context.invocation,
375
+ context.session.kernel.command(KernelOp.EnterExecution, {
376
+ call: context.invocation!.id,
377
+ context: context.frame || undefined,
378
+ }),
379
+ );
380
+ const arguments_ = check(
381
+ this.contract,
382
+ binding.slot,
383
+ true,
384
+ encode([input], VALUE_LIMIT, shape.params),
385
+ );
386
+ const result = await this.executeText(
387
+ packet(
388
+ { kind: "contribute", environment: rootScope.id, function: binding.slot },
389
+ "args",
390
+ arguments_,
391
+ ),
392
+ rootScope.exchange({ context: entered }),
393
+ );
394
+ const value = lift(
395
+ shape.result,
396
+ JSON.parse(checkedResult(this.contract, binding.slot, result).text),
397
+ );
398
+ return binding.optional && value === null ? undefined : value;
399
+ },
400
+ };
401
+ }
402
+ return {
403
+ name: identity.name,
404
+ apiVersion: identity.apiVersion,
405
+ services,
406
+ hooks,
407
+ contributes,
408
+ requires: Object.fromEntries(
409
+ plan.orb.requires.map((requirement) => [
410
+ requirement.orb,
411
+ { ...requirement, [signatures]: requirement.signatures },
412
+ ]),
413
+ ),
414
+ [isolatedRevision]: true,
415
+ [declareFactory]: create(null),
416
+ [validateEnvironment]: async (environment: Environment, value: unknown) => {
417
+ const scope = this.scopes.get(environment.id);
418
+ if (!scope) throw new Error("Validator scope is gone");
419
+ const release = await this.gate.enter();
420
+ try {
421
+ for (const callback of scope.validators)
422
+ await this.declare(
423
+ packet({ kind: "validate", callback }, "value", encode(value)),
424
+ scope.exchange({ validation: true }),
425
+ );
426
+ } finally {
427
+ release();
428
+ }
429
+ },
430
+ [admitFactory]: () => this.gate.enter(Math.max(1, Math.floor(this.timeout / 2))),
431
+ [releaseEnvironment]: async (environment: Environment) => {
432
+ const scope = this.scopes.get(environment.id);
433
+ if (!scope) return;
434
+ this.scopes.delete(scope.id);
435
+ const release = await this.gate.enter();
436
+ try {
437
+ await this.port.release(scope.id);
438
+ } finally {
439
+ release();
440
+ }
441
+ },
442
+ [disposeOrb]: async () => {
443
+ if (this.#closed) return;
444
+ if (this.scopes.size) throw new Error("Interpreter still owns physical scopes");
445
+ await this.port.close();
446
+ this.#closed = true;
447
+ },
448
+ } as AdaptedOrb;
449
+ }
450
+ }