@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,840 @@
1
+ /**
2
+ * Browser host of the generated standard WASI calls (private binary wire).
3
+ *
4
+ * Packets come from the same generated table and codec that the guest bindings and the native
5
+ * dispatcher use. One instance belongs to one Orb revision: it admits only the interfaces that
6
+ * revision imported, issues opaque handle numbers and validates every incoming handle for
7
+ * identity, liveness and type before any implementation sees it. This module owns transport
8
+ * and ownership only; method semantics live in `standard-filesystem.ts`, `standard-system.ts`,
9
+ * `standard-cli.ts` and `standard-http.ts`, keyed by the generated method names.
10
+ *
11
+ * Ownership rules: owned resources, streams and futures belong to the revision. Every handle a
12
+ * packet names (owned, borrowed, stream or future) is claimed and checked for aliasing while
13
+ * the packet decodes; nothing is transferred until the whole packet validated, so a refused
14
+ * packet consumes nothing. An owned parameter moves the table's reference to the call: the
15
+ * implementation retains what it keeps, and the host releases the transfer reference once the
16
+ * implementation was invoked. Asynchronous calls lend their borrowed resources until they
17
+ * settle. Input writers (streams and futures) created during a callback end with it: an
18
+ * unfinished stream reaches end of stream and an unwritten future resolves to its abandoned
19
+ * error, so no consumer outlives its producer's callback or mistakes it for completion.
20
+ * Callback cancellation settles pending calls but never kills a provider promise: physical
21
+ * work stays tracked until the provider returns.
22
+ */
23
+ import { METHODS, RESOURCES, TYPES, WRITABLE_FUTURES } from "./standard.ts";
24
+ import {
25
+ CALL,
26
+ DROP,
27
+ FUTURE_NEW,
28
+ FUTURE_READ,
29
+ FUTURE_WRITE,
30
+ type HandleCodec,
31
+ INGRESS_HEAD,
32
+ Reader,
33
+ STANDARD_PACKET,
34
+ STREAM_CHUNK,
35
+ STREAM_IMPORT,
36
+ STREAM_NEW,
37
+ STREAM_READ,
38
+ STREAM_WRITE,
39
+ WRITE_ACCEPTED,
40
+ WRITE_CLOSED,
41
+ Writer,
42
+ decode,
43
+ encode,
44
+ } from "./standard-codec.ts";
45
+ import { filesystemMethods, type StandardMount } from "./standard-filesystem.ts";
46
+ import { StandardCli, type StdioStreams } from "./standard-cli.ts";
47
+ import { httpMethods, type HttpClient } from "./standard-http.ts";
48
+ import type { IngressExchange } from "./http-ingress.ts";
49
+ import { IngressCall } from "./standard-ingress.ts";
50
+ import type { HttpResponse } from "./standard-http-values.ts";
51
+ import { socketMethods, type SocketBindings } from "./standard-sockets.ts";
52
+ import type { CliOptions } from "../authoring/types.ts";
53
+ import {
54
+ abortable,
55
+ cancelled,
56
+ HostFuture,
57
+ type Implementation,
58
+ InputBudget,
59
+ InputStream,
60
+ methodKey,
61
+ OutputStream,
62
+ type StandardResource,
63
+ type StandardServices,
64
+ WritableFuture,
65
+ } from "./standard-streams.ts";
66
+ import {
67
+ browserClocks,
68
+ browserRandom,
69
+ checkedClocks,
70
+ revisionRandom,
71
+ systemMethods,
72
+ type ClockProvider,
73
+ type RandomProvider,
74
+ type SystemProviders,
75
+ } from "./standard-system.ts";
76
+
77
+ export type { StandardMount } from "./standard-filesystem.ts";
78
+
79
+ /** Live handles per revision, matching the native table. */
80
+ const HANDLE_LIMIT = 4096;
81
+ const NONE = -1;
82
+ /** The only qualified input stream type. */
83
+ const BYTE_STREAM = TYPES.findIndex(([kind, item]) => kind === "stream" && item === "u8");
84
+ /** `wasi:http/handler#handle`'s result, the same generated type `client.send` returns. */
85
+ const HANDLER_RESULT = METHODS.find(
86
+ (method) => method.interface === "wasi:http/client@0.3.0" && method.name === "send",
87
+ )!.result!;
88
+ const HTTP_REQUEST = RESOURCES.indexOf("wasi:http/types@0.3.0#request");
89
+ /** What an unwritten writable future resolves to; every writable payload has this error case. */
90
+ const ABANDONED = { tag: "err", val: { tag: "internal-error", val: "callback ended" } } as const;
91
+
92
+ /**
93
+ * Handle numbers are issued once per realm and never reused, so a number taken from another
94
+ * revision, or a dropped one, can never name a live entry of this table.
95
+ */
96
+ let issued = 0;
97
+
98
+ type Entry =
99
+ | { kind: "own"; resource: number; value: StandardResource }
100
+ | { kind: "output"; item: number | undefined; value: OutputStream }
101
+ | { kind: "input"; value: InputStream }
102
+ | { kind: "future"; payload: number; value: HostFuture }
103
+ | { kind: "writable"; value: WritableFuture };
104
+
105
+ /** Fixed handle slots a value of `type` publishes; lists are bounded by rollback instead. */
106
+ function slots(type: number): number {
107
+ const [kind, a, b] = TYPES[type]!;
108
+ switch (kind) {
109
+ case "own":
110
+ case "stream":
111
+ case "future":
112
+ return 1;
113
+ case "tuple":
114
+ return (a as number[]).reduce((sum, item) => sum + slots(item), 0);
115
+ case "record":
116
+ return (a as [string, number][]).reduce((sum, [, item]) => sum + slots(item), 0);
117
+ case "option":
118
+ return slots(a as number);
119
+ case "result":
120
+ return Math.max(a === NONE ? 0 : slots(a as number), b === NONE ? 0 : slots(b as number));
121
+ case "variant":
122
+ return Math.max(
123
+ 0,
124
+ ...(a as [string, number][]).map(([, item]) => (item === NONE ? 0 : slots(item))),
125
+ );
126
+ default:
127
+ return 0;
128
+ }
129
+ }
130
+
131
+ /** Codec for values that must not carry handles, such as typed stream items. */
132
+ const HANDLE_FREE: HandleCodec = {
133
+ handle() {
134
+ throw new Error("handle-bearing stream items are unsupported");
135
+ },
136
+ value() {
137
+ throw new Error("handle-bearing stream items are unsupported");
138
+ },
139
+ };
140
+
141
+ /** Handles named by one packet, checked while it decodes and committed only once it is valid. */
142
+ interface Claims {
143
+ readonly codec: HandleCodec;
144
+ /** Resources whose table reference moves to the receiver on commit. */
145
+ readonly owned: StandardResource[];
146
+ /** Resources borrowed by the packet. */
147
+ readonly borrowed: StandardResource[];
148
+ commit(): void;
149
+ }
150
+
151
+ /** Encoded result and the handles it publishes only when resumed into the guest. */
152
+ export interface StandardDelivery {
153
+ readonly bytes: Uint8Array;
154
+ readonly issued: readonly number[];
155
+ /** Streams advanced by this reply; an unpublished read poisons its stream. */
156
+ readonly reads?: readonly number[] | undefined;
157
+ }
158
+
159
+ /** Per-revision standard WASI host for the browser. */
160
+ export class StandardHost implements StandardServices {
161
+ readonly clocks: ClockProvider;
162
+ readonly random: RandomProvider;
163
+ readonly #cli: StandardCli;
164
+ readonly #entries = new Map<number, Entry>();
165
+ /** Handle slots held by owned-item reads whose pull is still running. */
166
+ #reserved = 0;
167
+ readonly #work = new Set<Promise<unknown>>();
168
+ readonly #implementations: (Implementation | undefined)[];
169
+ readonly #allowed: boolean[];
170
+ /** Input writers (streams and futures) created during the current callback. */
171
+ readonly #inputs = new Set<number>();
172
+ /** Accepted guest input across all of this revision's writers. */
173
+ readonly #budget = new InputBudget();
174
+ /** The incoming HTTP request the current callback serves. */
175
+ #ingress: IngressCall | undefined;
176
+ #closed = false;
177
+
178
+ /**
179
+ * @param allowed interfaces imported by this revision's checked contract
180
+ * @param mounts filesystem grants opened for this revision, in grant order
181
+ */
182
+ constructor(
183
+ allowed: ReadonlySet<string>,
184
+ readonly mounts: readonly StandardMount[],
185
+ readonly packetBytes: number,
186
+ providers: SystemProviders & {
187
+ cli?: CliOptions | undefined;
188
+ stdio?: StdioStreams | undefined;
189
+ /** Granted outgoing HTTP; absent means every `wasi:http/client#send` is denied. */
190
+ http?: HttpClient | undefined;
191
+ /** Providers and grants bound to this revision's `wasi:sockets` imports. */
192
+ sockets?: SocketBindings | undefined;
193
+ } = {},
194
+ ) {
195
+ this.clocks = checkedClocks(providers.clocks ?? browserClocks());
196
+ this.random = revisionRandom(providers.random ?? browserRandom());
197
+ this.#cli = new StandardCli(providers.cli, providers.stdio);
198
+ const implementations: Record<string, Implementation> = {
199
+ ...systemMethods(this.clocks, this.random),
200
+ ...filesystemMethods(() => this.mounts),
201
+ ...this.#cli.methods,
202
+ ...httpMethods(providers.http),
203
+ ...socketMethods(providers.sockets ?? {}),
204
+ };
205
+ this.#allowed = METHODS.map((method) => allowed.has(method.interface));
206
+ this.#implementations = METHODS.map((method, index) =>
207
+ this.#allowed[index]
208
+ ? (implementations[methodKey(method)] ??
209
+ implementations[`${method.interface}#${method.name}`])
210
+ : undefined,
211
+ );
212
+ }
213
+
214
+ /** Whether the revision is retired; late physical results are then released, not issued. */
215
+ get closed(): boolean {
216
+ return this.#closed;
217
+ }
218
+
219
+ /** Live handles; used by acceptance to observe retirement. */
220
+ get size(): number {
221
+ return this.#entries.size;
222
+ }
223
+
224
+ /** Accepted, unconsumed guest input bytes; bounded by `INPUT_BUDGET`. */
225
+ get inputBytes(): number {
226
+ return this.#budget.used;
227
+ }
228
+
229
+ /** Physical operations and destructors still running; zero once retirement settled. */
230
+ get pending(): number {
231
+ return this.#work.size;
232
+ }
233
+
234
+ /** Retain physical work even when the caller no longer accepts its result. */
235
+ #track<T>(work: Promise<T>): Promise<T> {
236
+ this.#work.add(work);
237
+ const done = () => this.#work.delete(work);
238
+ work.then(done, done);
239
+ return work;
240
+ }
241
+
242
+ /** Wait for actual provider work and destructors before releasing a callback or revision. */
243
+ async settled(): Promise<void> {
244
+ while (this.#work.size) await Promise.allSettled([...this.#work]);
245
+ }
246
+
247
+ physical<T>(signal: AbortSignal | undefined, operation: () => Promise<T>): Promise<T> {
248
+ if (this.#closed) return Promise.reject(new Error("Standard host is closed"));
249
+ if (signal?.aborted) return Promise.reject(cancelled());
250
+ return this.#track((async () => operation())());
251
+ }
252
+
253
+ cleanup(operation: () => unknown): void {
254
+ this.#track((async () => operation())().catch(() => {}));
255
+ }
256
+
257
+ /** Issue a fresh handle for an outgoing resource, stream or future. */
258
+ #issue(entry: Entry): number {
259
+ const full = this.#entries.size + this.#reserved >= HANDLE_LIMIT;
260
+ if (full || issued >= Number.MAX_SAFE_INTEGER)
261
+ throw new Error(
262
+ full ? "standard handle table is full" : "standard handle space is exhausted",
263
+ );
264
+ this.#entries.set(++issued, entry);
265
+ return issued;
266
+ }
267
+
268
+ /** Release a value of a host future whenever it arrives; nobody will read it. */
269
+ #orphan(future: HostFuture, payload: number): void {
270
+ future.value.then(
271
+ (value) => this.#releaseValue(payload, value),
272
+ () => {},
273
+ );
274
+ }
275
+
276
+ /**
277
+ * Release whatever an entry holds. `undelivered` marks a handle whose publishing reply never
278
+ * reached the guest (or a retiring revision): its future work is cancelled, not just orphaned.
279
+ */
280
+ #release(entry: Entry, undelivered = false): void {
281
+ switch (entry.kind) {
282
+ case "own":
283
+ return entry.value.release();
284
+ case "output":
285
+ case "input":
286
+ return entry.value.close();
287
+ case "future":
288
+ if (undelivered) entry.value.cancel?.();
289
+ return this.#orphan(entry.value, entry.payload);
290
+ case "writable":
291
+ entry.value.abandon();
292
+ if (!entry.value.transferred) entry.value.close();
293
+ return;
294
+ }
295
+ }
296
+
297
+ /** Release host values of `type` that were never issued as handles. */
298
+ #releaseValue(type: number | undefined, value: any, issued?: ReadonlySet<unknown>): void {
299
+ if (type === undefined || type === NONE || value === undefined || value === null) return;
300
+ const [kind, a, b] = TYPES[type]!;
301
+ switch (kind) {
302
+ case "own":
303
+ case "stream":
304
+ case "future":
305
+ if (issued?.has(value)) return;
306
+ if (value instanceof OutputStream || value instanceof InputStream) value.close();
307
+ else if (value instanceof HostFuture) {
308
+ value.cancel?.();
309
+ this.#orphan(value, a as number);
310
+ } else (value as StandardResource).release();
311
+ return;
312
+ case "list":
313
+ for (const item of value) this.#releaseValue(a as number, item, issued);
314
+ return;
315
+ case "tuple":
316
+ (a as number[]).forEach((item, position) =>
317
+ this.#releaseValue(item, value[position], issued),
318
+ );
319
+ return;
320
+ case "record":
321
+ for (const [name, item] of a as [string, number][])
322
+ this.#releaseValue(item, value[name], issued);
323
+ return;
324
+ case "option":
325
+ return this.#releaseValue(a as number, value, issued);
326
+ case "result":
327
+ return this.#releaseValue((value.tag === "ok" ? a : b) as number, value.val, issued);
328
+ case "variant": {
329
+ const found = (a as [string, number][]).find(([tag]) => tag === value.tag);
330
+ return this.#releaseValue(found?.[1], value.val, issued);
331
+ }
332
+ }
333
+ }
334
+
335
+ readonly #handles: HandleCodec = {
336
+ handle: (kind, detail, value) => {
337
+ if (kind === "own" && typeof detail === "number" && RESOURCES[detail] !== undefined)
338
+ return this.#issue({ kind: "own", resource: detail, value: value as StandardResource });
339
+ if (kind === "stream" && value instanceof OutputStream)
340
+ return this.#issue({
341
+ kind: "output",
342
+ item: detail === "u8" ? undefined : (detail as number),
343
+ value,
344
+ });
345
+ if (kind === "future" && value instanceof HostFuture)
346
+ return this.#issue({ kind: "future", payload: detail as number, value });
347
+ throw new Error(`standard ${kind} results are unsupported in this browser host`);
348
+ },
349
+ value: () => {
350
+ throw new Error("standard handles are decoded only as call parameters");
351
+ },
352
+ };
353
+
354
+ /**
355
+ * Claim every handle one packet names. An owned handle may appear once and never alongside a
356
+ * borrow of itself, and it cannot move while a pending call has it lent; an input stream or
357
+ * writable future readable end moves once. Nothing changes until `commit`.
358
+ */
359
+ #claims(): Claims {
360
+ const commits: (() => void)[] = [];
361
+ const owned: StandardResource[] = [];
362
+ const borrowed: StandardResource[] = [];
363
+ const moved = new Set<number>();
364
+ const lent = new Set<number>();
365
+ const codec: HandleCodec = {
366
+ handle: this.#handles.handle,
367
+ value: (kind, detail, handle) => {
368
+ const entry = this.#entries.get(handle);
369
+ if (!entry) throw new Error("unknown or dropped handle");
370
+ if (moved.has(handle)) throw new Error("handle is passed more than once");
371
+ switch (kind) {
372
+ case "own":
373
+ case "borrow":
374
+ if (entry.kind !== "own" || entry.resource !== detail)
375
+ throw new Error("handle has a different type");
376
+ if (kind === "borrow") {
377
+ lent.add(handle);
378
+ borrowed.push(entry.value);
379
+ return entry.value;
380
+ }
381
+ if (lent.has(handle)) throw new Error("handle is passed more than once");
382
+ if (entry.value.borrows) throw new Error("handle is borrowed by a pending call");
383
+ moved.add(handle);
384
+ owned.push(entry.value);
385
+ commits.push(() => this.#entries.delete(handle));
386
+ return entry.value;
387
+ case "stream":
388
+ if (entry.kind !== "input" || TYPES[entry.value.type]![1] !== detail)
389
+ throw new Error("handle has a different type");
390
+ if (entry.value.transferred) throw new Error("stream was already transferred");
391
+ moved.add(handle);
392
+ commits.push(() => {
393
+ entry.value.transferred = true;
394
+ });
395
+ return entry.value;
396
+ case "future":
397
+ if (entry.kind !== "writable" || TYPES[entry.value.type]![1] !== detail)
398
+ throw new Error("handle has a different type");
399
+ if (entry.value.transferred) throw new Error("future was already transferred");
400
+ moved.add(handle);
401
+ commits.push(() => {
402
+ entry.value.transferred = true;
403
+ });
404
+ return entry.value;
405
+ default:
406
+ throw new Error(`standard ${kind} parameters are unsupported`);
407
+ }
408
+ },
409
+ };
410
+ return {
411
+ codec,
412
+ owned,
413
+ borrowed,
414
+ commit: () => {
415
+ for (const commit of commits) commit();
416
+ },
417
+ };
418
+ }
419
+
420
+ /** Decode a call header and refuse methods this revision may not use. */
421
+ #method(reader: Reader, asynchronous: boolean): number {
422
+ const index = reader.u32();
423
+ const method = METHODS[index];
424
+ if (!method) throw new Error("unknown standard method");
425
+ if (!this.#allowed[index]) throw new Error("standard interface is not imported by this Orb");
426
+ if (method.asynchronous !== asynchronous)
427
+ throw new Error("standard call uses the wrong calling convention");
428
+ if (!this.#implementations[index])
429
+ throw new Error(`${method.interface}#${method.name} is unavailable in this browser host`);
430
+ return index;
431
+ }
432
+
433
+ /**
434
+ * Decode and validate every argument, then commit transfers and loans together. A refused
435
+ * packet (bad or aliased handle, trailing bytes, full table) consumes nothing. Returns the
436
+ * owned parameters whose transfer reference the caller releases after invoking the method.
437
+ */
438
+ #arguments(
439
+ index: number,
440
+ reader: Reader,
441
+ lent?: StandardResource[],
442
+ ): { args: unknown[]; owned: StandardResource[] } {
443
+ const claims = this.#claims();
444
+ const method = METHODS[index]!;
445
+ const args = method.params.map((type) => decode(reader, type, claims.codec));
446
+ reader.end();
447
+ const needed = method.result === undefined ? 0 : slots(method.result);
448
+ if (this.#entries.size + this.#reserved + needed > HANDLE_LIMIT)
449
+ throw new Error("standard handle table is full");
450
+ claims.commit();
451
+ for (const resource of lent ? claims.borrowed : []) {
452
+ resource.borrows++;
453
+ resource.retain();
454
+ lent!.push(resource);
455
+ }
456
+ return { args, owned: claims.owned };
457
+ }
458
+
459
+ /** Encode a delivery; on failure roll back its new handles and release unissued values. */
460
+ #deliver(
461
+ type: number | undefined,
462
+ value: unknown,
463
+ head?: (writer: Writer) => void,
464
+ ): StandardDelivery {
465
+ const issued: number[] = [];
466
+ const values = new Set<unknown>();
467
+ const codec: HandleCodec = {
468
+ ...this.#handles,
469
+ handle: (kind, detail, item) => {
470
+ const handle = this.#handles.handle(kind, detail, item);
471
+ issued.push(handle);
472
+ values.add(item);
473
+ return handle;
474
+ },
475
+ };
476
+ try {
477
+ const writer = new Writer();
478
+ head?.(writer);
479
+ if (type !== undefined && type !== NONE) encode(writer, type, value, codec);
480
+ const bytes = writer.finish();
481
+ if (bytes.length > this.packetBytes)
482
+ throw new Error("standard reply exceeds the packet bound");
483
+ return { bytes, issued };
484
+ } catch (error) {
485
+ this.discard({ issued });
486
+ this.#releaseValue(type, value, values);
487
+ throw error;
488
+ }
489
+ }
490
+
491
+ /** Serve one WIT-synchronous packet while the guest stack waits. */
492
+ sync(packet: Uint8Array): Uint8Array {
493
+ if (this.#closed) throw new Error("Standard host is closed");
494
+ const reader = new Reader(packet);
495
+ if (reader.u8() !== STANDARD_PACKET) throw new Error("not a standard packet");
496
+ switch (reader.u8()) {
497
+ case CALL: {
498
+ const index = this.#method(reader, false);
499
+ const { args, owned } = this.#arguments(index, reader);
500
+ let value: unknown;
501
+ try {
502
+ value = this.#implementations[index]!({ host: this }, args);
503
+ } finally {
504
+ for (const resource of owned) resource.release();
505
+ }
506
+ return this.#deliver(METHODS[index]!.result, value).bytes;
507
+ }
508
+ case DROP: {
509
+ const handle = reader.handle();
510
+ reader.end();
511
+ const entry = this.#entries.get(handle);
512
+ if (!entry) throw new Error("unknown or dropped handle");
513
+ if (entry.kind === "own" && entry.value.borrows)
514
+ throw new Error("handle is borrowed by a pending call");
515
+ this.#entries.delete(handle);
516
+ this.#inputs.delete(handle);
517
+ this.#release(entry);
518
+ return new Uint8Array();
519
+ }
520
+ case STREAM_NEW: {
521
+ const type = reader.u32();
522
+ reader.end();
523
+ // Only byte input streams are qualified; typed input streams are refused.
524
+ if (type !== BYTE_STREAM) throw new Error("unsupported input stream type");
525
+ const handle = this.#issue({ kind: "input", value: new InputStream(type, this.#budget) });
526
+ this.#inputs.add(handle);
527
+ const writer = new Writer();
528
+ writer.handle(handle);
529
+ return writer.finish();
530
+ }
531
+ case FUTURE_NEW: {
532
+ const type = reader.u32();
533
+ reader.end();
534
+ if (!WRITABLE_FUTURES.includes(type)) throw new Error("unsupported writable future type");
535
+ const payload = TYPES[type]![1] as number;
536
+ const future = new WritableFuture<unknown>(type, ABANDONED, (value) =>
537
+ this.#releaseValue(payload, value),
538
+ );
539
+ const handle = this.#issue({ kind: "writable", value: future });
540
+ this.#inputs.add(handle);
541
+ const writer = new Writer();
542
+ writer.handle(handle);
543
+ return writer.finish();
544
+ }
545
+ case FUTURE_WRITE: {
546
+ const handle = reader.handle();
547
+ const entry = this.#entries.get(handle);
548
+ if (entry?.kind !== "writable") throw new Error("handle is not a live writable future");
549
+ if (entry.value.written) throw new Error("future was already written");
550
+ // The whole payload, including every owned handle inside it, validates first.
551
+ const claims = this.#claims();
552
+ const value = decode(reader, TYPES[entry.value.type]![1] as number, claims.codec);
553
+ reader.end();
554
+ if (claims.borrowed.length) throw new Error("future payloads cannot borrow");
555
+ claims.commit();
556
+ entry.value.write(value);
557
+ return new Uint8Array();
558
+ }
559
+ default:
560
+ throw new Error("unknown standard operation");
561
+ }
562
+ }
563
+
564
+ /** Serve one asynchronous packet owned by the callback whose `signal` is supplied. */
565
+ async async(packet: Uint8Array, signal?: AbortSignal): Promise<StandardDelivery> {
566
+ if (this.#closed) throw new Error("Standard host is closed");
567
+ const reader = new Reader(packet);
568
+ if (reader.u8() !== STANDARD_PACKET) throw new Error("not a standard packet");
569
+ switch (reader.u8()) {
570
+ case CALL: {
571
+ const index = this.#method(reader, true);
572
+ // A cancelled callback starts nothing and transfers nothing.
573
+ if (signal?.aborted) throw cancelled();
574
+ const lent: StandardResource[] = [];
575
+ const { args, owned } = this.#arguments(index, reader, lent);
576
+ let release = () => {};
577
+ // A loan is physical ownership: retirement waits until the call's provider work settles.
578
+ if (lent.length)
579
+ this.#track(
580
+ new Promise<void>((resolve) => {
581
+ release = resolve;
582
+ }),
583
+ );
584
+ // Provider work started by this call; cancellation answers the guest promptly, but
585
+ // the borrowed descriptors stay lent until that work returns.
586
+ const work: Promise<unknown>[] = [];
587
+ const host = this;
588
+ const services: StandardServices = {
589
+ packetBytes: this.packetBytes,
590
+ get closed() {
591
+ return host.closed;
592
+ },
593
+ physical: (signal, operation) => {
594
+ const started = this.physical(signal, operation);
595
+ work.push(started);
596
+ return started;
597
+ },
598
+ cleanup: (operation) => this.cleanup(operation),
599
+ };
600
+ try {
601
+ let started: unknown;
602
+ try {
603
+ started = this.#implementations[index]!({ host: services, signal }, args);
604
+ } finally {
605
+ // The implementation's first turn has run: it adopted what it keeps.
606
+ for (const resource of owned) resource.release();
607
+ }
608
+ const value = await started;
609
+ if (signal?.aborted || this.#closed) {
610
+ this.#releaseValue(METHODS[index]!.result, value);
611
+ throw cancelled();
612
+ }
613
+ return this.#deliver(METHODS[index]!.result, value);
614
+ } finally {
615
+ void Promise.allSettled(work).then(() => {
616
+ for (const resource of lent) {
617
+ resource.borrows--;
618
+ resource.release();
619
+ }
620
+ release();
621
+ });
622
+ }
623
+ }
624
+ case STREAM_READ: {
625
+ const handle = reader.handle();
626
+ const requested = reader.u32();
627
+ reader.end();
628
+ const entry = this.#entries.get(handle);
629
+ if (entry?.kind !== "output") throw new Error("handle is not a live output stream");
630
+ const item = entry.item;
631
+ if (item !== undefined && slots(item) > 0) {
632
+ // Owned items: the item's handle slots are reserved before the pull, so no concurrent
633
+ // read or issue can take them. The reservation is returned on every outcome, and on
634
+ // success it becomes the handles this reply issues, with no await in between. Those
635
+ // handles are journaled with the read, so an undelivered reply rolls them back and
636
+ // poisons the stream, as every stream read does.
637
+ let reserved = slots(item);
638
+ if (this.#entries.size + this.#reserved + reserved > HANDLE_LIMIT)
639
+ throw new Error("standard handle table is full");
640
+ this.#reserved += reserved;
641
+ const unreserve = () => {
642
+ this.#reserved -= reserved;
643
+ reserved = 0;
644
+ };
645
+ try {
646
+ const taken = await this.#track(entry.value.take(signal));
647
+ unreserve();
648
+ if (!taken) return { bytes: Uint8Array.of(1), issued: [], reads: [handle] };
649
+ // The value is this read's alone now; a drop or retirement since the pull means
650
+ // nobody will receive it, so it is released here instead of being issued.
651
+ if (this.#closed || entry.value.closed) {
652
+ this.#releaseValue(item, taken.value);
653
+ throw new Error(this.#closed ? "Standard host is closed" : "stream was dropped");
654
+ }
655
+ const delivery = this.#deliver(item, taken.value, (writer) => {
656
+ writer.u8(0);
657
+ writer.u32(1);
658
+ });
659
+ return { ...delivery, reads: [handle] };
660
+ } finally {
661
+ unreserve();
662
+ }
663
+ }
664
+ const limit =
665
+ item === undefined
666
+ ? Math.min(Math.max(requested, 1), STREAM_CHUNK, this.packetBytes - 5)
667
+ : Math.max(requested, 1);
668
+ if (limit < 1) throw new Error("standard reply exceeds the packet bound");
669
+ const encodeItem =
670
+ item === undefined
671
+ ? undefined
672
+ : (value: unknown) => {
673
+ const writer = new Writer();
674
+ encode(writer, item, value, HANDLE_FREE);
675
+ return writer.finish();
676
+ };
677
+ // Include queued reads, before their provider call starts, in retirement accounting.
678
+ const bytes = await this.#track(
679
+ entry.value.read(limit, this.packetBytes, signal, encodeItem),
680
+ );
681
+ return { bytes, issued: [], reads: [handle] };
682
+ }
683
+ case STREAM_WRITE: {
684
+ const handle = reader.handle();
685
+ const length = reader.u32();
686
+ // Refuse a bad packet or stream before reserving budget or copying the chunk.
687
+ if (length > STREAM_CHUNK) throw new Error("stream write exceeds the 64 KiB chunk bound");
688
+ if (reader.remaining !== length)
689
+ throw new RangeError(
690
+ reader.remaining < length
691
+ ? "standard packet is truncated"
692
+ : "standard packet has trailing bytes",
693
+ );
694
+ const entry = this.#entries.get(handle);
695
+ if (entry?.kind !== "input") throw new Error("handle is not a live input stream");
696
+ try {
697
+ await entry.value.write(length, () => reader.raw(length), signal);
698
+ } catch (error) {
699
+ // A stopped consumer is an ordinary end of production; anything else fails it.
700
+ if (entry.value.cancelled) return { bytes: Uint8Array.of(WRITE_CLOSED), issued: [] };
701
+ throw error;
702
+ }
703
+ return { bytes: Uint8Array.of(WRITE_ACCEPTED), issued: [] };
704
+ }
705
+ case INGRESS_HEAD: {
706
+ const call = this.#ingress;
707
+ if (!call) throw new Error("no incoming HTTP request is being served");
708
+ if (call.exchange.published) throw new Error("the response head was already published");
709
+ if (signal?.aborted) throw cancelled();
710
+ // The whole result validates before the response moves to the host.
711
+ const claims = this.#claims();
712
+ const result = decode(reader, HANDLER_RESULT, claims.codec) as
713
+ | { tag: "ok"; val: HttpResponse }
714
+ | { tag: "err"; val: import("wasi:http/types@0.3.0").ErrorCode };
715
+ reader.end();
716
+ claims.commit();
717
+ // The head leaves now; this operation completes only when the delivery ended, which
718
+ // keeps the handler's callback (and its context authority) alive while it streams.
719
+ const ended = call.respond(this, result);
720
+ try {
721
+ await abortable(ended, signal);
722
+ } catch (error) {
723
+ call.end(error);
724
+ throw error;
725
+ }
726
+ return { bytes: new Uint8Array(), issued: [] };
727
+ }
728
+ case FUTURE_READ: {
729
+ const handle = reader.handle();
730
+ reader.end();
731
+ const entry = this.#entries.get(handle);
732
+ if (entry?.kind !== "future") throw new Error("handle is not a live future");
733
+ // A future value is read once; the handle is consumed now. A value that arrives after
734
+ // this read was cancelled is released, never issued.
735
+ this.#entries.delete(handle);
736
+ let value: unknown;
737
+ try {
738
+ value = await abortable(entry.value.value, signal);
739
+ } catch (error) {
740
+ if (signal?.aborted) this.#orphan(entry.value, entry.payload);
741
+ throw error;
742
+ }
743
+ if (signal?.aborted || this.#closed) {
744
+ this.#releaseValue(entry.payload, value);
745
+ throw cancelled();
746
+ }
747
+ return this.#deliver(entry.payload, value);
748
+ }
749
+ case STREAM_IMPORT:
750
+ // Stream imports need a host stream carrier; until the browser port has one, a source
751
+ // Orb importing a stream is refused at installation, and a forged packet here.
752
+ throw new Error("stream imports are served only through the native Rust facade");
753
+ default:
754
+ throw new Error("unknown standard operation");
755
+ }
756
+ }
757
+
758
+ /** Release resources from a reply that was never resumed into the guest. */
759
+ discard(delivery: Pick<StandardDelivery, "issued" | "reads">): void {
760
+ for (const handle of delivery.reads ?? []) {
761
+ const entry = this.#entries.get(handle);
762
+ if (entry?.kind === "output") entry.value.abandon();
763
+ }
764
+ for (const handle of delivery.issued) {
765
+ const entry = this.#entries.get(handle);
766
+ if (!entry) continue;
767
+ this.#entries.delete(handle);
768
+ this.#release(entry, true);
769
+ }
770
+ }
771
+
772
+ /**
773
+ * End of the current callback: every input writer it created and did not drop ends, so its
774
+ * consumer reaches end of stream (streams) or the abandoned error (futures) instead of
775
+ * waiting for a producer that is gone.
776
+ */
777
+ /**
778
+ * Begin serving one incoming request in the next callback: issue its `own<request>` handle.
779
+ * Invalid input is refused before anything is issued.
780
+ */
781
+ beginIngress(exchange: IngressExchange): number {
782
+ if (this.#closed) throw new Error("Standard host is closed");
783
+ if (this.#ingress) throw new Error("an incoming HTTP request is already being served");
784
+ const call = new IngressCall(exchange, (operation) => this.cleanup(operation));
785
+ const request = call.resource();
786
+ try {
787
+ const handle = this.#issue({ kind: "own", resource: HTTP_REQUEST, value: request });
788
+ this.#ingress = call;
789
+ return handle;
790
+ } catch (error) {
791
+ request.release();
792
+ throw error;
793
+ }
794
+ }
795
+
796
+ /** The serving callback ended: whatever its delivery had not finished ends with `reason`. */
797
+ endIngress(reason: unknown): void {
798
+ const call = this.#ingress;
799
+ this.#ingress = undefined;
800
+ call?.end(reason);
801
+ }
802
+
803
+ endCallback(): void {
804
+ for (const handle of this.#inputs) {
805
+ const entry = this.#entries.get(handle);
806
+ if (entry?.kind !== "input" && entry?.kind !== "writable") continue;
807
+ this.#entries.delete(handle);
808
+ this.#release(entry);
809
+ }
810
+ this.#inputs.clear();
811
+ }
812
+
813
+ /** Retire the revision: drop every handle after physical provider work has settled. */
814
+ async dispose(): Promise<void> {
815
+ this.#closed = true;
816
+ this.endIngress(new Error("Standard host is closed"));
817
+ this.#cli.retire();
818
+ // Producers first, so no consumer waits for a writer that can no longer run.
819
+ for (const [handle, entry] of this.#entries)
820
+ if (entry.kind === "input" || entry.kind === "writable") {
821
+ this.#entries.delete(handle);
822
+ this.#release(entry);
823
+ }
824
+ this.#inputs.clear();
825
+ await this.settled();
826
+ const entries = [...this.#entries.values()];
827
+ this.#entries.clear();
828
+ for (const entry of entries) this.#release(entry, true);
829
+ await this.settled();
830
+ this.#cli.close(this);
831
+ await this.settled();
832
+ // Every consumer had its turn; input nobody will read returns to the budget.
833
+ this.#budget.discard();
834
+ }
835
+ }
836
+
837
+ /** Whether an interpreter packet is a binary standard packet rather than UTF-8 JSON. */
838
+ export function isStandardPacket(packet: Uint8Array): boolean {
839
+ return packet.byteLength > 0 && packet[0] === STANDARD_PACKET;
840
+ }