@syntropika/tembra-sdk 0.0.0-stage → 0.1.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 (130) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +47 -2
  3. package/dist/authoring/declaration.d.ts +47 -0
  4. package/dist/authoring/hooks.d.ts +11 -0
  5. package/dist/authoring/orb.d.ts +3 -0
  6. package/dist/authoring/types.d.ts +166 -0
  7. package/dist/bridge/identifiers.d.ts +207 -0
  8. package/dist/bridge/kernel.d.ts +117 -0
  9. package/dist/bridge/protocol.d.ts +181 -0
  10. package/dist/browser.d.ts +21 -0
  11. package/dist/browser.js +3282 -0
  12. package/dist/codec.d.ts +1 -0
  13. package/dist/codecs/json.d.ts +13 -0
  14. package/dist/codecs/msgpack.d.ts +3 -0
  15. package/dist/context-key.d.ts +35 -0
  16. package/dist/coordinator.d.ts +1 -0
  17. package/dist/coordinator.js +543 -0
  18. package/dist/embedded.d.ts +1 -0
  19. package/dist/embedded.js +1 -0
  20. package/dist/error.d.ts +13 -0
  21. package/dist/errors.d.ts +122 -0
  22. package/dist/hooks.d.ts +1 -0
  23. package/dist/host.d.ts +96 -0
  24. package/dist/host.js +3225 -0
  25. package/dist/identifiers.d.ts +1 -0
  26. package/dist/index.d.ts +12 -0
  27. package/dist/index.js +833 -0
  28. package/dist/infrastructure/coordinator.d.ts +13 -0
  29. package/dist/infrastructure/manager.d.ts +23 -0
  30. package/dist/infrastructure/rpc/channel.d.ts +52 -0
  31. package/dist/infrastructure/rpc/client.d.ts +20 -0
  32. package/dist/infrastructure/rpc/server.d.ts +10 -0
  33. package/dist/infrastructure/rpc/state.d.ts +16 -0
  34. package/dist/kernel.d.ts +1 -0
  35. package/dist/manager.d.ts +1 -0
  36. package/dist/manager.js +390 -0
  37. package/dist/msgpack.d.ts +1 -0
  38. package/dist/msgpack.js +635 -0
  39. package/dist/node.d.ts +14 -0
  40. package/dist/node.js +3283 -0
  41. package/dist/orb.d.ts +1 -0
  42. package/dist/protocol.d.ts +1 -0
  43. package/dist/rpc.d.ts +3 -0
  44. package/dist/rpc.js +1036 -0
  45. package/dist/runtime/activities.d.ts +30 -0
  46. package/dist/runtime/calls.d.ts +22 -0
  47. package/dist/runtime/context.d.ts +37 -0
  48. package/dist/runtime/declaration.d.ts +1 -0
  49. package/dist/runtime/lifecycle.d.ts +28 -0
  50. package/dist/runtime/orbs.d.ts +39 -0
  51. package/dist/runtime/programs.d.ts +31 -0
  52. package/dist/runtime/records.d.ts +107 -0
  53. package/dist/runtime/references.d.ts +38 -0
  54. package/dist/runtime/reload.d.ts +17 -0
  55. package/dist/runtime/resources.d.ts +24 -0
  56. package/dist/runtime/scopes.d.ts +35 -0
  57. package/dist/runtime/session.d.ts +69 -0
  58. package/dist/state/binding.d.ts +28 -0
  59. package/dist/state/selection.d.ts +21 -0
  60. package/dist/state/types.d.ts +35 -0
  61. package/dist/state.d.ts +2 -0
  62. package/dist/telemetry.d.ts +23 -0
  63. package/dist/telemetry.js +27 -0
  64. package/dist/tooling/build.d.ts +3 -0
  65. package/dist/tooling/index.d.ts +2 -0
  66. package/dist/tooling/index.js +181 -0
  67. package/dist/tooling/resolver.d.ts +5 -0
  68. package/dist/tooling/typecheck.d.ts +2 -0
  69. package/dist/tooling/types.d.ts +29 -0
  70. package/dist/types.d.ts +1 -0
  71. package/dist/values.d.ts +23 -0
  72. package/package.json +103 -4
  73. package/src/authoring/declaration.ts +220 -0
  74. package/src/authoring/hooks.ts +101 -0
  75. package/src/authoring/orb.ts +77 -0
  76. package/src/authoring/types.ts +212 -0
  77. package/src/bridge/identifiers.ts +212 -0
  78. package/src/bridge/kernel.ts +117 -0
  79. package/src/bridge/protocol.ts +193 -0
  80. package/src/browser.ts +59 -0
  81. package/src/codec.ts +1 -0
  82. package/src/codecs/json.ts +147 -0
  83. package/src/codecs/msgpack.ts +26 -0
  84. package/src/context-key.ts +94 -0
  85. package/src/coordinator.ts +1 -0
  86. package/src/embedded.ts +293 -0
  87. package/src/error.ts +50 -0
  88. package/src/errors.ts +237 -0
  89. package/src/hooks.ts +1 -0
  90. package/src/host.ts +142 -0
  91. package/src/identifiers.ts +1 -0
  92. package/src/index.ts +22 -0
  93. package/src/infrastructure/coordinator.ts +76 -0
  94. package/src/infrastructure/manager.ts +77 -0
  95. package/src/infrastructure/rpc/channel.ts +88 -0
  96. package/src/infrastructure/rpc/client.ts +161 -0
  97. package/src/infrastructure/rpc/server.ts +201 -0
  98. package/src/infrastructure/rpc/state.ts +70 -0
  99. package/src/kernel.ts +1 -0
  100. package/src/manager.ts +1 -0
  101. package/src/msgpack.ts +1 -0
  102. package/src/node.ts +53 -0
  103. package/src/orb.ts +1 -0
  104. package/src/protocol.ts +1 -0
  105. package/src/rpc.ts +3 -0
  106. package/src/runtime/activities.ts +197 -0
  107. package/src/runtime/calls.ts +165 -0
  108. package/src/runtime/context.ts +113 -0
  109. package/src/runtime/declaration.ts +1 -0
  110. package/src/runtime/lifecycle.ts +227 -0
  111. package/src/runtime/orbs.ts +292 -0
  112. package/src/runtime/programs.ts +274 -0
  113. package/src/runtime/records.ts +127 -0
  114. package/src/runtime/references.ts +398 -0
  115. package/src/runtime/reload.ts +161 -0
  116. package/src/runtime/resources.ts +157 -0
  117. package/src/runtime/scopes.ts +210 -0
  118. package/src/runtime/session.ts +181 -0
  119. package/src/state/binding.ts +157 -0
  120. package/src/state/selection.ts +122 -0
  121. package/src/state/types.ts +47 -0
  122. package/src/state.ts +2 -0
  123. package/src/telemetry.ts +45 -0
  124. package/src/tooling/build.ts +83 -0
  125. package/src/tooling/index.ts +8 -0
  126. package/src/tooling/resolver.ts +95 -0
  127. package/src/tooling/typecheck.ts +32 -0
  128. package/src/tooling/types.ts +32 -0
  129. package/src/types.ts +1 -0
  130. package/src/values.ts +85 -0
@@ -0,0 +1,3282 @@
1
+ // src/bridge/identifiers.ts
2
+ var Code = Object.freeze({
3
+ Invalid: "invalid",
4
+ Unavailable: "unavailable",
5
+ Released: "released",
6
+ Gone: "gone",
7
+ Expired: "expired",
8
+ Cancelled: "cancelled",
9
+ Forbidden: "forbidden",
10
+ Conflict: "conflict",
11
+ Unsupported: "unsupported",
12
+ Closed: "closed",
13
+ Exhausted: "exhausted"
14
+ });
15
+ var Reason = Object.freeze({
16
+ ActivationBusy: "activation_busy",
17
+ Address: "address",
18
+ AlreadyCommitted: "already_committed",
19
+ AmbiguousScope: "ambiguous_scope",
20
+ ApiVersion: "api_version",
21
+ Arguments: "arguments",
22
+ AsyncFactory: "async_factory",
23
+ AsyncState: "async_state",
24
+ Bigint: "bigint",
25
+ ByteResult: "byte_result",
26
+ Call: "call",
27
+ Callback: "callback",
28
+ CleanupBusy: "cleanup_busy",
29
+ Clock: "clock",
30
+ Codec: "codec",
31
+ Connection: "connection",
32
+ Context: "context",
33
+ Contribution: "contribution",
34
+ CoordinationLimits: "coordination_limits",
35
+ Deadline: "deadline",
36
+ Dependency: "dependency",
37
+ DependencyCycle: "dependency_cycle",
38
+ DependencyService: "dependency_service",
39
+ Disposing: "disposing",
40
+ Driver: "driver",
41
+ Duplicate: "duplicate",
42
+ DuplicateContribution: "duplicate_contribution",
43
+ DuplicateListener: "duplicate_listener",
44
+ DuplicateResource: "duplicate_resource",
45
+ DuplicateService: "duplicate_service",
46
+ EffectResults: "effect_results",
47
+ EffectsRunning: "effects_running",
48
+ EngineEffect: "engine_effect",
49
+ EventSource: "event_source",
50
+ ExclusiveDependent: "exclusive_dependent",
51
+ Executor: "executor",
52
+ Orb: "orb",
53
+ OrbGone: "orb_gone",
54
+ OrbInstalled: "orb_installed",
55
+ OrbScope: "orb_scope",
56
+ Factory: "factory",
57
+ FactoryExpired: "factory_expired",
58
+ FrameSize: "frame_size",
59
+ GateBusy: "gate_busy",
60
+ GateOrb: "gate_orb",
61
+ GateObject: "gate_object",
62
+ Hook: "hook",
63
+ HookDependency: "hook_dependency",
64
+ Hooks: "hooks",
65
+ HooksDisabled: "hooks_disabled",
66
+ Host: "host",
67
+ HostAddress: "host_address",
68
+ HostResource: "host_resource",
69
+ HostResourceReload: "host_resource_reload",
70
+ Identities: "identities",
71
+ Implementation: "implementation",
72
+ Invocation: "invocation",
73
+ Javascript: "javascript",
74
+ JsonAccessor: "json_accessor",
75
+ JsonCycle: "json_cycle",
76
+ JsonNumber: "json_number",
77
+ JsonSymbol: "json_symbol",
78
+ JsonTag: "json_tag",
79
+ JsonType: "json_type",
80
+ JsonValue: "json_value",
81
+ Lifetime: "lifetime",
82
+ Linger: "linger",
83
+ ListenerCallback: "listener_callback",
84
+ LiveConsumer: "live_consumer",
85
+ LiveReference: "live_reference",
86
+ LocalValue: "local_value",
87
+ Memory: "memory",
88
+ Metadata: "metadata",
89
+ MetadataSize: "metadata_size",
90
+ Method: "method",
91
+ MigrationGate: "migration_gate",
92
+ MigrationRequired: "migration_required",
93
+ MigrationValue: "migration_value",
94
+ MissingHook: "missing_hook",
95
+ MissingMethod: "missing_method",
96
+ NativeEffect: "native_effect",
97
+ NativeMethod: "native_method",
98
+ NativeObject: "native_object",
99
+ NativeService: "native_service",
100
+ Next: "next",
101
+ NextUsed: "next_used",
102
+ NotReady: "not_ready",
103
+ Object: "object",
104
+ ObjectState: "object_state",
105
+ ObservationSource: "observation_source",
106
+ ObservationAdmitted: "observation_admitted",
107
+ Opaque: "opaque",
108
+ Operation: "operation",
109
+ OperationOwner: "operation_owner",
110
+ Owner: "owner",
111
+ Payload: "payload",
112
+ PendingRequests: "pending_requests",
113
+ PrepareDeadline: "prepare_deadline",
114
+ Priority: "priority",
115
+ Program: "program",
116
+ ProgramPhase: "program_phase",
117
+ ProgramRunning: "program_running",
118
+ Reference: "reference",
119
+ ReloadAborted: "reload_aborted",
120
+ ReloadDeadline: "reload_deadline",
121
+ ReloadPreparing: "reload_preparing",
122
+ ReloadRunning: "reload_running",
123
+ ReloadTicket: "reload_ticket",
124
+ RemoteOpaque: "remote_opaque",
125
+ RemoteReferences: "remote_references",
126
+ Request: "request",
127
+ RequestIds: "request_ids",
128
+ Requires: "requires",
129
+ Resource: "resource",
130
+ ResourceDependencies: "resource_dependencies",
131
+ ResourceDependency: "resource_dependency",
132
+ ResourceHost: "resource_host",
133
+ ResourceInFactory: "resource_in_factory",
134
+ ResourceState: "resource_state",
135
+ ResourceVersion: "resource_version",
136
+ Result: "result",
137
+ RetainedVersions: "retained_versions",
138
+ RevisionExhausted: "revision_exhausted",
139
+ Root: "root",
140
+ Route: "route",
141
+ RpcFrame: "rpc_frame",
142
+ RpcOperation: "rpc_operation",
143
+ RpcRequest: "rpc_request",
144
+ RustType: "rust_type",
145
+ Scope: "scope",
146
+ ScopeClosed: "scope_closed",
147
+ ScopeOrb: "scope_orb",
148
+ ScopeOwner: "scope_owner",
149
+ ScopeResource: "scope_resource",
150
+ Serialization: "serialization",
151
+ Service: "service",
152
+ ServiceGone: "service_gone",
153
+ State: "state",
154
+ StateCycle: "state_cycle",
155
+ StateInitialized: "state_initialized",
156
+ StateOwner: "state_owner",
157
+ StateRevision: "state_revision",
158
+ StateValidation: "state_validation",
159
+ StateValue: "state_value",
160
+ StateVersion: "state_version",
161
+ Subscription: "subscription",
162
+ SubscriptionBusy: "subscription_busy",
163
+ SubscriptionIdle: "subscription_idle",
164
+ SubscriptionQueue: "subscription_queue",
165
+ SubscriptionSize: "subscription_size",
166
+ SubscriptionsDisabled: "subscriptions_disabled",
167
+ Superseded: "superseded",
168
+ Task: "task",
169
+ Telemetry: "telemetry",
170
+ UndeclaredDependency: "undeclared_dependency",
171
+ UndeclaredService: "undeclared_service",
172
+ UnknownService: "unknown_service",
173
+ UpgradeConflict: "upgrade_conflict",
174
+ Utf8: "utf8",
175
+ Value: "value",
176
+ ValueGone: "value_gone",
177
+ ValuesExhausted: "values_exhausted",
178
+ Views: "views"
179
+ });
180
+ var Lifetime = Object.freeze({
181
+ Referenced: "referenced",
182
+ Host: "host"
183
+ });
184
+ var Status = Object.freeze({
185
+ Loading: "loading",
186
+ Live: "live",
187
+ Released: "released",
188
+ Gone: "gone"
189
+ });
190
+ var ReloadStatus = Object.freeze({
191
+ Prepared: "prepared",
192
+ Committed: "committed",
193
+ Aborted: "aborted"
194
+ });
195
+ var HookCapability = Object.freeze({
196
+ Observe: "observe",
197
+ Transform: "transform",
198
+ Decide: "decide"
199
+ });
200
+
201
+ // src/errors.ts
202
+ function define(code, reason, message) {
203
+ return Object.freeze({ code, reason, message });
204
+ }
205
+ var Errors = Object.freeze({
206
+ Cancelled: Object.freeze({
207
+ EngineEffect: define(Code.Cancelled, Reason.EngineEffect, "The engine effect was cancelled"),
208
+ Request: define(Code.Cancelled, Reason.Request, "The request was cancelled"),
209
+ Resource: define(Code.Cancelled, Reason.Resource, "Resource opening was cancelled"),
210
+ Root: define(Code.Cancelled, Reason.Root, "The operation was cancelled"),
211
+ Task: define(Code.Cancelled, Reason.Task, "The task was cancelled")
212
+ }),
213
+ Closed: Object.freeze({
214
+ Host: define(Code.Closed, Reason.Host, "The host is closing")
215
+ }),
216
+ Conflict: Object.freeze({
217
+ AlreadyCommitted: define(Code.Conflict, Reason.AlreadyCommitted, "The replacement is already committed"),
218
+ Codec: define(Code.Conflict, Reason.Codec, "The Rust and JS host codecs must agree"),
219
+ PrepareDeadline: define(Code.Conflict, Reason.PrepareDeadline, "The preparation deadline expired"),
220
+ ReloadRunning: define(Code.Conflict, Reason.ReloadRunning, "A replacement is already running"),
221
+ ReloadTicket: define(Code.Conflict, Reason.ReloadTicket, "The replacement is no longer prepared")
222
+ }),
223
+ Exhausted: Object.freeze({
224
+ FrameSize: define(Code.Exhausted, Reason.FrameSize, "The frame exceeds the configured size limit"),
225
+ PendingRequests: define(Code.Exhausted, Reason.PendingRequests, "The pending request limit was reached"),
226
+ RemoteReferences: define(Code.Exhausted, Reason.RemoteReferences, "The remote reference limit was reached"),
227
+ RequestIds: define(Code.Exhausted, Reason.RequestIds, "Request identities are exhausted"),
228
+ SubscriptionQueue: define(Code.Exhausted, Reason.SubscriptionQueue, "The subscription queue is full")
229
+ }),
230
+ Expired: Object.freeze({
231
+ Next: define(Code.Expired, Reason.Next, "Continuation scope has ended")
232
+ }),
233
+ Forbidden: Object.freeze({
234
+ Context: define(Code.Forbidden, Reason.Context, "An issued context from this host is required"),
235
+ HostResource: define(Code.Forbidden, Reason.HostResource, "The host resource was not declared"),
236
+ Method: define(Code.Forbidden, Reason.Method, "The method is not allowed by this reference"),
237
+ ObservationSource: define(Code.Forbidden, Reason.ObservationSource, "Hook observation requires the original physical invocation"),
238
+ Opaque: define(Code.Forbidden, Reason.Opaque, "The resource is not available as an opaque local value"),
239
+ Service: define(Code.Forbidden, Reason.Service, "Access to this service is forbidden"),
240
+ StateOwner: define(Code.Forbidden, Reason.StateOwner, "Only the owning orb may change this state"),
241
+ UndeclaredDependency: define(Code.Forbidden, Reason.UndeclaredDependency, "The dependency was not declared"),
242
+ UndeclaredService: define(Code.Forbidden, Reason.UndeclaredService, "The service was not declared as a dependency")
243
+ }),
244
+ Gone: Object.freeze({
245
+ Connection: define(Code.Gone, Reason.Connection, "The connection is closed"),
246
+ Contribution: define(Code.Gone, Reason.Contribution, "The contribution is no longer available"),
247
+ Implementation: define(Code.Gone, Reason.Implementation, "The implementation is no longer available"),
248
+ ListenerCallback: define(Code.Gone, Reason.ListenerCallback, "The listener callback is no longer available"),
249
+ Reference: define(Code.Gone, Reason.Reference, "The reference is no longer available"),
250
+ Resource: define(Code.Gone, Reason.Resource, "The resource is no longer available"),
251
+ Scope: define(Code.Gone, Reason.Scope, "The declaration scope is no longer available"),
252
+ State: define(Code.Gone, Reason.State, "State owner is gone")
253
+ }),
254
+ Invalid: Object.freeze({
255
+ Address: define(Code.Invalid, Reason.Address, "Invalid address"),
256
+ AsyncFactory: define(Code.Invalid, Reason.AsyncFactory, "Factories must be synchronous"),
257
+ AsyncState: define(Code.Invalid, Reason.AsyncState, "State updates and migrations must be synchronous"),
258
+ CoordinationLimits: define(Code.Invalid, Reason.CoordinationLimits, "Invalid coordination limits"),
259
+ DependencyCycle: define(Code.Invalid, Reason.DependencyCycle, "Orb factories cannot acquire their own services"),
260
+ DependencyService: define(Code.Invalid, Reason.DependencyService, "Invalid dependency service"),
261
+ DuplicateListener: define(Code.Invalid, Reason.DuplicateListener, "Invalid duplicate listener"),
262
+ DuplicateResource: define(Code.Invalid, Reason.DuplicateResource, "Invalid duplicate resource"),
263
+ EventSource: define(Code.Invalid, Reason.EventSource, "Invalid event source"),
264
+ Orb: define(Code.Invalid, Reason.Orb, "An orb needs a name and positive API version"),
265
+ OrbGone: define(Code.Invalid, Reason.OrbGone, "Invalid orb gone"),
266
+ OrbInstalled: define(Code.Invalid, Reason.OrbInstalled, "Use reload to replace an installed orb"),
267
+ Factory: define(Code.Invalid, Reason.Factory, "Invalid factory"),
268
+ FactoryExpired: define(Code.Invalid, Reason.FactoryExpired, "Declarations must be synchronous"),
269
+ Hook: define(Code.Invalid, Reason.Hook, "Hooks need a run function"),
270
+ HookDependency: define(Code.Invalid, Reason.HookDependency, "Invalid hook dependency"),
271
+ HooksDisabled: define(Code.Invalid, Reason.HooksDisabled, "Invalid hooks disabled"),
272
+ JsonAccessor: define(Code.Invalid, Reason.JsonAccessor, "Invalid json accessor"),
273
+ JsonCycle: define(Code.Invalid, Reason.JsonCycle, "Invalid json cycle"),
274
+ JsonNumber: define(Code.Invalid, Reason.JsonNumber, "Use BigInt for integers outside the safe Number range"),
275
+ JsonSymbol: define(Code.Invalid, Reason.JsonSymbol, "Invalid json symbol"),
276
+ JsonTag: define(Code.Invalid, Reason.JsonTag, "Unknown or malformed portable type tag"),
277
+ JsonType: define(Code.Invalid, Reason.JsonType, "Supply a codec for custom object types"),
278
+ JsonValue: define(Code.Invalid, Reason.JsonValue, "This JSON codec requires explicit portable values"),
279
+ Method: define(Code.Invalid, Reason.Method, "Methods must be functions"),
280
+ NextUsed: define(Code.Invalid, Reason.NextUsed, "Invalid next used"),
281
+ Priority: define(Code.Invalid, Reason.Priority, "Invalid priority"),
282
+ Reference: define(Code.Invalid, Reason.Reference, "An issued local reference is required"),
283
+ Resource: define(Code.Invalid, Reason.Resource, "Invalid resource"),
284
+ ResourceHost: define(Code.Invalid, Reason.ResourceHost, "Resource dependencies must belong to the same host"),
285
+ ResourceInFactory: define(Code.Invalid, Reason.ResourceInFactory, "Resources open after declaration"),
286
+ RpcFrame: define(Code.Invalid, Reason.RpcFrame, "Invalid rpc frame"),
287
+ RpcOperation: define(Code.Invalid, Reason.RpcOperation, "Invalid rpc operation"),
288
+ RpcRequest: define(Code.Invalid, Reason.RpcRequest, "Invalid rpc request"),
289
+ Service: define(Code.Invalid, Reason.Service, "Invalid service"),
290
+ ServiceGone: define(Code.Invalid, Reason.ServiceGone, "Invalid service gone"),
291
+ State: define(Code.Invalid, Reason.State, "Service does not expose state"),
292
+ StateCycle: define(Code.Invalid, Reason.StateCycle, "State cannot contain cycles"),
293
+ StateValidation: define(Code.Invalid, Reason.StateValidation, "The orb rejected the state candidate"),
294
+ StateValue: define(Code.Invalid, Reason.StateValue, "State cannot contain accessors"),
295
+ StateVersion: define(Code.Invalid, Reason.StateVersion, "Invalid state version"),
296
+ SubscriptionsDisabled: define(Code.Invalid, Reason.SubscriptionsDisabled, "Invalid subscriptions disabled"),
297
+ SubscriptionSize: define(Code.Invalid, Reason.SubscriptionSize, "A local byte budget requires an explicit sizeOf function"),
298
+ Task: define(Code.Invalid, Reason.Task, "Invalid task"),
299
+ Utf8: define(Code.Invalid, Reason.Utf8, "Invalid utf8"),
300
+ ValueGone: define(Code.Invalid, Reason.ValueGone, "Invalid value gone"),
301
+ ValuesExhausted: define(Code.Invalid, Reason.ValuesExhausted, "Invalid values exhausted")
302
+ }),
303
+ Released: Object.freeze({
304
+ Reference: define(Code.Released, Reason.Reference, "The reference has been released")
305
+ }),
306
+ Unavailable: Object.freeze({
307
+ Callback: define(Code.Unavailable, Reason.Callback, "A callback failed"),
308
+ OrbScope: define(Code.Unavailable, Reason.OrbScope, "The orb scope is unavailable"),
309
+ NotReady: define(Code.Unavailable, Reason.NotReady, "The object is not ready"),
310
+ Route: define(Code.Unavailable, Reason.Route, "The route is unavailable")
311
+ }),
312
+ Unsupported: Object.freeze({
313
+ EngineEffect: define(Code.Unsupported, Reason.EngineEffect, "The engine effect is not supported by this adapter"),
314
+ RemoteOpaque: define(Code.Unsupported, Reason.RemoteOpaque, "Opaque resources are local to their language environment"),
315
+ Telemetry: define(Code.Unsupported, Reason.Telemetry, "Telemetry is disabled in this kernel"),
316
+ Views: define(Code.Unsupported, Reason.Views, "Reference views are disabled in this kernel")
317
+ })
318
+ });
319
+
320
+ // src/error.ts
321
+ var codes = new Set(Object.values(Code));
322
+ function isDescriptor(value) {
323
+ return typeof value === "object" && value !== null && "code" in value && codes.has(value.code) && "reason" in value && typeof value.reason === "string" && "message" in value && typeof value.message === "string";
324
+ }
325
+
326
+ class TembraError extends Error {
327
+ code;
328
+ reason;
329
+ constructor(error, message = error.message, options) {
330
+ super(message, options);
331
+ this.name = "TembraError";
332
+ this.code = error.code;
333
+ this.reason = error.reason;
334
+ }
335
+ }
336
+ function failure(error) {
337
+ let message = Errors.Unavailable.Callback.message;
338
+ try {
339
+ if (error instanceof TembraError)
340
+ return error;
341
+ if (isDescriptor(error))
342
+ return new TembraError(error, error.message, { cause: error });
343
+ message = String(error instanceof Error ? error.message : error);
344
+ } catch {}
345
+ return new TembraError(Errors.Unavailable.Callback, message, { cause: error });
346
+ }
347
+ function refuse(error, message = error.message) {
348
+ throw new TembraError(error, message);
349
+ }
350
+
351
+ // src/authoring/orb.ts
352
+ function orb(definition) {
353
+ if (!definition.name || !Number.isInteger(definition.apiVersion) || definition.apiVersion <= 0)
354
+ refuse(Errors.Invalid.Orb, "An orb needs a name and positive API version");
355
+ const services = Object.fromEntries(Object.entries(definition.services ?? {}).map(([name, service]) => {
356
+ if (!name || !service.methods || typeof service.methods !== "object")
357
+ refuse(Errors.Invalid.Service);
358
+ if (service.create && typeof service.create !== "function")
359
+ refuse(Errors.Invalid.Factory);
360
+ for (const handler of Object.values(service.methods)) {
361
+ if (typeof handler !== "function")
362
+ refuse(Errors.Invalid.Method, "Methods must be functions");
363
+ }
364
+ const copy = {
365
+ ...service,
366
+ methods: Object.freeze({ ...service.methods })
367
+ };
368
+ return [name, Object.freeze(copy)];
369
+ }));
370
+ const requires = Object.fromEntries(Object.entries(definition.requires ?? {}).map(([name, requirement]) => [
371
+ name,
372
+ Object.freeze({
373
+ ...requirement,
374
+ ...requirement.methods ? { methods: Object.freeze([...requirement.methods]) } : {},
375
+ ...requirement.hooks ? { hooks: Object.freeze([...requirement.hooks]) } : {},
376
+ ...requirement.services ? {
377
+ services: Object.freeze(Object.fromEntries(Object.entries(requirement.services).map(([name, methods]) => [
378
+ name,
379
+ Object.freeze([...methods])
380
+ ])))
381
+ } : {}
382
+ })
383
+ ]));
384
+ const hooks = Object.fromEntries(Object.entries(definition.hooks ?? {}).map(([name, hook]) => {
385
+ if (typeof hook.run !== "function")
386
+ refuse(Errors.Invalid.Hook, "Hooks need a run function");
387
+ return [
388
+ name,
389
+ Object.freeze({ ...hook, capabilities: Object.freeze([...hook.capabilities ?? []]) })
390
+ ];
391
+ }));
392
+ const contributes = Object.fromEntries(Object.entries(definition.contributes ?? {}).map(([alias, hooks]) => [
393
+ alias,
394
+ Object.freeze(Object.fromEntries(Object.entries(hooks).map(([name, contribution]) => [
395
+ name,
396
+ typeof contribution === "function" ? contribution : Object.freeze({ ...contribution })
397
+ ])))
398
+ ]));
399
+ return Object.freeze({
400
+ ...definition,
401
+ services: Object.freeze(services),
402
+ requires: Object.freeze(requires),
403
+ hooks: Object.freeze(hooks),
404
+ contributes: Object.freeze(contributes)
405
+ });
406
+ }
407
+
408
+ // src/bridge/protocol.ts
409
+ var KernelOp = Object.freeze({
410
+ ContextDerive: "context-derive",
411
+ ContextValue: "context-value",
412
+ ContextStats: "context-stats",
413
+ Allocate: "allocate",
414
+ ScopeRegister: "scope-register",
415
+ ScopeExists: "scope-exists",
416
+ ScopesForOwner: "scopes-for-owner",
417
+ ScopesForOrb: "scopes-for-orb",
418
+ ScopeAddResource: "scope-add-resource",
419
+ ScopeActivate: "scope-activate",
420
+ ScopesCleanup: "scopes-cleanup",
421
+ ScopesReloadRegistered: "scopes-reload-registered",
422
+ ScopesReload: "scopes-reload",
423
+ ProgramRun: "program-run",
424
+ ProgramNext: "program-next",
425
+ ProgramCompleteStep: "program-complete-step",
426
+ ProgramCommit: "program-commit",
427
+ ProgramAbort: "program-abort",
428
+ ProgramForget: "program-forget",
429
+ Features: "features",
430
+ Prepare: "prepare",
431
+ Gate: "gate",
432
+ GateOrbs: "gate-orbs",
433
+ Commit: "commit",
434
+ Abort: "abort",
435
+ Orbs: "orbs",
436
+ Orb: "orb",
437
+ OrbNamed: "orb-named",
438
+ NextDeadline: "next-deadline",
439
+ Address: "address",
440
+ Acquire: "acquire",
441
+ Ready: "ready",
442
+ Dependency: "dependency",
443
+ Undepend: "undepend",
444
+ Fail: "fail",
445
+ Status: "status",
446
+ Release: "release",
447
+ Forget: "forget",
448
+ Root: "root",
449
+ CleanupRoot: "cleanup-root",
450
+ RootPrincipal: "root-principal",
451
+ CheckContext: "check-context",
452
+ CheckRoot: "check-root",
453
+ EndRoot: "end-root",
454
+ CancelRoot: "cancel-root",
455
+ BeginCall: "begin-call",
456
+ BeginOperation: "begin-operation",
457
+ BeginHookObservation: "begin-hook-observation",
458
+ FinishCall: "finish-call",
459
+ Invocation: "invocation",
460
+ StateInit: "state-init",
461
+ Snapshot: "snapshot",
462
+ StateAdopt: "state-adopt",
463
+ Task: "task",
464
+ TaskRoot: "task-root",
465
+ StopTask: "stop-task",
466
+ FinishTask: "finish-task",
467
+ Resource: "resource",
468
+ ResourceOpened: "resource-opened",
469
+ ResourceValue: "resource-value",
470
+ CloseResource: "close-resource",
471
+ ResourceClosed: "resource-closed",
472
+ Disposed: "disposed",
473
+ Tick: "tick",
474
+ NextWake: "next-wake",
475
+ NextIdle: "next-idle",
476
+ Close: "close",
477
+ FinishClose: "finish-close",
478
+ Diagnostics: "diagnostics",
479
+ Drain: "drain",
480
+ Restrict: "restrict",
481
+ Contribute: "contribute",
482
+ ContributionOrdinal: "contribution-ordinal",
483
+ HookPlan: "hook-plan",
484
+ Listen: "listen",
485
+ Subscribe: "subscribe",
486
+ Enqueue: "enqueue",
487
+ NextDelivery: "next-delivery",
488
+ FinishDelivery: "finish-delivery",
489
+ Unsubscribe: "unsubscribe"
490
+ });
491
+ var ActionType = Object.freeze({
492
+ Execute: "execute",
493
+ CancelEffects: "cancel-effects",
494
+ ProgramPrepared: "program-prepared",
495
+ ProgramComplete: "program-complete",
496
+ Dispose: "dispose",
497
+ CloseResource: "close-resource",
498
+ DropValue: "drop-value",
499
+ CancelRoot: "cancel-root",
500
+ CancelTask: "cancel-task",
501
+ RetireOrb: "retire-orb",
502
+ State: "state",
503
+ SubscriptionFailed: "subscription-failed",
504
+ DetachSubscription: "detach-subscription",
505
+ Deliver: "deliver"
506
+ });
507
+ var EffectType = Object.freeze({
508
+ Stop: "stop",
509
+ Open: "open",
510
+ Close: "close",
511
+ Restore: "restore",
512
+ Prepare: "prepare",
513
+ Validate: "validate",
514
+ Initialize: "initialize",
515
+ Migrate: "migrate",
516
+ Adopt: "adopt",
517
+ Start: "start",
518
+ Drop: "drop"
519
+ });
520
+ var StepType = Object.freeze({
521
+ Execute: "execute",
522
+ Wait: "wait",
523
+ Prepared: "prepared",
524
+ Complete: "complete",
525
+ Failed: "failed"
526
+ });
527
+ var NativeOp = Object.freeze({
528
+ Activate: "activate",
529
+ Dispose: "dispose",
530
+ CancelEffect: "cancel-effect",
531
+ Effect: "effect",
532
+ Invoke: "invoke",
533
+ Contribute: "contribute"
534
+ });
535
+ var RpcOp = Object.freeze({
536
+ Describe: "describe",
537
+ Get: "get",
538
+ Release: "release",
539
+ Call: "call",
540
+ Cancel: "cancel"
541
+ });
542
+ var RpcEvent = Object.freeze({
543
+ State: "state"
544
+ });
545
+ var OwnerKind = Object.freeze({
546
+ Host: "host",
547
+ Orb: "orb",
548
+ Object: "object"
549
+ });
550
+ var EnvironmentPhase = Object.freeze({
551
+ Declaring: "declaring",
552
+ Prepared: "prepared",
553
+ Live: "live",
554
+ Closed: "closed"
555
+ });
556
+ var CoordinationDecision = Object.freeze({
557
+ Preparing: "preparing",
558
+ Commit: "commit",
559
+ Abort: "abort"
560
+ });
561
+ var Outcome = Object.freeze({
562
+ Ok: "ok",
563
+ Error: "error"
564
+ });
565
+ var CodecTag = Object.freeze({
566
+ Bigint: "bigint",
567
+ Bytes: "bytes",
568
+ Object: "object"
569
+ });
570
+ var CodecId = Object.freeze({
571
+ Json: "tembra-json/1",
572
+ MessagePack: "tembra-msgpack/1"
573
+ });
574
+
575
+ // src/values.ts
576
+ class Values {
577
+ allocate;
578
+ #next = 1;
579
+ #values = new Map;
580
+ constructor(allocate) {
581
+ this.allocate = allocate;
582
+ }
583
+ put(value) {
584
+ if (this.#next > 4294967295)
585
+ refuse(Errors.Invalid.ValuesExhausted);
586
+ const id = this.allocate ? this.allocate() : this.#next++;
587
+ this.#values.set(id, value);
588
+ return id;
589
+ }
590
+ get(id) {
591
+ if (!this.#values.has(id))
592
+ refuse(Errors.Invalid.ValueGone);
593
+ return this.#values.get(id);
594
+ }
595
+ drop(id) {
596
+ this.#values.delete(id);
597
+ }
598
+ has(id) {
599
+ return this.#values.has(id);
600
+ }
601
+ set(id, value) {
602
+ this.#values.set(id, value);
603
+ }
604
+ clear() {
605
+ this.#values.clear();
606
+ }
607
+ get size() {
608
+ return this.#values.size;
609
+ }
610
+ }
611
+ var protectedValues = new WeakSet;
612
+ function protect(value) {
613
+ const visiting = new WeakSet;
614
+ function visit(value) {
615
+ if (value === null || typeof value !== "object") {
616
+ if (["function", "symbol"].includes(typeof value))
617
+ refuse(Errors.Invalid.StateValue, "State must contain plain data");
618
+ return;
619
+ }
620
+ if (protectedValues.has(value))
621
+ return;
622
+ if (visiting.has(value))
623
+ refuse(Errors.Invalid.StateCycle, "State cannot contain cycles");
624
+ const proto = Object.getPrototypeOf(value);
625
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null)
626
+ refuse(Errors.Invalid.StateValue, "State requires plain objects and arrays");
627
+ visiting.add(value);
628
+ for (const key of Reflect.ownKeys(value)) {
629
+ if (typeof key !== "string")
630
+ refuse(Errors.Invalid.StateValue, "State cannot contain symbol properties");
631
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
632
+ if (!Object.hasOwn(descriptor, "value"))
633
+ refuse(Errors.Invalid.StateValue, "State cannot contain accessors");
634
+ visit(descriptor.value);
635
+ }
636
+ visiting.delete(value);
637
+ Object.freeze(value);
638
+ protectedValues.add(value);
639
+ }
640
+ visit(value);
641
+ return value;
642
+ }
643
+
644
+ // src/state/selection.ts
645
+ class Selection {
646
+ compute;
647
+ report;
648
+ check;
649
+ #value;
650
+ #listeners = new Set;
651
+ #children = new Set;
652
+ #active = true;
653
+ #cleanups;
654
+ #cleanup;
655
+ #remove;
656
+ constructor(compute, value, report, check) {
657
+ this.compute = compute;
658
+ this.report = report;
659
+ this.check = check;
660
+ this.#value = protect(compute(value));
661
+ }
662
+ get value() {
663
+ this.check();
664
+ return this.#value;
665
+ }
666
+ track(cleanups, remove) {
667
+ this.#cleanups = cleanups;
668
+ this.#remove = remove;
669
+ const weak = new WeakRef(this);
670
+ this.#cleanup = () => weak.deref()?.detach();
671
+ cleanups?.add(this.#cleanup);
672
+ }
673
+ detach() {
674
+ if (!this.#active)
675
+ return;
676
+ this.#active = false;
677
+ if (this.#cleanup)
678
+ this.#cleanups?.delete(this.#cleanup);
679
+ this.#remove?.();
680
+ this.#listeners.clear();
681
+ for (const weak of this.#children)
682
+ weak.deref()?.detach();
683
+ this.#children.clear();
684
+ }
685
+ prepare(value) {
686
+ if (!this.#active)
687
+ return;
688
+ try {
689
+ this.check();
690
+ } catch {
691
+ this.detach();
692
+ return;
693
+ }
694
+ let next;
695
+ try {
696
+ next = protect(this.compute(value));
697
+ } catch (error) {
698
+ this.detach();
699
+ this.report(error);
700
+ return;
701
+ }
702
+ if (!this.#active)
703
+ return;
704
+ const children = [];
705
+ if (!Object.is(next, this.#value)) {
706
+ for (const weak of this.#children) {
707
+ const child = weak.deref();
708
+ const prepared = child?.prepare(next);
709
+ if (prepared)
710
+ children.push(prepared);
711
+ else
712
+ this.#children.delete(weak);
713
+ }
714
+ }
715
+ return {
716
+ adopt: () => {
717
+ if (!this.#active || Object.is(next, this.#value))
718
+ return () => {};
719
+ this.#value = next;
720
+ const notifyChildren = children.map((child) => child.adopt());
721
+ const listeners = [...this.#listeners];
722
+ return () => {
723
+ if (!this.#active)
724
+ return;
725
+ for (const notify of notifyChildren)
726
+ notify();
727
+ for (const listener of listeners) {
728
+ try {
729
+ listener(next);
730
+ } catch (error) {
731
+ this.report(error);
732
+ }
733
+ }
734
+ };
735
+ }
736
+ };
737
+ }
738
+ select(compute) {
739
+ this.check();
740
+ const child = new Selection(compute, this.#value, this.report, this.check);
741
+ this.check();
742
+ const weak = new WeakRef(child);
743
+ this.#children.add(weak);
744
+ child.track(this.#cleanups, () => this.#children.delete(weak));
745
+ return child;
746
+ }
747
+ subscribe(listener) {
748
+ this.check();
749
+ this.#listeners.add(listener);
750
+ try {
751
+ listener(this.#value);
752
+ } catch (error) {
753
+ this.report(error);
754
+ }
755
+ return () => {
756
+ this.#listeners.delete(listener);
757
+ };
758
+ }
759
+ }
760
+
761
+ // src/state/binding.ts
762
+ class StateBinding {
763
+ backend;
764
+ object;
765
+ closed = false;
766
+ #value;
767
+ #listeners = new Set;
768
+ #selections = new Set;
769
+ constructor(backend, object, initial) {
770
+ this.backend = backend;
771
+ this.object = object;
772
+ this.#value = arguments.length >= 3 ? initial : backend.value(backend.snapshot(object).value);
773
+ }
774
+ check() {
775
+ if (this.closed)
776
+ throw new TembraError(Errors.Gone.State, "State owner is gone");
777
+ }
778
+ get value() {
779
+ this.check();
780
+ return this.#value;
781
+ }
782
+ view(options, check = () => this.check()) {
783
+ const binding = this;
784
+ return {
785
+ get value() {
786
+ check();
787
+ return binding.value;
788
+ },
789
+ update(context, change) {
790
+ check();
791
+ binding.backend.check(context, binding.object);
792
+ const previous = binding.backend.snapshot(binding.object);
793
+ const current = binding.backend.value(previous.value);
794
+ const candidate = change(current);
795
+ validate(candidate, options);
796
+ binding.backend.check(context, binding.object);
797
+ if (Object.is(candidate, current))
798
+ return current;
799
+ const selected = binding.prepare(candidate);
800
+ binding.backend.adopt(binding.object, context, previous.revision, candidate);
801
+ const publish = binding.adopt(selected, candidate);
802
+ binding.backend.publish(publish);
803
+ return candidate;
804
+ },
805
+ select: (compute) => {
806
+ check();
807
+ return binding.select(compute, check);
808
+ },
809
+ subscribe: (listener) => {
810
+ check();
811
+ return binding.subscribe(listener);
812
+ }
813
+ };
814
+ }
815
+ select(compute, check = () => this.check(), cleanups) {
816
+ check();
817
+ const selection = new Selection(compute, this.value, (error) => this.backend.report(error), check);
818
+ check();
819
+ const weak = new WeakRef(selection);
820
+ this.#selections.add(weak);
821
+ selection.track(cleanups, () => this.#selections.delete(weak));
822
+ return selection;
823
+ }
824
+ subscribe(listener) {
825
+ this.check();
826
+ this.#listeners.add(listener);
827
+ try {
828
+ listener(this.value);
829
+ } catch (error) {
830
+ this.backend.report(error);
831
+ }
832
+ return () => {
833
+ this.#listeners.delete(listener);
834
+ };
835
+ }
836
+ prepare(candidate) {
837
+ const prepared = [];
838
+ for (const weak of this.#selections) {
839
+ const selection = weak.deref();
840
+ const next = selection?.prepare(candidate);
841
+ if (next)
842
+ prepared.push(next);
843
+ else
844
+ this.#selections.delete(weak);
845
+ }
846
+ return prepared;
847
+ }
848
+ adopt(prepared, candidate) {
849
+ this.#value = candidate;
850
+ const selections = prepared.map((p) => p.adopt());
851
+ const listeners = [...this.#listeners];
852
+ return () => {
853
+ for (const notify of selections)
854
+ notify();
855
+ for (const listener of listeners) {
856
+ try {
857
+ listener(candidate);
858
+ } catch (error) {
859
+ this.backend.report(error);
860
+ }
861
+ }
862
+ };
863
+ }
864
+ close() {
865
+ this.closed = true;
866
+ this.#value = undefined;
867
+ this.#listeners.clear();
868
+ for (const weak of this.#selections)
869
+ weak.deref()?.detach();
870
+ this.#selections.clear();
871
+ }
872
+ }
873
+ function validate(candidate, options) {
874
+ if (candidate && typeof candidate.then === "function")
875
+ refuse(Errors.Invalid.AsyncState, "State updates and migrations must be synchronous");
876
+ const protectedValue = protect(candidate);
877
+ const result = options.validate?.(protectedValue);
878
+ if (result !== undefined && result !== true)
879
+ refuse(Errors.Invalid.StateValidation, "Orb rejected the candidate state");
880
+ return protectedValue;
881
+ }
882
+ // src/authoring/declaration.ts
883
+ class Declaration {
884
+ session;
885
+ environment;
886
+ constructor(session, environment) {
887
+ this.session = session;
888
+ this.environment = environment;
889
+ }
890
+ check() {
891
+ if (this.environment.phase !== EnvironmentPhase.Declaring)
892
+ refuse(Errors.Invalid.FactoryExpired, "Declarations must be synchronous");
893
+ }
894
+ get principal() {
895
+ return this.session.principalFor(this.environment.object?.id ?? 0);
896
+ }
897
+ get orb() {
898
+ return this.environment.orb.scope?.value;
899
+ }
900
+ get key() {
901
+ return this.environment.object?.address.key ?? ["main"];
902
+ }
903
+ state(initial, options = {}) {
904
+ this.check();
905
+ const environment = this.environment;
906
+ const object = environment.object;
907
+ if (!object || environment.state)
908
+ refuse(Errors.Invalid.State, "An object declares exactly one state");
909
+ const version = options.version ?? 1;
910
+ if (!Number.isInteger(version) || version <= 0)
911
+ refuse(Errors.Invalid.StateVersion);
912
+ let binding = object.binding;
913
+ if (!binding && object.live)
914
+ binding = new StateBinding(this.session, object.id, validate(initial, options));
915
+ if (!binding) {
916
+ const value = validate(initial, options);
917
+ const id = this.session.values.put(value);
918
+ try {
919
+ this.session.kernel.command(KernelOp.StateInit, { object: object.id, value: id, version });
920
+ } catch (error) {
921
+ this.session.values.drop(id);
922
+ throw error;
923
+ }
924
+ object.binding = binding = new StateBinding(this.session, object.id);
925
+ }
926
+ const handle = binding.view(options);
927
+ environment.state = { initial, options, binding };
928
+ return handle;
929
+ }
930
+ get(service, key, options = {}) {
931
+ this.check();
932
+ const requirement = this.session.scopes.requirement(this.environment, service);
933
+ const resolved = requirement.service;
934
+ if (!this.environment.object && this.environment.orb.definition.services?.[resolved])
935
+ refuse(Errors.Invalid.DependencyCycle);
936
+ const identity = JSON.stringify([resolved, key, options.principal ?? this.principal]);
937
+ const existing = this.environment.dependencies.get(identity);
938
+ if (existing)
939
+ return existing;
940
+ const reference = this.session.handles.hold(resolved, key, {
941
+ ...options,
942
+ ...requirement.apiVersion ? { apiVersion: requirement.apiVersion } : {},
943
+ ...requirement.methods ? { methods: requirement.methods } : {},
944
+ principal: options.principal ?? this.principal
945
+ });
946
+ if (this.environment.object) {
947
+ try {
948
+ this.session.kernel.command(KernelOp.Dependency, {
949
+ object: this.environment.object.id,
950
+ reference: this.session.handles.reference(reference).id
951
+ });
952
+ } catch (error) {
953
+ reference.release();
954
+ throw error;
955
+ }
956
+ }
957
+ this.environment.dependencies.set(identity, reference);
958
+ return reference;
959
+ }
960
+ resource(name, options) {
961
+ this.check();
962
+ if (!options)
963
+ return this.session.scopes.hostResource(name);
964
+ if (this.environment.resources.has(name))
965
+ refuse(Errors.Invalid.DuplicateResource, name);
966
+ const resource = this.session.resources.declare(this.environment, name, options);
967
+ this.environment.resources.set(name, resource);
968
+ return resource.handle;
969
+ }
970
+ task(start) {
971
+ this.check();
972
+ if (typeof start !== "function")
973
+ refuse(Errors.Invalid.Task);
974
+ this.environment.tasks.push({ start });
975
+ }
976
+ on(name, source, handle, options = {}) {
977
+ this.check();
978
+ if (!this.session.kernel.features.subscriptions)
979
+ refuse(Errors.Invalid.SubscriptionsDisabled);
980
+ if (options.maxBytes !== undefined && !options.sizeOf)
981
+ refuse(Errors.Invalid.SubscriptionSize, "A local byte budget requires an explicit sizeOf function");
982
+ if (!name || this.environment.listeners.some((listener) => listener.name === name))
983
+ refuse(Errors.Invalid.DuplicateListener, name);
984
+ this.environment.listeners.push({ name, source, handle, options });
985
+ }
986
+ hook(name) {
987
+ this.check();
988
+ if (!this.session.kernel.features.hooks)
989
+ refuse(Errors.Invalid.HooksDisabled);
990
+ if (!this.environment.orb.definition.hooks?.[name])
991
+ refuse(Errors.Invalid.Hook, name);
992
+ const operation = this.session.kernel.command(KernelOp.Allocate);
993
+ return {
994
+ run: (context, input) => this.session.orbs.runHook(this.environment, name, context, input),
995
+ observe: (source, input) => this.session.orbs.observe(this.environment, name, operation, source, input)
996
+ };
997
+ }
998
+ }
999
+ function consumerState(binding, check, cleanups) {
1000
+ return {
1001
+ get value() {
1002
+ check();
1003
+ return binding.value;
1004
+ },
1005
+ select(compute) {
1006
+ check();
1007
+ return binding.select(compute, check, cleanups);
1008
+ },
1009
+ subscribe(listener) {
1010
+ check();
1011
+ const detach = binding.subscribe((value) => {
1012
+ try {
1013
+ check();
1014
+ } catch {
1015
+ return;
1016
+ }
1017
+ listener(value);
1018
+ });
1019
+ let active = true;
1020
+ const cleanup = () => {
1021
+ if (!active)
1022
+ return;
1023
+ active = false;
1024
+ cleanups.delete(cleanup);
1025
+ detach();
1026
+ };
1027
+ cleanups.add(cleanup);
1028
+ try {
1029
+ check();
1030
+ } catch {
1031
+ cleanup();
1032
+ }
1033
+ return cleanup;
1034
+ }
1035
+ };
1036
+ }
1037
+
1038
+ // src/bridge/kernel.ts
1039
+ class Kernel {
1040
+ port;
1041
+ features;
1042
+ constructor(port) {
1043
+ this.port = port;
1044
+ this.features = this.command(KernelOp.Features);
1045
+ }
1046
+ command(op, fields = {}) {
1047
+ const envelope = JSON.parse(this.port.request(JSON.stringify({ ...fields, op })));
1048
+ if (envelope.error)
1049
+ throw new TembraError(envelope.error);
1050
+ return envelope.ok;
1051
+ }
1052
+ }
1053
+
1054
+ // src/codecs/json.ts
1055
+ var marker = "$tembra";
1056
+ function pack(value, visiting) {
1057
+ if (typeof value === "bigint")
1058
+ return { [marker]: [CodecTag.Bigint, value.toString()] };
1059
+ if (value instanceof Uint8Array)
1060
+ return { [marker]: [CodecTag.Bytes, [...value]] };
1061
+ if (value === null || typeof value === "string" || typeof value === "boolean")
1062
+ return value;
1063
+ if (typeof value === "number") {
1064
+ if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value))
1065
+ refuse(Errors.Invalid.JsonNumber, "Use BigInt for integers outside the safe Number range");
1066
+ return value;
1067
+ }
1068
+ if (typeof value !== "object")
1069
+ refuse(Errors.Invalid.JsonValue, "This JSON codec requires explicit portable values");
1070
+ if (visiting.has(value))
1071
+ refuse(Errors.Invalid.JsonCycle);
1072
+ const prototype = Object.getPrototypeOf(value);
1073
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
1074
+ refuse(Errors.Invalid.JsonType, "Supply a codec for custom object types");
1075
+ visiting.add(value);
1076
+ try {
1077
+ if (Array.isArray(value))
1078
+ return Array.from(value, (child) => pack(child, visiting));
1079
+ const entries = Reflect.ownKeys(value).map((key) => {
1080
+ if (typeof key !== "string")
1081
+ refuse(Errors.Invalid.JsonSymbol);
1082
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1083
+ if (!Object.hasOwn(descriptor, "value"))
1084
+ refuse(Errors.Invalid.JsonAccessor);
1085
+ return [key, pack(descriptor.value, visiting)];
1086
+ });
1087
+ return Object.hasOwn(value, marker) ? { [marker]: [CodecTag.Object, entries] } : Object.fromEntries(entries);
1088
+ } finally {
1089
+ visiting.delete(value);
1090
+ }
1091
+ }
1092
+ function unpack(value) {
1093
+ if (value === null || typeof value !== "object") {
1094
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value))
1095
+ refuse(Errors.Invalid.JsonNumber);
1096
+ return value;
1097
+ }
1098
+ if (Array.isArray(value))
1099
+ return value.map(unpack);
1100
+ if (Object.hasOwn(value, marker)) {
1101
+ const tag = value[marker];
1102
+ if (Object.keys(value).length !== 1 || !Array.isArray(tag) || tag.length !== 2)
1103
+ refuse(Errors.Invalid.JsonTag);
1104
+ const [type, data] = tag;
1105
+ if (type === CodecTag.Bigint && typeof data === "string" && /^-?(0|[1-9]\d*)$/.test(data))
1106
+ return BigInt(data);
1107
+ if (type === CodecTag.Bytes && Array.isArray(data) && data.every((v) => Number.isInteger(v) && v >= 0 && v <= 255))
1108
+ return Uint8Array.from(data);
1109
+ if (type === CodecTag.Object && Array.isArray(data)) {
1110
+ if (!data.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string"))
1111
+ refuse(Errors.Invalid.JsonTag);
1112
+ return Object.fromEntries(data.map(([key, child]) => [key, unpack(child)]));
1113
+ }
1114
+ refuse(Errors.Invalid.JsonTag, "Unknown or malformed portable type tag");
1115
+ }
1116
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, unpack(child)]));
1117
+ }
1118
+ function utf8(text) {
1119
+ const output = [];
1120
+ for (const character of text) {
1121
+ let point = character.codePointAt(0);
1122
+ if (point >= 55296 && point <= 57343)
1123
+ point = 65533;
1124
+ if (point < 128)
1125
+ output.push(point);
1126
+ else if (point < 2048)
1127
+ output.push(192 | point >> 6, 128 | point & 63);
1128
+ else if (point < 65536)
1129
+ output.push(224 | point >> 12, 128 | point >> 6 & 63, 128 | point & 63);
1130
+ else
1131
+ output.push(240 | point >> 18, 128 | point >> 12 & 63, 128 | point >> 6 & 63, 128 | point & 63);
1132
+ }
1133
+ return Uint8Array.from(output);
1134
+ }
1135
+ function text(bytes) {
1136
+ const output = [];
1137
+ for (let index = 0;index < bytes.length; ) {
1138
+ const first = bytes[index++];
1139
+ if (first < 128) {
1140
+ output.push(String.fromCharCode(first));
1141
+ continue;
1142
+ }
1143
+ const count = first >= 194 && first <= 223 ? 1 : first >= 224 && first <= 239 ? 2 : first >= 240 && first <= 244 ? 3 : -1;
1144
+ if (count < 0 || index + count > bytes.length)
1145
+ refuse(Errors.Invalid.Utf8);
1146
+ let point = first & 127 >> count + 1;
1147
+ for (let offset = 0;offset < count; offset++) {
1148
+ const next = bytes[index++];
1149
+ if ((next & 192) !== 128)
1150
+ refuse(Errors.Invalid.Utf8);
1151
+ point = point << 6 | next & 63;
1152
+ }
1153
+ if (point < [0, 128, 2048, 65536][count] || point > 1114111 || point >= 55296 && point <= 57343)
1154
+ refuse(Errors.Invalid.Utf8);
1155
+ output.push(String.fromCodePoint(point));
1156
+ }
1157
+ return output.join("");
1158
+ }
1159
+ var jsonCodec = Object.freeze({
1160
+ id: CodecId.Json,
1161
+ serialize: (value) => utf8(JSON.stringify(pack(value, new WeakSet))),
1162
+ deserialize: (bytes) => unpack(JSON.parse(text(bytes)))
1163
+ });
1164
+
1165
+ // src/telemetry.ts
1166
+ class Telemetry {
1167
+ capacity;
1168
+ sampleEvery;
1169
+ #events = [];
1170
+ #next = 0;
1171
+ constructor(capacity = 256, sampleEvery = 1) {
1172
+ this.capacity = capacity;
1173
+ this.sampleEvery = sampleEvery;
1174
+ if (!Number.isInteger(capacity) || capacity <= 0 || !Number.isInteger(sampleEvery) || sampleEvery <= 0)
1175
+ throw new RangeError("Invalid telemetry limits");
1176
+ }
1177
+ sample() {
1178
+ return this.#next++ % this.sampleEvery === 0;
1179
+ }
1180
+ record(trace) {
1181
+ if (this.#events.length === this.capacity)
1182
+ this.#events.shift();
1183
+ this.#events.push(trace);
1184
+ }
1185
+ drain() {
1186
+ return this.#events.splice(0);
1187
+ }
1188
+ }
1189
+
1190
+ // src/runtime/activities.ts
1191
+ class Activities {
1192
+ session;
1193
+ tasks = new Map;
1194
+ listeners = new Map;
1195
+ #identities = new WeakMap;
1196
+ constructor(session) {
1197
+ this.session = session;
1198
+ }
1199
+ prepare(environment, previous) {
1200
+ for (const definition of environment.listeners) {
1201
+ const source = typeof definition.source === "function" ? definition.source() : definition.source;
1202
+ if (!source || typeof source.subscribe !== "function")
1203
+ refuse(Errors.Invalid.EventSource);
1204
+ const id = this.session.kernel.command(KernelOp.Listen, {
1205
+ scope: environment.id,
1206
+ previous: previous?.id,
1207
+ name: definition.name,
1208
+ source: this.identity(source),
1209
+ sizing: definition.options.sizeOf ? this.identity(definition.options.sizeOf) : 0,
1210
+ operation: this.session.kernel.command(KernelOp.Allocate),
1211
+ maxPending: definition.options.maxPending ?? 64,
1212
+ ...definition.options.maxBytes ? { maxBytes: definition.options.maxBytes } : {},
1213
+ coalesce: "select" in source
1214
+ });
1215
+ const existing = this.listeners.get(id);
1216
+ if (existing) {
1217
+ definition.running = existing;
1218
+ continue;
1219
+ }
1220
+ const record = {
1221
+ id,
1222
+ definition,
1223
+ environment,
1224
+ stopped: false,
1225
+ detach() {}
1226
+ };
1227
+ definition.running = record;
1228
+ this.listeners.set(id, record);
1229
+ try {
1230
+ record.detach = source.subscribe((value) => {
1231
+ if (record.stopped)
1232
+ return;
1233
+ const payload = this.session.values.put(value);
1234
+ try {
1235
+ const bytes = definition.options.sizeOf?.(value) ?? 0;
1236
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > 4294967295)
1237
+ throw new TembraError(Errors.Invalid.SubscriptionSize);
1238
+ this.session.kernel.command(KernelOp.Enqueue, { subscription: id, payload, bytes });
1239
+ } catch (error) {
1240
+ this.session.values.drop(payload);
1241
+ this.session.report(error);
1242
+ this.failed(id);
1243
+ }
1244
+ this.session.lifecycle.flush();
1245
+ });
1246
+ if (record.stopped)
1247
+ record.detach();
1248
+ } catch (error) {
1249
+ this.stopListener(record);
1250
+ throw error;
1251
+ }
1252
+ }
1253
+ }
1254
+ start(environment) {
1255
+ environment.phase = EnvironmentPhase.Live;
1256
+ for (const definition of environment.listeners) {
1257
+ const record = definition.running;
1258
+ record.environment = environment;
1259
+ record.definition = definition;
1260
+ }
1261
+ for (const task of environment.tasks)
1262
+ this.startTask(environment, task);
1263
+ }
1264
+ startTask(environment, definition) {
1265
+ if (definition.running || environment.phase !== EnvironmentPhase.Live || this.session.closing)
1266
+ return;
1267
+ const id = this.session.kernel.command(KernelOp.Task, { owner: environment.owner });
1268
+ const controller = new AbortController;
1269
+ const operation = this.session.kernel.command(KernelOp.Allocate);
1270
+ const record = { id, controller, done: Promise.resolve() };
1271
+ definition.running = record;
1272
+ this.tasks.set(id, record);
1273
+ record.done = this.session.track(Promise.resolve().then(async () => {
1274
+ try {
1275
+ await definition.start({
1276
+ signal: controller.signal,
1277
+ root: (callback) => {
1278
+ const root = this.session.kernel.command(KernelOp.TaskRoot, {
1279
+ task: id,
1280
+ principal: this.session.principalFor(environment.object?.id ?? 0)
1281
+ });
1282
+ return this.session.calls.root(() => this.session.calls.owned(environment, operation, callback, root), false, root);
1283
+ }
1284
+ });
1285
+ } catch (error) {
1286
+ if (!controller.signal.aborted)
1287
+ this.session.report(error);
1288
+ } finally {
1289
+ this.session.kernel.command(KernelOp.Tick, { now: this.session.now() });
1290
+ this.session.kernel.command(KernelOp.FinishTask, { task: id });
1291
+ this.tasks.delete(id);
1292
+ delete definition.running;
1293
+ this.session.lifecycle.flush();
1294
+ }
1295
+ }));
1296
+ }
1297
+ identity(value) {
1298
+ let id = this.#identities.get(value);
1299
+ if (id === undefined) {
1300
+ id = this.session.kernel.command(KernelOp.Allocate);
1301
+ this.#identities.set(value, id);
1302
+ }
1303
+ return id;
1304
+ }
1305
+ deliver(subscription, payload, operation) {
1306
+ const record = this.listeners.get(subscription);
1307
+ const job = Promise.resolve().then(async () => {
1308
+ try {
1309
+ if (!record)
1310
+ throw new TembraError(Errors.Gone.ListenerCallback);
1311
+ await this.session.calls.owned(record.environment, operation, (ctx) => record.definition.handle(ctx, this.session.values.get(payload)));
1312
+ } catch (error) {
1313
+ this.session.report(error);
1314
+ } finally {
1315
+ this.session.kernel.command(KernelOp.FinishDelivery, { subscription });
1316
+ this.session.lifecycle.flush();
1317
+ }
1318
+ });
1319
+ if (record)
1320
+ record.done = job;
1321
+ this.session.track(job);
1322
+ }
1323
+ detach(id) {
1324
+ const record = this.listeners.get(id);
1325
+ if (record)
1326
+ this.stopListener(record);
1327
+ }
1328
+ cancel(id) {
1329
+ this.tasks.get(id)?.controller.abort(new TembraError(Errors.Cancelled.Task));
1330
+ }
1331
+ failed(id) {
1332
+ const record = this.listeners.get(id);
1333
+ if (!record)
1334
+ return;
1335
+ this.session.report(new TembraError(Errors.Exhausted.SubscriptionQueue));
1336
+ this.stopListener(record);
1337
+ }
1338
+ stopListener(record) {
1339
+ if (record.stopped)
1340
+ return;
1341
+ record.stopped = true;
1342
+ try {
1343
+ record.detach();
1344
+ } catch (error) {
1345
+ this.session.report(error);
1346
+ }
1347
+ this.session.kernel.command(KernelOp.Unsubscribe, { subscription: record.id });
1348
+ this.listeners.delete(record.id);
1349
+ this.session.lifecycle.flush();
1350
+ }
1351
+ async stop(environment) {
1352
+ for (const definition of environment.tasks) {
1353
+ if (definition.running)
1354
+ this.session.kernel.command(KernelOp.StopTask, { task: definition.running.id });
1355
+ }
1356
+ this.session.lifecycle.flush();
1357
+ await Promise.all(environment.tasks.map((task) => task.running?.done));
1358
+ await Promise.all(environment.listeners.map((listener) => listener.running?.done));
1359
+ }
1360
+ }
1361
+
1362
+ // src/context-key.ts
1363
+ var ContextKind = Object.freeze({
1364
+ Text: "text",
1365
+ Integer: "integer",
1366
+ Boolean: "boolean",
1367
+ Opaque: "opaque"
1368
+ });
1369
+
1370
+ class ContextKey {
1371
+ name;
1372
+ version;
1373
+ kind;
1374
+ constructor(name, version, kind) {
1375
+ this.name = name;
1376
+ this.version = version;
1377
+ this.kind = kind;
1378
+ Object.freeze(this);
1379
+ }
1380
+ static text(name, version = 1) {
1381
+ return new ContextKey(name, version, ContextKind.Text);
1382
+ }
1383
+ static integer(name, version = 1) {
1384
+ return new ContextKey(name, version, ContextKind.Integer);
1385
+ }
1386
+ static boolean(name, version = 1) {
1387
+ return new ContextKey(name, version, ContextKind.Boolean);
1388
+ }
1389
+ static opaque(name, version = 1) {
1390
+ return new ContextKey(name, version, ContextKind.Opaque);
1391
+ }
1392
+ source(value, ctx) {
1393
+ if (this.kind !== ContextKind.Opaque)
1394
+ return;
1395
+ const token = typeof value === "object" && value !== null ? ctx.session.contextTokens.get(value) : undefined;
1396
+ if (!token || token.root !== ctx.root)
1397
+ throw new TypeError("An owner-issued opaque reference from this host and root is required");
1398
+ return token.source;
1399
+ }
1400
+ }
1401
+ function readContextValue(ctx, key, frame) {
1402
+ const entry = ctx.session.kernel.command(KernelOp.ContextValue, {
1403
+ root: ctx.root,
1404
+ context: frame,
1405
+ call: ctx.invocation?.id,
1406
+ key
1407
+ });
1408
+ if (!entry)
1409
+ return;
1410
+ if (entry.kind !== ContextKind.Opaque)
1411
+ return entry.value;
1412
+ const token = Object.freeze({ opaque: true });
1413
+ ctx.session.contextTokens.set(token, { root: ctx.root, source: entry.source });
1414
+ return token;
1415
+ }
1416
+ function opaqueFrom(ctx, key, issuedFrame) {
1417
+ const token = readContextValue(ctx, key, issuedFrame);
1418
+ if (!token)
1419
+ throw new TypeError("The owner did not issue a reference");
1420
+ return token;
1421
+ }
1422
+
1423
+ // src/runtime/context.ts
1424
+ var issued = new WeakMap;
1425
+
1426
+ class Context {
1427
+ session;
1428
+ root;
1429
+ invocation;
1430
+ frame;
1431
+ constructor(session, root, invocation, frame = 0) {
1432
+ this.session = session;
1433
+ this.root = root;
1434
+ this.invocation = invocation;
1435
+ this.frame = frame;
1436
+ issued.set(this, this);
1437
+ }
1438
+ with(key, value) {
1439
+ const source = key.source(value, this);
1440
+ const frame = this.session.kernel.command(KernelOp.ContextDerive, {
1441
+ root: this.root,
1442
+ context: this.frame,
1443
+ call: this.invocation?.id,
1444
+ key,
1445
+ ...key.kind === ContextKind.Opaque ? { source } : { value }
1446
+ });
1447
+ return new Context(this.session, this.root, this.invocation, frame);
1448
+ }
1449
+ value(key) {
1450
+ return readContextValue(this, key, this.frame);
1451
+ }
1452
+ exportValues(keys) {
1453
+ const result = {};
1454
+ for (const key of keys) {
1455
+ if (key.kind === ContextKind.Opaque)
1456
+ throw new TypeError("Local opaque references cannot be exported");
1457
+ const value = this.value(key);
1458
+ if (value !== undefined)
1459
+ result[`${key.name}@${key.version}`] = value;
1460
+ }
1461
+ return result;
1462
+ }
1463
+ get principal() {
1464
+ return this.session.kernel.command(KernelOp.RootPrincipal, { root: this.root });
1465
+ }
1466
+ get signal() {
1467
+ return this.session.calls.signal(this.root);
1468
+ }
1469
+ check() {
1470
+ this.session.kernel.command(KernelOp.CheckContext, {
1471
+ root: this.root,
1472
+ call: this.invocation?.id
1473
+ });
1474
+ }
1475
+ cancel() {
1476
+ this.session.kernel.command(KernelOp.CancelRoot, { root: this.root });
1477
+ this.session.lifecycle.flush();
1478
+ }
1479
+ get(service, key, options = {}) {
1480
+ this.check();
1481
+ return this.session.handles.get(service, key, options, this);
1482
+ }
1483
+ resource(name) {
1484
+ this.check();
1485
+ return this.session.scopes.hostResource(name);
1486
+ }
1487
+ }
1488
+ function issuedContext(value, session) {
1489
+ if (typeof value !== "object" || value === null || issued.get(value)?.session !== session) {
1490
+ throw new TembraError(Errors.Forbidden.Context, "An issued context from this host is required");
1491
+ }
1492
+ return issued.get(value);
1493
+ }
1494
+ function context(value, session) {
1495
+ const result = issuedContext(value, session);
1496
+ result.check();
1497
+ return result;
1498
+ }
1499
+ function isContext(value) {
1500
+ return typeof value === "object" && value !== null && issued.has(value);
1501
+ }
1502
+
1503
+ // src/runtime/calls.ts
1504
+ class Calls {
1505
+ session;
1506
+ constructor(session) {
1507
+ this.session = session;
1508
+ }
1509
+ signal(root) {
1510
+ const session = this.session;
1511
+ let controller = session.controllers.get(root);
1512
+ if (!controller) {
1513
+ controller = new AbortController;
1514
+ try {
1515
+ session.kernel.command(KernelOp.CheckRoot, { root });
1516
+ } catch (error) {
1517
+ if (!(error instanceof TembraError) || error.code !== Code.Cancelled)
1518
+ throw error;
1519
+ controller.abort(error);
1520
+ }
1521
+ session.controllers.set(root, controller);
1522
+ }
1523
+ return controller.signal;
1524
+ }
1525
+ releaseRoot(root) {
1526
+ for (const reference of this.session.rootReferences.get(root) ?? [])
1527
+ this.session.handles.release(reference);
1528
+ this.session.rootReferences.delete(root);
1529
+ this.session.controllers.delete(root);
1530
+ }
1531
+ async root(operation, cleanup = false, issuedRoot, principal = this.session.principal) {
1532
+ const session = this.session;
1533
+ const root = issuedRoot ?? session.kernel.command(cleanup ? KernelOp.CleanupRoot : KernelOp.Root, { principal });
1534
+ const ctx = new Context(session, root);
1535
+ try {
1536
+ return await operation(ctx);
1537
+ } finally {
1538
+ this.releaseRoot(root);
1539
+ session.options.native?.rootEnded?.(root);
1540
+ if (!session.lifecycle.closedDiagnostics)
1541
+ session.kernel.command(KernelOp.EndRoot, { root });
1542
+ session.controllers.delete(root);
1543
+ session.lifecycle.flush();
1544
+ }
1545
+ }
1546
+ async invoke(reference, method, arguments_, ctx) {
1547
+ const session = this.session;
1548
+ context(ctx, session);
1549
+ if (reference.released)
1550
+ throw new TembraError(Errors.Released.Reference);
1551
+ await reference.ready;
1552
+ const admission = session.options.native?.admit?.(reference.id, method, ctx);
1553
+ let invocation;
1554
+ if (admission)
1555
+ invocation = admission.call;
1556
+ else {
1557
+ ctx.check();
1558
+ invocation = session.kernel.command(KernelOp.BeginCall, {
1559
+ reference: reference.id,
1560
+ root: ctx.root,
1561
+ context: ctx.frame || undefined,
1562
+ method
1563
+ });
1564
+ }
1565
+ const entered = new Context(session, ctx.root, invocation, ctx.frame);
1566
+ const physical = session.track((async () => {
1567
+ const sampled = session.telemetry?.sample();
1568
+ const started = sampled ? session.now() : 0;
1569
+ let outcome = Outcome.Ok;
1570
+ try {
1571
+ const native = session.options.native;
1572
+ if (native && (admission?.native ?? native.hasOrb(invocation.orb)))
1573
+ return await native.invoke(invocation, arguments_, entered);
1574
+ const object = session.objects.get(invocation.object);
1575
+ const environment = object?.versions.get(invocation.orb);
1576
+ const handle = environment?.orb.definition.services?.[reference.address.service]?.methods[method];
1577
+ if (!environment || !handle)
1578
+ throw new TembraError(Errors.Gone.Implementation);
1579
+ return await handle(environment.value, entered, ...arguments_);
1580
+ } catch (error) {
1581
+ outcome = Outcome.Error;
1582
+ throw error;
1583
+ } finally {
1584
+ if (sampled)
1585
+ session.telemetry.record({
1586
+ service: reference.address.service,
1587
+ method,
1588
+ root: invocation.root,
1589
+ codeVersion: invocation.codeVersion,
1590
+ duration: session.now() - started,
1591
+ outcome
1592
+ });
1593
+ session.lifecycle.finishCall(invocation.id);
1594
+ }
1595
+ })());
1596
+ return this.observe(physical, ctx.signal);
1597
+ }
1598
+ async owned(environment, operation, handle, root) {
1599
+ const session = this.session;
1600
+ const execute = async (ctx) => {
1601
+ const invocation = session.kernel.command(KernelOp.BeginOperation, {
1602
+ orb: environment.orb.info.id,
1603
+ root: ctx.root,
1604
+ context: ctx.frame || undefined,
1605
+ operation,
1606
+ ...environment.object ? { object: environment.object.id } : {}
1607
+ });
1608
+ try {
1609
+ return await handle(new Context(session, ctx.root, invocation, ctx.frame));
1610
+ } finally {
1611
+ session.kernel.command(KernelOp.FinishCall, { call: invocation.id });
1612
+ session.lifecycle.flush();
1613
+ }
1614
+ };
1615
+ return root === undefined ? this.root(execute, false, undefined, session.principalFor(environment.object?.id ?? 0)) : execute(typeof root === "number" ? new Context(session, root) : root);
1616
+ }
1617
+ async observe(physical, signal) {
1618
+ if (signal.aborted)
1619
+ throw signal.reason;
1620
+ let abort;
1621
+ const cancelled = new Promise((_, reject) => {
1622
+ abort = () => reject(signal.reason ?? new TembraError(Errors.Cancelled.Root));
1623
+ signal.addEventListener("abort", abort, { once: true });
1624
+ });
1625
+ try {
1626
+ return await Promise.race([physical, cancelled]);
1627
+ } finally {
1628
+ signal.removeEventListener("abort", abort);
1629
+ }
1630
+ }
1631
+ }
1632
+
1633
+ // src/runtime/orbs.ts
1634
+ class Orbs {
1635
+ session;
1636
+ records = new Map;
1637
+ operations = new Map;
1638
+ #ready = new Map;
1639
+ #ordinals = new Map;
1640
+ constructor(session) {
1641
+ this.session = session;
1642
+ }
1643
+ declarations(definitions) {
1644
+ const captured = definitions.map((definition) => orb(definition));
1645
+ const current = this.session.kernel.command(KernelOp.Orbs);
1646
+ const lookup = (name) => captured.find((f) => f.name === name);
1647
+ const metadata = captured.map((definition) => {
1648
+ if (!this.session.kernel.features.views && Object.values(definition.services ?? {}).some((service) => service.access))
1649
+ throw new TembraError(Errors.Unsupported.Views);
1650
+ const requires = Object.entries(definition.requires ?? {}).map(([alias, requirement]) => {
1651
+ const name = requirement.orb ?? alias;
1652
+ const provider = lookup(name);
1653
+ const info = current.find((f) => f.name === name);
1654
+ const names = provider ? Object.keys(provider.services ?? {}) : info?.services.map((s) => s.name) ?? [];
1655
+ const service = names.includes(alias) ? alias : names.length === 1 ? names[0] : undefined;
1656
+ if (requirement.methods && !service)
1657
+ refuse(Errors.Invalid.DependencyService, `Use explicit services for ${name}`);
1658
+ return {
1659
+ orb: name,
1660
+ apiVersion: requirement.apiVersion,
1661
+ services: requirement.services ?? (requirement.methods ? { [service]: requirement.methods } : {}),
1662
+ hooks: requirement.hooks ?? []
1663
+ };
1664
+ });
1665
+ for (const [alias, hooks] of Object.entries(definition.contributes ?? {})) {
1666
+ const requirement = definition.requires?.[alias];
1667
+ if (!requirement)
1668
+ refuse(Errors.Invalid.HookDependency, alias);
1669
+ for (const [hook, contribution] of Object.entries(hooks)) {
1670
+ if (!requirement.hooks?.includes(hook))
1671
+ refuse(Errors.Invalid.HookDependency, hook);
1672
+ const priority = typeof contribution === "function" ? 0 : contribution.priority ?? 0;
1673
+ if (!Number.isInteger(priority) || priority < -2147483648 || priority > 2147483647)
1674
+ refuse(Errors.Invalid.Priority);
1675
+ }
1676
+ }
1677
+ return {
1678
+ name: definition.name,
1679
+ apiVersion: definition.apiVersion,
1680
+ requires,
1681
+ hooks: Object.keys(definition.hooks ?? {}),
1682
+ services: Object.entries(definition.services ?? {}).map(([name, service]) => ({
1683
+ name,
1684
+ methods: Object.keys(service.methods),
1685
+ lifetime: service.lifetime ?? Lifetime.Referenced,
1686
+ linger: service.linger ?? 0
1687
+ }))
1688
+ };
1689
+ });
1690
+ return { definitions: captured, metadata };
1691
+ }
1692
+ async install(definitions) {
1693
+ const current = this.session.kernel.command(KernelOp.Orbs);
1694
+ if (definitions.some((f) => current.some((installed) => installed.name === f.name)))
1695
+ refuse(Errors.Invalid.OrbInstalled, "Use reload to replace an installed orb");
1696
+ const prepared = this.declarations(definitions);
1697
+ const reload = this.session.kernel.command(KernelOp.Prepare, {
1698
+ orbs: prepared.metadata
1699
+ });
1700
+ this.session.kernel.command(KernelOp.Commit, { ticket: reload.id });
1701
+ const records = reload.orbs.map((info) => ({
1702
+ info,
1703
+ definition: prepared.definitions.find((f) => f.name === info.name)
1704
+ }));
1705
+ for (const record of records)
1706
+ this.records.set(record.info.id, record);
1707
+ for (const record of records)
1708
+ this.registerContributions(record);
1709
+ await Promise.all(records.map((record) => this.ready(record)));
1710
+ for (const record of records) {
1711
+ for (const service of record.info.services.filter((s) => s.lifetime === Lifetime.Host)) {
1712
+ const reference = await this.session.handles.get(service.name, "main", {
1713
+ principal: "host"
1714
+ });
1715
+ reference.release();
1716
+ }
1717
+ }
1718
+ this.session.lifecycle.flush();
1719
+ }
1720
+ scope(record) {
1721
+ if (record.scope)
1722
+ return record.scope;
1723
+ const environment = this.session.scopes.environment({ kind: OwnerKind.Orb, id: record.info.owner }, record);
1724
+ record.scope = environment;
1725
+ try {
1726
+ const value = record.definition.create?.(new Declaration(this.session, environment)) ?? {};
1727
+ if (value && typeof value.then === "function")
1728
+ refuse(Errors.Invalid.AsyncFactory);
1729
+ environment.value = value;
1730
+ } finally {
1731
+ environment.phase = EnvironmentPhase.Prepared;
1732
+ this.session.programs.register(environment);
1733
+ }
1734
+ return environment;
1735
+ }
1736
+ ready(record) {
1737
+ if (record.scope?.phase === EnvironmentPhase.Live)
1738
+ return Promise.resolve();
1739
+ let ready = this.#ready.get(record.info.id);
1740
+ if (!ready) {
1741
+ ready = (async () => {
1742
+ try {
1743
+ await this.session.scopes.readyHostScope();
1744
+ if (record.scope?.phase === EnvironmentPhase.Closed)
1745
+ delete record.scope;
1746
+ const scope = this.scope(record);
1747
+ await this.session.programs.activate(scope.id);
1748
+ } catch (error) {
1749
+ if (record.scope) {
1750
+ await this.session.programs.cleanup([record.scope]);
1751
+ delete record.scope;
1752
+ }
1753
+ throw error;
1754
+ }
1755
+ })();
1756
+ this.#ready.set(record.info.id, ready);
1757
+ const clear = () => {
1758
+ if (this.#ready.get(record.info.id) === ready)
1759
+ this.#ready.delete(record.info.id);
1760
+ };
1761
+ ready.then(clear, clear);
1762
+ }
1763
+ return ready;
1764
+ }
1765
+ registerContributions(record) {
1766
+ for (const [alias, hooks] of Object.entries(record.definition.contributes ?? {})) {
1767
+ const requirement = record.definition.requires[alias];
1768
+ const target = requirement.orb ?? alias;
1769
+ for (const [hook, contribution] of Object.entries(hooks)) {
1770
+ const operation = this.session.kernel.command(KernelOp.Allocate);
1771
+ const key = JSON.stringify([record.info.name, target, hook]);
1772
+ if (!this.#ordinals.has(key))
1773
+ this.#ordinals.set(key, this.session.kernel.command(KernelOp.ContributionOrdinal));
1774
+ this.operations.set(operation, {
1775
+ orb: record,
1776
+ handler: typeof contribution === "function" ? contribution : contribution.handle
1777
+ });
1778
+ this.session.kernel.command(KernelOp.Contribute, {
1779
+ orb: record.info.id,
1780
+ target,
1781
+ hook,
1782
+ operation,
1783
+ priority: typeof contribution === "function" ? 0 : contribution.priority ?? 0,
1784
+ ordinal: this.#ordinals.get(key)
1785
+ });
1786
+ }
1787
+ }
1788
+ }
1789
+ async runHook(environment, name, context2, input) {
1790
+ context2 = context(context2, this.session);
1791
+ const definition = environment.orb.definition.hooks?.[name];
1792
+ if (!definition)
1793
+ refuse(Errors.Invalid.Hook, name);
1794
+ const plan = this.session.kernel.command(KernelOp.HookPlan, {
1795
+ root: context2.root,
1796
+ target: environment.orb.info.name,
1797
+ hook: name
1798
+ });
1799
+ const participants = plan.map((operation) => async (ctx, input, next) => {
1800
+ return this.runContribution(operation, ctx, input, next);
1801
+ });
1802
+ return definition.run(context2, input, participants);
1803
+ }
1804
+ async observe(environment, name, operation, source, input) {
1805
+ source = issuedContext(source, this.session);
1806
+ const definition = environment.orb.definition.hooks?.[name];
1807
+ if (!definition)
1808
+ refuse(Errors.Invalid.Hook, name);
1809
+ if (!source.invocation)
1810
+ throw new TembraError(Errors.Forbidden.ObservationSource);
1811
+ const admitted = this.session.kernel.command(KernelOp.BeginHookObservation, {
1812
+ source: source.invocation.id,
1813
+ orb: environment.orb.info.id,
1814
+ operation,
1815
+ ...environment.object ? { object: environment.object.id } : {},
1816
+ hook: name
1817
+ });
1818
+ await this.session.track(this.session.calls.root(async () => {
1819
+ try {
1820
+ const context = new Context(this.session, admitted.invocation.root, admitted.invocation);
1821
+ const participants = admitted.plan.map((operation) => async (ctx, input, next) => this.runContribution(operation, ctx, input, next));
1822
+ await definition.run(context, input, participants);
1823
+ } finally {
1824
+ this.session.lifecycle.finishCall(admitted.invocation.id);
1825
+ }
1826
+ }, false, admitted.invocation.root));
1827
+ }
1828
+ async runContribution(operation, ctx, input, next) {
1829
+ ctx = context(ctx, this.session);
1830
+ const contributor = this.operations.get(operation);
1831
+ if (!contributor) {
1832
+ const native = this.session.options.native;
1833
+ if (native?.hasContribution?.(operation) && native.contribute)
1834
+ return native.contribute(operation, ctx, input);
1835
+ throw new TembraError(Errors.Gone.Contribution);
1836
+ }
1837
+ const scope = contributor.orb.scope;
1838
+ if (!scope)
1839
+ throw new TembraError(Errors.Unavailable.OrbScope);
1840
+ return this.session.calls.owned(scope, operation, (entered) => contributor.handler(entered, input, next), ctx);
1841
+ }
1842
+ retire(id) {
1843
+ const scopes = this.session.kernel.command(KernelOp.ScopesForOrb, { orb: id });
1844
+ const cleanup = this.session.programs.cleanupScopes(scopes);
1845
+ this.session.track(cleanup.then(() => {
1846
+ for (const [operation, contribution] of this.operations)
1847
+ if (contribution.orb.info.id === id)
1848
+ this.operations.delete(operation);
1849
+ this.records.delete(id);
1850
+ this.#ready.delete(id);
1851
+ }), true);
1852
+ }
1853
+ }
1854
+
1855
+ // src/runtime/lifecycle.ts
1856
+ class Lifecycle {
1857
+ session;
1858
+ constructor(session) {
1859
+ this.session = session;
1860
+ }
1861
+ get closedDiagnostics() {
1862
+ return this.#finalDiagnostics;
1863
+ }
1864
+ #closed;
1865
+ #flushing = false;
1866
+ #linger;
1867
+ #lingerDeadline;
1868
+ #finalDiagnostics;
1869
+ flush(initial) {
1870
+ if (this.#flushing)
1871
+ return;
1872
+ this.#flushing = true;
1873
+ try {
1874
+ for (;; ) {
1875
+ const actions = initial ?? this.session.kernel.command(KernelOp.Drain);
1876
+ initial = undefined;
1877
+ if (!actions.length)
1878
+ break;
1879
+ for (const action of actions) {
1880
+ try {
1881
+ this.action(action);
1882
+ } catch (error) {
1883
+ this.session.report(error);
1884
+ }
1885
+ }
1886
+ }
1887
+ } finally {
1888
+ this.#flushing = false;
1889
+ this.scheduleLinger();
1890
+ }
1891
+ }
1892
+ finishCall(call) {
1893
+ const session = this.session;
1894
+ if (!this.#flushing && session.options.native?.finish) {
1895
+ const batch = session.options.native.finish(call, session.now());
1896
+ if (!batch.actions.length) {
1897
+ this.scheduleLinger(batch.deadline);
1898
+ return;
1899
+ }
1900
+ this.flush(batch.actions);
1901
+ return;
1902
+ }
1903
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
1904
+ session.kernel.command(KernelOp.FinishCall, { call });
1905
+ this.flush();
1906
+ }
1907
+ action(action) {
1908
+ const session = this.session;
1909
+ const nativeHandled = session.options.native?.notify?.(action);
1910
+ if (nativeHandled && !(action.type === ActionType.ProgramComplete && session.programs.pending(action.id)))
1911
+ return;
1912
+ switch (action.type) {
1913
+ case ActionType.Execute:
1914
+ case ActionType.CancelEffects:
1915
+ case ActionType.ProgramPrepared:
1916
+ case ActionType.ProgramComplete:
1917
+ session.programs.dispatch(action);
1918
+ break;
1919
+ case ActionType.DropValue:
1920
+ session.values.drop(action.id);
1921
+ session.options.native?.dropValue?.(action.id);
1922
+ break;
1923
+ case ActionType.CancelRoot:
1924
+ session.controllers.get(action.id)?.abort(new TembraError(Errors.Cancelled.Root));
1925
+ break;
1926
+ case ActionType.CancelTask:
1927
+ session.activities.cancel(action.id);
1928
+ break;
1929
+ case ActionType.Deliver:
1930
+ session.activities.deliver(action.id, action.payload, action.operation);
1931
+ break;
1932
+ case ActionType.DetachSubscription:
1933
+ session.activities.detach(action.id);
1934
+ break;
1935
+ case ActionType.SubscriptionFailed:
1936
+ session.activities.failed(action.id);
1937
+ break;
1938
+ case ActionType.Dispose:
1939
+ session.track(this.dispose(action.id), true);
1940
+ break;
1941
+ case ActionType.CloseResource: {
1942
+ break;
1943
+ }
1944
+ case ActionType.RetireOrb:
1945
+ session.handles.retire(action.id);
1946
+ session.orbs.retire(action.id);
1947
+ break;
1948
+ case ActionType.State: {
1949
+ const object = session.objects.get(action.id);
1950
+ if (!object?.binding)
1951
+ break;
1952
+ const snapshot = session.snapshot(action.id);
1953
+ if (!session.values.has(snapshot.value)) {
1954
+ const candidate = session.value(snapshot.value);
1955
+ session.publish(object.binding.adopt(object.binding.prepare(candidate), candidate));
1956
+ }
1957
+ break;
1958
+ }
1959
+ }
1960
+ }
1961
+ async dispose(id) {
1962
+ const session = this.session;
1963
+ const object = session.objects.get(id);
1964
+ if (!object) {
1965
+ await session.options.native?.dispose(id);
1966
+ session.kernel.command(KernelOp.Disposed, { object: id });
1967
+ this.flush();
1968
+ return;
1969
+ }
1970
+ object.disposing ??= (async () => {
1971
+ const errors = [];
1972
+ await object.activation.catch(() => {});
1973
+ const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
1974
+ owner: { kind: OwnerKind.Object, id }
1975
+ });
1976
+ try {
1977
+ await session.programs.cleanupScopes(scopes);
1978
+ } catch (error) {
1979
+ errors.push(error);
1980
+ }
1981
+ try {
1982
+ if (session.options.native?.hasOrb(object.orb))
1983
+ await session.options.native.dispose(id);
1984
+ } catch (error) {
1985
+ errors.push(error);
1986
+ }
1987
+ object.binding?.close();
1988
+ session.kernel.command(KernelOp.Disposed, { object: id });
1989
+ session.objects.delete(id);
1990
+ this.flush();
1991
+ if (errors.length)
1992
+ throw new AggregateError(errors, "Object cleanup failed");
1993
+ })();
1994
+ return object.disposing;
1995
+ }
1996
+ scheduleLinger(known) {
1997
+ const session = this.session;
1998
+ if (session.closing)
1999
+ return;
2000
+ const deadline = (known === undefined ? session.kernel.command(KernelOp.NextDeadline) : known) ?? undefined;
2001
+ if (deadline === this.#lingerDeadline)
2002
+ return;
2003
+ if (this.#linger !== undefined)
2004
+ clearTimeout(this.#linger);
2005
+ this.#linger = undefined;
2006
+ this.#lingerDeadline = deadline;
2007
+ if (deadline === undefined)
2008
+ return;
2009
+ this.#linger = setTimeout(() => {
2010
+ if (this.#lingerDeadline !== deadline)
2011
+ return;
2012
+ this.#linger = undefined;
2013
+ this.#lingerDeadline = undefined;
2014
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
2015
+ this.flush();
2016
+ }, Math.max(0, deadline - session.now()));
2017
+ this.#linger.unref?.();
2018
+ }
2019
+ diagnostics() {
2020
+ const session = this.session;
2021
+ if (this.#finalDiagnostics)
2022
+ return this.#finalDiagnostics;
2023
+ return {
2024
+ ...session.kernel.command(KernelOp.Diagnostics),
2025
+ values: session.values.size,
2026
+ pendingJobs: session.jobs.size
2027
+ };
2028
+ }
2029
+ close() {
2030
+ const session = this.session;
2031
+ this.#closed ??= (async () => {
2032
+ session.closing = true;
2033
+ clearTimeout(this.#linger);
2034
+ this.#linger = undefined;
2035
+ this.#lingerDeadline = undefined;
2036
+ session.kernel.command(KernelOp.Close);
2037
+ await session.replacements.cancel();
2038
+ this.flush();
2039
+ for (;; ) {
2040
+ await session.options.native?.settled?.();
2041
+ this.flush();
2042
+ const pending = [...session.jobs];
2043
+ if (!pending.length)
2044
+ break;
2045
+ await Promise.allSettled(pending);
2046
+ this.flush();
2047
+ }
2048
+ session.kernel.command(KernelOp.FinishClose);
2049
+ session.values.clear();
2050
+ session.handles.clear();
2051
+ session.orbs.records.clear();
2052
+ session.scopes.clear();
2053
+ this.#finalDiagnostics = this.diagnostics();
2054
+ session.kernel.port.free?.();
2055
+ if (session.cleanupErrors.length)
2056
+ throw new AggregateError(session.cleanupErrors, "Host cleanup failed");
2057
+ })();
2058
+ return this.#closed;
2059
+ }
2060
+ }
2061
+
2062
+ // src/runtime/records.ts
2063
+ function deferred() {
2064
+ let resolve;
2065
+ let reject;
2066
+ const promise = new Promise((accept, refuse) => {
2067
+ resolve = accept;
2068
+ reject = refuse;
2069
+ });
2070
+ promise.catch(() => {});
2071
+ return { promise, resolve, reject };
2072
+ }
2073
+
2074
+ // src/runtime/programs.ts
2075
+ function errorText(value, limit) {
2076
+ return value.slice(0, limit).replace(/[\uD800-\uDFFF]/gu, "�");
2077
+ }
2078
+
2079
+ class Programs {
2080
+ session;
2081
+ scopes = new Map;
2082
+ #pending = new Map;
2083
+ constructor(session) {
2084
+ this.session = session;
2085
+ }
2086
+ register(environment) {
2087
+ const parent = environment.owner.kind === OwnerKind.Host ? undefined : environment.object ? environment.orb.scope : this.session.hostScope;
2088
+ this.session.kernel.command(KernelOp.ScopeRegister, {
2089
+ scope: environment.id,
2090
+ owner: environment.owner,
2091
+ orb: environment.orb.info.id,
2092
+ parents: parent ? [parent.id] : [],
2093
+ dependencies: [...environment.dependencies.values()].map((reference) => this.session.handles.reference(reference).id),
2094
+ resources: [...environment.resources.values()].map((resource) => resource.id),
2095
+ stateVersion: environment.state?.options.version ?? (environment.state ? 1 : undefined),
2096
+ migrate: Boolean(environment.state?.options.migrate)
2097
+ });
2098
+ }
2099
+ activate(scope) {
2100
+ return this.run(this.session.kernel.command(KernelOp.ScopeActivate, { scope }));
2101
+ }
2102
+ cleanup(environments) {
2103
+ const scopes = environments.map((environment) => environment.id).filter((scope) => this.session.kernel.command(KernelOp.ScopeExists, { scope }));
2104
+ return this.cleanupScopes(scopes);
2105
+ }
2106
+ cleanupScopes(scopes) {
2107
+ return scopes.length ? this.run(this.session.kernel.command(KernelOp.ScopesCleanup, { scopes })) : Promise.resolve();
2108
+ }
2109
+ pending(program) {
2110
+ return this.#pending.has(program);
2111
+ }
2112
+ run(program) {
2113
+ const pending = this.#pending.get(program);
2114
+ if (pending)
2115
+ return pending.promise;
2116
+ const completion = deferred();
2117
+ this.#pending.set(program, completion);
2118
+ try {
2119
+ this.session.kernel.command(KernelOp.ProgramRun, { program });
2120
+ this.session.lifecycle.flush();
2121
+ } catch (error) {
2122
+ this.#pending.delete(program);
2123
+ completion.reject(error);
2124
+ }
2125
+ return completion.promise;
2126
+ }
2127
+ dispatch(action) {
2128
+ if (action.type === ActionType.Execute) {
2129
+ this.session.track(Promise.allSettled(action.effects.map((effect) => this.execute(effect))).then((settled) => {
2130
+ const limit = Math.max(0, Math.min(2048, Math.floor((1024 * 1024 - 128 - settled.length * 96) / (12 * settled.length))));
2131
+ const results = settled.map((result) => {
2132
+ if (result.status === "fulfilled")
2133
+ return { value: result.value ?? null };
2134
+ try {
2135
+ const { code, reason, message } = failure(result.reason);
2136
+ if (!Object.values(Code).includes(code) || typeof reason !== "string" || typeof message !== "string")
2137
+ return { error: Errors.Unavailable.Callback };
2138
+ return {
2139
+ error: {
2140
+ code,
2141
+ reason: errorText(reason, limit),
2142
+ message: errorText(message, limit)
2143
+ }
2144
+ };
2145
+ } catch {
2146
+ return { error: Errors.Unavailable.Callback };
2147
+ }
2148
+ });
2149
+ this.session.kernel.command(KernelOp.ProgramCompleteStep, {
2150
+ program: action.id,
2151
+ results
2152
+ });
2153
+ this.session.lifecycle.flush();
2154
+ }));
2155
+ } else if (action.type === ActionType.CancelEffects) {
2156
+ for (const effect of action.effects) {
2157
+ if (effect.type !== EffectType.Open && effect.type !== EffectType.Restore)
2158
+ continue;
2159
+ const resource = this.session.resources.find(effect.resource);
2160
+ if (resource)
2161
+ resource.controller.abort(new TembraError(Errors.Cancelled.EngineEffect));
2162
+ else if (this.session.options.native?.cancelEffect) {
2163
+ const cancel = this.session.options.native.cancelEffect.bind(this.session.options.native);
2164
+ this.session.track(Promise.resolve().then(() => cancel(effect))).catch((error) => this.session.report(error));
2165
+ }
2166
+ }
2167
+ } else {
2168
+ const completion = this.#pending.get(action.id);
2169
+ this.#pending.delete(action.id);
2170
+ if (action.error) {
2171
+ const error = new TembraError(action.error);
2172
+ if (completion)
2173
+ completion.reject(error);
2174
+ else {
2175
+ this.session.cleanupErrors.push(error);
2176
+ this.session.report(error);
2177
+ }
2178
+ } else
2179
+ completion?.resolve();
2180
+ }
2181
+ }
2182
+ resource(id) {
2183
+ const direct = this.session.resources.find(id);
2184
+ if (direct)
2185
+ return direct;
2186
+ throw new TembraError(Errors.Gone.Resource);
2187
+ }
2188
+ async execute(effect) {
2189
+ const environment = effect.scope === undefined ? undefined : this.scopes.get(effect.scope);
2190
+ if (effect.scope !== undefined && !environment && this.session.options.native)
2191
+ return this.session.options.native.effect(effect);
2192
+ if ((effect.type === EffectType.Close || effect.type === EffectType.Open) && !this.session.resources.find(effect.resource) && this.session.options.native)
2193
+ return this.session.options.native.effect(effect);
2194
+ switch (effect.type) {
2195
+ case EffectType.Open:
2196
+ await this.resource(effect.resource).start();
2197
+ break;
2198
+ case EffectType.Close:
2199
+ await this.session.resources.close(this.resource(effect.resource));
2200
+ break;
2201
+ case EffectType.Restore:
2202
+ await this.session.resources.reopen(this.resource(effect.previous), effect.resource);
2203
+ break;
2204
+ case EffectType.Stop:
2205
+ if (environment)
2206
+ await this.session.activities.stop(environment);
2207
+ break;
2208
+ case EffectType.Prepare: {
2209
+ if (!environment)
2210
+ throw new TembraError(Errors.Gone.Scope);
2211
+ this.session.activities.prepare(environment, effect.previous ? this.scopes.get(effect.previous) : undefined);
2212
+ break;
2213
+ }
2214
+ case EffectType.Validate:
2215
+ validate(this.session.value(effect.value), environment.state.options);
2216
+ break;
2217
+ case EffectType.Initialize:
2218
+ return this.candidate(environment, environment.state.initial);
2219
+ case EffectType.Migrate: {
2220
+ const state = environment.state;
2221
+ return this.candidate(environment, state.options.migrate(this.session.value(effect.value), effect.version));
2222
+ }
2223
+ case EffectType.Adopt: {
2224
+ const orbs = new Map;
2225
+ for (const pair of effect.replacements) {
2226
+ if (!pair.next)
2227
+ continue;
2228
+ const next = this.scopes.get(pair.next);
2229
+ for (const [resource, declaration] of next.resourceDeclarations ?? [])
2230
+ resource.options = declaration;
2231
+ delete next.resourceDeclarations;
2232
+ orbs.set(next.orb.info.id, next.orb);
2233
+ if (next.object) {
2234
+ if (next.state)
2235
+ next.object.binding = next.state.binding;
2236
+ next.object.orb = next.orb.info.id;
2237
+ next.object.versions.set(next.orb.info.id, next);
2238
+ }
2239
+ }
2240
+ for (const record of orbs.values()) {
2241
+ this.session.orbs.records.set(record.info.id, record);
2242
+ this.session.orbs.registerContributions(record);
2243
+ }
2244
+ for (const pair of effect.replacements) {
2245
+ const next = pair.next ? this.scopes.get(pair.next) : undefined;
2246
+ if (next?.object)
2247
+ this.session.handles.refreshReferences(next.object, next.orb);
2248
+ }
2249
+ for (const pair of effect.replacements)
2250
+ if (pair.next)
2251
+ this.scopes.get(pair.next)?.state?.publish?.();
2252
+ break;
2253
+ }
2254
+ case EffectType.Start:
2255
+ if (environment) {
2256
+ this.session.activities.start(environment);
2257
+ if (environment.object)
2258
+ environment.object.live = true;
2259
+ }
2260
+ break;
2261
+ case EffectType.Drop: {
2262
+ if (!environment)
2263
+ break;
2264
+ for (const reference of environment.dependencies.values())
2265
+ this.session.handles.revoke(this.session.handles.reference(reference).id);
2266
+ environment.dependencies.clear();
2267
+ for (const resource of environment.resources.values())
2268
+ this.session.resources.closedRecords.delete(resource.id);
2269
+ environment.phase = EnvironmentPhase.Closed;
2270
+ if (environment.object)
2271
+ environment.object.versions.delete(environment.orb.info.id);
2272
+ this.scopes.delete(environment.id);
2273
+ break;
2274
+ }
2275
+ default:
2276
+ throw new TembraError(Errors.Unsupported.EngineEffect, effect.type);
2277
+ }
2278
+ }
2279
+ candidate(environment, candidate) {
2280
+ const state = environment.state;
2281
+ const value = validate(candidate, state.options);
2282
+ const id = this.session.values.put(value);
2283
+ state.publish = () => this.session.publish(state.binding.adopt(state.binding.prepare(value), value));
2284
+ return id;
2285
+ }
2286
+ }
2287
+
2288
+ // src/runtime/references.ts
2289
+ var references = new WeakMap;
2290
+ var finalizer = typeof FinalizationRegistry === "undefined" ? undefined : new FinalizationRegistry((held) => held.session.deref()?.handles.release(held.id));
2291
+
2292
+ class References {
2293
+ session;
2294
+ constructor(session) {
2295
+ this.session = session;
2296
+ }
2297
+ #metadata = new Map;
2298
+ #byObject = new Map;
2299
+ activateAcquired(acquired, address, requiredMethods = []) {
2300
+ const session = this.session;
2301
+ let object = session.objects.get(acquired.object);
2302
+ if (!object) {
2303
+ const activation = deferred();
2304
+ object = {
2305
+ id: acquired.object,
2306
+ address,
2307
+ orb: acquired.orb,
2308
+ versions: new Map,
2309
+ activation: activation.promise
2310
+ };
2311
+ session.objects.set(object.id, object);
2312
+ const record = object;
2313
+ session.track(session.scopes.activate(record, acquired).then(activation.resolve, (error) => {
2314
+ record.error = error;
2315
+ try {
2316
+ session.kernel.command(KernelOp.Fail, { object: record.id });
2317
+ } catch {}
2318
+ activation.reject(error);
2319
+ session.lifecycle.flush();
2320
+ }));
2321
+ }
2322
+ if (!this.claimExists(acquired.reference))
2323
+ return object.activation;
2324
+ const provider = this.orbMetadata(object.orb);
2325
+ const methods = provider.services.find((service) => service.name === address.service)?.methods ?? [];
2326
+ const record = {
2327
+ id: acquired.reference,
2328
+ object: acquired.object,
2329
+ address,
2330
+ methods: new Set(methods),
2331
+ requiredMethods: new Set(requiredMethods),
2332
+ stateCleanups: new Set,
2333
+ ready: object.activation,
2334
+ released: false,
2335
+ nativeOwned: true
2336
+ };
2337
+ const access = session.orbs.records.get(object.orb)?.definition.services?.[address.service]?.access;
2338
+ try {
2339
+ this.referenceMethods(record, methods, access);
2340
+ } catch (error) {
2341
+ if (session.kernel.features.views && this.claimExists(record.id))
2342
+ session.kernel.command(KernelOp.Restrict, { reference: record.id, methods: [] });
2343
+ throw error;
2344
+ }
2345
+ session.references.set(record.id, record);
2346
+ let owned = this.#byObject.get(record.object);
2347
+ if (!owned)
2348
+ this.#byObject.set(record.object, owned = new Set);
2349
+ owned.add(record);
2350
+ return object.activation;
2351
+ }
2352
+ hold(service, key, options = {}, ctx) {
2353
+ const session = this.session;
2354
+ if (ctx)
2355
+ context(ctx, session);
2356
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
2357
+ const address = {
2358
+ service,
2359
+ key: typeof key === "string" ? [key] : [...key],
2360
+ principal: options.principal ?? ctx?.principal ?? session.principal
2361
+ };
2362
+ const acquired = session.kernel.command(KernelOp.Acquire, {
2363
+ ...address,
2364
+ apiVersion: options.apiVersion ?? 0,
2365
+ methods: options.methods ?? []
2366
+ });
2367
+ let object = session.objects.get(acquired.object);
2368
+ if (!object) {
2369
+ const activation = deferred();
2370
+ object = {
2371
+ id: acquired.object,
2372
+ address,
2373
+ orb: acquired.orb,
2374
+ versions: new Map,
2375
+ activation: activation.promise
2376
+ };
2377
+ session.objects.set(object.id, object);
2378
+ const record = object;
2379
+ queueMicrotask(() => {
2380
+ session.track(session.scopes.activate(record, acquired).then(activation.resolve, (error) => {
2381
+ record.error = error;
2382
+ try {
2383
+ session.kernel.command(KernelOp.Fail, { object: record.id });
2384
+ } catch {}
2385
+ activation.reject(error);
2386
+ session.lifecycle.flush();
2387
+ }));
2388
+ });
2389
+ }
2390
+ const provider = this.orbMetadata(acquired.orb);
2391
+ const methods = new Set(provider.services.find((s) => s.name === service)?.methods ?? []);
2392
+ const record = {
2393
+ id: acquired.reference,
2394
+ object: acquired.object,
2395
+ address,
2396
+ methods,
2397
+ requiredMethods: new Set(options.methods ?? []),
2398
+ stateCleanups: new Set,
2399
+ ready: object.activation,
2400
+ released: false,
2401
+ ...ctx ? { context: ctx } : {}
2402
+ };
2403
+ const nativeAccess = session.options.native?.access?.(acquired.orb, service, address.principal);
2404
+ const access = nativeAccess ? () => ({ methods: nativeAccess }) : session.orbs.records.get(acquired.orb)?.definition.services?.[service]?.access;
2405
+ try {
2406
+ this.referenceMethods(record, methods, access);
2407
+ } catch (error) {
2408
+ session.kernel.command(KernelOp.Release, { reference: record.id });
2409
+ session.kernel.command(KernelOp.Forget, { reference: record.id });
2410
+ session.lifecycle.flush();
2411
+ throw error;
2412
+ }
2413
+ session.references.set(record.id, record);
2414
+ let owned = this.#byObject.get(record.object);
2415
+ if (!owned) {
2416
+ owned = new Set;
2417
+ this.#byObject.set(record.object, owned);
2418
+ }
2419
+ owned.add(record);
2420
+ if (ctx) {
2421
+ let owned = session.rootReferences.get(ctx.root);
2422
+ if (!owned) {
2423
+ owned = new Set;
2424
+ session.rootReferences.set(ctx.root, owned);
2425
+ }
2426
+ owned.add(record.id);
2427
+ }
2428
+ const check = () => {
2429
+ if (record.released)
2430
+ throw new TembraError(Errors.Released.Reference);
2431
+ if (session.closing)
2432
+ throw new TembraError(Errors.Gone.Reference);
2433
+ const object = session.objects.get(record.object);
2434
+ if (!object || object.disposing || object.error)
2435
+ throw new TembraError(Errors.Gone.Reference);
2436
+ if (!object.live)
2437
+ throw new TembraError(Errors.Unavailable.NotReady);
2438
+ };
2439
+ const target = {
2440
+ get ready() {
2441
+ return record.ready;
2442
+ },
2443
+ get status() {
2444
+ return record.released ? Status.Released : recordSession.closing ? Status.Gone : recordSession.kernel.command(KernelOp.Status, { reference: record.id });
2445
+ },
2446
+ get state() {
2447
+ check();
2448
+ const binding = recordSession.objects.get(record.object)?.binding;
2449
+ if (!binding)
2450
+ refuse(Errors.Invalid.State, "Service does not expose state");
2451
+ return consumerState(binding, check, record.stateCleanups);
2452
+ },
2453
+ release: () => this.release(record.id),
2454
+ opaque: (name) => {
2455
+ check();
2456
+ const object = session.objects.get(record.object);
2457
+ const resource = object.versions.get(object.orb)?.resources.get(name);
2458
+ if (!resource?.options.opaque)
2459
+ throw new TembraError(Errors.Forbidden.Opaque, name);
2460
+ return resource.handle.value;
2461
+ }
2462
+ };
2463
+ const recordSession = session;
2464
+ const proxy = new Proxy(target, {
2465
+ get: (target, property, receiver) => {
2466
+ if (property === "then")
2467
+ return;
2468
+ if (Object.hasOwn(target, property))
2469
+ return Reflect.get(target, property, receiver);
2470
+ if (typeof property !== "string")
2471
+ return;
2472
+ if (!record.methods.has(property))
2473
+ return;
2474
+ return (...arguments_) => {
2475
+ let callContext = record.context;
2476
+ if (isContext(arguments_.at(-1)))
2477
+ callContext = arguments_.pop();
2478
+ return callContext ? session.calls.invoke(record, property, arguments_, context(callContext, session)) : session.calls.root((ctx) => session.calls.invoke(record, property, arguments_, ctx), false, undefined, record.address.principal);
2479
+ };
2480
+ }
2481
+ });
2482
+ references.set(proxy, { session, record });
2483
+ finalizer?.register(proxy, { session: new WeakRef(session), id: record.id }, record);
2484
+ return proxy;
2485
+ }
2486
+ async get(service, key, options = {}, ctx) {
2487
+ const reference = this.hold(service, key, options, ctx);
2488
+ try {
2489
+ await reference.ready;
2490
+ return reference;
2491
+ } catch (error) {
2492
+ reference.release();
2493
+ throw error;
2494
+ }
2495
+ }
2496
+ reference(value) {
2497
+ const issued = typeof value === "object" && value !== null ? references.get(value) : undefined;
2498
+ if (!issued || issued.session !== this.session)
2499
+ refuse(Errors.Invalid.Reference, "An issued local reference is required");
2500
+ return issued.record;
2501
+ }
2502
+ orbMetadata(id) {
2503
+ const definition = this.session.orbs.records.get(id)?.info;
2504
+ if (definition)
2505
+ return definition;
2506
+ let metadata = this.#metadata.get(id);
2507
+ if (!metadata) {
2508
+ metadata = this.session.kernel.command(KernelOp.Orb, { id });
2509
+ this.#metadata.set(id, metadata);
2510
+ }
2511
+ return metadata;
2512
+ }
2513
+ referenceMethods(record, methods, access, resetAccess = false) {
2514
+ const session = this.session;
2515
+ if (access && !session.kernel.features.views)
2516
+ throw new TembraError(Errors.Unsupported.Views);
2517
+ const allowed = access ? new Set(access(record.address.principal).methods) : undefined;
2518
+ const visible = new Set([...methods].filter((method) => (!record.requiredMethods.size || record.requiredMethods.has(method)) && (!allowed || allowed.has(method))));
2519
+ if (access || resetAccess && session.kernel.features.views)
2520
+ session.kernel.command(KernelOp.Restrict, {
2521
+ reference: record.id,
2522
+ methods: [...visible]
2523
+ });
2524
+ record.methods = visible;
2525
+ }
2526
+ refreshReferences(object, orb) {
2527
+ const session = this.session;
2528
+ const service = orb.definition.services?.[object.address.service];
2529
+ if (!service)
2530
+ return;
2531
+ const methods = Object.keys(service.methods);
2532
+ for (const reference of this.#byObject.get(object.id) ?? []) {
2533
+ if (reference.released)
2534
+ continue;
2535
+ if (reference.nativeOwned && !this.claimExists(reference.id)) {
2536
+ this.revoke(reference.id);
2537
+ continue;
2538
+ }
2539
+ try {
2540
+ this.referenceMethods(reference, methods, service.access, true);
2541
+ } catch (error) {
2542
+ reference.methods.clear();
2543
+ if (!reference.released && session.kernel.features.views)
2544
+ session.kernel.command(KernelOp.Restrict, { reference: reference.id, methods: [] });
2545
+ session.report(error);
2546
+ }
2547
+ }
2548
+ }
2549
+ claimExists(reference) {
2550
+ try {
2551
+ const status = this.session.kernel.command(KernelOp.Status, { reference });
2552
+ return status !== Status.Released && status !== Status.Gone;
2553
+ } catch (error) {
2554
+ if (error instanceof TembraError && (error.code === Code.Gone || error.code === Code.Released))
2555
+ return false;
2556
+ throw error;
2557
+ }
2558
+ }
2559
+ forget(record) {
2560
+ for (const cleanup of record.stateCleanups)
2561
+ cleanup();
2562
+ record.stateCleanups.clear();
2563
+ this.session.references.delete(record.id);
2564
+ const owned = this.#byObject.get(record.object);
2565
+ owned?.delete(record);
2566
+ if (!owned?.size)
2567
+ this.#byObject.delete(record.object);
2568
+ }
2569
+ release(id) {
2570
+ const session = this.session;
2571
+ const record = session.references.get(id);
2572
+ if (!record || record.released)
2573
+ return;
2574
+ record.released = true;
2575
+ finalizer?.unregister(record);
2576
+ if (session.lifecycle.closedDiagnostics) {
2577
+ this.forget(record);
2578
+ return;
2579
+ }
2580
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
2581
+ session.kernel.command(KernelOp.Release, { reference: id });
2582
+ session.kernel.command(KernelOp.Forget, { reference: id });
2583
+ this.forget(record);
2584
+ session.lifecycle.flush();
2585
+ }
2586
+ revoke(id) {
2587
+ const record = this.session.references.get(id);
2588
+ if (!record)
2589
+ return;
2590
+ record.released = true;
2591
+ finalizer?.unregister(record);
2592
+ this.forget(record);
2593
+ }
2594
+ retire(orb) {
2595
+ this.#metadata.delete(orb);
2596
+ }
2597
+ clear() {
2598
+ for (const reference of this.session.references.values())
2599
+ this.forget(reference);
2600
+ this.session.references.clear();
2601
+ this.#byObject.clear();
2602
+ this.#metadata.clear();
2603
+ }
2604
+ }
2605
+
2606
+ // src/runtime/reload.ts
2607
+ class Replacements {
2608
+ session;
2609
+ #pending;
2610
+ #program;
2611
+ #prepared;
2612
+ constructor(session) {
2613
+ this.session = session;
2614
+ }
2615
+ async replace(definitions, options = {}, remove = []) {
2616
+ return (await this.prepare(definitions, options, remove)).commit();
2617
+ }
2618
+ prepare(definitions, options = {}, remove = []) {
2619
+ if (this.session.closing)
2620
+ return Promise.reject(new TembraError(Errors.Closed.Host));
2621
+ if (this.#pending)
2622
+ return Promise.reject(new TembraError(Errors.Conflict.ReloadRunning));
2623
+ const pending = this.capture(definitions, options, remove);
2624
+ this.#pending = pending;
2625
+ pending.catch(() => {
2626
+ if (this.#pending === pending)
2627
+ this.#pending = undefined;
2628
+ });
2629
+ return pending;
2630
+ }
2631
+ async cancel() {
2632
+ if (this.#prepared?.status === ReloadStatus.Prepared)
2633
+ return this.#prepared.abort();
2634
+ if (this.#program !== undefined) {
2635
+ this.session.kernel.command(KernelOp.ProgramAbort, { program: this.#program });
2636
+ const settled = this.session.programs.run(this.#program);
2637
+ this.session.lifecycle.flush();
2638
+ await settled.catch(() => {});
2639
+ }
2640
+ await this.#pending?.catch(() => {
2641
+ return;
2642
+ });
2643
+ }
2644
+ async capture(definitions, options, remove) {
2645
+ const session = this.session;
2646
+ const declarations = session.orbs.declarations(definitions);
2647
+ const reload = session.kernel.command(KernelOp.Prepare, {
2648
+ orbs: declarations.metadata,
2649
+ remove
2650
+ });
2651
+ const definitionsByName = new Map(declarations.definitions.map((definition) => [definition.name, definition]));
2652
+ const records = reload.orbs.map((info) => ({
2653
+ info,
2654
+ definition: definitionsByName.get(info.name),
2655
+ ticket: reload.id
2656
+ }));
2657
+ const recordsById = new Map(records.map((record) => [record.info.id, record]));
2658
+ let program;
2659
+ try {
2660
+ for (const record of records)
2661
+ session.orbs.scope(record);
2662
+ for (const id of reload.objects) {
2663
+ const object = session.objects.get(id);
2664
+ if (!object)
2665
+ continue;
2666
+ const orb = reload.providers[object.address.service];
2667
+ const record = orb === undefined ? undefined : recordsById.get(orb);
2668
+ if (record)
2669
+ session.scopes.createEnvironment(object, record);
2670
+ }
2671
+ for (const record of records)
2672
+ record.ticket = undefined;
2673
+ program = session.kernel.command(KernelOp.ScopesReloadRegistered, {
2674
+ ticket: reload.id,
2675
+ deadline: options.deadline ?? 5000,
2676
+ now: session.now()
2677
+ });
2678
+ this.#program = program;
2679
+ await session.programs.run(program);
2680
+ if (session.closing)
2681
+ await session.programs.run(program);
2682
+ } catch (error) {
2683
+ this.#program = undefined;
2684
+ if (program === undefined) {
2685
+ session.kernel.command(KernelOp.Abort, { ticket: reload.id });
2686
+ const scopes = reload.orbs.flatMap((orb) => session.kernel.command(KernelOp.ScopesForOrb, { orb: orb.id }));
2687
+ await session.programs.cleanupScopes(scopes);
2688
+ }
2689
+ throw error;
2690
+ }
2691
+ this.#program = undefined;
2692
+ const id = program;
2693
+ const report = {
2694
+ codeVersion: reload.codeVersion,
2695
+ orbs: records.map((record) => record.info.name)
2696
+ };
2697
+ let status = ReloadStatus.Prepared;
2698
+ return this.#prepared = {
2699
+ report,
2700
+ get status() {
2701
+ return status;
2702
+ },
2703
+ commit: async () => {
2704
+ if (status !== ReloadStatus.Prepared)
2705
+ throw new TembraError(Errors.Conflict.ReloadTicket);
2706
+ this.#prepared = undefined;
2707
+ try {
2708
+ session.kernel.command(KernelOp.ProgramCommit, { program: id });
2709
+ } catch (error) {
2710
+ session.kernel.command(KernelOp.ProgramAbort, { program: id });
2711
+ await session.programs.run(id).catch(() => {});
2712
+ status = ReloadStatus.Aborted;
2713
+ this.#pending = undefined;
2714
+ throw error;
2715
+ }
2716
+ status = ReloadStatus.Committed;
2717
+ this.#pending = undefined;
2718
+ await session.programs.run(id);
2719
+ return report;
2720
+ },
2721
+ abort: async () => {
2722
+ if (status === ReloadStatus.Aborted)
2723
+ return;
2724
+ if (status !== ReloadStatus.Prepared)
2725
+ throw new TembraError(Errors.Conflict.AlreadyCommitted);
2726
+ status = ReloadStatus.Aborted;
2727
+ this.#prepared = undefined;
2728
+ this.#pending = undefined;
2729
+ session.kernel.command(KernelOp.ProgramAbort, { program: id });
2730
+ try {
2731
+ await session.programs.run(id);
2732
+ } catch (error) {
2733
+ if (!(error instanceof TembraError) || error.reason !== Reason.ReloadAborted)
2734
+ throw error;
2735
+ }
2736
+ }
2737
+ };
2738
+ }
2739
+ }
2740
+
2741
+ // src/runtime/resources.ts
2742
+ var issued2 = new WeakMap;
2743
+
2744
+ class Resources {
2745
+ session;
2746
+ records = new Map;
2747
+ closedRecords = new Map;
2748
+ constructor(session) {
2749
+ this.session = session;
2750
+ }
2751
+ find(id) {
2752
+ return this.records.get(id) ?? this.closedRecords.get(id);
2753
+ }
2754
+ dependencyIds(options) {
2755
+ const dependencies = [];
2756
+ for (const dependency of options.deps ?? []) {
2757
+ const resource = typeof dependency === "object" && dependency !== null ? issued2.get(dependency) : undefined;
2758
+ if (resource) {
2759
+ if (resource.session !== this.session)
2760
+ refuse(Errors.Invalid.ResourceHost, "Resource dependencies must belong to the same host");
2761
+ dependencies.push(resource.id);
2762
+ } else {
2763
+ this.session.handles.reference(dependency);
2764
+ }
2765
+ }
2766
+ return dependencies;
2767
+ }
2768
+ register(environment, name, options) {
2769
+ return this.session.kernel.command(KernelOp.Resource, {
2770
+ owner: environment.owner,
2771
+ name,
2772
+ version: options.version ?? 1,
2773
+ exclusive: options.exclusive ?? false,
2774
+ dependencies: this.dependencyIds(options)
2775
+ }).id;
2776
+ }
2777
+ redeclare(environment, previous) {
2778
+ for (const resource of previous.resources.values()) {
2779
+ this.records.delete(resource.id);
2780
+ this.closedRecords.delete(resource.id);
2781
+ resource.reset(this.register(environment, resource.name, resource.options));
2782
+ resource.dependencies = this.dependencyIds(resource.options);
2783
+ this.records.set(resource.id, resource);
2784
+ environment.resources.set(resource.name, resource);
2785
+ }
2786
+ }
2787
+ declare(environment, name, options) {
2788
+ if (!name || typeof options.open !== "function")
2789
+ refuse(Errors.Invalid.Resource);
2790
+ const id = this.register(environment, name, options);
2791
+ const reused = this.records.get(id);
2792
+ if (reused) {
2793
+ (environment.resourceDeclarations ??= new Map).set(reused, options);
2794
+ return reused;
2795
+ }
2796
+ const controller = new AbortController;
2797
+ const handle = Object.freeze({
2798
+ get value() {
2799
+ if (environment.phase === EnvironmentPhase.Declaring)
2800
+ refuse(Errors.Invalid.ResourceInFactory, "Resources open after declaration");
2801
+ const value = record.session.kernel.command(KernelOp.ResourceValue, {
2802
+ resource: record.id
2803
+ });
2804
+ return record.session.value(value);
2805
+ },
2806
+ version: options.version ?? 1
2807
+ });
2808
+ const record = {
2809
+ id,
2810
+ name,
2811
+ options,
2812
+ handle,
2813
+ dependencies: this.dependencyIds(options),
2814
+ controller,
2815
+ session: this.session,
2816
+ reset: (id) => {
2817
+ record.id = id;
2818
+ record.controller = new AbortController;
2819
+ delete record.value;
2820
+ delete record.closed;
2821
+ delete record.started;
2822
+ },
2823
+ start: () => {
2824
+ record.started ??= (async () => {
2825
+ const declaration = record.options;
2826
+ const value = await declaration.open(record.controller.signal);
2827
+ const id = this.session.values.put(value);
2828
+ try {
2829
+ this.session.kernel.command(KernelOp.ResourceOpened, {
2830
+ resource: record.id,
2831
+ value: id
2832
+ });
2833
+ } catch (error) {
2834
+ this.session.values.drop(id);
2835
+ if (declaration.close)
2836
+ await this.session.calls.root((ctx) => declaration.close(value, ctx), true);
2837
+ throw error;
2838
+ }
2839
+ record.value = id;
2840
+ })();
2841
+ record.started.catch(() => {});
2842
+ return record.started;
2843
+ }
2844
+ };
2845
+ issued2.set(handle, record);
2846
+ this.records.set(id, record);
2847
+ return record;
2848
+ }
2849
+ async close(record) {
2850
+ record.closed ??= (async () => {
2851
+ record.controller.abort(new TembraError(Errors.Cancelled.Resource));
2852
+ await record.started?.catch(() => {});
2853
+ try {
2854
+ if (record.value !== undefined && record.options.close) {
2855
+ const value = this.session.value(record.value);
2856
+ await this.session.calls.root((ctx) => record.options.close(value, ctx), true);
2857
+ }
2858
+ } finally {
2859
+ this.session.kernel.command(KernelOp.ResourceClosed, { resource: record.id });
2860
+ this.records.delete(record.id);
2861
+ this.closedRecords.set(record.id, record);
2862
+ this.session.lifecycle.flush();
2863
+ }
2864
+ })();
2865
+ return record.closed;
2866
+ }
2867
+ async reopen(record, id) {
2868
+ this.closedRecords.delete(record.id);
2869
+ record.reset(id);
2870
+ this.records.set(id, record);
2871
+ await record.start();
2872
+ }
2873
+ }
2874
+
2875
+ // src/runtime/scopes.ts
2876
+ class Scopes {
2877
+ session;
2878
+ constructor(session) {
2879
+ this.session = session;
2880
+ }
2881
+ #hostResources = new Map;
2882
+ #pendingHostScopes = new Set;
2883
+ #hostActivation;
2884
+ environment(owner, orb, object) {
2885
+ const environment = {
2886
+ id: this.session.kernel.command(KernelOp.Allocate),
2887
+ owner,
2888
+ orb,
2889
+ ...object ? { object } : {},
2890
+ phase: EnvironmentPhase.Declaring,
2891
+ value: {},
2892
+ dependencies: new Map,
2893
+ resources: new Map,
2894
+ tasks: [],
2895
+ listeners: []
2896
+ };
2897
+ this.session.programs.scopes.set(environment.id, environment);
2898
+ return environment;
2899
+ }
2900
+ async activate(object, acquired) {
2901
+ const session = this.session;
2902
+ if (session.options.native?.hasOrb(acquired.orb)) {
2903
+ await session.options.native.activate(object.id, acquired.orb, object.address.service, object.address.key, object.address.principal);
2904
+ const scopes = session.kernel.command(KernelOp.ScopesForOwner, {
2905
+ owner: { kind: OwnerKind.Object, id: object.id }
2906
+ });
2907
+ await Promise.all(scopes.map((scope) => session.programs.activate(scope)));
2908
+ try {
2909
+ session.snapshot(object.id);
2910
+ object.binding = new StateBinding(session, object.id);
2911
+ } catch {}
2912
+ } else {
2913
+ const orb = session.orbs.records.get(acquired.orb);
2914
+ if (!orb)
2915
+ refuse(Errors.Invalid.OrbGone);
2916
+ await session.orbs.ready(orb);
2917
+ const environment = this.createEnvironment(object, orb);
2918
+ object.versions.set(orb.info.id, environment);
2919
+ await this.session.programs.activate(environment.id);
2920
+ }
2921
+ if (session.kernel.command(KernelOp.Status, { reference: acquired.reference }) === Status.Loading)
2922
+ session.kernel.command(KernelOp.Ready, { object: object.id });
2923
+ object.live = true;
2924
+ session.lifecycle.flush();
2925
+ }
2926
+ createEnvironment(object, orb) {
2927
+ const definition = orb.definition.services?.[object.address.service];
2928
+ if (!definition)
2929
+ refuse(Errors.Invalid.ServiceGone);
2930
+ const environment = this.environment({ kind: OwnerKind.Object, id: object.id }, orb, object);
2931
+ try {
2932
+ const value = definition.create?.(new Declaration(this.session, environment)) ?? {};
2933
+ if (value && typeof value.then === "function")
2934
+ refuse(Errors.Invalid.AsyncFactory, "Factories must be synchronous");
2935
+ environment.value = value;
2936
+ return environment;
2937
+ } finally {
2938
+ environment.phase = EnvironmentPhase.Prepared;
2939
+ this.session.programs.register(environment);
2940
+ }
2941
+ }
2942
+ readyHostScope() {
2943
+ const session = this.session;
2944
+ if (session.closing)
2945
+ return Promise.reject(new TembraError(Errors.Closed.Host));
2946
+ if (this.#hostActivation)
2947
+ return this.#hostActivation;
2948
+ const activation = (async () => {
2949
+ if (session.hostScope.phase === EnvironmentPhase.Closed)
2950
+ session.hostScope = await this.redeclareHostScope(session.hostScope);
2951
+ await this.session.programs.activate(session.hostScope.id);
2952
+ while (this.#pendingHostScopes.size) {
2953
+ let environment = this.#pendingHostScopes.values().next().value;
2954
+ if (environment.phase === EnvironmentPhase.Closed || [...environment.resources.values()].some((resource) => session.resources.dependencyIds(resource.options).some((id, index) => id !== resource.dependencies[index]))) {
2955
+ const previous = environment;
2956
+ environment = await this.redeclareHostScope(previous);
2957
+ this.#pendingHostScopes.delete(previous);
2958
+ this.#pendingHostScopes.add(environment);
2959
+ }
2960
+ await this.session.programs.activate(environment.id);
2961
+ this.#pendingHostScopes.delete(environment);
2962
+ }
2963
+ })();
2964
+ this.#hostActivation = activation;
2965
+ const clear = () => {
2966
+ if (this.#hostActivation === activation)
2967
+ this.#hostActivation = undefined;
2968
+ };
2969
+ activation.then(clear, clear);
2970
+ return activation;
2971
+ }
2972
+ async redeclareHostScope(previous) {
2973
+ const session = this.session;
2974
+ await session.programs.cleanup([previous]);
2975
+ const environment = this.environment({ kind: OwnerKind.Host }, previous.orb);
2976
+ session.resources.redeclare(environment, previous);
2977
+ environment.phase = EnvironmentPhase.Prepared;
2978
+ session.programs.register(environment);
2979
+ return environment;
2980
+ }
2981
+ requirement(environment, service) {
2982
+ const own = environment.orb.definition.services?.[service];
2983
+ if (own)
2984
+ return { service, apiVersion: environment.orb.info.apiVersion };
2985
+ for (const [alias, requirement] of Object.entries(environment.orb.definition.requires ?? {})) {
2986
+ let provider;
2987
+ try {
2988
+ provider = this.session.kernel.command(KernelOp.OrbNamed, {
2989
+ name: requirement.orb ?? alias,
2990
+ ticket: environment.orb.ticket
2991
+ });
2992
+ } catch (error) {
2993
+ if (error instanceof TembraError && error.code === Code.Gone && error.reason === Reason.Orb)
2994
+ continue;
2995
+ throw error;
2996
+ }
2997
+ const selected = alias === service ? provider.services.find((s) => s.name === alias) ?? (provider.services.length === 1 ? provider.services[0] : undefined) : provider.services.find((s) => s.name === service);
2998
+ if (!selected)
2999
+ continue;
3000
+ const methods = requirement.services?.[selected.name] ?? requirement.methods;
3001
+ if (!methods)
3002
+ throw new TembraError(Errors.Forbidden.UndeclaredService, service);
3003
+ return { service: selected.name, apiVersion: requirement.apiVersion, methods };
3004
+ }
3005
+ throw new TembraError(Errors.Forbidden.UndeclaredDependency, service);
3006
+ }
3007
+ hostResource(name) {
3008
+ const resource = this.#hostResources.get(name);
3009
+ if (!resource)
3010
+ throw new TembraError(Errors.Forbidden.HostResource, name);
3011
+ return resource.handle;
3012
+ }
3013
+ resource(name, options) {
3014
+ const session = this.session;
3015
+ if (session.closing)
3016
+ throw new TembraError(Errors.Closed.Host);
3017
+ if (this.#hostResources.has(name))
3018
+ refuse(Errors.Invalid.DuplicateResource);
3019
+ const environment = this.environment({ kind: OwnerKind.Host }, session.hostScope.orb);
3020
+ try {
3021
+ const resource = new Declaration(session, environment).resource(name, options);
3022
+ this.#hostResources.set(name, environment.resources.get(name));
3023
+ environment.phase = EnvironmentPhase.Prepared;
3024
+ session.programs.register(environment);
3025
+ this.#pendingHostScopes.add(environment);
3026
+ session.track(this.readyHostScope()).catch((error) => session.report(error));
3027
+ return resource;
3028
+ } catch (error) {
3029
+ session.programs.scopes.delete(environment.id);
3030
+ throw error;
3031
+ }
3032
+ }
3033
+ registerHost(environment) {
3034
+ for (const [name, resource] of environment.resources)
3035
+ this.#hostResources.set(name, resource);
3036
+ }
3037
+ clear() {
3038
+ this.#hostResources.clear();
3039
+ this.#pendingHostScopes.clear();
3040
+ }
3041
+ }
3042
+
3043
+ // src/runtime/session.ts
3044
+ class Session {
3045
+ options;
3046
+ contextTokens = new WeakMap;
3047
+ calls = new Calls(this);
3048
+ handles = new References(this);
3049
+ scopes = new Scopes(this);
3050
+ lifecycle = new Lifecycle(this);
3051
+ kernel;
3052
+ values;
3053
+ resources = new Resources(this);
3054
+ activities = new Activities(this);
3055
+ orbs = new Orbs(this);
3056
+ replacements = new Replacements(this);
3057
+ programs = new Programs(this);
3058
+ objects = new Map;
3059
+ references = new Map;
3060
+ rootReferences = new Map;
3061
+ controllers = new Map;
3062
+ jobs = new Set;
3063
+ cleanupErrors = [];
3064
+ hostScope;
3065
+ codec;
3066
+ name;
3067
+ principal;
3068
+ errors = [];
3069
+ now;
3070
+ telemetry;
3071
+ closing = false;
3072
+ #publishing = false;
3073
+ #publications = [];
3074
+ constructor(options) {
3075
+ this.options = options;
3076
+ this.kernel = new Kernel(options.kernel);
3077
+ if (options.telemetry && !this.kernel.features.telemetry)
3078
+ throw new TembraError(Errors.Unsupported.Telemetry);
3079
+ this.telemetry = options.telemetry ? new Telemetry(options.telemetry.capacity, options.telemetry.sampleEvery) : undefined;
3080
+ this.values = new Values(() => this.kernel.command(KernelOp.Allocate));
3081
+ this.codec = options.serialization ?? jsonCodec;
3082
+ this.name = options.name ?? "host";
3083
+ this.principal = options.principal ?? "host";
3084
+ const clock = options.now ?? (() => performance.now());
3085
+ const origin = options.clockOrigin ?? clock();
3086
+ this.now = () => Math.floor(clock() - origin);
3087
+ const hostOrb = {
3088
+ info: {
3089
+ id: 0,
3090
+ owner: 0,
3091
+ name: "$host",
3092
+ apiVersion: 1,
3093
+ codeVersion: 1,
3094
+ services: [],
3095
+ hooks: [],
3096
+ requires: []
3097
+ },
3098
+ definition: { name: "$host", apiVersion: 1 }
3099
+ };
3100
+ this.hostScope = this.scopes.environment({ kind: OwnerKind.Host }, hostOrb);
3101
+ for (const [name, declaration] of Object.entries(options.resources ?? {})) {
3102
+ new Declaration(this, this.hostScope).resource(name, declaration);
3103
+ }
3104
+ this.scopes.registerHost(this.hostScope);
3105
+ this.hostScope.phase = EnvironmentPhase.Prepared;
3106
+ this.programs.register(this.hostScope);
3107
+ }
3108
+ principalFor(object) {
3109
+ return this.objects.get(object)?.address.principal ?? this.principal;
3110
+ }
3111
+ snapshot(object) {
3112
+ return this.kernel.command(KernelOp.Snapshot, { object });
3113
+ }
3114
+ value(id) {
3115
+ if (this.values.has(id))
3116
+ return this.values.get(id);
3117
+ if (!this.options.native)
3118
+ refuse(Errors.Invalid.ValueGone);
3119
+ const value = this.options.native.value(id);
3120
+ this.values.set(id, value);
3121
+ return value;
3122
+ }
3123
+ check(value, object) {
3124
+ const ctx = context(value, this);
3125
+ if (!ctx.invocation || ctx.invocation.object !== object)
3126
+ throw new TembraError(Errors.Forbidden.StateOwner);
3127
+ return ctx.invocation;
3128
+ }
3129
+ adopt(object, value, revision, candidate) {
3130
+ const invocation = this.check(value, object);
3131
+ const id = this.values.put(candidate);
3132
+ try {
3133
+ return this.kernel.command(KernelOp.StateAdopt, {
3134
+ call: invocation.id,
3135
+ object,
3136
+ revision,
3137
+ value: id
3138
+ });
3139
+ } catch (error) {
3140
+ this.values.drop(id);
3141
+ throw error;
3142
+ } finally {
3143
+ this.lifecycle.flush();
3144
+ }
3145
+ }
3146
+ publish(operation) {
3147
+ this.#publications.push(operation);
3148
+ if (this.#publishing)
3149
+ return;
3150
+ this.#publishing = true;
3151
+ try {
3152
+ while (this.#publications.length)
3153
+ this.#publications.shift()();
3154
+ } finally {
3155
+ this.#publishing = false;
3156
+ }
3157
+ }
3158
+ report(error) {
3159
+ const reported = failure(error);
3160
+ if (this.errors.length === 64)
3161
+ this.errors.shift();
3162
+ this.errors.push(reported);
3163
+ try {
3164
+ this.options.onError?.(reported);
3165
+ } catch {}
3166
+ }
3167
+ track(job, cleanup = false) {
3168
+ this.jobs.add(job);
3169
+ job.then(() => {
3170
+ this.jobs.delete(job);
3171
+ }, (error) => {
3172
+ this.jobs.delete(job);
3173
+ if (cleanup) {
3174
+ this.cleanupErrors.push(error);
3175
+ this.report(error);
3176
+ }
3177
+ });
3178
+ return job;
3179
+ }
3180
+ }
3181
+
3182
+ // src/host.ts
3183
+ class Host {
3184
+ session;
3185
+ constructor(options) {
3186
+ this.session = new Session(options);
3187
+ }
3188
+ get name() {
3189
+ return this.session.name;
3190
+ }
3191
+ get features() {
3192
+ return this.session.kernel.features;
3193
+ }
3194
+ install(definition) {
3195
+ return this.session.orbs.install(Array.isArray(definition) ? definition : [definition]);
3196
+ }
3197
+ async load(location) {
3198
+ if (!this.session.options.load)
3199
+ throw new Error("This host has no module loader");
3200
+ await this.install(await this.session.options.load(location));
3201
+ }
3202
+ reload(definitions, options) {
3203
+ return this.session.replacements.replace(definitions, options);
3204
+ }
3205
+ prepare(definitions, options) {
3206
+ return this.session.replacements.prepare(definitions, options);
3207
+ }
3208
+ remove(names, options) {
3209
+ return this.session.replacements.replace([], options, names);
3210
+ }
3211
+ hold(service, key, options) {
3212
+ return this.session.handles.hold(service, key, options);
3213
+ }
3214
+ get(service, key, options) {
3215
+ return this.session.handles.get(service, key, options);
3216
+ }
3217
+ root(operation, options = {}) {
3218
+ return this.session.calls.root(operation, false, undefined, options.principal);
3219
+ }
3220
+ resource(name, options) {
3221
+ return this.session.scopes.resource(name, options);
3222
+ }
3223
+ diagnostics() {
3224
+ return this.session.lifecycle.diagnostics();
3225
+ }
3226
+ errors() {
3227
+ return this.session.errors.splice(0);
3228
+ }
3229
+ traces() {
3230
+ return this.session.telemetry?.drain() ?? [];
3231
+ }
3232
+ installedOrbs() {
3233
+ return this.session.kernel.command(KernelOp.Orbs).map((info) => {
3234
+ const definition = this.session.orbs.records.get(info.id)?.definition;
3235
+ const description = Object.freeze({
3236
+ ...info,
3237
+ hookCapabilities: Object.fromEntries(info.hooks.map((name) => [name, definition?.hooks?.[name]?.capabilities ?? []]))
3238
+ });
3239
+ return Object.freeze({
3240
+ ...info,
3241
+ describe: () => description
3242
+ });
3243
+ });
3244
+ }
3245
+ close() {
3246
+ return this.session.lifecycle.close();
3247
+ }
3248
+ }
3249
+
3250
+ // src/browser.ts
3251
+ async function createHost(options = {}) {
3252
+ let kernel = options.kernel;
3253
+ if (!kernel) {
3254
+ const supplied = options.wasm;
3255
+ const module = typeof supplied === "function" ? await supplied() : supplied ?? await import("@syntropika/tembra-engine-wasm");
3256
+ await module.default?.(options.wasmInput);
3257
+ kernel = new module.WasmKernel;
3258
+ }
3259
+ return new Host({
3260
+ ...options,
3261
+ kernel,
3262
+ load: options.load ?? (async (location) => {
3263
+ const base = options.baseURL ?? globalThis.location?.href;
3264
+ const url = location instanceof URL ? location : base ? new URL(location, base) : new URL(location);
3265
+ return orb((await import(url.href)).default);
3266
+ })
3267
+ });
3268
+ }
3269
+ export {
3270
+ Code,
3271
+ ContextKey,
3272
+ ContextKind,
3273
+ Errors,
3274
+ HookCapability,
3275
+ Lifetime,
3276
+ Reason,
3277
+ ReloadStatus,
3278
+ Status,
3279
+ createHost,
3280
+ opaqueFrom,
3281
+ orb
3282
+ };