@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,314 @@
1
+ import { EnvironmentPhase } from "../bridge/protocol.ts";
2
+ import { refuse } from "../error.ts";
3
+ import { Errors } from "../errors.ts";
4
+ import type { Declaration } from "../authoring/declaration.ts";
5
+ import type {
6
+ HostOptions,
7
+ OrbDefinition,
8
+ OrbInput,
9
+ OrbArtifact,
10
+ ServiceDefinition,
11
+ HookDefinition,
12
+ } from "../authoring/types.ts";
13
+ import type { Environment, ReferenceRecord } from "./records.ts";
14
+ import type { Session } from "./session.ts";
15
+
16
+ import type { Handler } from "../authoring/types.ts";
17
+ import type { Context } from "./context.ts";
18
+ import type { Encoded } from "../interpreter/codec.ts";
19
+ /** Internal platform-neutral resource transport; implementations keep their issuer state private. */
20
+ export interface ResourceReceiver {
21
+ redeem(
22
+ issuer: object,
23
+ environment: number,
24
+ expected: { readonly interface: string; readonly name: string },
25
+ ): object;
26
+ }
27
+ export interface ResourceLoan {
28
+ (): void;
29
+ readonly receiver: ResourceReceiver;
30
+ }
31
+ export interface ResourceCapability extends ResourceReceiver {
32
+ readonly kind: "resource";
33
+ readonly nominal: { readonly interface: string; readonly name: string };
34
+ readonly reference: ReferenceRecord;
35
+ anchor(session: Session, reference: ReferenceRecord): void;
36
+ lend(): ResourceLoan;
37
+ /** Move authority out of this wrapper; stale aliases keep no backend or claim. */
38
+ move(): ResourceCapability;
39
+ issuedBy(issuer: object): boolean;
40
+ /** Return an owner to its issuing component instance, without running its destructor. */
41
+ take(issuer: object, expected: ResourceCapability["nominal"]): object;
42
+ whenClosed(operation: () => void): void;
43
+ close(): void;
44
+ }
45
+
46
+ /** Internal byte-source authority; concrete browser state never enters shared runtime types. */
47
+ export interface ByteStreamCapability {
48
+ readonly kind: "bytes";
49
+ readonly finished: Promise<void>;
50
+ /** Share one host notification across publication, receiver reads and abandonment. */
51
+ reportFailure(error: unknown, report: (error: unknown) => void): void;
52
+ bind(context: Context): void;
53
+ close(): void;
54
+ }
55
+
56
+ /** Private capability lane, available only between matched prepared handlers. */
57
+ export interface CapturedDelivery {
58
+ readonly value: Encoded;
59
+ readonly capabilities?: readonly (ResourceCapability | ByteStreamCapability)[];
60
+ /** Bounded provider outcome after an early result head; actual work uses the retain sink. */
61
+ readonly finished?: Promise<void>;
62
+ }
63
+
64
+ /** A private data path, never passed to ordinary application handlers or stored on Context. */
65
+ export interface CapturedInvocation {
66
+ readonly signature: string;
67
+ readonly input: Encoded;
68
+ /** Permit checked ordinary data results when this caller does not require captured delivery. */
69
+ readonly dataResult?: true;
70
+ output?: Encoded;
71
+ receiver?: ResourceCapability;
72
+ capabilities?: readonly (ResourceCapability | ByteStreamCapability)[];
73
+ arguments?: CapturedArguments;
74
+ }
75
+ /** Ownership is accepted only after checked preflight and entry into the receiving callback. */
76
+ export interface CapturedArguments {
77
+ readonly owners: readonly ResourceCapability[];
78
+ readonly accepted: boolean;
79
+ accept(): void;
80
+ }
81
+ /** The ordinary checked data entry of a prepared backend, with physical retention. */
82
+ type CapturedDataMethod = (
83
+ environment: any,
84
+ context: Context,
85
+ args: readonly unknown[],
86
+ retain: (physical: Promise<void>) => void,
87
+ ) => Promise<unknown>;
88
+ interface CapturedMethod {
89
+ readonly signature: string | undefined;
90
+ readonly invokeData?: CapturedDataMethod;
91
+ invoke(
92
+ environment: any,
93
+ context: Context,
94
+ input: Encoded,
95
+ receiver?: ResourceReceiver,
96
+ /** Register actual physical completion before the bounded result may resolve or reject. */
97
+ retain?: (physical: Promise<void>) => void,
98
+ arguments_?: CapturedArguments,
99
+ ): Promise<Encoded | CapturedDelivery>;
100
+ }
101
+ const capturedMethods = new WeakMap<Handler, CapturedMethod>();
102
+
103
+ /** Register the actual prepared handler, rather than certifying a caller-owned object or frame. */
104
+ export function bindCaptured(
105
+ handle: Handler,
106
+ signature: string | undefined,
107
+ invoke: CapturedMethod["invoke"],
108
+ invokeData?: CapturedDataMethod,
109
+ ): Handler {
110
+ if (signature || invokeData)
111
+ capturedMethods.set(handle, {
112
+ signature,
113
+ invoke,
114
+ ...(invokeData ? { invokeData } : {}),
115
+ });
116
+ return handle;
117
+ }
118
+
119
+ /** Resolve only the implementation selected by admission and only for an identical contract. */
120
+ export function capturedMethod(handle: Handler, signature: string): CapturedMethod | undefined {
121
+ const adapter = capturedMethods.get(handle);
122
+ return adapter?.signature === signature ? adapter : undefined;
123
+ }
124
+
125
+ /** Ordinary data callers retain backend work without receiving the capability channel. */
126
+ export function capturedDataMethod(handle: Handler): CapturedDataMethod | undefined {
127
+ return capturedMethods.get(handle)?.invokeData;
128
+ }
129
+
130
+ // These hooks connect execution backends to the existing lifecycle; they grant no guest authority.
131
+ export const declareFactory = Symbol("tembra.declare-factory");
132
+ export const validateEnvironment = Symbol("tembra.validate-environment");
133
+ export const isolate = Symbol("tembra.isolate");
134
+ export const signature = Symbol("tembra.signature");
135
+ export const signatures = Symbol("tembra.signatures");
136
+ export type AdaptedHostOptions = HostOptions & {
137
+ [isolate]?: (definition: OrbArtifact) => Promise<OrbDefinition>;
138
+ };
139
+ export const disposeOrb = Symbol("tembra.dispose-orb");
140
+ export const releaseEnvironment = Symbol("tembra.release-environment");
141
+ // Executor-backed revisions; the kernel derives a private resource realm from each revision.
142
+ export const isolatedRevision = Symbol("tembra.isolated-revision");
143
+ export const admitFactory = Symbol("tembra.admit-factory");
144
+ export type AdaptedOrb = OrbDefinition & {
145
+ [isolatedRevision]?: true;
146
+ [declareFactory]?: (declaration: Declaration) => Promise<unknown>;
147
+ [admitFactory]?: () => Promise<() => void>;
148
+ [disposeOrb]?: () => void | Promise<void>;
149
+ [validateEnvironment]?: (environment: Environment, value: unknown) => Promise<void>;
150
+ [releaseEnvironment]?: (environment: Environment) => void | Promise<void>;
151
+ };
152
+ export type AdaptedService = ServiceDefinition & {
153
+ [signature]?: string;
154
+ [declareFactory]?: (declaration: Declaration) => Promise<unknown>;
155
+ [admitFactory]?: () => Promise<() => void>;
156
+ };
157
+ export type AdaptedHook = HookDefinition & { [signature]?: string };
158
+
159
+ /** Materialize a fresh revision per installation, disposing earlier candidates on failure. */
160
+ export function prepareDefinitions(
161
+ definitions: readonly OrbInput[],
162
+ isolated?: (definition: OrbArtifact) => Promise<OrbDefinition>,
163
+ ): OrbDefinition[] | Promise<OrbDefinition[]> {
164
+ if (!definitions.some((definition) => "artifact" in definition))
165
+ return [...definitions] as OrbDefinition[];
166
+ const captured = definitions.map((definition) =>
167
+ "artifact" in definition
168
+ ? {
169
+ ...(definition.requires
170
+ ? {
171
+ requires: Object.fromEntries(
172
+ Object.entries(definition.requires).map(([name, provider]) => [
173
+ name,
174
+ { ...provider },
175
+ ]),
176
+ ),
177
+ }
178
+ : {}),
179
+ ...(definition.grants
180
+ ? {
181
+ grants: {
182
+ ...definition.grants,
183
+ ...(definition.grants.system ? { system: [...definition.grants.system] } : {}),
184
+ ...(definition.grants.filesystem
185
+ ? {
186
+ filesystem: definition.grants.filesystem.map((mount) => ({ ...mount })),
187
+ }
188
+ : {}),
189
+ ...(definition.grants.http
190
+ ? {
191
+ http: definition.grants.http.map((grant) => ({
192
+ ...grant,
193
+ origins: [...grant.origins],
194
+ })),
195
+ }
196
+ : {}),
197
+ ...(definition.grants.network
198
+ ? {
199
+ network: definition.grants.network.map((grant) => ({
200
+ ...grant,
201
+ ...(grant.connect ? { connect: [...grant.connect] } : {}),
202
+ ...(grant.listen ? { listen: [...grant.listen] } : {}),
203
+ ...(grant.bind ? { bind: [...grant.bind] } : {}),
204
+ ...(grant.datagrams ? { datagrams: [...grant.datagrams] } : {}),
205
+ })),
206
+ }
207
+ : {}),
208
+ },
209
+ }
210
+ : {}),
211
+ artifact: definition.artifact.slice(),
212
+ ...(definition.cli ? { cli: captureCli(definition.cli) } : {}),
213
+ }
214
+ : definition,
215
+ );
216
+ return prepareBackends(captured, isolated);
217
+ }
218
+
219
+ /** Overlap independent native preparations while bounding transient Stores and draining failures. */
220
+ async function prepareBackends(
221
+ definitions: (OrbInput | undefined)[],
222
+ isolated?: (definition: OrbArtifact) => Promise<OrbDefinition>,
223
+ ): Promise<OrbDefinition[]> {
224
+ const prepared: (OrbDefinition | undefined)[] = new Array(definitions.length);
225
+ let next = 0;
226
+ const failures: { index: number; reason: unknown }[] = [];
227
+ async function prepare(): Promise<void> {
228
+ while (failures.length === 0 && next < definitions.length) {
229
+ const index = next++;
230
+ const definition = definitions[index]!;
231
+ try {
232
+ if ("artifact" in definition) {
233
+ if (!isolated) throw new Error("This host has no isolated execution backend");
234
+ const materialized = await isolated(definition);
235
+ if (!materialized) throw new Error("Execution backend returned no Orb definition");
236
+ prepared[index] = materialized;
237
+ } else prepared[index] = definition;
238
+ } catch (error) {
239
+ failures.push({ index, reason: error });
240
+ } finally {
241
+ // Release our captured input once the backend owns the prepared revision.
242
+ definitions[index] = undefined;
243
+ }
244
+ }
245
+ }
246
+ // Workers consume their errors so every in-flight Store settles before disposal begins.
247
+ await Promise.all(Array.from({ length: Math.min(4, definitions.length) }, prepare));
248
+ const completed = prepared.filter((definition) => definition !== undefined);
249
+ if (failures.length) {
250
+ const errors = failures.sort((a, b) => a.index - b.index).map((failure) => failure.reason);
251
+ return discardDefinitions(
252
+ completed,
253
+ errors.length === 1 ? errors[0] : new AggregateError(errors, "Orb preparation failed"),
254
+ );
255
+ }
256
+ return completed;
257
+ }
258
+
259
+ /** Dispose failed candidates while retaining both the operation and cleanup causes. */
260
+ export async function discardDefinitions(
261
+ definitions: readonly OrbDefinition[],
262
+ error: unknown,
263
+ ): Promise<never> {
264
+ try {
265
+ await disposeDefinitions(definitions);
266
+ } catch (disposal) {
267
+ throw new AggregateError([error, disposal], "Orb operation and disposal failed");
268
+ }
269
+ throw error;
270
+ }
271
+
272
+ /** Release backend revisions only after their physically owning scopes are gone. */
273
+ export async function disposeDefinitions(definitions: readonly OrbDefinition[]): Promise<void> {
274
+ const results = await Promise.allSettled(
275
+ definitions.map(async (definition) => (definition as AdaptedOrb)[disposeOrb]?.()),
276
+ );
277
+ const failures = results.filter((result) => result.status === "rejected");
278
+ if (failures.length)
279
+ throw new AggregateError(
280
+ failures.map((result) => result.reason),
281
+ "Backend disposal failed",
282
+ );
283
+ }
284
+
285
+ /** Keep source factories synchronous while a backend prepares their transport asynchronously. */
286
+ export function captureEnvironment(
287
+ definition: OrbDefinition | ServiceDefinition,
288
+ declaration: import("../authoring/declaration.ts").Declaration,
289
+ ): import("./records.ts").Environment | Promise<import("./records.ts").Environment> {
290
+ const environment = declaration.environment;
291
+ const finish = () => {
292
+ environment.phase = EnvironmentPhase.Prepared;
293
+ declaration.session.programs.register(environment);
294
+ };
295
+ const prepare = (definition as AdaptedService)[declareFactory];
296
+ if (prepare)
297
+ return Promise.resolve()
298
+ .then(() => prepare(declaration))
299
+ .then((value) => {
300
+ environment.value = value ?? {};
301
+ return environment;
302
+ })
303
+ .finally(finish);
304
+ try {
305
+ const value = definition.create?.(declaration) ?? {};
306
+ if (value && typeof (value as { then?: unknown }).then === "function")
307
+ refuse(Errors.Invalid.AsyncFactory);
308
+ environment.value = value;
309
+ return environment;
310
+ } finally {
311
+ finish();
312
+ }
313
+ }
314
+ import { captureCli } from "../interpreter/cli.ts";
@@ -1,3 +1,4 @@
1
+ import { capturedMethod, capturedDataMethod, type CapturedInvocation } from "#tembra-adapters";
1
2
  import type { Completion } from "../authoring/types.ts";
2
3
  import { Code } from "../bridge/identifiers.ts";
3
4
  import type { Invocation } from "../bridge/kernel.ts";
@@ -7,13 +8,21 @@ import { Errors } from "../errors.ts";
7
8
  import { Context, context } from "./context.ts";
8
9
  import type { Environment, ReferenceRecord } from "./records.ts";
9
10
  import type { Session } from "./session.ts";
11
+ import { Encoded } from "../interpreter/codec.ts";
12
+ import { checkSignal } from "./signals.ts";
10
13
 
11
14
  /** Execute JS calls. Rust controls admission and physical lifetime. */
12
15
  export class Calls {
16
+ readonly #rootCapabilities = new Map<number, Set<{ close(): void }>>();
13
17
  /** Connect JS callback execution to the session kernel. */
14
18
  constructor(readonly session: Session) {}
15
19
 
16
- /** Lazily mirror root cancellation into an AbortSignal. */
20
+ /** Invoke callbacks in a microtask and retain their actual promise until physical settlement. */
21
+ execute<T>(operation: () => Completion<T>): Promise<T> {
22
+ return Promise.resolve().then(operation);
23
+ }
24
+
25
+ /** Read the root mirror; foreign-issued roots are checked before its first creation. */
17
26
  signal(root: number): AbortSignal {
18
27
  const session = this.session;
19
28
  let controller = session.controllers.get(root);
@@ -32,6 +41,8 @@ export class Calls {
32
41
 
33
42
  /** Revoke claims and cancellation mirrors when either language ends a root. */
34
43
  releaseRoot(root: number): void {
44
+ for (const capability of this.#rootCapabilities.get(root) ?? []) capability.close();
45
+ this.#rootCapabilities.delete(root);
35
46
  for (const reference of this.session.rootReferences.get(root) ?? [])
36
47
  this.session.handles.release(reference);
37
48
  this.session.rootReferences.delete(root);
@@ -48,76 +59,225 @@ export class Calls {
48
59
  const session = this.session;
49
60
  const root =
50
61
  issuedRoot ??
51
- session.kernel.command<number>(cleanup ? KernelOp.CleanupRoot : KernelOp.Root, { principal });
62
+ session.kernel.command(cleanup ? KernelOp.CleanupRoot : KernelOp.Root, {
63
+ principal,
64
+ });
65
+ // A newly issued root is live and uncancelled on this synchronous path. Register its
66
+ // cancellation mirror before user code runs; admission still rechecks after every wait.
67
+ if (issuedRoot === undefined) session.controllers.set(root, new AbortController());
52
68
  const ctx = new Context(session, root);
53
69
  try {
54
70
  return await operation(ctx);
55
71
  } finally {
56
72
  this.releaseRoot(root);
57
73
  session.options.native?.rootEnded?.(root);
58
- if (!session.lifecycle.closedDiagnostics) session.kernel.command(KernelOp.EndRoot, { root });
74
+ if (!session.lifecycle.closedDiagnostics) session.lifecycle.endRoot(root);
59
75
  session.controllers.delete(root);
60
- session.lifecycle.flush();
61
76
  }
62
77
  }
63
78
 
64
- /** Execute one admitted service call and retain physical ownership. */
79
+ /** Let an application stop observing a call while its actual work remains owned. */
65
80
  async invoke(
66
81
  reference: ReferenceRecord,
67
82
  method: string,
68
83
  arguments_: unknown[],
69
84
  ctx: Context,
85
+ capture?: CapturedInvocation,
86
+ ): Promise<unknown> {
87
+ context(ctx, this.session);
88
+ checkSignal(ctx.signal);
89
+ return this.observe(
90
+ this.invokePhysical(reference, method, arguments_, ctx, capture),
91
+ ctx.signal,
92
+ );
93
+ }
94
+
95
+ /** Foreign callbacks retain their dependency until it physically settles, including on cancellation. */
96
+ async invokePhysical(
97
+ reference: ReferenceRecord,
98
+ method: string,
99
+ arguments_: unknown[],
100
+ ctx: Context,
101
+ capture?: CapturedInvocation,
70
102
  ): Promise<unknown> {
71
103
  const session = this.session;
72
- context(ctx, session);
73
- if (reference.released) throw new TembraError(Errors.Released.Reference);
74
- await reference.ready;
75
- const admission = session.options.native?.admit?.(reference.id, method, ctx);
76
- let invocation: Invocation;
77
- if (admission) invocation = admission.call;
78
- else {
79
- ctx.check();
80
- invocation = session.kernel.command<Invocation>(KernelOp.BeginCall, {
81
- reference: reference.id,
82
- root: ctx.root,
83
- context: ctx.frame || undefined,
84
- method,
85
- });
104
+ try {
105
+ context(ctx, session);
106
+ if (reference.released) throw new TembraError(Errors.Released.Reference);
107
+ await this.observe(reference.ready, ctx.signal);
108
+ const admission = session.options.native?.admit?.(reference.id, method, ctx);
109
+ let invocation: Invocation;
110
+ if (admission) invocation = admission.call;
111
+ else
112
+ // One bounded exchange rechecks the caller's context, then admits the call.
113
+ invocation = session.kernel.command(KernelOp.AdmitCall, {
114
+ reference: reference.id,
115
+ root: ctx.root,
116
+ parent: ctx.invocation?.id,
117
+ context: ctx.frame || undefined,
118
+ method,
119
+ });
120
+ const entered = new Context(session, ctx.root, invocation, ctx.frame);
121
+ const physical = session.track(
122
+ (async () => {
123
+ const sampled = session.telemetry?.sample();
124
+ const started = sampled ? session.now() : 0;
125
+ let outcome: Outcome = Outcome.Ok;
126
+ let retainedSource: Promise<void> | undefined;
127
+ let retained: Promise<void> | undefined;
128
+ let physicalFailure: { error: unknown } | undefined;
129
+ let published = false;
130
+ let capabilities: NonNullable<CapturedInvocation["capabilities"]> = [];
131
+ let reported = false;
132
+ const reportFailure = (error: unknown) => {
133
+ outcome = Outcome.Error;
134
+ if (reported) return;
135
+ reported = true;
136
+ const stream = capabilities.find((capability) => capability.kind === "bytes");
137
+ if (stream?.kind === "bytes")
138
+ stream.reportFailure(error, (cause) => session.report(cause));
139
+ else session.report(error);
140
+ };
141
+ const retain = (actual: Promise<void>) => {
142
+ if (retainedSource) {
143
+ if (retainedSource !== actual)
144
+ throw new Error(
145
+ "One prepared invocation cannot retain different physical operations",
146
+ );
147
+ return;
148
+ }
149
+ retainedSource = actual;
150
+ // Observe rejection immediately, while keeping the invocation and any resource loan
151
+ // until both provider completion and processing of its bounded head are finished.
152
+ retained = actual.then(
153
+ () => {},
154
+ (error: unknown) => {
155
+ outcome = Outcome.Error;
156
+ physicalFailure = { error };
157
+ },
158
+ );
159
+ };
160
+ const finish = () => {
161
+ if (sampled)
162
+ session.telemetry!.record({
163
+ service: reference.address.service,
164
+ method,
165
+ root: invocation.root,
166
+ codeVersion: invocation.codeVersion,
167
+ duration: session.now() - started,
168
+ outcome,
169
+ });
170
+ session.lifecycle.finishCall(invocation.id);
171
+ };
172
+ let unlend: (() => void) | undefined;
173
+ try {
174
+ const loan = capture?.receiver?.lend();
175
+ unlend = loan;
176
+ const native = session.options.native;
177
+ if (native && (admission?.native ?? native.hasOrb(invocation.orb))) {
178
+ if (
179
+ capture &&
180
+ (!capture.dataResult || capture.receiver || capture.arguments?.owners.length)
181
+ )
182
+ throw new Error("Provider does not support the matching WIT capability signature");
183
+ return await native.invoke(invocation, arguments_, entered);
184
+ }
185
+ const object = session.objects.get(invocation.object);
186
+ const environment = object?.versions.get(invocation.orb);
187
+ const handle =
188
+ environment?.orb.definition.services?.[reference.address.service]?.methods[method];
189
+ if (!environment || !handle) throw new TembraError(Errors.Gone.Implementation);
190
+ const prepared = capture && capturedMethod(handle, capture.signature);
191
+ if (prepared) {
192
+ // This channel never enters user arguments. A trusted intermediary cannot forward it.
193
+ const output = await this.execute(() =>
194
+ prepared.invoke(
195
+ environment.value,
196
+ entered,
197
+ capture!.input,
198
+ loan?.receiver,
199
+ retain,
200
+ capture!.arguments,
201
+ ),
202
+ );
203
+ if (output instanceof Encoded) capture!.output = output;
204
+ else {
205
+ capabilities = output.capabilities ?? [];
206
+ published = true;
207
+ // The bounded outcome reports failures promptly; it never substitutes for
208
+ // actual task exit once the prepared backend registered physical retention.
209
+ if (output.finished) {
210
+ session.track(
211
+ output.finished.catch((error: unknown) => {
212
+ reportFailure(error);
213
+ throw error;
214
+ }),
215
+ );
216
+ if (!retainedSource) {
217
+ for (const capability of capabilities) capability.close();
218
+ throw new Error(
219
+ "A prepared continuation must retain its actual physical operation",
220
+ );
221
+ }
222
+ }
223
+ try {
224
+ checkSignal(entered.signal);
225
+ for (const capability of capabilities) {
226
+ if (capability.kind === "resource") capability.anchor(session, reference);
227
+ else {
228
+ capability.bind(entered);
229
+ let owned = this.#rootCapabilities.get(entered.root);
230
+ if (!owned) this.#rootCapabilities.set(entered.root, (owned = new Set()));
231
+ owned.add(capability);
232
+ }
233
+ }
234
+ capture!.output = output.value;
235
+ capture!.capabilities = capabilities;
236
+ } catch (error) {
237
+ for (const capability of capabilities) capability.close();
238
+ throw error;
239
+ }
240
+ }
241
+ return undefined;
242
+ }
243
+ if (
244
+ capture &&
245
+ (!capture.dataResult || capture.receiver || capture.arguments?.owners.length)
246
+ )
247
+ throw new Error("Provider does not support the matching WIT capability signature");
248
+ const data = capturedDataMethod(handle);
249
+ return await this.execute(() =>
250
+ data
251
+ ? data(environment.value, entered, arguments_, retain)
252
+ : handle(environment.value, entered, ...arguments_),
253
+ );
254
+ } catch (error) {
255
+ outcome = Outcome.Error;
256
+ throw error;
257
+ } finally {
258
+ if (retained) {
259
+ session.track(
260
+ retained
261
+ .then(() => {
262
+ if (published && physicalFailure) reportFailure(physicalFailure.error);
263
+ })
264
+ .finally(() => {
265
+ unlend?.();
266
+ finish();
267
+ }),
268
+ );
269
+ } else {
270
+ unlend?.();
271
+ finish();
272
+ }
273
+ }
274
+ })(),
275
+ );
276
+ return await physical;
277
+ } finally {
278
+ if (capture?.arguments && !capture.arguments.accepted)
279
+ for (const owner of capture.arguments.owners) owner.close();
86
280
  }
87
- const entered = new Context(session, ctx.root, invocation, ctx.frame);
88
- const physical = session.track(
89
- (async () => {
90
- const sampled = session.telemetry?.sample();
91
- const started = sampled ? session.now() : 0;
92
- let outcome: Outcome = Outcome.Ok;
93
- try {
94
- const native = session.options.native;
95
- if (native && (admission?.native ?? native.hasOrb(invocation.orb)))
96
- return await native.invoke(invocation, arguments_, entered);
97
- const object = session.objects.get(invocation.object);
98
- const environment = object?.versions.get(invocation.orb);
99
- const handle =
100
- environment?.orb.definition.services?.[reference.address.service]?.methods[method];
101
- if (!environment || !handle) throw new TembraError(Errors.Gone.Implementation);
102
- return await handle(environment.value, entered, ...arguments_);
103
- } catch (error) {
104
- outcome = Outcome.Error;
105
- throw error;
106
- } finally {
107
- if (sampled)
108
- session.telemetry!.record({
109
- service: reference.address.service,
110
- method,
111
- root: invocation.root,
112
- codeVersion: invocation.codeVersion,
113
- duration: session.now() - started,
114
- outcome,
115
- });
116
- session.lifecycle.finishCall(invocation.id);
117
- }
118
- })(),
119
- );
120
- return this.observe(physical, ctx.signal);
121
281
  }
122
282
 
123
283
  /** Fresh callback roots inherit owner identity; supplied roots retain the caller's authority. */
@@ -129,7 +289,7 @@ export class Calls {
129
289
  ): Promise<T> {
130
290
  const session = this.session;
131
291
  const execute = async (ctx: Context) => {
132
- const invocation = session.kernel.command<Invocation>(KernelOp.BeginOperation, {
292
+ const invocation = session.kernel.command(KernelOp.BeginOperation, {
133
293
  orb: environment.orb.info.id,
134
294
  root: ctx.root,
135
295
  context: ctx.frame || undefined,
@@ -137,7 +297,9 @@ export class Calls {
137
297
  ...(environment.object ? { object: environment.object.id } : {}),
138
298
  });
139
299
  try {
140
- return await handle(new Context(session, ctx.root, invocation, ctx.frame));
300
+ return await this.execute(() =>
301
+ handle(new Context(session, ctx.root, invocation, ctx.frame)),
302
+ );
141
303
  } finally {
142
304
  session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
143
305
  session.lifecycle.flush();
@@ -150,7 +312,7 @@ export class Calls {
150
312
 
151
313
  /** Stop waiting on cancellation while physical work remains tracked. */
152
314
  async observe<T>(physical: Promise<T>, signal: AbortSignal): Promise<T> {
153
- if (signal.aborted) throw signal.reason;
315
+ if (signal.aborted) throw signal.reason ?? new TembraError(Errors.Cancelled.Root);
154
316
  let abort!: () => void;
155
317
  const cancelled = new Promise<never>((_, reject) => {
156
318
  abort = () => reject(signal.reason ?? new TembraError(Errors.Cancelled.Root));