@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
@@ -29,12 +29,15 @@ export class Context {
29
29
  /** Derive one binding without changing identity or lifetime. */
30
30
  with<T>(key: ContextKey<T>, value: T): Context {
31
31
  const source = key.source(value, this);
32
- const frame = this.session.kernel.command<number>(KernelOp.ContextDerive, {
32
+ const frame = this.session.kernel.command(KernelOp.ContextDerive, {
33
33
  root: this.root,
34
34
  context: this.frame,
35
35
  call: this.invocation?.id,
36
36
  key,
37
- ...(key.kind === ContextKind.Opaque ? { source } : { value }),
37
+ // Rust checks that the scalar matches the key kind.
38
+ ...(key.kind === ContextKind.Opaque
39
+ ? { source }
40
+ : { value: value as string | number | boolean }),
38
41
  });
39
42
  return new Context(this.session, this.root, this.invocation, frame);
40
43
  }
@@ -58,7 +61,7 @@ export class Context {
58
61
 
59
62
  /** Read the root identity from the kernel. */
60
63
  get principal(): string {
61
- return this.session.kernel.command<string>(KernelOp.RootPrincipal, { root: this.root });
64
+ return this.session.kernel.command(KernelOp.RootPrincipal, { root: this.root });
62
65
  }
63
66
 
64
67
  /** Read the shared cancellation signal for this root. */
@@ -68,10 +71,7 @@ export class Context {
68
71
 
69
72
  /** Reject a cancelled root or expired invocation. */
70
73
  check(): void {
71
- this.session.kernel.command(KernelOp.CheckContext, {
72
- root: this.root,
73
- call: this.invocation?.id,
74
- });
74
+ this.session.kernel.check(this.root, this.invocation?.id);
75
75
  }
76
76
 
77
77
  /** Cancel the root and dispatch its cancellation actions. */
@@ -1,3 +1,4 @@
1
+ import { disposeDefinitions } from "#tembra-adapters";
1
2
  import type { Action, Diagnostics } from "../bridge/kernel.ts";
2
3
  import { ActionType, KernelOp, OwnerKind } from "../bridge/protocol.ts";
3
4
  import { TembraError } from "../error.ts";
@@ -26,7 +27,7 @@ export class Lifecycle {
26
27
  this.#flushing = true;
27
28
  try {
28
29
  for (;;) {
29
- const actions = initial ?? this.session.kernel.command<Action[]>(KernelOp.Drain);
30
+ const actions = initial ?? this.session.kernel.command(KernelOp.Drain);
30
31
  initial = undefined;
31
32
  if (!actions.length) break;
32
33
  for (const action of actions) {
@@ -43,21 +44,34 @@ export class Lifecycle {
43
44
  }
44
45
  }
45
46
 
46
- /** Compose kernel finish bookkeeping through the embedded adapter when available. */
47
+ /** End a logical root and dispatch its resulting cleanup without extra drain/deadline queries. */
48
+ endRoot(root: number): void {
49
+ if (this.#flushing) {
50
+ this.session.kernel.command(KernelOp.EndRoot, { root });
51
+ return;
52
+ }
53
+ const batch = this.session.kernel.command(KernelOp.EndRootBatch, { root });
54
+ if (batch.actions.length) this.flush(batch.actions);
55
+ else this.scheduleLinger(batch.deadline);
56
+ }
57
+
58
+ /** Finish a call in one bounded kernel exchange: tick, finish, drain and next deadline. */
47
59
  finishCall(call: number): void {
48
60
  const session = this.session;
49
- if (!this.#flushing && session.options.native?.finish) {
50
- const batch = session.options.native.finish(call, session.now());
51
- if (!batch.actions.length) {
52
- this.scheduleLinger(batch.deadline);
53
- return;
54
- }
55
- this.flush(batch.actions);
61
+ if (this.#flushing) {
62
+ // The active flush drains these actions in order; do not dispatch them reentrantly.
63
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
64
+ session.kernel.command(KernelOp.FinishCall, { call });
56
65
  return;
57
66
  }
58
- session.kernel.command(KernelOp.Tick, { now: session.now() });
59
- session.kernel.command(KernelOp.FinishCall, { call });
60
- this.flush();
67
+ const batch = session.options.native?.finish
68
+ ? session.options.native.finish(call, session.now())
69
+ : session.kernel.command(KernelOp.FinishCallBatch, { call, now: session.now() });
70
+ if (!batch.actions.length) {
71
+ this.scheduleLinger(batch.deadline);
72
+ return;
73
+ }
74
+ this.flush(batch.actions);
61
75
  }
62
76
 
63
77
  /** Execute one action using its owning JS module. */
@@ -134,7 +148,7 @@ export class Lifecycle {
134
148
  object.disposing ??= (async () => {
135
149
  const errors: unknown[] = [];
136
150
  await object.activation.catch(() => {});
137
- const scopes = session.kernel.command<number[]>(KernelOp.ScopesForOwner, {
151
+ const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
138
152
  owner: { kind: OwnerKind.Object, id },
139
153
  });
140
154
  try {
@@ -161,9 +175,7 @@ export class Lifecycle {
161
175
  const session = this.session;
162
176
  if (session.closing) return;
163
177
  const deadline =
164
- (known === undefined
165
- ? session.kernel.command<number | null>(KernelOp.NextDeadline)
166
- : known) ?? undefined;
178
+ (known === undefined ? session.kernel.command(KernelOp.NextDeadline) : known) ?? undefined;
167
179
  if (deadline === this.#lingerDeadline) return;
168
180
  if (this.#linger !== undefined) clearTimeout(this.#linger);
169
181
  this.#linger = undefined;
@@ -187,7 +199,7 @@ export class Lifecycle {
187
199
  const session = this.session;
188
200
  if (this.#finalDiagnostics) return this.#finalDiagnostics;
189
201
  return {
190
- ...session.kernel.command<Diagnostics>(KernelOp.Diagnostics),
202
+ ...session.kernel.command(KernelOp.Diagnostics),
191
203
  values: session.values.size,
192
204
  pendingJobs: session.jobs.size,
193
205
  };
@@ -215,6 +227,13 @@ export class Lifecycle {
215
227
  session.kernel.command(KernelOp.FinishClose);
216
228
  session.values.clear();
217
229
  session.handles.clear();
230
+ try {
231
+ await disposeDefinitions(
232
+ [...session.orbs.records.values()].map((record) => record.definition),
233
+ );
234
+ } catch (error) {
235
+ session.cleanupErrors.push(error);
236
+ }
218
237
  session.orbs.records.clear();
219
238
  session.scopes.clear();
220
239
  this.#finalDiagnostics = this.diagnostics();
@@ -1,8 +1,27 @@
1
+ import {
2
+ captureEnvironment,
3
+ admitFactory,
4
+ disposeDefinitions,
5
+ discardDefinitions,
6
+ prepareDefinitions,
7
+ isolate,
8
+ isolatedRevision,
9
+ signature,
10
+ signatures,
11
+ type AdaptedHostOptions,
12
+ type AdaptedService,
13
+ type AdaptedOrb,
14
+ } from "#tembra-adapters";
1
15
  import { Declaration } from "../authoring/declaration.ts";
2
16
  import { orb } from "../authoring/orb.ts";
3
- import type { ContributionHandler, OrbDefinition, Participant } from "../authoring/types.ts";
17
+ import type {
18
+ ContributionHandler,
19
+ OrbDefinition,
20
+ OrbInput,
21
+ Participant,
22
+ } from "../authoring/types.ts";
4
23
  import { Lifetime } from "../bridge/identifiers.ts";
5
- import type { HookObservation, KernelOrb, Reload } from "../bridge/kernel.ts";
24
+ import type { OrbDeclaration, Reload } from "../bridge/kernel.ts";
6
25
  import { EnvironmentPhase, KernelOp, OwnerKind } from "../bridge/protocol.ts";
7
26
  import { refuse, TembraError } from "../error.ts";
8
27
  import { Errors } from "../errors.ts";
@@ -22,10 +41,10 @@ export class Orbs {
22
41
  /** Capture definitions and encode their kernel-owned contracts. */
23
42
  declarations(definitions: readonly OrbDefinition[]): {
24
43
  definitions: OrbDefinition[];
25
- metadata: unknown[];
44
+ metadata: OrbDeclaration[];
26
45
  } {
27
46
  const captured = definitions.map((definition) => orb(definition));
28
- const current = this.session.kernel.command<KernelOrb[]>(KernelOp.Orbs);
47
+ const current = this.session.kernel.command(KernelOp.Orbs);
29
48
  const lookup = (name: string) => captured.find((f) => f.name === name);
30
49
  const metadata = captured.map((definition) => {
31
50
  if (
@@ -49,7 +68,12 @@ export class Orbs {
49
68
  services:
50
69
  requirement.services ??
51
70
  (requirement.methods ? { [service!]: requirement.methods } : {}),
71
+ signatures:
72
+ (requirement as typeof requirement & { [signatures]?: Record<string, string> })[
73
+ signatures
74
+ ] ?? {},
52
75
  hooks: requirement.hooks ?? [],
76
+ hookSignatures: requirement.hookSignatures ?? {},
53
77
  };
54
78
  });
55
79
  for (const [alias, hooks] of Object.entries(definition.contributes ?? {})) {
@@ -67,9 +91,17 @@ export class Orbs {
67
91
  apiVersion: definition.apiVersion,
68
92
  requires,
69
93
  hooks: Object.keys(definition.hooks ?? {}),
94
+ hookSignatures: Object.fromEntries(
95
+ Object.entries(definition.hooks ?? {}).flatMap(([name, hook]) => {
96
+ const prepared = (hook as import("./adapters.ts").AdaptedHook)[signature];
97
+ return prepared ? [[name, prepared]] : [];
98
+ }),
99
+ ),
100
+ isolated: (definition as AdaptedOrb)[isolatedRevision] === true,
70
101
  services: Object.entries(definition.services ?? {}).map(([name, service]) => ({
71
102
  name,
72
103
  methods: Object.keys(service.methods),
104
+ signature: (service as AdaptedService)[signature],
73
105
  lifetime: service.lifetime ?? Lifetime.Referenced,
74
106
  linger: service.linger ?? 0,
75
107
  })),
@@ -79,15 +111,25 @@ export class Orbs {
79
111
  }
80
112
 
81
113
  /** Commit new orb metadata before opening its scopes. */
82
- async install(definitions: readonly OrbDefinition[]): Promise<void> {
83
- const current = this.session.kernel.command<KernelOrb[]>(KernelOp.Orbs);
84
- if (definitions.some((f) => current.some((installed) => installed.name === f.name)))
85
- refuse(Errors.Invalid.OrbInstalled, "Use reload to replace an installed orb");
86
- const prepared = this.declarations(definitions);
87
- const reload = this.session.kernel.command<Reload>(KernelOp.Prepare, {
88
- orbs: prepared.metadata,
89
- });
90
- this.session.kernel.command(KernelOp.Commit, { ticket: reload.id });
114
+ async install(definitions: readonly OrbInput[]): Promise<void> {
115
+ const candidates = prepareDefinitions(
116
+ definitions,
117
+ (this.session.options as AdaptedHostOptions)[isolate],
118
+ );
119
+ const materialized = Array.isArray(candidates) ? candidates : await candidates;
120
+ let prepared: ReturnType<Orbs["declarations"]>;
121
+ let reload: Reload;
122
+ try {
123
+ if (this.session.closing) throw new TembraError(Errors.Closed.Host);
124
+ const current = this.session.kernel.command(KernelOp.Orbs);
125
+ if (materialized.some((candidate) => current.some((orb) => orb.name === candidate.name)))
126
+ refuse(Errors.Invalid.OrbInstalled, "Use reload to replace an installed orb");
127
+ prepared = this.declarations(materialized);
128
+ reload = this.session.kernel.command(KernelOp.Prepare, { orbs: prepared.metadata });
129
+ this.session.kernel.command(KernelOp.Commit, { ticket: reload.id });
130
+ } catch (error) {
131
+ return discardDefinitions(materialized, error);
132
+ }
91
133
  const records = reload.orbs.map((info) => ({
92
134
  info,
93
135
  definition: prepared.definitions.find((f) => f.name === info.name)!,
@@ -107,23 +149,14 @@ export class Orbs {
107
149
  }
108
150
 
109
151
  /** Declare one shared scope for this orb version. */
110
- scope(record: OrbRecord): Environment {
152
+ scope(record: OrbRecord): Environment | Promise<Environment> {
111
153
  if (record.scope) return record.scope;
112
154
  const environment = this.session.scopes.environment(
113
155
  { kind: OwnerKind.Orb, id: record.info.owner },
114
156
  record,
115
157
  );
116
158
  record.scope = environment;
117
- try {
118
- const value = record.definition.create?.(new Declaration(this.session, environment)) ?? {};
119
- if (value && typeof (value as { then?: unknown }).then === "function")
120
- refuse(Errors.Invalid.AsyncFactory);
121
- environment.value = value;
122
- } finally {
123
- environment.phase = EnvironmentPhase.Prepared;
124
- this.session.programs.register(environment);
125
- }
126
- return environment;
159
+ return captureEnvironment(record.definition, new Declaration(this.session, environment));
127
160
  }
128
161
 
129
162
  /** Share pending activation and clean up failed orb scopes. */
@@ -135,7 +168,14 @@ export class Orbs {
135
168
  try {
136
169
  await this.session.scopes.readyHostScope();
137
170
  if (record.scope?.phase === EnvironmentPhase.Closed) delete record.scope;
138
- const scope = this.scope(record);
171
+ const release = await (record.definition as AdaptedOrb)[admitFactory]?.();
172
+ let scope: Environment;
173
+ try {
174
+ const prepared = this.scope(record);
175
+ scope = prepared instanceof Promise ? await prepared : prepared;
176
+ } finally {
177
+ release?.();
178
+ }
139
179
  await this.session.programs.activate(scope.id);
140
180
  } catch (error) {
141
181
  if (record.scope) {
@@ -160,13 +200,10 @@ export class Orbs {
160
200
  const requirement = record.definition.requires![alias]!;
161
201
  const target = requirement.orb ?? alias;
162
202
  for (const [hook, contribution] of Object.entries(hooks)) {
163
- const operation = this.session.kernel.command<number>(KernelOp.Allocate);
203
+ const operation = this.session.kernel.command(KernelOp.Allocate);
164
204
  const key = JSON.stringify([record.info.name, target, hook]);
165
205
  if (!this.#ordinals.has(key))
166
- this.#ordinals.set(
167
- key,
168
- this.session.kernel.command<number>(KernelOp.ContributionOrdinal),
169
- );
206
+ this.#ordinals.set(key, this.session.kernel.command(KernelOp.ContributionOrdinal));
170
207
  this.operations.set(operation, {
171
208
  orb: record,
172
209
  handler: typeof contribution === "function" ? contribution : contribution.handle,
@@ -177,7 +214,7 @@ export class Orbs {
177
214
  hook,
178
215
  operation,
179
216
  priority: typeof contribution === "function" ? 0 : (contribution.priority ?? 0),
180
- ordinal: this.#ordinals.get(key),
217
+ ordinal: this.#ordinals.get(key)!,
181
218
  });
182
219
  }
183
220
  }
@@ -193,7 +230,7 @@ export class Orbs {
193
230
  context = checkedContext(context, this.session);
194
231
  const definition = environment.orb.definition.hooks?.[name];
195
232
  if (!definition) refuse(Errors.Invalid.Hook, name);
196
- const plan = this.session.kernel.command<number[]>(KernelOp.HookPlan, {
233
+ const plan = this.session.kernel.command(KernelOp.HookPlan, {
197
234
  root: context.root,
198
235
  target: environment.orb.info.name,
199
236
  hook: name,
@@ -219,7 +256,7 @@ export class Orbs {
219
256
  const definition = environment.orb.definition.hooks?.[name];
220
257
  if (!definition) refuse(Errors.Invalid.Hook, name);
221
258
  if (!source.invocation) throw new TembraError(Errors.Forbidden.ObservationSource);
222
- const admitted = this.session.kernel.command<HookObservation>(KernelOp.BeginHookObservation, {
259
+ const admitted = this.session.kernel.command(KernelOp.BeginHookObservation, {
223
260
  source: source.invocation.id,
224
261
  orb: environment.orb.info.id,
225
262
  operation,
@@ -277,14 +314,19 @@ export class Orbs {
277
314
 
278
315
  /** Clean up a retired version before removing its callbacks. */
279
316
  retire(id: number): void {
280
- const scopes = this.session.kernel.command<number[]>(KernelOp.ScopesForOrb, { orb: id });
317
+ const scopes = this.session.kernel.command(KernelOp.ScopesForOrb, { orb: id });
281
318
  const cleanup = this.session.programs.cleanupScopes(scopes);
282
319
  this.session.track(
283
- cleanup.then(() => {
284
- for (const [operation, contribution] of this.operations)
285
- if (contribution.orb.info.id === id) this.operations.delete(operation);
286
- this.records.delete(id);
287
- this.#ready.delete(id);
320
+ cleanup.finally(async () => {
321
+ try {
322
+ const record = this.records.get(id);
323
+ if (record) await disposeDefinitions([record.definition]);
324
+ } finally {
325
+ for (const [operation, contribution] of this.operations)
326
+ if (contribution.orb.info.id === id) this.operations.delete(operation);
327
+ this.records.delete(id);
328
+ this.#ready.delete(id);
329
+ }
288
330
  }),
289
331
  true,
290
332
  );
@@ -1,3 +1,4 @@
1
+ import { validateEnvironment, releaseEnvironment, type AdaptedOrb } from "#tembra-adapters";
1
2
  import { Code } from "../bridge/identifiers.ts";
2
3
  import {
3
4
  ActionType,
@@ -52,21 +53,21 @@ export class Programs {
52
53
 
53
54
  /** Activate an already registered scope and wait for its program. */
54
55
  activate(scope: number): Promise<void> {
55
- return this.run(this.session.kernel.command<number>(KernelOp.ScopeActivate, { scope }));
56
+ return this.run(this.session.kernel.command(KernelOp.ScopeActivate, { scope }));
56
57
  }
57
58
 
58
59
  /** Ask the kernel to retire existing scopes and await completion. */
59
60
  cleanup(environments: readonly Environment[]): Promise<void> {
60
61
  const scopes = environments
61
62
  .map((environment) => environment.id)
62
- .filter((scope) => this.session.kernel.command<boolean>(KernelOp.ScopeExists, { scope }));
63
+ .filter((scope) => this.session.kernel.command(KernelOp.ScopeExists, { scope }));
63
64
  return this.cleanupScopes(scopes);
64
65
  }
65
66
 
66
67
  /** Run cleanup for kernel-issued scope identities without resolving JS callbacks. */
67
68
  cleanupScopes(scopes: readonly number[]): Promise<void> {
68
69
  return scopes.length
69
- ? this.run(this.session.kernel.command<number>(KernelOp.ScopesCleanup, { scopes }))
70
+ ? this.run(this.session.kernel.command(KernelOp.ScopesCleanup, { scopes }))
70
71
  : Promise.resolve();
71
72
  }
72
73
 
@@ -150,8 +151,9 @@ export class Programs {
150
151
  } else {
151
152
  const completion = this.#pending.get(action.id);
152
153
  this.#pending.delete(action.id);
153
- if (action.error) {
154
- const error = new TembraError(action.error);
154
+ const failed = action.type === ActionType.ProgramComplete ? action.error : null;
155
+ if (failed) {
156
+ const error = new TembraError(failed);
155
157
  if (completion) completion.reject(error);
156
158
  else {
157
159
  this.session.cleanupErrors.push(error);
@@ -170,8 +172,9 @@ export class Programs {
170
172
 
171
173
  /** Execute a language effect without deciding lifecycle order. */
172
174
  private async execute(effect: Effect): Promise<number | void> {
173
- const environment = effect.scope === undefined ? undefined : this.scopes.get(effect.scope);
174
- if (effect.scope !== undefined && !environment && this.session.options.native)
175
+ const scope = "scope" in effect ? effect.scope : undefined;
176
+ const environment = scope === undefined ? undefined : this.scopes.get(scope);
177
+ if (scope !== undefined && !environment && this.session.options.native)
175
178
  return this.session.options.native.effect(effect);
176
179
  if (
177
180
  (effect.type === EffectType.Close || effect.type === EffectType.Open) &&
@@ -202,6 +205,10 @@ export class Programs {
202
205
  }
203
206
  case EffectType.Validate:
204
207
  validate(this.session.value(effect.value!), environment!.state!.options);
208
+ await (environment!.orb.definition as AdaptedOrb)[validateEnvironment]?.(
209
+ environment!,
210
+ this.session.value(effect.value!),
211
+ );
205
212
  break;
206
213
  case EffectType.Initialize:
207
214
  return this.candidate(environment!, environment!.state!.initial);
@@ -255,10 +262,11 @@ export class Programs {
255
262
  environment.phase = EnvironmentPhase.Closed;
256
263
  if (environment.object) environment.object.versions.delete(environment.orb.info.id);
257
264
  this.scopes.delete(environment.id);
265
+ await (environment.orb.definition as AdaptedOrb)[releaseEnvironment]?.(environment);
258
266
  break;
259
267
  }
260
268
  default:
261
- throw new TembraError(Errors.Unsupported.EngineEffect, effect.type);
269
+ throw new TembraError(Errors.Unsupported.EngineEffect, (effect as Effect).type);
262
270
  }
263
271
  }
264
272
 
@@ -5,7 +5,7 @@ import type {
5
5
  DynamicReference,
6
6
  ServiceDefinition,
7
7
  } from "../authoring/types.ts";
8
- import { Code, Status } from "../bridge/identifiers.ts";
8
+ import { Code, Reason, Status } from "../bridge/identifiers.ts";
9
9
  import type { Acquisition, KernelOrb } from "../bridge/kernel.ts";
10
10
  import { KernelOp } from "../bridge/protocol.ts";
11
11
  import { refuse, TembraError } from "../error.ts";
@@ -23,6 +23,13 @@ const finalizer =
23
23
  held.session.deref()?.handles.release(held.id),
24
24
  );
25
25
 
26
+ /** Resolve an SDK-issued handle for the existing portable WIT client lane. */
27
+ export function referenceOrigin(value: object): { session: Session; record: ReferenceRecord } {
28
+ const issued = references.get(value);
29
+ if (!issued) refuse(Errors.Invalid.Reference, "An issued local reference is required");
30
+ return issued;
31
+ }
32
+
26
33
  /** JS reference handles and per-object visibility. */
27
34
  export class References {
28
35
  /** Retain handle metadata and index references by object. */
@@ -112,12 +119,8 @@ export class References {
112
119
  const session = this.session;
113
120
  if (ctx) context(ctx, session);
114
121
  session.kernel.command(KernelOp.Tick, { now: session.now() });
115
- const address: Address = {
116
- service,
117
- key: typeof key === "string" ? [key] : [...key],
118
- principal: options.principal ?? ctx?.principal ?? session.principal,
119
- };
120
- const acquired = session.kernel.command<Acquisition>(KernelOp.Acquire, {
122
+ const address = this.address(service, key, options, ctx);
123
+ const acquired = session.kernel.command(KernelOp.Acquire, {
121
124
  ...address,
122
125
  apiVersion: options.apiVersion ?? 0,
123
126
  methods: options.methods ?? [],
@@ -254,14 +257,105 @@ export class References {
254
257
  return proxy;
255
258
  }
256
259
 
257
- /** Release the acquired claim if activation fails. */
260
+ /** The canonical service name and effective options of an acquisition. */
261
+ private service(
262
+ definition: string | ServiceDefinition,
263
+ options: AcquisitionOptions,
264
+ ): { service: string; options: AcquisitionOptions } {
265
+ if (typeof definition === "string") return { service: definition, options };
266
+ const acquisition = serviceAcquisition(definition, options);
267
+ return { service: acquisition.name, options: acquisition.options };
268
+ }
269
+
270
+ /** The address an acquisition targets; the principal defaults to the caller's root. */
271
+ private address(
272
+ service: string,
273
+ key: string | readonly string[],
274
+ options: AcquisitionOptions,
275
+ ctx?: Context,
276
+ ): Address {
277
+ return {
278
+ service,
279
+ key: typeof key === "string" ? [key] : [...key],
280
+ principal: options.principal ?? ctx?.principal ?? this.session.principal,
281
+ };
282
+ }
283
+
284
+ /**
285
+ * The physical disposal of the exact local instance a refusal names: the kernel refused
286
+ * because the previous instance at this address is still closing. Only a concrete matching
287
+ * object's `disposing` promise qualifies; anything else keeps the original refusal.
288
+ */
289
+ private closing(
290
+ error: unknown,
291
+ definition: string | ServiceDefinition,
292
+ key: string | readonly string[],
293
+ options: AcquisitionOptions,
294
+ ctx?: Context,
295
+ ): Promise<void> | undefined {
296
+ if (
297
+ !(error instanceof TembraError) ||
298
+ error.code !== Code.Unavailable ||
299
+ error.reason !== Reason.Disposing
300
+ )
301
+ return undefined;
302
+ let address: Address;
303
+ try {
304
+ const resolved = this.service(definition, options);
305
+ address = this.address(resolved.service, key, resolved.options, ctx);
306
+ } catch {
307
+ // An ended root has no address to wait for; the original refusal stands.
308
+ return undefined;
309
+ }
310
+ for (const object of this.session.objects.values()) {
311
+ const previous = object.address;
312
+ if (
313
+ object.disposing &&
314
+ previous.service === address.service &&
315
+ previous.principal === address.principal &&
316
+ previous.key.length === address.key.length &&
317
+ previous.key.every((part, index) => part === address.key[index])
318
+ )
319
+ return object.disposing;
320
+ }
321
+ return undefined;
322
+ }
323
+
324
+ /**
325
+ * Acquire and wait for activation; release the acquired claim if activation fails.
326
+ *
327
+ * Unlike the synchronous `hold`, an acquisition refused only because the previous instance
328
+ * at the same address is still closing waits for that instance's physical disposal, then
329
+ * acquires anew with every check repeated. The old instance is never revived or overlapped
330
+ * and no factory runs early. The caller's root cancellation ends the wait, never the
331
+ * teardown. A failed disposal is recorded and reported by the lifecycle that owns it; the
332
+ * caller then acquires a fresh instance. Every other refusal is returned at once.
333
+ */
258
334
  async get(
259
335
  service: string | ServiceDefinition,
260
336
  key: string | readonly string[],
261
337
  options: AcquisitionOptions = {},
262
338
  ctx?: Context,
263
339
  ): Promise<DynamicReference> {
264
- const reference = this.hold(service, key, options, ctx);
340
+ let reference: DynamicReference;
341
+ let waited: Promise<void> | undefined;
342
+ for (;;) {
343
+ try {
344
+ reference = this.hold(service, key, options, ctx);
345
+ break;
346
+ } catch (error) {
347
+ const closing = this.closing(error, service, key, options, ctx);
348
+ // Each wait is for a new concrete disposal; nothing is retried without one.
349
+ if (!closing || closing === waited) throw error;
350
+ waited = closing;
351
+ const settled = closing.then(
352
+ () => {},
353
+ () => {},
354
+ );
355
+ if (ctx) await this.session.calls.observe(settled, ctx.signal);
356
+ else await settled;
357
+ }
358
+ }
265
359
  try {
266
360
  await reference.ready;
267
361
  return reference;
@@ -271,6 +365,29 @@ export class References {
271
365
  }
272
366
  }
273
367
 
368
+ /** Retain exactly this claim, without reacquisition or re-evaluating access policy. */
369
+ duplicate(original: ReferenceRecord): ReferenceRecord {
370
+ if (this.session.references.get(original.id) !== original || original.released)
371
+ throw new TembraError(Errors.Released.Reference);
372
+ const id = this.session.kernel.command(KernelOp.Duplicate, { reference: original.id });
373
+ const record: ReferenceRecord = {
374
+ ...original,
375
+ id,
376
+ address: { ...original.address, key: [...original.address.key] },
377
+ methods: new Set(original.methods),
378
+ requiredMethods: new Set(original.requiredMethods),
379
+ stateCleanups: new Set(),
380
+ nativeOwned: false,
381
+ released: false,
382
+ };
383
+ delete record.context;
384
+ this.session.references.set(id, record);
385
+ let owned = this.#byObject.get(record.object);
386
+ if (!owned) this.#byObject.set(record.object, (owned = new Set()));
387
+ owned.add(record);
388
+ return record;
389
+ }
390
+
274
391
  /** Require a reference issued by this session. */
275
392
  reference(value: unknown): ReferenceRecord {
276
393
  const issued = typeof value === "object" && value !== null ? references.get(value) : undefined;
@@ -285,7 +402,7 @@ export class References {
285
402
  if (definition) return definition;
286
403
  let metadata = this.#metadata.get(id);
287
404
  if (!metadata) {
288
- metadata = this.session.kernel.command<KernelOrb>(KernelOp.Orb, { id });
405
+ metadata = this.session.kernel.command(KernelOp.Orb, { id });
289
406
  this.#metadata.set(id, metadata);
290
407
  }
291
408
  return metadata;
@@ -342,7 +459,7 @@ export class References {
342
459
  /** Native claim release can precede its asynchronous metadata notification. */
343
460
  private claimExists(reference: number): boolean {
344
461
  try {
345
- const status = this.session.kernel.command<Status>(KernelOp.Status, { reference });
462
+ const status = this.session.kernel.command(KernelOp.Status, { reference });
346
463
  return status !== Status.Released && status !== Status.Gone;
347
464
  } catch (error) {
348
465
  if (