@almadar/shell-runtime 0.0.0-stage → 1.0.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 (127) hide show
  1. package/dist/chunk-4SEK5ER2.js +8 -0
  2. package/dist/chunk-57SBCUSM.js +62 -0
  3. package/dist/chunk-625EP7W2.js +108 -0
  4. package/dist/chunk-64IH2SMY.js +22 -0
  5. package/dist/chunk-7SDV3QWR.js +67 -0
  6. package/dist/chunk-7WB6VWRK.js +798 -0
  7. package/dist/chunk-A2JJT4GA.js +56 -0
  8. package/dist/chunk-BAS26HBN.js +10 -0
  9. package/dist/chunk-BOVU4TCQ.js +65 -0
  10. package/dist/chunk-BY5G4225.js +6 -0
  11. package/dist/chunk-DFDNHVDW.js +284 -0
  12. package/dist/chunk-ELBLT2HZ.js +1 -0
  13. package/dist/chunk-EZZYLTWY.js +1 -0
  14. package/dist/chunk-FWA5K7Q2.js +48 -0
  15. package/dist/chunk-HC6ERSAH.js +55 -0
  16. package/dist/chunk-HLOUDLPI.js +48 -0
  17. package/dist/chunk-I3TKINSO.js +398 -0
  18. package/dist/chunk-IOPUS6Q5.js +15 -0
  19. package/dist/chunk-LKWYCYX5.js +22 -0
  20. package/dist/chunk-LYFIQPXX.js +1 -0
  21. package/dist/chunk-LZIOTBFX.js +1 -0
  22. package/dist/chunk-MU335ZA4.js +63 -0
  23. package/dist/chunk-MZKIL5IN.js +74 -0
  24. package/dist/chunk-N7HYNKK6.js +83 -0
  25. package/dist/chunk-NTFQ36UN.js +52 -0
  26. package/dist/chunk-NU6LVKGS.js +15 -0
  27. package/dist/chunk-O57GKTYU.js +30 -0
  28. package/dist/chunk-P2N6K2IV.js +20 -0
  29. package/dist/chunk-P53CKOME.js +1 -0
  30. package/dist/chunk-QCJWPXLH.js +40 -0
  31. package/dist/chunk-SKLMWHQD.js +109 -0
  32. package/dist/chunk-SOQDEPME.js +131 -0
  33. package/dist/chunk-UBN5JJKZ.js +26 -0
  34. package/dist/chunk-UD2CXYSJ.js +244 -0
  35. package/dist/chunk-UP6GGGAN.js +34 -0
  36. package/dist/chunk-V4EMDPCO.js +33 -0
  37. package/dist/chunk-VNGXRYFF.js +9 -0
  38. package/dist/chunk-WGCWJOT2.js +21 -0
  39. package/dist/chunk-X6W44WHO.js +26 -0
  40. package/dist/chunk-XXWNMJI6.js +15 -0
  41. package/dist/chunk-ZUSM4VW4.js +197 -0
  42. package/dist/client/EventTransport.d.ts +147 -0
  43. package/dist/client/EventTransport.js +1 -0
  44. package/dist/client/awaiting.d.ts +28 -0
  45. package/dist/client/awaiting.js +1 -0
  46. package/dist/client/channel-transport.d.ts +69 -0
  47. package/dist/client/channel-transport.js +1 -0
  48. package/dist/client/circuit-store.d.ts +87 -0
  49. package/dist/client/circuit-store.js +3 -0
  50. package/dist/client/client-kernel.d.ts +134 -0
  51. package/dist/client/client-kernel.js +1 -0
  52. package/dist/client/declared-input-dispatch.d.ts +22 -0
  53. package/dist/client/declared-input-dispatch.js +1 -0
  54. package/dist/client/inbound-dispatch.d.ts +24 -0
  55. package/dist/client/inbound-dispatch.js +1 -0
  56. package/dist/client/local-fold.d.ts +33 -0
  57. package/dist/client/local-fold.js +1 -0
  58. package/dist/client/render-sigils.d.ts +24 -0
  59. package/dist/client/render-sigils.js +1 -0
  60. package/dist/client/state-book.d.ts +30 -0
  61. package/dist/client/state-book.js +1 -0
  62. package/dist/client/trait-mount-error.d.ts +9 -0
  63. package/dist/client/trait-mount-error.js +1 -0
  64. package/dist/client/trait-types.d.ts +67 -0
  65. package/dist/client/trait-types.js +1 -0
  66. package/dist/credentials/env-vars.d.ts +18 -0
  67. package/dist/credentials/env-vars.js +1 -0
  68. package/dist/credentials/scope.d.ts +51 -0
  69. package/dist/credentials/scope.js +1 -0
  70. package/dist/credentials/vault.d.ts +142 -0
  71. package/dist/credentials/vault.js +1 -0
  72. package/dist/effects/in-flight-calls.d.ts +36 -0
  73. package/dist/effects/in-flight-calls.js +1 -0
  74. package/dist/effects/on-device-model.d.ts +22 -0
  75. package/dist/effects/on-device-model.js +1 -0
  76. package/dist/events/EventBus.d.ts +87 -0
  77. package/dist/events/EventBus.js +1 -0
  78. package/dist/events/emit-stamp.d.ts +47 -0
  79. package/dist/events/emit-stamp.js +1 -0
  80. package/dist/index.d.ts +43 -0
  81. package/dist/index.js +41 -0
  82. package/dist/kernel/decode.d.ts +13 -0
  83. package/dist/kernel/decode.js +1 -0
  84. package/dist/kernel/engine.d.ts +195 -0
  85. package/dist/kernel/engine.js +9 -0
  86. package/dist/kernel/frame-applier.d.ts +44 -0
  87. package/dist/kernel/frame-applier.js +1 -0
  88. package/dist/kernel/host.d.ts +206 -0
  89. package/dist/kernel/host.js +6 -0
  90. package/dist/kernel/lane.d.ts +7 -0
  91. package/dist/kernel/lane.js +1 -0
  92. package/dist/kernel/os-fetch-port.d.ts +7 -0
  93. package/dist/kernel/os-fetch-port.js +3 -0
  94. package/dist/kernel/os-port.d.ts +155 -0
  95. package/dist/kernel/os-port.js +1 -0
  96. package/dist/kernel/program-effects.d.ts +48 -0
  97. package/dist/kernel/program-effects.js +1 -0
  98. package/dist/kernel/secret-ports.d.ts +139 -0
  99. package/dist/kernel/secret-ports.js +2 -0
  100. package/dist/kernel/wire.d.ts +104 -0
  101. package/dist/kernel/wire.js +1 -0
  102. package/dist/loader/fetch-loader.d.ts +26 -0
  103. package/dist/loader/fetch-loader.js +1 -0
  104. package/dist/loader/lazy-page.d.ts +12 -0
  105. package/dist/loader/lazy-page.js +1 -0
  106. package/dist/loader/schema-loader.d.ts +144 -0
  107. package/dist/loader/schema-loader.js +1 -0
  108. package/dist/persistence/native-memory.d.ts +28 -0
  109. package/dist/persistence/native-memory.js +1 -0
  110. package/dist/runtime/entities/declaredCollections.d.ts +6 -0
  111. package/dist/runtime/entities/declaredCollections.js +1 -0
  112. package/dist/runtime/evaluation/local-store-transport.d.ts +59 -0
  113. package/dist/runtime/evaluation/local-store-transport.js +14 -0
  114. package/dist/runtime/evaluation/residence-transport.d.ts +15 -0
  115. package/dist/runtime/evaluation/residence-transport.js +1 -0
  116. package/dist/runtime/evaluation/routed-persistence.d.ts +9 -0
  117. package/dist/runtime/evaluation/routed-persistence.js +1 -0
  118. package/dist/runtime/events/identity/routing.d.ts +33 -0
  119. package/dist/runtime/events/identity/routing.js +1 -0
  120. package/dist/runtime/types.d.ts +374 -0
  121. package/dist/runtime/types.js +1 -0
  122. package/dist/service/default-call-service.d.ts +23 -0
  123. package/dist/service/default-call-service.js +2 -0
  124. package/dist/service/service-provider.d.ts +37 -0
  125. package/dist/service/service-provider.js +1 -0
  126. package/package.json +49 -3
  127. package/README.md +0 -3
@@ -0,0 +1,398 @@
1
+ import { LaneHeldByParkedDispatch } from './chunk-NU6LVKGS.js';
2
+ import { decodeDueTicks, decodeResolveProgress, decodeProgress, decodeNext } from './chunk-X6W44WHO.js';
3
+ import { declareCapabilities, answerRequest } from './chunk-7WB6VWRK.js';
4
+ import { installKernelEvaluator, LiveBroadcastItemSchema, MountSeedSchema, ExternalInputSchema, NameListSchema, PayloadJsonSchemaSchema, PayloadIssueSchema, InboundOnlySchema, OptionalNameSchema, EntityRowSchema, isEntityReferenceAny, InboundAnswerSchema, EventPayloadSchema, InboundFoundSchema } from '@almadar/core';
5
+
6
+ var PROGRAM_SURFACE = {
7
+ parse(input) {
8
+ return input;
9
+ }
10
+ };
11
+ function declaredEntityTypes(schema) {
12
+ return schema.orbitals.flatMap((orbital) => [orbital.entity, ...orbital.auxiliaryEntities ?? []].flatMap((entity) => isEntityReferenceAny(entity) ? [] : [entity.name]));
13
+ }
14
+ function contractAnswers(ask) {
15
+ return {
16
+ findExternalInput(orbital, trait, event) {
17
+ return ask(ExternalInputSchema.nullable(), { kind: "findExternalInput", orbital, trait, event }) ?? void 0;
18
+ },
19
+ findInbound(name) {
20
+ return ask(InboundFoundSchema, { kind: "findInbound", name });
21
+ },
22
+ inboundPayload(route, delivery, credential) {
23
+ const headers = Object.fromEntries(Object.entries(delivery.headers).flatMap(([name, value]) => value === void 0 ? [] : [[name, value]]));
24
+ return ask(EventPayloadSchema, { kind: "inboundPayload", route, headers, rawBody: delivery.rawBody, ...typeof credential === "string" ? { credential } : {} });
25
+ },
26
+ inboundAnswer(route, emitted, error) {
27
+ return ask(InboundAnswerSchema, { kind: "inboundAnswer", route, emitted, ...error !== void 0 ? { error } : {} });
28
+ },
29
+ credentialUnset(credential) {
30
+ return ask(InboundAnswerSchema, { kind: "credentialUnset", credential });
31
+ },
32
+ dispatchFailed(message) {
33
+ return ask(InboundAnswerSchema, { kind: "dispatchFailed", message });
34
+ }
35
+ };
36
+ }
37
+ var KernelEngine = class _KernelEngine {
38
+ constructor(kernel, schemaJson, ports, entityTypes = [], forkedFrom, providedHandle, preserveProgramContext = false, lazyDir) {
39
+ this.kernel = kernel;
40
+ this.schemaJson = schemaJson;
41
+ this.ports = ports;
42
+ this.entityTypes = entityTypes;
43
+ this.preserveProgramContext = preserveProgramContext;
44
+ this.lazyDir = lazyDir;
45
+ installKernelEvaluator(kernel);
46
+ this.ports = {
47
+ ...ports,
48
+ substrateMessage: (site, key, value) => JSON.parse(kernel.osCompletionEvent(JSON.stringify({ ...site, emit: { success: site.emit.onMessage } }), key, JSON.stringify({ ok: value }))),
49
+ substrateCompletion: (site, key, op, args, outcome) => JSON.parse(kernel.substrateCompletionEvent(JSON.stringify(site), key, op, JSON.stringify(args), JSON.stringify(outcome)))
50
+ };
51
+ this.handle = providedHandle ?? forkedFrom?.fork() ?? this.openServer();
52
+ this.declare();
53
+ }
54
+ kernel;
55
+ schemaJson;
56
+ ports;
57
+ entityTypes;
58
+ preserveProgramContext;
59
+ lazyDir;
60
+ handle;
61
+ turns = /* @__PURE__ */ new Map();
62
+ tickRelayIntervalMs;
63
+ stateful = false;
64
+ /**
65
+ * A kernel on the same program, registered once, holding none of this one's session: every trait at its initial
66
+ * state, no rows the kernel held, its mounted ticks kept. A stateless host serves each request a
67
+ * fork (EXEC-DIST-5), `ports` answering it.
68
+ */
69
+ fork(ports = this.ports) {
70
+ return new _KernelEngine(this.kernel, this.schemaJson, ports, this.entityTypes, this.handle, void 0, this.preserveProgramContext, this.lazyDir);
71
+ }
72
+ forkProgram(program, ports = this.ports) {
73
+ const schemaJson = JSON.stringify(program);
74
+ const entityTypes = [.../* @__PURE__ */ new Set([
75
+ ...this.entityTypes,
76
+ ...declaredEntityTypes(program)
77
+ ])];
78
+ return new _KernelEngine(this.kernel, schemaJson, ports, entityTypes, void 0, this.handle.forkProgram(schemaJson), true);
79
+ }
80
+ /** A server over the host's ports. */
81
+ openServer() {
82
+ return new this.kernel.Server(this.schemaJson, this.lazyDir);
83
+ }
84
+ declare() {
85
+ const handle = this.handle;
86
+ declareCapabilities(this.ports.persistence, (entityType, queryJson, writeJson) => handle.setCapabilities(entityType, queryJson, writeJson), this.entityTypes);
87
+ }
88
+ /** The contract answers for a host with no program registered yet: the kernel's, asked with no program. */
89
+ static withoutProgram(kernel) {
90
+ return contractAnswers((schema, query) => schema.parse(JSON.parse(kernel.contractQueryWithoutProgram(JSON.stringify(query)))));
91
+ }
92
+ static open(kernel, schema, ports, lazyDir) {
93
+ return new _KernelEngine(kernel, JSON.stringify(schema), ports, declaredEntityTypes(schema), void 0, void 0, false, lazyDir);
94
+ }
95
+ /** A fresh kernel on the same program: every trait back at its initial state. */
96
+ reset() {
97
+ const contextualHandle = this.preserveProgramContext ? this.handle.fork() : void 0;
98
+ this.handle.free();
99
+ this.handle = contextualHandle ?? this.openServer();
100
+ this.declare();
101
+ if (this.tickRelayIntervalMs !== void 0) this.handle.setTickRelayInterval(this.tickRelayIntervalMs);
102
+ if (this.stateful) this.handle.setStateful(true);
103
+ if (this.managedProgram !== void 0) this.handle.setManagedProgram(this.managedProgram);
104
+ }
105
+ managedProgram;
106
+ /** The program whose declared credentials this kernel's credential effects manage beside its own (a console's app). */
107
+ setManagedProgram(program) {
108
+ this.managedProgram = JSON.stringify(program);
109
+ this.handle.setManagedProgram(this.managedProgram);
110
+ }
111
+ /** `client` mounted `traits` of `orbital`: their mount-scoped ticks fire while any client holds them. A request derives this itself; this is for a mount made outside a request. */
112
+ mountClient(client, orbital, traits) {
113
+ this.handle.mountClient(client, orbital, JSON.stringify(traits));
114
+ }
115
+ unmountClient(client, orbital, traits) {
116
+ this.handle.unmountClient(client, orbital, JSON.stringify(traits));
117
+ }
118
+ /** `client` is gone: everything it mounted is released. */
119
+ releaseClient(client) {
120
+ this.handle.releaseClient(client);
121
+ }
122
+ /** This host holds the circuit state: the kernel takes a client's copy of it only on a delegated leg and refuses any other request carrying one. */
123
+ setStateful() {
124
+ this.stateful = true;
125
+ this.handle.setStateful(true);
126
+ }
127
+ /** Whether the program declares any tick: the host runs its timer only then. */
128
+ declaresTicks() {
129
+ return this.handle.declaresTicks();
130
+ }
131
+ /** Queue a tick-stamped dispatch for the coalesced peer relay; the ms after which to flush when it opened a window. */
132
+ relayTick(orbital, request) {
133
+ const window = JSON.parse(this.handle.relayTick(orbital, JSON.stringify(request)));
134
+ return window ?? void 0;
135
+ }
136
+ /** The relay window's length in ms; the kernel's default is 50. */
137
+ setTickRelayInterval(intervalMs) {
138
+ this.tickRelayIntervalMs = intervalMs;
139
+ this.handle.setTickRelayInterval(intervalMs);
140
+ }
141
+ /** Every item queued since the window opened, in first-arrival order; the window closes. */
142
+ flushTickRelay() {
143
+ return LiveBroadcastItemSchema.array().parse(JSON.parse(this.handle.flushTickRelay()));
144
+ }
145
+ /** One pass of the kernel's tick clock: the ticks due at monotonic `nowMs` that this server runs (`[background]` ticks, and those of a mounted trait), keyed by the orbital each `runTick` request is addressed to. */
146
+ tickPass(nowMs) {
147
+ return decodeDueTicks(this.handle.tickPass(nowMs));
148
+ }
149
+ /** Stop the kernel's tick clock; its phase is kept. */
150
+ tickPause() {
151
+ this.handle.tickPause();
152
+ }
153
+ /** Restart the kernel's tick clock; the paused span is never counted. */
154
+ tickResume() {
155
+ this.handle.tickResume();
156
+ }
157
+ tickPaused() {
158
+ return this.handle.tickPaused();
159
+ }
160
+ /** What this host mounts when it starts: the kernel's boot mounts for the side it serves (EXEC-ENDPOINT-3). */
161
+ bootMounts(side) {
162
+ return MountSeedSchema.array().parse(JSON.parse(this.handle.bootMounts(side)));
163
+ }
164
+ /** What mounts when a client opens `routePath` (EXEC-ENDPOINT-3). */
165
+ routeMounts(routePath) {
166
+ return MountSeedSchema.array().parse(JSON.parse(this.handle.routeMounts(routePath)));
167
+ }
168
+ dispose() {
169
+ this.handle.free();
170
+ }
171
+ answers = contractAnswers((schema, query) => this.contract(schema, query));
172
+ contract(schema, query) {
173
+ return schema.parse(JSON.parse(this.handle.contractQuery(JSON.stringify(query))));
174
+ }
175
+ /** Every external input the program declares: what an outside client may send which trait. */
176
+ externalInputs() {
177
+ return this.contract(ExternalInputSchema.array(), { kind: "externalInputs" });
178
+ }
179
+ /** What the kernel holds of every trait of the program, in name order, and the browser-stored entities. */
180
+ programSurface() {
181
+ return this.contract(PROGRAM_SURFACE, { kind: "programSurface" });
182
+ }
183
+ /** The entities a provider acting as the caller may read. */
184
+ readableEntities() {
185
+ return this.contract(NameListSchema, { kind: "readableEntities" });
186
+ }
187
+ /** The declared input of `trait.event` in `orbital`, when there is one. */
188
+ findExternalInput(orbital, trait, event) {
189
+ return this.answers.findExternalInput(orbital, trait, event);
190
+ }
191
+ /** The declared input a `listens`-addressed event names from `caller`'s position (`EVENT`, `Trait.EVENT`, `Orbital.Trait.EVENT`), when there is one. */
192
+ findInputByAddress(address, caller) {
193
+ return this.contract(ExternalInputSchema.nullable(), { kind: "findInputByAddress", address, caller }) ?? void 0;
194
+ }
195
+ /** A declared payload as the JSON Schema of one object: what a tool-calling model fills. */
196
+ payloadJsonSchema(fields) {
197
+ return this.contract(PayloadJsonSchemaSchema, { kind: "payloadSchemaToJsonSchema", fields });
198
+ }
199
+ /** The ways `value` misses the declared payload `fields`. */
200
+ payloadIssues(fields, value) {
201
+ return this.contract(PayloadIssueSchema.array(), { kind: "payloadIssues", fields, value });
202
+ }
203
+ /** The route a hook name is delivered to, or the answer to write for a hook the program does not serve. */
204
+ findInbound(name) {
205
+ return this.answers.findInbound(name);
206
+ }
207
+ /** The trait that handles `event` as an inbound hook in `orbital`, with the refusal message, when a client-facing request names it. */
208
+ inboundOnly(orbital, trait, event) {
209
+ return this.contract(InboundOnlySchema, { kind: "inboundOnly", orbital, ...trait !== void 0 ? { trait } : {}, event }) ?? void 0;
210
+ }
211
+ /** The payload an inbound event is delivered with. */
212
+ inboundPayload(route, delivery, credential) {
213
+ return this.answers.inboundPayload(route, delivery, credential);
214
+ }
215
+ /** The HTTP answer a finished dispatch produced for `route`. */
216
+ inboundAnswer(route, emitted, error) {
217
+ return this.answers.inboundAnswer(route, emitted, error);
218
+ }
219
+ /** The answer for a route whose credential the host holds no value for. */
220
+ credentialUnset(credential) {
221
+ return this.answers.credentialUnset(credential);
222
+ }
223
+ /** The answer for a delivery whose dispatch failed. */
224
+ dispatchFailed(message) {
225
+ return this.answers.dispatchFailed(message);
226
+ }
227
+ /** The name of the program's `[identity]` entity, when it declares one. */
228
+ identityEntity() {
229
+ return this.contract(OptionalNameSchema, { kind: "identityEntity" }) ?? void 0;
230
+ }
231
+ /** The orbital that declares `entity` inline. */
232
+ entityOwnerOrbital(entity) {
233
+ return this.contract(OptionalNameSchema, { kind: "entityOwner", entity }) ?? void 0;
234
+ }
235
+ /** `rows` of `entity` as `user` reads them: narrowed by the entity's declared `@read`, which the kernel evaluates with `@user` bound to the viewer. */
236
+ readRows(entity, rows, user) {
237
+ return this.contract(EntityRowSchema.array(), { kind: "readRows", entity, rows, viewer: user ?? null });
238
+ }
239
+ liveItemDelivered(item, clientId) {
240
+ return this.handle.liveItemDelivered(JSON.stringify(item), clientId);
241
+ }
242
+ /** `OsGrants::allows` over the grants of `orbital` in the program this kernel runs (the app level alone with no orbital). */
243
+ osAllows(requirementJson, orbital) {
244
+ return this.handle.osAllows(requirementJson, orbital);
245
+ }
246
+ /** Whether `url`'s origin is declared in the program's `egress` (the kernel's rule). */
247
+ egressAllows(url) {
248
+ return this.handle.egressAllows(url);
249
+ }
250
+ /** Place the program's anchored grants and arguments under the host's anchors. */
251
+ setOsAnchors(anchorsJson) {
252
+ return this.handle.setOsAnchors(anchorsJson);
253
+ }
254
+ /** An `os/` call's arguments with its anchored parts resolved under the host's anchors. */
255
+ osResolveArgs(op, argsJson) {
256
+ return this.handle.osResolveArgs(op, argsJson);
257
+ }
258
+ tlsComplete(key, outcomeJson) {
259
+ return this.handle.tlsComplete(key, outcomeJson);
260
+ }
261
+ /** A live stream of `client`'s session opened (EXEC-DIST-9); the id closes it. */
262
+ openSessionStream(client) {
263
+ return this.handle.openSessionStream(client);
264
+ }
265
+ /** The live stream `id` dropped: the kernel frees the session once its streams have all dropped and it is quiet. */
266
+ closeSessionStream(id) {
267
+ return this.handle.closeSessionStream(id);
268
+ }
269
+ /** The current state of a trait instance, `''` when it has none. */
270
+ stateOf(traitName, entityId) {
271
+ return this.handle.getState(traitName, entityId);
272
+ }
273
+ /**
274
+ * `reference` resolved for the identity `scope.originClientId`'s session bound (the anonymous viewer with none) against the host-answered store (EXEC-RENDER-3): the rows that still
275
+ * match its query and that identity's `@read` in the reference's order, a missing or hidden row omitted, and `total`
276
+ * re-counted (a `total: none` reference is not re-counted: the total is the resolved window). Each read the
277
+ * kernel makes is answered here, as in `evaluate`.
278
+ */
279
+ async resolveRows(reference, scope) {
280
+ const handle = this.handle;
281
+ let progress = decodeResolveProgress(handle.resolveRows(JSON.stringify(reference), scope.originClientId));
282
+ while (progress.status === "await") {
283
+ const { flight, requests } = progress;
284
+ let replies;
285
+ try {
286
+ replies = await Promise.all(
287
+ requests.map(async (pending) => ({ id: pending.id, answer: await answerRequest(this.ports, pending.request, scope) }))
288
+ );
289
+ } catch (error) {
290
+ handle.abandon(flight);
291
+ throw error;
292
+ }
293
+ progress = decodeResolveProgress(handle.resumeResolve(flight, JSON.stringify(replies)));
294
+ }
295
+ return { rows: progress.rows, total: progress.total };
296
+ }
297
+ /**
298
+ * Run `request` against `orbital`. The kernel orders every start and every resumption (EXEC-CONC-2): while another
299
+ * dispatch holds the lane it answers `queued` and runs the work itself once the lane frees; this host only answers
300
+ * what each dispatch asks.
301
+ */
302
+ async evaluate(orbital, request, scope) {
303
+ const handle = this.handle;
304
+ const streams = scope.onStream !== void 0;
305
+ let running = await this.ran(handle.start(orbital, JSON.stringify(request)), streams);
306
+ try {
307
+ while (running.progress.status === "await") {
308
+ const { flight, requests } = running.progress;
309
+ const assertReentry = () => {
310
+ if (handle.holdsLane(flight)) throw new LaneHeldByParkedDispatch(flight, request.event);
311
+ };
312
+ let replies;
313
+ try {
314
+ replies = await Promise.all(
315
+ requests.map(async (pending) => ({ id: pending.id, answer: await answerRequest(this.ports, pending.request, { ...scope, assertReentry }) }))
316
+ );
317
+ } catch (error) {
318
+ handle.abandon(flight);
319
+ throw error;
320
+ }
321
+ running = await this.ran(handle.resume(flight, JSON.stringify(replies)), streams);
322
+ }
323
+ } finally {
324
+ this.runQueued();
325
+ }
326
+ if (scope.onStream !== void 0 && running.stream !== void 0) {
327
+ const items = JSON.parse(running.stream);
328
+ for (const item of items) scope.onStream(item);
329
+ scope.onStream({ type: "complete", data: running.progress.response, timestamp: Date.now() });
330
+ }
331
+ return running.progress.response;
332
+ }
333
+ /** The kernel's answer to a start or resume, once it has run: at once, or when the kernel takes it from its queue. */
334
+ ran(json, streams) {
335
+ const progress = decodeProgress(json);
336
+ if (progress.status !== "queued") return this.running(progress, streams);
337
+ const turn = new Promise((ran, failed) => {
338
+ this.turns.set(progress.ticket, { streams, ran, failed });
339
+ });
340
+ queueMicrotask(() => this.runQueued());
341
+ return turn;
342
+ }
343
+ running(progress, streams) {
344
+ return { progress, stream: streams && progress.status === "done" ? this.handle.dispatchStream() : void 0 };
345
+ }
346
+ /** Run each piece of queued work that can run now, in the kernel's order, handing each to the dispatch it continues. */
347
+ runQueued() {
348
+ for (; ; ) {
349
+ const next = decodeNext(this.handle.next());
350
+ if (next === null) return;
351
+ const turn = this.turns.get(next.ticket);
352
+ if (turn === void 0) throw new Error(`kernel wire: the kernel ran ticket ${next.ticket}, which nothing waits on`);
353
+ this.turns.delete(next.ticket);
354
+ if (next.outcome === "failed") {
355
+ turn.failed(new Error(next.error));
356
+ continue;
357
+ }
358
+ if (next.progress.status === "queued") throw new Error("kernel wire: the kernel queued work it was running");
359
+ turn.ran(this.running(next.progress, turn.streams));
360
+ }
361
+ }
362
+ };
363
+ function kernelRequest(request, locale) {
364
+ const { _activeTraits: _dropped, _targetTrait: sidecarTarget, ...rest } = request.payload ?? {};
365
+ const payload = rest;
366
+ const target = request.targetTrait ?? (typeof sidecarTarget === "string" ? sidecarTarget : void 0);
367
+ const { payload: _payload, user: _hostViewer, ...others } = request;
368
+ return {
369
+ ...others,
370
+ ...request.payload !== void 0 ? { payload } : {},
371
+ ...target !== void 0 ? { targetTrait: target } : {},
372
+ ...locale !== void 0 ? { locale } : {}
373
+ };
374
+ }
375
+ function withOriginClient(response, clientId) {
376
+ if (clientId === void 0) return response;
377
+ return {
378
+ ...response,
379
+ emittedEvents: response.emittedEvents.map((emitted) => emitted.source === void 0 ? emitted : { ...emitted, source: { ...emitted.source, originClientId: emitted.source.originClientId ?? clientId } })
380
+ };
381
+ }
382
+ async function evaluateOnKernel(kernel, request, locale) {
383
+ return withOriginClient(await kernel.engine.evaluate(kernel.orbital, kernelRequest(request, locale), {
384
+ orbital: kernel.orbital,
385
+ ...request.clientId !== void 0 ? { originClientId: request.clientId } : {},
386
+ ...locale !== void 0 ? { locale } : {},
387
+ ...request.entityId !== void 0 ? { entityId: request.entityId } : {},
388
+ ...kernel.onStream !== void 0 ? { onStream: (item) => {
389
+ if (item.type === "event" && item.data.source !== void 0 && request.clientId !== void 0) {
390
+ kernel.onStream?.({ ...item, data: { ...item.data, source: { ...item.data.source, originClientId: item.data.source.originClientId ?? request.clientId } } });
391
+ } else if (item.type === "complete") {
392
+ kernel.onStream?.({ ...item, data: withOriginClient(item.data, request.clientId) });
393
+ } else kernel.onStream?.(item);
394
+ } } : {}
395
+ }), request.clientId);
396
+ }
397
+
398
+ export { KernelEngine, evaluateOnKernel, kernelRequest };
@@ -0,0 +1,15 @@
1
+ // src/client/trait-mount-error.ts
2
+ var TraitMountError = class extends Error {
3
+ trait;
4
+ event;
5
+ original;
6
+ constructor(trait, event, original) {
7
+ super(original.message);
8
+ this.name = "TraitMountError";
9
+ this.trait = trait;
10
+ this.event = event;
11
+ this.original = original;
12
+ }
13
+ };
14
+
15
+ export { TraitMountError };
@@ -0,0 +1,22 @@
1
+ // src/client/declared-input-dispatch.ts
2
+ async function dispatchDeclaredInput(contract, orbitalName, request, send) {
3
+ const declared = contract.findExternalInput(orbitalName, request.targetTrait, request.event);
4
+ if (!declared) {
5
+ return {
6
+ success: false,
7
+ transitioned: false,
8
+ states: {},
9
+ emittedEvents: [],
10
+ error: `'${request.event}' is not an external input of ${orbitalName}.${request.targetTrait}`,
11
+ rejections: [{ code: "not-an-external-input", trait: request.targetTrait, event: request.event }]
12
+ };
13
+ }
14
+ return send(orbitalName, {
15
+ event: request.event,
16
+ payload: request.payload ?? {},
17
+ targetTrait: request.targetTrait,
18
+ ...request.entityId !== void 0 ? { entityId: request.entityId } : {}
19
+ });
20
+ }
21
+
22
+ export { dispatchDeclaredInput };
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,63 @@
1
+ import { defaultCallService } from './chunk-4SEK5ER2.js';
2
+ import { routeByEntity } from './chunk-O57GKTYU.js';
3
+ import { KernelEngine, evaluateOnKernel } from './chunk-I3TKINSO.js';
4
+ import { InFlightCalls } from './chunk-MZKIL5IN.js';
5
+ import { createInProcessTransport } from './chunk-UD2CXYSJ.js';
6
+ import { orbitalInlineEntities, storesRowsInBrowser, inlineTraitRefs } from '@almadar/core';
7
+
8
+ var LOCAL_CLIENT = "local";
9
+ function localStorePersistence(schema, store, memory) {
10
+ const browserStored = new Set(schema.orbitals.flatMap(orbitalInlineEntities).filter(storesRowsInBrowser).map((entity) => entity.name));
11
+ return routeByEntity(browserStored, store, memory);
12
+ }
13
+ function openLocalKernel(options) {
14
+ const { schema, persistence } = options;
15
+ const callService = options.callService ?? defaultCallService;
16
+ const engine = KernelEngine.open(options.kernel, { ...schema, orbitals: inlineTraitRefs(schema.orbitals) }, {
17
+ persistence,
18
+ callService: (service, action, params, context) => callService(service, action, params, context),
19
+ programEffect: () => void 0,
20
+ inFlightCalls: new InFlightCalls(),
21
+ servicePorts: options.servicePorts ?? ((caller, user, message) => ({
22
+ caller,
23
+ message,
24
+ inputs: () => engine.externalInputs(),
25
+ readableEntities: () => engine.readableEntities(),
26
+ dispatchInput: () => Promise.reject(new Error("a local store host takes no input dispatch")),
27
+ read: async (entity) => engine.readRows(entity, await persistence.list(entity), user)
28
+ })),
29
+ deliverLive: () => void 0,
30
+ deferCallOutcome: options.deferCallOutcome ?? (() => void 0),
31
+ ...options.pageFacts !== void 0 ? { pageFacts: options.pageFacts } : {},
32
+ ...options.hostActions !== void 0 ? { hostActions: options.hostActions } : {},
33
+ ...options.secretPorts !== void 0 ? { secretPorts: options.secretPorts } : {},
34
+ ...options.onDevice !== void 0 ? { onDevice: options.onDevice } : {},
35
+ ...options.tabs !== void 0 ? { tabs: options.tabs } : {},
36
+ ...options.os !== void 0 ? { os: options.os } : {}
37
+ });
38
+ for (const trait of engine.programSurface().traits) engine.mountClient(LOCAL_CLIENT, trait.orbital, [trait.name]);
39
+ return engine;
40
+ }
41
+ function createLocalStoreTransport(options) {
42
+ return createInProcessTransport(
43
+ async (orbital, request) => evaluateOnKernel(
44
+ { engine: await options.kernelEngine, orbital },
45
+ request,
46
+ request.locale ?? options.locale?.()
47
+ ),
48
+ {
49
+ carriesCircuitState: false,
50
+ ...options.schema !== void 0 ? { resolveRows: resolveOn(options) } : {}
51
+ }
52
+ );
53
+ }
54
+ function resolveOn(options) {
55
+ return async (reference) => resolveLocalRows(await options.kernelEngine, reference);
56
+ }
57
+ function resolveLocalRows(engine, reference) {
58
+ const owner = engine.entityOwnerOrbital(reference.entityType);
59
+ if (owner === void 0) return Promise.reject(new Error(`${reference.entityType}: no orbital of the local program declares this entity`));
60
+ return engine.resolveRows(reference, { orbital: owner });
61
+ }
62
+
63
+ export { createLocalStoreTransport, localStorePersistence, openLocalKernel, resolveLocalRows };
@@ -0,0 +1,74 @@
1
+ // src/effects/in-flight-calls.ts
2
+ var InFlightCalls = class {
3
+ calls = /* @__PURE__ */ new Map();
4
+ /** Whether a call started with `key` is still running. */
5
+ inFlight(key) {
6
+ return (this.calls.get(key)?.size ?? 0) > 0;
7
+ }
8
+ /**
9
+ * Run `work` registered under `key`, handing it the abort signal; `work` must settle promptly once the
10
+ * signal aborts (see `untilAborted`). The call is cancelled when the signal was aborted by the time
11
+ * `work` settles, whatever it settled with.
12
+ */
13
+ async run(key, work) {
14
+ const lease = this.track(key);
15
+ try {
16
+ const value = await work(lease.signal);
17
+ return lease.signal.aborted ? { cancelled: true } : { cancelled: false, value };
18
+ } catch (err) {
19
+ if (lease.signal.aborted) return { cancelled: true };
20
+ throw err;
21
+ } finally {
22
+ lease.release();
23
+ }
24
+ }
25
+ reserve(key) {
26
+ return this.inFlight(key) ? void 0 : this.track(key);
27
+ }
28
+ track(key) {
29
+ const controller = new AbortController();
30
+ const running = this.calls.get(key) ?? /* @__PURE__ */ new Set();
31
+ running.add(controller);
32
+ this.calls.set(key, running);
33
+ return {
34
+ signal: controller.signal,
35
+ release: () => {
36
+ running.delete(controller);
37
+ if (running.size === 0 && this.calls.get(key) === running) this.calls.delete(key);
38
+ }
39
+ };
40
+ }
41
+ cancelAll() {
42
+ for (const key of this.calls.keys()) this.cancel(key);
43
+ }
44
+ /** Abort every call running under `key`; false (a no-op) when none is. */
45
+ cancel(key) {
46
+ const running = this.calls.get(key);
47
+ if (running === void 0 || running.size === 0) return false;
48
+ this.calls.delete(key);
49
+ for (const controller of running) controller.abort();
50
+ return true;
51
+ }
52
+ };
53
+ function untilAborted(signal, promise) {
54
+ if (signal.aborted) {
55
+ promise.catch(() => void 0);
56
+ return Promise.reject(new Error("The call was cancelled"));
57
+ }
58
+ return new Promise((resolve, reject) => {
59
+ const onAbort = () => reject(new Error("The call was cancelled"));
60
+ signal.addEventListener("abort", onAbort, { once: true });
61
+ promise.then(
62
+ (value) => {
63
+ signal.removeEventListener("abort", onAbort);
64
+ resolve(value);
65
+ },
66
+ (err) => {
67
+ signal.removeEventListener("abort", onAbort);
68
+ reject(err);
69
+ }
70
+ );
71
+ });
72
+ }
73
+
74
+ export { InFlightCalls, untilAborted };
@@ -0,0 +1,83 @@
1
+ import { StateBook } from './chunk-A2JJT4GA.js';
2
+ import { AwaitingRegistry } from './chunk-HC6ERSAH.js';
3
+
4
+ // src/client/circuit-store.ts
5
+ function createMemoryCircuitStore(traits = [], observer) {
6
+ const states = new StateBook(traits, observer);
7
+ const frames = /* @__PURE__ */ new Map();
8
+ const listeners = /* @__PURE__ */ new Set();
9
+ let version = 0;
10
+ let frameVersion = 0;
11
+ let frameSession;
12
+ return {
13
+ states,
14
+ frames,
15
+ get frameVersion() {
16
+ return frameVersion;
17
+ },
18
+ applyFrames(delta) {
19
+ if (delta.session !== void 0) {
20
+ const snapshot = delta.from === 0 && delta.ops[0]?.[0] === "clear";
21
+ if (!snapshot) {
22
+ const current = (frameSession === void 0 || delta.session === frameSession) && delta.from === frameVersion;
23
+ if (delta.session === frameSession && delta.to <= frameVersion && !current) return "stale";
24
+ if (!current) return "gap";
25
+ }
26
+ frameSession = delta.session;
27
+ frameVersion = delta.to;
28
+ }
29
+ for (const op of delta.ops) {
30
+ switch (op[0]) {
31
+ case "clear":
32
+ frames.clear();
33
+ break;
34
+ case "del":
35
+ frames.delete(op[1]);
36
+ break;
37
+ case "put":
38
+ frames.set(op[1], { ...op[2] });
39
+ break;
40
+ case "set":
41
+ for (const [frame, fields] of Object.entries(op[1])) frames.set(frame, { ...frames.get(frame) ?? {}, ...fields });
42
+ break;
43
+ }
44
+ }
45
+ return "applied";
46
+ },
47
+ awaiting: new AwaitingRegistry(),
48
+ snapshot(trait, entityId, frameKey) {
49
+ const key = frameKey ?? trait;
50
+ const frame = frames.get(key);
51
+ return {
52
+ state: states.getState(trait, entityId)?.currentState ?? "",
53
+ frame: frame !== void 0 ? { ...frame } : void 0
54
+ };
55
+ },
56
+ restore(trait, entityId, snap, frameKey, cause) {
57
+ const key = frameKey ?? trait;
58
+ if (snap.state !== "") {
59
+ states.rollbackState(trait, snap.state, entityId, cause);
60
+ }
61
+ if (snap.frame === void 0) {
62
+ frames.delete(key);
63
+ } else {
64
+ frames.set(key, { ...snap.frame });
65
+ }
66
+ },
67
+ notify() {
68
+ version += 1;
69
+ for (const listener of listeners) listener();
70
+ },
71
+ subscribe(listener) {
72
+ listeners.add(listener);
73
+ return () => {
74
+ listeners.delete(listener);
75
+ };
76
+ },
77
+ getVersion() {
78
+ return version;
79
+ }
80
+ };
81
+ }
82
+
83
+ export { createMemoryCircuitStore };