@syntropika/tembra-sdk 0.2.2 → 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 -3332
  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 -3310
  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 -3321
  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 +7 -6
  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 +213 -90
  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 -301
@@ -0,0 +1,447 @@
1
+ /**
2
+ * Host authority of one compiled component environment.
3
+ *
4
+ * A compiled component reaches the kernel only through the `tembra:guest` interfaces its world
5
+ * imports (kernel state, root resources, declared hooks, the call's context), served under the
6
+ * callback's own authority by the same `Scope` as a source Orb (`kernel.ts`); it declares no
7
+ * named host resources or references. Provider-owned WIT resources travel only through the
8
+ * private typed capability lane. Its only host authority beyond granted WASI and those kernel
9
+ * interfaces is calling its typed Orb dependency
10
+ * imports. A plain import targets the default `main` reference the root factory declared for its
11
+ * binding. A checked reference view (an artifact role) declares no default: the guest acquires
12
+ * root claims by key through the view's acquisition function and calls the provider through the
13
+ * returned host-local handle. Every call runs under the admitted invocation of the callback that
14
+ * issued it, with arguments and results checked by the import's own WIT signature.
15
+ */
16
+ import type { CapturedInvocation, CapturedArguments, ResourceCapability } from "#tembra-adapters";
17
+ import type { Declaration } from "../../authoring/declaration.ts";
18
+ import type { DynamicReference } from "../../authoring/types.ts";
19
+ import type { Context } from "../../runtime/context.ts";
20
+ import { checkSignal, combinedSignal } from "../../runtime/signals.ts";
21
+ import { acquireReference } from "../acquire.ts";
22
+ import { check, encode, VALUE_LIMIT } from "../codec.ts";
23
+ import type { Authority } from "../scope.ts";
24
+ import type { ContractPort, ExecutionScope } from "../types.ts";
25
+ import type { KernelAccess, KernelTable } from "./kernel.ts";
26
+ import type { ResourceRoles } from "./resources.ts";
27
+ import { lift, type Signature } from "../wit-shape.ts";
28
+
29
+ const scopeEnded = Object.freeze(new Error("Component callback scope ended"));
30
+
31
+ /**
32
+ * The principal of a call while it is admitted. The kernel refuses to read it once the call is
33
+ * cancelled; a call cancelled before it starts has none here, and its guest asks the kernel.
34
+ */
35
+ function admittedPrincipal(context: Context): string | undefined {
36
+ try {
37
+ return context.principal;
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ }
42
+
43
+ /** One prepared import function: the provider method it calls and its original WIT slot. */
44
+ export interface BoundMethod {
45
+ readonly name: string;
46
+ readonly slot: number;
47
+ readonly roles?: ResourceRoles;
48
+ }
49
+
50
+ /**
51
+ * An opaque, unforgeable token naming one ready root claim of a reference view. Only the scope
52
+ * that issued it can resolve it, and only for a callback of the root owning the claim.
53
+ */
54
+ export interface ReferenceClaim {
55
+ readonly binding: string;
56
+ }
57
+
58
+ interface Claim {
59
+ readonly owner: ScopeOwner;
60
+ readonly binding: string;
61
+ readonly reference: DynamicReference;
62
+ readonly root: number;
63
+ }
64
+
65
+ /** Issued claims; a token absent from this map was not issued by any component scope. */
66
+ const claims = new WeakMap<ReferenceClaim, Claim>();
67
+
68
+ /** The callback authority a component port serves host imports with. */
69
+ export interface CallbackScope {
70
+ readonly signal?: AbortSignal;
71
+ check(): void;
72
+ report(error: unknown): void;
73
+ /** Revoke the callback: later calls are refused and pending waits stop. */
74
+ cancel(): void;
75
+ /**
76
+ * Call a plain Orb dependency import with host-domain arguments (WIT 64-bit positions as
77
+ * `bigint`) and answer its checked host-domain result.
78
+ */
79
+ call(
80
+ binding: string,
81
+ method: string,
82
+ args: readonly unknown[],
83
+ arguments_?: CapturedArguments,
84
+ ): Promise<unknown>;
85
+ releaseResource(owner: ResourceCapability): void;
86
+ resource?(
87
+ owner: ResourceCapability,
88
+ binding: string,
89
+ method: string,
90
+ args: readonly unknown[],
91
+ arguments_?: CapturedArguments,
92
+ ): Promise<unknown>;
93
+ /**
94
+ * Acquire a reference view's provider at `key` for this callback's admitted invocation and
95
+ * root. `abandoned` stops a pending readiness wait and releases the claim.
96
+ */
97
+ acquire(binding: string, key: readonly string[], abandoned: AbortSignal): Promise<ReferenceClaim>;
98
+ /** Call view `method` (its original WIT name) on the claim of exactly `binding`. */
99
+ invoke(
100
+ claim: ReferenceClaim,
101
+ binding: string,
102
+ method: string,
103
+ args: readonly unknown[],
104
+ ): Promise<unknown>;
105
+ /**
106
+ * Release a claim of this callback's root. A claim of another root is left to its root, which
107
+ * releases it when it ends; a drop never acts for another root.
108
+ */
109
+ release(claim: ReferenceClaim): void;
110
+ /**
111
+ * This callback's kernel requests (`tembra:guest`), served under its own authority by its
112
+ * environment's table; absent for an Orb that uses no kernel interface.
113
+ */
114
+ readonly kernel?: KernelAccess;
115
+ }
116
+
117
+ /** The revision tables a component scope resolves import calls against. */
118
+ export interface ScopeOwner {
119
+ readonly contract: ContractPort;
120
+ readonly imports: ReadonlyMap<string, string>;
121
+ /** Plain import methods by JavaScript spelling. */
122
+ readonly importMethods: ReadonlyMap<string, ReadonlyMap<string, BoundMethod>>;
123
+ /** Reference-view methods by original WIT name (`[method]R.name`). */
124
+ readonly views: ReadonlyMap<string, ReadonlyMap<string, BoundMethod>>;
125
+ readonly importSignatures: ReadonlyMap<string, string>;
126
+ readonly signatures: ReadonlyMap<number, Signature>;
127
+ readonly scopes: ReadonlyMap<number, ComponentScope>;
128
+ readonly importedResources?: Set<ResourceCapability>;
129
+ }
130
+
131
+ /** One kernel environment (the Orb root or a service instance) of a compiled component. */
132
+ export class ComponentScope {
133
+ readonly id: number;
134
+ readonly parent: ComponentScope | undefined;
135
+ /** Default `main` reference per plain Orb import binding (root scope only). */
136
+ readonly defaults = new Map<string, DynamicReference>();
137
+ /** The kernel handles this environment declared; absent for an Orb that uses none. */
138
+ kernel: KernelTable | undefined;
139
+
140
+ constructor(
141
+ readonly owner: ScopeOwner,
142
+ readonly declaration: Declaration,
143
+ service: string | null,
144
+ ) {
145
+ this.id = declaration.environment.id;
146
+ const parent = service === null ? undefined : declaration.environment.orb.scope;
147
+ this.parent = parent ? owner.scopes.get(parent.id) : undefined;
148
+ if (service !== null && !this.parent) throw new Error("Missing component Orb scope");
149
+ // Only the root factory declares the default dependency handles, once. A reference view
150
+ // selects its objects by key and has no default.
151
+ if (service === null)
152
+ for (const [binding, name] of owner.imports)
153
+ if (!owner.views.has(binding)) this.defaults.set(binding, declaration.get(name, ["main"]));
154
+ }
155
+
156
+ /**
157
+ * Adapt one admitted invocation to the component port without exposing it to the guest.
158
+ * `execution` is the kernel's scope of a callback the kernel issued (a resource closer).
159
+ */
160
+ exchange(context: Context, execution?: ExecutionScope): CallbackScope {
161
+ const kernel = this.access({ context }, execution);
162
+ const ended = new AbortController();
163
+ // Match native guest drops: a long callback can drop and reacquire the same address
164
+ // without prematurely retiring its provider. Root cancellation remains immediate.
165
+ const dropped = new Set<ReferenceClaim>();
166
+ const droppedResources = new Set<ResourceCapability>();
167
+ const release = (token: ReferenceClaim) => {
168
+ const claim = this.claim(token, token.binding);
169
+ if (claim.root === context.root) claim.reference.release();
170
+ };
171
+ const live = () => {
172
+ if (ended.signal.aborted) throw scopeEnded;
173
+ };
174
+ return {
175
+ signal: context.signal,
176
+ check: () => context.check(),
177
+ ...(kernel ? { kernel } : {}),
178
+ report: (error) => this.declaration.session.report(error),
179
+ cancel: () => {
180
+ if (!ended.signal.aborted) ended.abort(scopeEnded);
181
+ kernel?.execution.cancel();
182
+ for (const token of dropped) {
183
+ try {
184
+ release(token);
185
+ } catch (error) {
186
+ this.declaration.session.report(error);
187
+ }
188
+ }
189
+ dropped.clear();
190
+ for (const owner of droppedResources) {
191
+ try {
192
+ owner.close();
193
+ } catch (error) {
194
+ this.declaration.session.report(error);
195
+ }
196
+ }
197
+ droppedResources.clear();
198
+ },
199
+ call: async (binding, method, args, arguments_) => {
200
+ live();
201
+ const reference = (this.parent ?? this).defaults.get(binding);
202
+ if (!reference) throw new Error("The component has no Orb dependency for this import");
203
+ const bound = this.owner.importMethods.get(binding)?.get(method);
204
+ if (!bound) throw new Error("Unknown prepared import method");
205
+ return this.call(
206
+ reference,
207
+ binding,
208
+ bound,
209
+ args,
210
+ context,
211
+ ended.signal,
212
+ undefined,
213
+ arguments_,
214
+ );
215
+ },
216
+ releaseResource: (owner) => {
217
+ if (ended.signal.aborted) owner.close();
218
+ else droppedResources.add(owner);
219
+ },
220
+ resource: async (owner, binding, method, args, arguments_) => {
221
+ live();
222
+ const bound = this.owner.importMethods.get(binding)?.get(method);
223
+ if (!bound?.roles?.receiver) throw new Error("Not a prepared resource method");
224
+ if (
225
+ owner.nominal.interface !== bound.roles.receiver.interface ||
226
+ owner.nominal.name !== bound.roles.receiver.name
227
+ )
228
+ throw new Error("Resource has another nominal type");
229
+ return this.call(
230
+ owner.reference,
231
+ binding,
232
+ bound,
233
+ args,
234
+ context,
235
+ ended.signal,
236
+ owner,
237
+ arguments_,
238
+ );
239
+ },
240
+ acquire: async (binding, key, abandoned) => {
241
+ live();
242
+ return this.acquire(binding, key, context, combinedSignal(ended.signal, abandoned));
243
+ },
244
+ invoke: async (token, binding, method, args) => {
245
+ live();
246
+ const claim = this.claim(token, binding);
247
+ if (claim.root !== context.root) throw new Error("Reference belongs to another root");
248
+ const session = this.declaration.session;
249
+ if (!session.rootReferences.has(claim.root))
250
+ throw new Error("Reference expired with its root");
251
+ if (session.handles.reference(claim.reference).released)
252
+ throw new Error("Reference was released");
253
+ const bound = this.owner.views.get(binding)?.get(method);
254
+ if (!bound) throw new Error("Unknown prepared reference method");
255
+ return this.call(claim.reference, binding, bound, args, context, ended.signal);
256
+ },
257
+ release: (token) => {
258
+ const claim = this.claim(token, token.binding);
259
+ if (claim.root !== context.root) return;
260
+ if (ended.signal.aborted) release(token);
261
+ else dropped.add(token);
262
+ },
263
+ };
264
+ }
265
+
266
+ /**
267
+ * A callback the kernel itself runs on this environment: its declaration, a validation of the
268
+ * state a reload hands over, a resource opener. It serves only the kernel's interfaces, under
269
+ * `authority`; an Orb dependency call needs an admitted invocation and is refused, as it is for
270
+ * a source Orb. `execution` is the kernel's scope when the kernel issued the callback.
271
+ */
272
+ callback(
273
+ authority: Exclude<Authority, { context: Context }>,
274
+ execution?: ExecutionScope,
275
+ ): CallbackScope {
276
+ const kernel = this.access(authority, execution);
277
+ if (!kernel) throw new Error("This Orb uses no kernel interface");
278
+ const refused = () => Promise.reject(new Error("Operation requires an admitted invocation"));
279
+ return {
280
+ ...("signal" in authority ? { signal: authority.signal } : {}),
281
+ check: () => kernel.execution.check(),
282
+ report: (error) => this.declaration.session.report(error),
283
+ kernel,
284
+ cancel: () => kernel.execution.cancel(),
285
+ call: refused,
286
+ acquire: refused,
287
+ invoke: refused,
288
+ // No claim is issued here; a claim of a root stays with that root.
289
+ release: () => {},
290
+ // Nothing can reacquire a resource here: a dropped one closes at once.
291
+ releaseResource: (owner) => owner.close(),
292
+ };
293
+ }
294
+
295
+ /** The kernel access of a callback under `authority`, when this environment has a table. */
296
+ private access(authority: Authority, execution?: ExecutionScope): KernelAccess | undefined {
297
+ const table = this.kernel;
298
+ if (!table) return undefined;
299
+ return {
300
+ table,
301
+ execution: execution ?? table.scope.exchange(authority),
302
+ ...("context" in authority && table.context
303
+ ? { principal: admittedPrincipal(authority.context) }
304
+ : {}),
305
+ };
306
+ }
307
+
308
+ /** Resolve a token this revision issued for exactly `binding`. */
309
+ private claim(token: ReferenceClaim, binding: string): Claim {
310
+ const claim = claims.get(token);
311
+ if (!claim || claim.owner !== this.owner || claim.binding !== binding)
312
+ throw new Error("Foreign reference handle");
313
+ return claim;
314
+ }
315
+
316
+ /** Acquire a ready root claim and issue its opaque token. */
317
+ private async acquire(
318
+ binding: string,
319
+ key: readonly string[],
320
+ context: Context,
321
+ ended: AbortSignal,
322
+ ): Promise<ReferenceClaim> {
323
+ if (!this.owner.views.has(binding)) throw new Error("The import is not a reference view");
324
+ const service = this.owner.imports.get(binding);
325
+ if (!service) throw new Error("Reference is not a selected WIT Orb import");
326
+ return acquireReference(this.declaration, service, key, context, ended, (reference) => {
327
+ const token: ReferenceClaim = Object.freeze({ binding });
328
+ claims.set(token, {
329
+ owner: this.owner,
330
+ binding,
331
+ reference,
332
+ root: context.root,
333
+ });
334
+ return token;
335
+ });
336
+ }
337
+
338
+ /** Arguments are checked under the import's own WIT slot before the provider sees them. */
339
+ private async call(
340
+ reference: DynamicReference | import("../../runtime/records.ts").ReferenceRecord,
341
+ binding: string,
342
+ bound: BoundMethod,
343
+ args: readonly unknown[],
344
+ context: Context,
345
+ ended: AbortSignal,
346
+ receiver?: ResourceCapability,
347
+ arguments_?: CapturedArguments,
348
+ ): Promise<unknown> {
349
+ checkSignal(ended);
350
+ context.check();
351
+ const shape = this.owner.signatures.get(bound.slot);
352
+ // Typed guest values are captured once, with WIT 64-bit positions read as bigint.
353
+ const input = check(
354
+ this.owner.contract,
355
+ bound.slot,
356
+ true,
357
+ encode(args, VALUE_LIMIT, shape?.params),
358
+ );
359
+ const signature = this.owner.importSignatures.get(binding);
360
+ const resources = Boolean(
361
+ bound.roles?.owned || bound.roles?.receiver || bound.roles?.stream || bound.roles?.arguments,
362
+ );
363
+ const capture: CapturedInvocation | undefined = signature
364
+ ? {
365
+ signature,
366
+ input,
367
+ ...(!resources ? { dataResult: true as const } : {}),
368
+ ...(receiver ? { receiver } : {}),
369
+ ...(arguments_ ? { arguments: arguments_ } : {}),
370
+ }
371
+ : undefined;
372
+ if (resources && !capture)
373
+ throw new Error("Resource transport requires an exact prepared signature");
374
+ const session = this.declaration.session;
375
+ const record = receiver ? receiver.reference : session.handles.reference(reference);
376
+ if (!record.methods.has(bound.name)) throw new Error("Reference does not expose this method");
377
+ const result =
378
+ (await session.calls.invokePhysical(
379
+ record,
380
+ bound.name,
381
+ lift(shape?.params, JSON.parse(input.text)) as unknown[],
382
+ context,
383
+ capture,
384
+ )) ?? null;
385
+ try {
386
+ checkSignal(ended);
387
+ context.check();
388
+ } catch (error) {
389
+ for (const owner of capture?.capabilities ?? []) owner.close();
390
+ throw error;
391
+ }
392
+ if (bound.roles?.owned || bound.roles?.stream) {
393
+ const capabilities = capture?.capabilities ?? [];
394
+ try {
395
+ if (!capture?.output) throw new Error("Prepared provider returned no captured result");
396
+ const output = check(this.owner.contract, bound.slot, false, capture.output);
397
+ const value = lift(shape?.result, JSON.parse(output.text));
398
+ if (bound.roles.stream) {
399
+ const owner = capabilities[0];
400
+ if (capabilities.length !== 1 || value !== 0 || owner?.kind !== "bytes")
401
+ throw new Error("A byte stream result names exactly one stream attachment");
402
+ return owner;
403
+ }
404
+ const consumed = new Set<number>();
405
+ const result = bound.roles.result!(value, (nominal, index) => {
406
+ if (
407
+ typeof index !== "number" ||
408
+ !Number.isInteger(index) ||
409
+ index < 0 ||
410
+ consumed.has(index)
411
+ )
412
+ throw new Error("An owned result must redeem each attachment exactly once");
413
+ const owner = capabilities[index];
414
+ if (
415
+ owner?.kind !== "resource" ||
416
+ owner.nominal.interface !== nominal.interface ||
417
+ owner.nominal.name !== nominal.name
418
+ )
419
+ throw new Error("Resource has another nominal type");
420
+ consumed.add(index);
421
+ return owner;
422
+ });
423
+ if (consumed.size !== capabilities.length)
424
+ throw new Error("Unused result capability attachment");
425
+ for (const owner of capabilities) {
426
+ if (owner.kind !== "resource") throw new Error("Unexpected stream attachment");
427
+ this.owner.importedResources?.add(owner);
428
+ owner.whenClosed(() => this.owner.importedResources?.delete(owner));
429
+ }
430
+ return result;
431
+ } catch (error) {
432
+ for (const owner of capabilities) owner.close();
433
+ throw error;
434
+ }
435
+ }
436
+ if (capture?.capabilities?.length) {
437
+ for (const owner of capture.capabilities) owner.close();
438
+ throw new Error("A data result cannot carry a capability");
439
+ }
440
+ // The provider may be an ordinary host implementation returning hostile JavaScript: reply
441
+ // with the checked capture or a checked copy, never with the original object graph.
442
+ const output =
443
+ capture?.output ??
444
+ check(this.owner.contract, bound.slot, false, encode(result, VALUE_LIMIT, shape?.result));
445
+ return lift(shape?.result, JSON.parse(output.text));
446
+ }
447
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Private, single-owner transport for the canonical whole-result `stream<u8>` profile.
3
+ * A published stream is a capability, never JSON or a JCO representation shared between
4
+ * instances. The producer's physical completion remains independent of publication and drop.
5
+ */
6
+ import type { Context } from "../../runtime/context.ts";
7
+ import type { ByteStreamCapability } from "../../runtime/adapters.ts";
8
+ import { abortable, guestBytes, hostBytes, STREAM_CHUNK } from "./wasi-host.ts";
9
+
10
+ const sources = new WeakMap<ByteStreamCapability, Source>();
11
+
12
+ /** The receiving call may retain this capability only for its original root. */
13
+ export class ByteStreamOwner implements ByteStreamCapability {
14
+ readonly kind = "bytes" as const;
15
+
16
+ private constructor(
17
+ readonly finished: Promise<void>,
18
+ source: Source,
19
+ ) {
20
+ sources.set(this, source);
21
+ }
22
+
23
+ /** Issue only at the checked whole-result stream seam. */
24
+ static issue(stream: unknown, finished: Promise<void>, signal: AbortSignal): ByteStreamOwner {
25
+ return new ByteStreamOwner(finished, new Source(stream, finished, signal));
26
+ }
27
+
28
+ /** Anchor publication to the admitted receiver; cancellation promptly drops the reader. */
29
+ bind(context: Context): void {
30
+ const source = claim(this);
31
+ context.check();
32
+ if (source.binding) {
33
+ if (source.binding.session !== context.session || source.binding.root !== context.root)
34
+ throw new Error("Byte stream belongs to another root");
35
+ return;
36
+ }
37
+ source.binding = { session: context.session, root: context.root };
38
+ source.attach(context.signal);
39
+ }
40
+
41
+ /** Request reader drop immediately. `finished` separately acknowledges physical completion. */
42
+ close(): void {
43
+ claim(this).close();
44
+ }
45
+
46
+ /** Publication and receipt share one host report even if the receiver never takes its head. */
47
+ reportFailure(error: unknown, report: (error: unknown) => void): void {
48
+ claim(this).reportFailure(error, report);
49
+ }
50
+ }
51
+
52
+ export const issueByteStream = ByteStreamOwner.issue;
53
+
54
+ function claim(owner: ByteStreamCapability): Source {
55
+ const source = sources.get(owner);
56
+ if (!source) throw new TypeError("Foreign byte stream capability");
57
+ return source;
58
+ }
59
+
60
+ /** One bounded demand source. Queued readers never overlap a JCO stream read. */
61
+ class Source {
62
+ readonly #iterator: AsyncIterableIterator<Uint8Array>;
63
+ readonly #stopped = new AbortController();
64
+ readonly #detach = new Set<() => void>();
65
+ readonly #failed: Promise<never>;
66
+ #queue = Promise.resolve();
67
+ #closed = false;
68
+ #failure: { error: unknown } | undefined;
69
+ #reported = false;
70
+ taken = false;
71
+ binding: { session: object; root: number } | undefined;
72
+
73
+ constructor(
74
+ stream: unknown,
75
+ readonly finished: Promise<void>,
76
+ signal: AbortSignal,
77
+ ) {
78
+ this.#iterator = guestBytes(stream, this.#stopped.signal);
79
+ this.#failed = finished.then(
80
+ () => new Promise<never>(() => {}),
81
+ (error: unknown) => {
82
+ this.#failure = { error };
83
+ this.close();
84
+ throw error;
85
+ },
86
+ );
87
+ this.#failed.catch(() => {});
88
+ this.attach(signal);
89
+ }
90
+
91
+ attach(signal: AbortSignal): void {
92
+ if (this.#closed) return;
93
+ if (signal.aborted) return this.close();
94
+ const close = () => this.close();
95
+ signal.addEventListener("abort", close, { once: true });
96
+ this.#detach.add(() => signal.removeEventListener("abort", close));
97
+ }
98
+
99
+ close(): void {
100
+ if (this.#closed) return;
101
+ this.#closed = true;
102
+ this.#stopped.abort();
103
+ for (const detach of this.#detach) detach();
104
+ this.#detach.clear();
105
+ // guestBytes.return drops the raw JCO stream synchronously, including during a quiet read.
106
+ void this.#iterator.return?.().catch(() => {});
107
+ }
108
+
109
+ #checkFailure(): void {
110
+ if (this.#failure) throw this.#failure.error;
111
+ }
112
+
113
+ reportFailure(error: unknown, report: (error: unknown) => void): void {
114
+ if (this.#reported) return;
115
+ this.#reported = true;
116
+ report(error);
117
+ }
118
+
119
+ read(): Promise<Uint8Array | undefined> {
120
+ const next = this.#queue.then(async () => {
121
+ this.#checkFailure();
122
+ if (this.#closed) return undefined;
123
+ try {
124
+ const result = await Promise.race([this.#iterator.next(), this.#failed]);
125
+ this.#checkFailure();
126
+ if (this.#closed) return undefined;
127
+ if (result.done) {
128
+ // Writer EOF alone is insufficient: a task can trap after publishing its last byte.
129
+ await abortable(this.finished, this.#stopped.signal);
130
+ this.close();
131
+ return undefined;
132
+ }
133
+ if (result.value.byteLength > STREAM_CHUNK)
134
+ throw new Error("Byte stream chunk exceeds the 64 KiB bound");
135
+ // No producer memory or mutable view crosses into another component instance.
136
+ return result.value.slice();
137
+ } catch (error) {
138
+ const dropped = this.#closed;
139
+ this.close();
140
+ this.#checkFailure();
141
+ if (dropped) return undefined;
142
+ throw error;
143
+ }
144
+ });
145
+ this.#queue = next.then(
146
+ () => {},
147
+ () => {},
148
+ );
149
+ return next;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Redeem once as a symbol-free iterator accepted by the receiving JCO glue. Plain byte streams
155
+ * have no guest error lane: report the producer cause to the host and end the guest stream.
156
+ * Cleanup retains the physical producer after early drop without blocking drop acknowledgement.
157
+ */
158
+ export function receiveByteStream(
159
+ owner: ByteStreamCapability,
160
+ ended: AbortSignal,
161
+ cleanup: (operation: () => unknown) => void,
162
+ failed: (error: unknown) => void,
163
+ ): AsyncIterableIterator<Uint8Array> {
164
+ const source = claim(owner);
165
+ if (source.taken) throw new Error("Byte stream capability was already consumed");
166
+ source.taken = true;
167
+ source.attach(ended);
168
+ const report = (error: unknown) => {
169
+ owner.reportFailure(error, failed);
170
+ };
171
+ return hostBytes(
172
+ () => source.read(),
173
+ (end, failure) => {
174
+ owner.close();
175
+ if (end === "failed") report(failure);
176
+ cleanup(() => owner.finished.catch(report));
177
+ },
178
+ ended,
179
+ );
180
+ }