@almadar/shell-node 0.1.0 → 1.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.
- package/dist/OrbitalServerRuntime.d.ts +46 -267
- package/dist/OrbitalServerRuntime.js +3 -3
- package/dist/chunk-34JOE763.js +845 -0
- package/dist/{chunk-QYAPNUBH.js → chunk-7QE32QQR.js} +107 -182
- package/dist/{chunk-UBZT5LDW.js → chunk-EEYGL7AB.js} +3 -13
- package/dist/{chunk-BJA6GYC5.js → chunk-HXA6OB35.js} +65 -55
- package/dist/{chunk-WZFQ7T7V.js → chunk-LNEOE5TD.js} +2 -2
- package/dist/chunk-VQVAHUAX.js +183 -0
- package/dist/createProgramHandlers.js +5 -5
- package/dist/index.d.ts +97 -61
- package/dist/index.js +7 -7
- package/dist/kernel-loader-3JR6LJV5.js +1 -0
- package/dist/{kernel-workspace-host-CU56iOlt.d.ts → kernel-workspace-host-cT9JGJur.d.ts} +7 -12
- package/dist/kernelWorkspace.d.ts +1 -1
- package/dist/kernelWorkspace.js +3 -3
- package/dist/program-6DB6LK5B.js +2 -0
- package/package.json +9 -7
- package/dist/chunk-23YAOI6P.js +0 -42
- package/dist/chunk-A2TIXOLJ.js +0 -1326
- package/dist/kernel-loader-24KWM5C7.js +0 -1
- package/dist/program-35OTIG6Y.js +0 -2
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
import { installNodeHostPorts, createNodeTokenPost } from './chunk-VQVAHUAX.js';
|
|
2
|
+
import { nativeMemoryOf } from './chunk-EEYGL7AB.js';
|
|
3
|
+
import { EventBus, bindDeclaredCollections, createSecretPorts, defaultCallService, kernelEventRequestParser, kernelOsTls, kernelOsCompletions, stampEmitSource, eventRouteKey, kernelOsGrants, KernelEngine, dispatchDeclaredInput, dispatchInbound, createSecretStore, evaluateOnKernel, InFlightCalls } from '@almadar/shell-runtime';
|
|
4
|
+
import { installKernelEvaluator, orbitalInlineEntities, asEventId, asTraitId, inlineTraitRefs, tickEventKey, toPayloadValue } from '@almadar/core';
|
|
5
|
+
import { createLogger } from '@almadar/logger';
|
|
6
|
+
|
|
7
|
+
var effectLog = createLogger("almadar:runtime:effects");
|
|
8
|
+
var busLog = createLogger("almadar:runtime:bus");
|
|
9
|
+
var renderLog = createLogger("almadar:runtime:render-ui");
|
|
10
|
+
var xOrbitalLog = createLogger("almadar:runtime:cross-orbital");
|
|
11
|
+
createLogger("almadar:runtime:persist");
|
|
12
|
+
var registerLog = createLogger("almadar:runtime:register");
|
|
13
|
+
var TICK_PASS_MS = 16;
|
|
14
|
+
function isNodeEnv() {
|
|
15
|
+
return typeof process !== "undefined" && Boolean(process.versions?.node);
|
|
16
|
+
}
|
|
17
|
+
var UnresolvedProgramError = class extends Error {
|
|
18
|
+
constructor(schemaName) {
|
|
19
|
+
super(`program "${schemaName}" has unresolved imports and this host cannot run orb: register its resolved form (orb resolve)`);
|
|
20
|
+
this.name = "UnresolvedProgramError";
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
function needsResolving(schema) {
|
|
24
|
+
for (const orbital of schema.orbitals) {
|
|
25
|
+
for (const t of orbital.traits ?? []) {
|
|
26
|
+
if (typeof t === "object" && "ref" in t && t.ref.includes(".") && t._resolved === void 0) {
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
var OrbitalServerRuntime = class {
|
|
34
|
+
orbitals = /* @__PURE__ */ new Map();
|
|
35
|
+
eventBus;
|
|
36
|
+
config;
|
|
37
|
+
/** The row store a host-supplied `persistence` replaces: the kernel's own `MemoryStore`, opened by the first `register()`. */
|
|
38
|
+
ownedStore;
|
|
39
|
+
/**
|
|
40
|
+
* The bound persistence adapter (host-supplied, else the kernel's own memory store). Public so a test can
|
|
41
|
+
* inspect committed rows honestly. A runtime that owns its store has one from the first `register()`.
|
|
42
|
+
*/
|
|
43
|
+
get persistence() {
|
|
44
|
+
const store = this.config.persistence ?? this.ownedStore;
|
|
45
|
+
if (store === void 0) throw new Error("OrbitalServerRuntime: the runtime opens its store when a program is registered; none is registered yet");
|
|
46
|
+
return store;
|
|
47
|
+
}
|
|
48
|
+
/** The kernel running the registered program; null before a program is registered. */
|
|
49
|
+
kernelEngine = null;
|
|
50
|
+
/** What the kernel holds of every trait of the registered program, read once when the kernel opens. */
|
|
51
|
+
programSurface;
|
|
52
|
+
/** The `os` handles of the program the kernel runs; closed when that program is replaced, reset or dropped. */
|
|
53
|
+
kernelOs;
|
|
54
|
+
/** Drives the kernel's one tick clock: every pass asks `KernelEngine.tickPass` which ticks are due. */
|
|
55
|
+
tickTimer = null;
|
|
56
|
+
programHandlersPromise = null;
|
|
57
|
+
resolvedSchema = null;
|
|
58
|
+
/** The folder the program's lazy files sit beside; the pages that name them are on `resolvedSchema.lazyPages`. */
|
|
59
|
+
lazyDir;
|
|
60
|
+
/** Wired by the hosting server (e.g. the playground SSE endpoint) via `setLiveBroadcastSink`. */
|
|
61
|
+
liveSubscribers = /* @__PURE__ */ new Set();
|
|
62
|
+
liveBroadcastSink = null;
|
|
63
|
+
hostDispatchSink = null;
|
|
64
|
+
/** The one-shot timer that flushes the kernel's coalesced tick relay window. */
|
|
65
|
+
tickRelayTimer = null;
|
|
66
|
+
constructor(config) {
|
|
67
|
+
installNodeHostPorts();
|
|
68
|
+
this.config = { ...config };
|
|
69
|
+
this.eventBus = new EventBus();
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Lazily wire the program host handlers (behavior/* and program/* effects),
|
|
73
|
+
* merging them UNDER any user-provided handlers. Only when `programHost`
|
|
74
|
+
* is configured; otherwise the effects fail explicitly.
|
|
75
|
+
*/
|
|
76
|
+
async ensureProgramHandlers() {
|
|
77
|
+
if (!isNodeEnv()) return;
|
|
78
|
+
const host = this.config.programHost;
|
|
79
|
+
if (host === void 0) return;
|
|
80
|
+
if (!this.programHandlersPromise) {
|
|
81
|
+
this.programHandlersPromise = (async () => {
|
|
82
|
+
const { createProgramHandlers } = await import('./createProgramHandlers.js');
|
|
83
|
+
this.config.effectHandlers = {
|
|
84
|
+
...createProgramHandlers(host),
|
|
85
|
+
...this.config.effectHandlers
|
|
86
|
+
};
|
|
87
|
+
})();
|
|
88
|
+
}
|
|
89
|
+
return this.programHandlersPromise;
|
|
90
|
+
}
|
|
91
|
+
// ==========================================================================
|
|
92
|
+
// Schema Registration
|
|
93
|
+
// ==========================================================================
|
|
94
|
+
/**
|
|
95
|
+
* Register an OrbitalSchema for execution.
|
|
96
|
+
*
|
|
97
|
+
* Auto-preprocesses the schema when it contains `uses` declarations or
|
|
98
|
+
* unresolved cross-orbital trait references (e.g. a trait with
|
|
99
|
+
* `ref: "Modal.traits.ModalRecordModal"` and no inline `stateMachine`).
|
|
100
|
+
* Without preprocessing, those refs arrive empty at the state machine and
|
|
101
|
+
* button clicks silently do nothing — see Phase 9.5.H.
|
|
102
|
+
*
|
|
103
|
+
* Preprocessing needs a loader. If `loaderConfig` is set, that loader is
|
|
104
|
+
* used. Otherwise, a default loader is constructed that points at
|
|
105
|
+
* `<cwd>` (for `basePath`) and the nearest `node_modules/@almadar/std` (for
|
|
106
|
+
* `stdLibPath`), which matches how every caller in this monorepo has the
|
|
107
|
+
* std registry on disk.
|
|
108
|
+
*/
|
|
109
|
+
/**
|
|
110
|
+
* The in-flight (or last-completed) app mutation — `register()` chains its
|
|
111
|
+
* body onto this, and `unregisterAll()` stamps a marker after clearing.
|
|
112
|
+
* `processOrbitalEvent` consults it when the requested orbital is missing:
|
|
113
|
+
* during a catalog-style app swap the new schema's registration is already
|
|
114
|
+
* in flight while a client's first events arrive, and answering those with
|
|
115
|
+
* an immediate `Orbital not found` 404 (the pre-fix behavior) races the
|
|
116
|
+
* swap — big multi-orbital organisms lost their mount INITs intermittently
|
|
117
|
+
* while single-orbital ones almost always won. Awaiting the epoch and
|
|
118
|
+
* re-reading the map turns the race into a brief wait. `BrowserPlayground`
|
|
119
|
+
* gated dispatches on registration ad hoc for the same race; the epoch is
|
|
120
|
+
* the canonical, host-wide fix.
|
|
121
|
+
*/
|
|
122
|
+
registrationEpoch = null;
|
|
123
|
+
/**
|
|
124
|
+
* Reentrancy guard for `withRegistrationMutation`. While a bracket is
|
|
125
|
+
* open, `register()`/`unregisterAll()` must NOT chain/stamp the epoch:
|
|
126
|
+
* the callback's sequential awaits already order them, and chaining a
|
|
127
|
+
* `register()` awaited by the callback onto the bracket's gate would
|
|
128
|
+
* deadlock (callback → register → epoch → gate → callback's finally).
|
|
129
|
+
*/
|
|
130
|
+
registrationMutationDepth = 0;
|
|
131
|
+
async register(schema, options = {}) {
|
|
132
|
+
if (this.registrationMutationDepth > 0) {
|
|
133
|
+
await this.doRegister(schema, options);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const previous = this.registrationEpoch ?? Promise.resolve();
|
|
137
|
+
const epoch = previous.then(
|
|
138
|
+
() => this.doRegister(schema, options),
|
|
139
|
+
() => this.doRegister(schema, options)
|
|
140
|
+
);
|
|
141
|
+
this.registrationEpoch = epoch;
|
|
142
|
+
await epoch;
|
|
143
|
+
}
|
|
144
|
+
async doRegister(schema, options) {
|
|
145
|
+
const kernel = await this.kernelModule();
|
|
146
|
+
installKernelEvaluator(kernel);
|
|
147
|
+
this.openOwnedStore(kernel);
|
|
148
|
+
if (this.config.debug) {
|
|
149
|
+
registerLog.debug("register:schema", { name: schema.name });
|
|
150
|
+
}
|
|
151
|
+
if (needsResolving(schema)) schema = await this.resolveWithOrb(schema);
|
|
152
|
+
this.lazyDir = options.lazyDir;
|
|
153
|
+
if ((schema.lazyPages ?? []).length > 0 && this.lazyDir === void 0) {
|
|
154
|
+
throw new Error(`OrbitalServerRuntime: program "${schema.name}" lists lazy pages and no folder their files sit beside was given; register it from its file`);
|
|
155
|
+
}
|
|
156
|
+
for (const orbital of schema.orbitals) {
|
|
157
|
+
await this.registerOrbitalAsync(orbital);
|
|
158
|
+
}
|
|
159
|
+
await this.openKernel(schema);
|
|
160
|
+
this.resolvedSchema = schema;
|
|
161
|
+
}
|
|
162
|
+
/** The kernel's own row store, opened once in the register phase when the host supplied none. */
|
|
163
|
+
openOwnedStore(kernel) {
|
|
164
|
+
if (this.config.persistence !== void 0 || this.ownedStore !== void 0) return;
|
|
165
|
+
this.ownedStore = nativeMemoryOf(kernel);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* One-call entry point: read an `.orb` file from disk, parse it, preprocess
|
|
169
|
+
* cross-orbital imports, and register the result. Callers never touch raw
|
|
170
|
+
* `.orb` bytes — `register()` handles preprocessing internally.
|
|
171
|
+
*
|
|
172
|
+
* Node only. Browsers must receive already-resolved schemas from their
|
|
173
|
+
* server (see `getResolvedSchema()`).
|
|
174
|
+
*/
|
|
175
|
+
async registerFromFile(path) {
|
|
176
|
+
if (typeof process === "undefined" || !process.versions?.node) {
|
|
177
|
+
throw new Error(
|
|
178
|
+
"registerFromFile is Node-only. Browsers should receive resolved schemas from their server."
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
const { readFile } = await import('fs/promises');
|
|
182
|
+
const raw = await readFile(path, "utf-8");
|
|
183
|
+
let schema;
|
|
184
|
+
try {
|
|
185
|
+
schema = JSON.parse(raw);
|
|
186
|
+
} catch (err) {
|
|
187
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
188
|
+
throw new Error(`registerFromFile: ${path} is not valid JSON: ${msg}`);
|
|
189
|
+
}
|
|
190
|
+
const { dirname } = await import('path');
|
|
191
|
+
await this.register(schema, { lazyDir: dirname(path) });
|
|
192
|
+
}
|
|
193
|
+
/** A program with imports resolved by `orb` from the configured base path (Node only: the one resolver is the compiler). */
|
|
194
|
+
async resolveWithOrb(schema) {
|
|
195
|
+
if (!isNodeEnv()) throw new UnresolvedProgramError(schema.name);
|
|
196
|
+
const { programResolveSchema } = await import('./program-6DB6LK5B.js');
|
|
197
|
+
const cwd = this.programRoot();
|
|
198
|
+
if (this.config.debug) registerLog.debug("register:resolve-with-orb", { name: schema.name, cwd });
|
|
199
|
+
return programResolveSchema(schema, { cwd, ...this.config.programHost?.orbBin !== void 0 ? { orbBin: this.config.programHost.orbBin } : {} });
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Register a single orbital
|
|
203
|
+
*/
|
|
204
|
+
async registerOrbitalAsync(orbital) {
|
|
205
|
+
this.orbitals.set(orbital.name, { schema: orbital });
|
|
206
|
+
bindDeclaredCollections(this.persistence, orbitalInlineEntities(orbital));
|
|
207
|
+
if (this.config.debug) {
|
|
208
|
+
registerLog.debug("register:orbital", {
|
|
209
|
+
name: orbital.name,
|
|
210
|
+
traitCount: (orbital.traits || []).length
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
/** The adapters the kernel's I/O is answered with: this runtime's persistence, services and program host. */
|
|
215
|
+
secretPorts() {
|
|
216
|
+
const options = this.config.secretPorts;
|
|
217
|
+
if (options === void 0) return void 0;
|
|
218
|
+
const kernel = this.config.kernel;
|
|
219
|
+
if (kernel === void 0 || options.tokenPost !== void 0) return createSecretPorts(options);
|
|
220
|
+
const tokenPost = createNodeTokenPost({ egressAllows: (url) => this.requireKernelEngine().egressAllows(url), isPublicAddress: (ip) => kernel.isPublicAddress(ip) });
|
|
221
|
+
return createSecretPorts({ tokenPost, ...options });
|
|
222
|
+
}
|
|
223
|
+
kernelPorts() {
|
|
224
|
+
const secretPorts = this.secretPorts();
|
|
225
|
+
return {
|
|
226
|
+
...secretPorts !== void 0 ? { secretPorts } : {},
|
|
227
|
+
...this.config.clock !== void 0 ? { now: this.config.clock } : {},
|
|
228
|
+
...this.kernelOs !== void 0 ? { os: this.kernelOs } : {},
|
|
229
|
+
...this.kernelOs !== void 0 && this.config.kernel !== void 0 ? { osCompletions: kernelOsCompletions(this.config.kernel) } : {},
|
|
230
|
+
...this.kernelOs !== void 0 ? { osTls: kernelOsTls(() => this.requireKernelEngine()) } : {},
|
|
231
|
+
...this.config.kernel !== void 0 ? { parseEventRequest: kernelEventRequestParser(this.config.kernel) } : {},
|
|
232
|
+
persistence: this.persistence,
|
|
233
|
+
inFlightCalls: this.inFlightCalls,
|
|
234
|
+
callService: (service, action, params, context) => {
|
|
235
|
+
const provider = this.config.effectHandlers?.callService;
|
|
236
|
+
if (provider !== void 0) return provider(service, action, params, context);
|
|
237
|
+
return defaultCallService(service, action, params, context);
|
|
238
|
+
},
|
|
239
|
+
programEffect: () => this.config.effectHandlers?.programEffect,
|
|
240
|
+
substrateStream: (op, args) => {
|
|
241
|
+
if (op !== "program/live") return void 0;
|
|
242
|
+
const first = args[0];
|
|
243
|
+
const options = first !== null && typeof first === "object" && !Array.isArray(first) ? first : {};
|
|
244
|
+
const clientId = typeof options["clientId"] === "string" ? options["clientId"] : void 0;
|
|
245
|
+
return {
|
|
246
|
+
subscribe: (message) => {
|
|
247
|
+
const engine = this.requireKernelEngine();
|
|
248
|
+
const stream = clientId !== void 0 ? engine.openSessionStream(clientId) : void 0;
|
|
249
|
+
const receive = (item) => {
|
|
250
|
+
if (engine.liveItemDelivered(item, clientId)) message(toPayloadValue({ event: item.event, ...item.payload !== void 0 ? { payload: item.payload } : {}, source: item.source }));
|
|
251
|
+
};
|
|
252
|
+
this.liveSubscribers.add(receive);
|
|
253
|
+
return () => {
|
|
254
|
+
this.liveSubscribers.delete(receive);
|
|
255
|
+
if (stream !== void 0) engine.closeSessionStream(stream);
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
},
|
|
260
|
+
servicePorts: (caller, user, message, assertReentry) => this.servicePorts(caller, user, message, assertReentry),
|
|
261
|
+
deliverLive: (site, payload, originClientId) => this.deliverLiveMessage(site, payload, originClientId),
|
|
262
|
+
deferCallOutcome: () => this.hostDispatchSink === null ? void 0 : (call) => this.runDeferredOutcome(call.orbital, {
|
|
263
|
+
event: call.event,
|
|
264
|
+
...call.payload !== void 0 ? { payload: call.payload } : {},
|
|
265
|
+
...call.heldPayload !== void 0 ? { heldPayload: call.heldPayload } : {},
|
|
266
|
+
targetTrait: call.traitName,
|
|
267
|
+
...call.entityId !== void 0 ? { entityId: call.entityId } : {},
|
|
268
|
+
...call.originClientId !== void 0 ? { clientId: call.originClientId } : {},
|
|
269
|
+
...call.locale !== void 0 ? { locale: call.locale } : {}
|
|
270
|
+
})
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
/** One live message of a running `call-service`, stamped as its calling trait, to the requesting tab only. */
|
|
274
|
+
deliverLiveMessage(site, payload, originClientId) {
|
|
275
|
+
const registered = this.orbitals.get(site.orbital);
|
|
276
|
+
const callingTrait = this.traitsOf(site.orbital).find((t) => t.name === site.trait);
|
|
277
|
+
const stamp = stampEmitSource(void 0, {
|
|
278
|
+
orbitalName: site.orbital,
|
|
279
|
+
traitName: site.trait,
|
|
280
|
+
orbitalId: registered?.schema.id,
|
|
281
|
+
traitId: callingTrait?.traitId === void 0 ? void 0 : asTraitId(callingTrait.traitId),
|
|
282
|
+
emitContractEventId: ((eventId) => eventId === void 0 ? void 0 : asEventId(eventId))(callingTrait?.emits.find((e) => e.event === site.event)?.eventId),
|
|
283
|
+
originClientId
|
|
284
|
+
});
|
|
285
|
+
this.eventBus.emit(site.event, payload, stamp, eventRouteKey(site.event, stamp.eventId));
|
|
286
|
+
this.publishLiveItem({ event: site.event, payload, source: stamp, originClientId, target: "origin" });
|
|
287
|
+
}
|
|
288
|
+
/** The traits of one orbital as the kernel holds them. */
|
|
289
|
+
traitsOf(orbital) {
|
|
290
|
+
return (this.programSurface?.traits ?? []).filter((trait) => trait.orbital === orbital);
|
|
291
|
+
}
|
|
292
|
+
/** The project root this runtime hands `orb` and the kernel's language data: the program host's cwd, else the loader base path. */
|
|
293
|
+
programRoot() {
|
|
294
|
+
return this.config.programHost?.cwd ?? this.config.loaderConfig?.basePath ?? process.cwd();
|
|
295
|
+
}
|
|
296
|
+
/** The kernel module this runtime runs on: the one the host handed in, else the installed `@almadar/kernel`. */
|
|
297
|
+
async kernelModule() {
|
|
298
|
+
if (this.config.kernel !== void 0) return this.config.kernel;
|
|
299
|
+
const { loadInstalledKernel } = await import('./kernel-loader-3JR6LJV5.js');
|
|
300
|
+
this.config.kernel = await loadInstalledKernel(this.programRoot());
|
|
301
|
+
return this.config.kernel;
|
|
302
|
+
}
|
|
303
|
+
/** (Re)open the kernel on the program just registered. */
|
|
304
|
+
async openKernel(registered) {
|
|
305
|
+
const kernel = await this.kernelModule();
|
|
306
|
+
const schema = { ...registered, orbitals: inlineTraitRefs(registered.orbitals) };
|
|
307
|
+
for (const orbital of schema.orbitals) {
|
|
308
|
+
for (const trait of orbital.traits ?? []) {
|
|
309
|
+
if (typeof trait === "object" && "ref" in trait && !("stateMachine" in trait)) {
|
|
310
|
+
throw new Error(`OrbitalServerRuntime: the kernel takes an orb-resolved program, but trait "${trait.ref}" of orbital "${orbital.name}" is still a reference`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
this.inFlightCalls.cancelAll();
|
|
315
|
+
this.kernelEngine?.dispose();
|
|
316
|
+
this.kernelOs?.close();
|
|
317
|
+
this.kernelOs = this.config.osHost?.(kernelOsGrants(kernel, () => this.requireKernelEngine()));
|
|
318
|
+
this.kernelEngine = KernelEngine.open(kernel, schema, this.kernelPorts(), this.lazyDir);
|
|
319
|
+
this.kernelEngine.setStateful();
|
|
320
|
+
this.programSurface = this.kernelEngine.programSurface();
|
|
321
|
+
if (this.config.tickRelayIntervalMs !== void 0) this.kernelEngine.setTickRelayInterval(this.config.tickRelayIntervalMs);
|
|
322
|
+
this.restartTickClock();
|
|
323
|
+
await this.mountBootEndpoints();
|
|
324
|
+
}
|
|
325
|
+
/** Run the kernel's boot mounts for the server side (EXEC-ENDPOINT-3): the host sends what the kernel lists and chooses nothing. */
|
|
326
|
+
async mountBootEndpoints() {
|
|
327
|
+
const owners = /* @__PURE__ */ new Map();
|
|
328
|
+
for (const trait of this.programSurface?.traits ?? []) {
|
|
329
|
+
const registered = this.orbitals.get(trait.orbital);
|
|
330
|
+
if (registered !== void 0) owners.set(trait.name, registered);
|
|
331
|
+
}
|
|
332
|
+
const batches = /* @__PURE__ */ new Map();
|
|
333
|
+
for (const seed of this.requireKernelEngine().bootMounts("server")) {
|
|
334
|
+
const owner = owners.get(seed.trait);
|
|
335
|
+
if (owner === void 0) continue;
|
|
336
|
+
batches.set(owner, [...batches.get(owner) ?? [], seed]);
|
|
337
|
+
}
|
|
338
|
+
for (const [registered, mount] of batches) {
|
|
339
|
+
const first = mount[0];
|
|
340
|
+
if (first === void 0) continue;
|
|
341
|
+
const response = await this.evaluateForOrbital(registered, { event: first.event, mount, payload: {} });
|
|
342
|
+
if (!response.success) {
|
|
343
|
+
throw new Error(`OrbitalServerRuntime: the boot mount of orbital "${registered.schema.name}" failed: ${response.error ?? "the kernel refused it"}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** What answers the declared contract: the registered program's kernel, else the kernel's own program-less answers, which refuse every input and hook. */
|
|
348
|
+
async contractEngine() {
|
|
349
|
+
return this.kernelEngine ?? KernelEngine.withoutProgram(await this.kernelModule());
|
|
350
|
+
}
|
|
351
|
+
requireKernelEngine() {
|
|
352
|
+
if (this.kernelEngine === null) throw new Error("OrbitalServerRuntime: an os ask arrived with no kernel program registered");
|
|
353
|
+
return this.kernelEngine;
|
|
354
|
+
}
|
|
355
|
+
/** Ask the kernel's clock which ticks are due and start each as a `runTick` request to the orbital it names. */
|
|
356
|
+
tickPass() {
|
|
357
|
+
const engine = this.kernelEngine;
|
|
358
|
+
if (engine === null) return;
|
|
359
|
+
for (const [orbital, ticks] of Object.entries(engine.tickPass(performance.now()))) {
|
|
360
|
+
for (const due of ticks) void this.executeTick(orbital, due.trait, due.tick);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
/** Run the kernel's clock on this host's timer when the program declares a tick. */
|
|
364
|
+
restartTickClock() {
|
|
365
|
+
this.cleanupTicks();
|
|
366
|
+
if (this.kernelEngine?.declaresTicks() !== true) return;
|
|
367
|
+
this.tickTimer = setInterval(() => this.tickPass(), TICK_PASS_MS);
|
|
368
|
+
}
|
|
369
|
+
/** A tick: the host owns the timer, the kernel decides whether and over which rows it fires. */
|
|
370
|
+
async executeTick(orbitalName, traitName, tickName) {
|
|
371
|
+
const response = await this.processOrbitalEvent(orbitalName, {
|
|
372
|
+
event: tickEventKey(tickName),
|
|
373
|
+
runTick: { trait: traitName, tick: tickName },
|
|
374
|
+
targetTrait: traitName
|
|
375
|
+
});
|
|
376
|
+
if (!response.success) {
|
|
377
|
+
effectLog.error("tick:execute-error", { tick: tickName, error: response.error ?? "the kernel refused the tick" });
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Stop the host's timers
|
|
382
|
+
*/
|
|
383
|
+
cleanupTicks() {
|
|
384
|
+
if (this.tickTimer !== null) clearInterval(this.tickTimer);
|
|
385
|
+
this.tickTimer = null;
|
|
386
|
+
if (this.tickRelayTimer !== null) clearTimeout(this.tickRelayTimer);
|
|
387
|
+
this.tickRelayTimer = null;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Unregister all orbitals and clean up
|
|
391
|
+
*/
|
|
392
|
+
unregisterAll() {
|
|
393
|
+
this.cleanupTicks();
|
|
394
|
+
this.orbitals.clear();
|
|
395
|
+
this.inFlightCalls.cancelAll();
|
|
396
|
+
this.kernelEngine?.dispose();
|
|
397
|
+
this.kernelEngine = null;
|
|
398
|
+
this.programSurface = void 0;
|
|
399
|
+
this.kernelOs?.close();
|
|
400
|
+
this.kernelOs = void 0;
|
|
401
|
+
this.eventBus.clear();
|
|
402
|
+
this.programHandlersPromise = null;
|
|
403
|
+
if (this.registrationMutationDepth === 0) {
|
|
404
|
+
this.registrationEpoch = (this.registrationEpoch ?? Promise.resolve()).then(() => void 0, () => void 0);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Bracket a multi-step app mutation (the classic swap is
|
|
409
|
+
* `unregisterAll()` → resolve next schema → `register()`) as ONE
|
|
410
|
+
* registration epoch. `register()` alone chains only its own body onto
|
|
411
|
+
* the epoch, so between `unregisterAll()` and the `register()` call the
|
|
412
|
+
* runtime's map is empty while the epoch marker has already resolved —
|
|
413
|
+
* any `processOrbitalEvent` that lands in that gap (the resolve of a big
|
|
414
|
+
* organism takes real time) 404s `Orbital not found` even though the
|
|
415
|
+
* requested orbital is milliseconds away from landing. Inside this
|
|
416
|
+
* bracket the epoch stays pending for the WHOLE callback, so mid-swap
|
|
417
|
+
* dispatches await the completed swap and then resolve against the new
|
|
418
|
+
* app. A failed callback still releases the epoch (chained on both
|
|
419
|
+
* branches), so a failed swap falls through to the honest 404 instead of
|
|
420
|
+
* wedging the queue. Callbacks SERIALIZE: each bracket awaits the previous
|
|
421
|
+
* epoch before running `fn`, so two hosts swapping at once (a catalog
|
|
422
|
+
* select racing a preview remount's `/register`) cannot interleave their
|
|
423
|
+
* unregister/register sequences into a mixed registry. A bracket opened
|
|
424
|
+
* from INSIDE another bracket's callback runs `fn` directly — detected
|
|
425
|
+
* via the AsyncLocalStorage context below (a depth counter alone can't
|
|
426
|
+
* tell a true nest from a concurrent caller) — because the outer
|
|
427
|
+
* callback's awaits already serialize it and queueing on the outer gate
|
|
428
|
+
* would deadlock. Deadlock-free otherwise: `doRegister` never dispatches
|
|
429
|
+
* events, so awaiting dispatches never block registration progress.
|
|
430
|
+
*/
|
|
431
|
+
/**
|
|
432
|
+
* Reentrancy context for `withRegistrationMutation`. A depth counter alone
|
|
433
|
+
* cannot distinguish "called from inside a bracket callback" (must run
|
|
434
|
+
* directly — queueing on the outer gate would deadlock) from "called
|
|
435
|
+
* concurrently while another bracket is in flight" (must queue — running
|
|
436
|
+
* directly would interleave two swaps). The ALS marks the callback's async
|
|
437
|
+
* context, which separates the two exactly.
|
|
438
|
+
*/
|
|
439
|
+
bracketAls = null;
|
|
440
|
+
ensureBracketAls() {
|
|
441
|
+
this.bracketAls ??= import('async_hooks').then(
|
|
442
|
+
({ AsyncLocalStorage }) => new AsyncLocalStorage()
|
|
443
|
+
);
|
|
444
|
+
return this.bracketAls;
|
|
445
|
+
}
|
|
446
|
+
async withRegistrationMutation(fn) {
|
|
447
|
+
const previous = this.registrationEpoch ?? Promise.resolve();
|
|
448
|
+
let release = () => void 0;
|
|
449
|
+
const gate = new Promise((resolve) => {
|
|
450
|
+
release = resolve;
|
|
451
|
+
});
|
|
452
|
+
this.registrationEpoch = previous.then(() => gate, () => gate);
|
|
453
|
+
this.registrationMutationDepth++;
|
|
454
|
+
try {
|
|
455
|
+
const als = await this.ensureBracketAls();
|
|
456
|
+
if (als.getStore() !== void 0) {
|
|
457
|
+
release();
|
|
458
|
+
return await fn();
|
|
459
|
+
}
|
|
460
|
+
await previous.catch(() => void 0);
|
|
461
|
+
const nestingToken = /* @__PURE__ */ Symbol("withRegistrationMutation");
|
|
462
|
+
return await als.run(nestingToken, fn);
|
|
463
|
+
} finally {
|
|
464
|
+
this.registrationMutationDepth--;
|
|
465
|
+
release();
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Return every registered orbital's circuit to boot: trait states to their
|
|
470
|
+
* initial states, frames and row cache emptied, and a fresh mount (no trait
|
|
471
|
+
* awaiting INIT, nothing held).
|
|
472
|
+
*/
|
|
473
|
+
resetCircuitState() {
|
|
474
|
+
this.inFlightCalls.cancelAll();
|
|
475
|
+
this.kernelEngine?.reset();
|
|
476
|
+
this.kernelOs?.close();
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Wire a live-broadcast sink. Called only from a `persist` effect's
|
|
480
|
+
* `emit:{success}` envelope firing site (batch and single-op) — see
|
|
481
|
+
* `docs/Almadar_Live_Push.md`. The hosting server (e.g. the playground's
|
|
482
|
+
* `/api/events` SSE endpoint) uses this to fan persist mutations out to
|
|
483
|
+
* every OTHER connected client; a fresh call replaces the previous sink.
|
|
484
|
+
*/
|
|
485
|
+
setLiveBroadcastSink(sink) {
|
|
486
|
+
this.liveBroadcastSink = sink;
|
|
487
|
+
}
|
|
488
|
+
publishLiveItem(item) {
|
|
489
|
+
this.liveBroadcastSink?.(item);
|
|
490
|
+
for (const receive of this.liveSubscribers) receive(item);
|
|
491
|
+
}
|
|
492
|
+
/** Wire where a host-run dispatch's result goes (see `HostDispatchItem`); a fresh call replaces the previous sink. */
|
|
493
|
+
setHostDispatchSink(sink) {
|
|
494
|
+
this.hostDispatchSink = sink;
|
|
495
|
+
}
|
|
496
|
+
/** Run a follow-on step's call outcome as its own dispatch, and hand its result to the host-dispatch sink. */
|
|
497
|
+
runDeferredOutcome(orbitalName, request) {
|
|
498
|
+
void this.processOrbitalEvent(orbitalName, request).then(
|
|
499
|
+
(response) => this.hostDispatchSink?.({ orbitalName, request, response, ...request.clientId !== void 0 ? { originClientId: request.clientId } : {} }),
|
|
500
|
+
(error) => effectLog.error("deferred-outcome:failed", { orbitalName, event: request.event, trait: request.targetTrait, error: error.message })
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* A tick-stamped dispatch is a latest-state broadcast (T6): the kernel coalesces it with the others of the window
|
|
505
|
+
* (newest per origin client, orbital and event) and says how long the window stays open; this host only runs
|
|
506
|
+
* the timer.
|
|
507
|
+
*/
|
|
508
|
+
queueTickRelay(orbitalName, request) {
|
|
509
|
+
const engine = this.requireKernelEngine();
|
|
510
|
+
const window = engine.relayTick(orbitalName, request);
|
|
511
|
+
if (window === void 0) return;
|
|
512
|
+
const timer = setTimeout(() => this.flushTickRelay(), window);
|
|
513
|
+
if (typeof timer === "object" && typeof timer.unref === "function") timer.unref();
|
|
514
|
+
this.tickRelayTimer = timer;
|
|
515
|
+
}
|
|
516
|
+
flushTickRelay() {
|
|
517
|
+
this.tickRelayTimer = null;
|
|
518
|
+
const engine = this.kernelEngine;
|
|
519
|
+
if (engine === null) return;
|
|
520
|
+
for (const item of engine.flushTickRelay()) this.publishLiveItem({ ...item, target: "peers" });
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* `reference` resolved for the identity bound to `clientId`'s session (none: the anonymous viewer) against the store as it is now: the rows that still match its query and that identity's `@read`, in the reference's order, `total` re-counted. The kernel resolves through its server
|
|
524
|
+
* resolve flight. A client reaches it with
|
|
525
|
+
* `POST /:orbital/../resolve-rows`.
|
|
526
|
+
*/
|
|
527
|
+
async resolveRows(reference, clientId) {
|
|
528
|
+
const engine = this.kernelEngine;
|
|
529
|
+
const owner = engine === null ? void 0 : engine.entityOwnerOrbital(reference.entityType);
|
|
530
|
+
if (engine === null || owner === void 0) throw new Error(`${reference.entityType}: no registered orbital declares this entity`);
|
|
531
|
+
return engine.resolveRows(reference, { orbital: owner, ...clientId !== void 0 ? { originClientId: clientId } : {} });
|
|
532
|
+
}
|
|
533
|
+
// ==========================================================================
|
|
534
|
+
// Event Processing
|
|
535
|
+
// ==========================================================================
|
|
536
|
+
/**
|
|
537
|
+
* Process an event for an orbital — the stateful host's thin shell over
|
|
538
|
+
* the unified `evaluateOrbitalEvent` composition (design:
|
|
539
|
+
* docs/Almadar_Runtime_Stateless_Stateful_PLAN.md §4.1). This method owns
|
|
540
|
+
* ONLY session concerns: orbital lookup, viewer normalization, the lazy
|
|
541
|
+
* OS/substrate handler wiring, the per-request relay mask
|
|
542
|
+
* (G-RUNTIME-031 — the client's mounted set as DATA, replacing the
|
|
543
|
+
* deleted blanket `originClientId` skip), the tick snapshot relay, and
|
|
544
|
+
* the cross-orbital listens relay (a listener registered under a
|
|
545
|
+
* DIFFERENT orbital than the emitter — the per-orbital composition's
|
|
546
|
+
* in-band fan-out covers the rest). Target resolution, payload
|
|
547
|
+
* validation, the cascade, the fan-out, structured rejections, and
|
|
548
|
+
* response assembly are the composition's, identical to the stateless
|
|
549
|
+
* path.
|
|
550
|
+
*
|
|
551
|
+
* Serialization: the whole evaluation runs on ONE runtime-wide async
|
|
552
|
+
* queue. The composition commits manager state directly (no per-trait
|
|
553
|
+
* actor queue), so concurrent requests against the long-lived session
|
|
554
|
+
* manager would otherwise both evaluate from the same held state and
|
|
555
|
+
* lose a transition. Coarser than the old per-(trait, entityId) actor
|
|
556
|
+
* queues — a deliberate W4 tradeoff, recorded in the plan doc.
|
|
557
|
+
*
|
|
558
|
+
* @param onPush - Optional incremental-push callback. Called immediately
|
|
559
|
+
* when an event is emitted or a client effect fires, before the promise
|
|
560
|
+
* resolves. Used by the SSE streaming path to write items to the
|
|
561
|
+
* response as they arrive rather than buffering and flushing at the end.
|
|
562
|
+
*/
|
|
563
|
+
/**
|
|
564
|
+
* Read an orbital by name, awaiting an in-flight registration mutation
|
|
565
|
+
* first when the lookup misses (G-RUNTIME-038): mid-swap lookups 404ed
|
|
566
|
+
* against the emptied map even though the requested orbital was
|
|
567
|
+
* milliseconds from landing. A failed mutation falls through to the miss.
|
|
568
|
+
*/
|
|
569
|
+
async resolveRegisteredOrbital(orbitalName) {
|
|
570
|
+
let registered = this.orbitals.get(orbitalName);
|
|
571
|
+
if (!registered && this.registrationEpoch !== null) {
|
|
572
|
+
await this.registrationEpoch.catch(() => void 0);
|
|
573
|
+
registered = this.orbitals.get(orbitalName);
|
|
574
|
+
}
|
|
575
|
+
if (!registered) {
|
|
576
|
+
await this.loadLazyOrbital(orbitalName);
|
|
577
|
+
registered = this.orbitals.get(orbitalName);
|
|
578
|
+
}
|
|
579
|
+
return registered;
|
|
580
|
+
}
|
|
581
|
+
/** The first request that names a `uses lazy` orbital registers it here; the kernel loads the same file on that request's dispatch (EXEC-LOAD-2). */
|
|
582
|
+
async loadLazyOrbital(orbitalName) {
|
|
583
|
+
const dir = this.lazyDir;
|
|
584
|
+
const pages = (this.resolvedSchema?.lazyPages ?? []).filter((page) => page.orbital === orbitalName);
|
|
585
|
+
const first = pages[0];
|
|
586
|
+
if (dir === void 0 || first === void 0) return;
|
|
587
|
+
const { readFile } = await import('fs/promises');
|
|
588
|
+
const { join } = await import('path');
|
|
589
|
+
const lazyPath = join(dir, first.orbRef);
|
|
590
|
+
let lazySchema;
|
|
591
|
+
try {
|
|
592
|
+
lazySchema = JSON.parse(await readFile(lazyPath, "utf-8"));
|
|
593
|
+
} catch (err) {
|
|
594
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
595
|
+
throw new Error(`lazy orbital "${orbitalName}": ${first.orbRef} could not be read: ${msg}`);
|
|
596
|
+
}
|
|
597
|
+
if (!lazySchema.orbitals.some((o) => o.name === orbitalName)) {
|
|
598
|
+
throw new Error(`lazy orbital "${orbitalName}" is not in ${first.orbRef}, found: ${lazySchema.orbitals.map((o) => o.name).join(", ")}`);
|
|
599
|
+
}
|
|
600
|
+
for (const orbital of lazySchema.orbitals) {
|
|
601
|
+
await this.registerOrbitalAsync(orbital);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
/** The program's declared external inputs: what an outside client may send which trait. */
|
|
605
|
+
listExternalInputs() {
|
|
606
|
+
return this.kernelEngine?.externalInputs() ?? [];
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* The outside-client input channel: an API caller, an agent acting as the
|
|
610
|
+
* user, an MCP client. Only a declared external input of the target trait is
|
|
611
|
+
* dispatched — through `processOrbitalEvent`, so guards, entity policies and
|
|
612
|
+
* cascades apply exactly as for a click. Anything else is refused with
|
|
613
|
+
* `not-an-external-input`. The app's own UI keeps using `processOrbitalEvent`.
|
|
614
|
+
*/
|
|
615
|
+
/**
|
|
616
|
+
* The running app lent to one `call-service` provider as the caller: the
|
|
617
|
+
* declared inputs, the input channel as `user`, and the rows `user` may read
|
|
618
|
+
* (the entity's `@read` policy, the same rule a `fetch` effect applies).
|
|
619
|
+
*/
|
|
620
|
+
servicePorts(caller, user, message = () => {
|
|
621
|
+
}, assertReentry) {
|
|
622
|
+
return {
|
|
623
|
+
caller,
|
|
624
|
+
message,
|
|
625
|
+
inputs: () => this.listExternalInputs(),
|
|
626
|
+
readableEntities: () => this.kernelEngine?.readableEntities() ?? [],
|
|
627
|
+
dispatchInput: (orbital, request) => {
|
|
628
|
+
assertReentry?.();
|
|
629
|
+
return this.dispatchExternalInput(orbital, request);
|
|
630
|
+
},
|
|
631
|
+
read: async (entity) => {
|
|
632
|
+
return this.requireKernelEngine().readRows(entity, await this.persistence.list(entity), user);
|
|
633
|
+
},
|
|
634
|
+
supportsDispatchStream: true,
|
|
635
|
+
dispatchRequest: (orbital, request, input, stream) => {
|
|
636
|
+
assertReentry?.();
|
|
637
|
+
return this.dispatchEventRequest(orbital, request, input, stream);
|
|
638
|
+
},
|
|
639
|
+
deliverInbound: (name, delivery) => this.deliverInbound(name, delivery),
|
|
640
|
+
resolveRows: (reference, clientId) => this.resolveRows(reference, clientId)
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* A `program/dispatch` event request, as the events route (or with `input`, the inputs route) runs it: the
|
|
645
|
+
* runs as the session's identity, never a viewer the request names. An unknown orbital is `ORBITAL_NOT_FOUND`, an undeclared
|
|
646
|
+
* locale `LOCALE_NOT_DECLARED`; an inbound-only event and an undeclared input are the routes' refusals.
|
|
647
|
+
*/
|
|
648
|
+
async dispatchEventRequest(orbital, parsed, input, stream = false) {
|
|
649
|
+
const request = parsed;
|
|
650
|
+
const streamItems = [];
|
|
651
|
+
const onPush = stream ? (item) => {
|
|
652
|
+
streamItems.push({ ...item, timestamp: item.timestamp ?? Date.now() });
|
|
653
|
+
} : void 0;
|
|
654
|
+
const answer = (response2) => ({
|
|
655
|
+
ok: true,
|
|
656
|
+
response: response2,
|
|
657
|
+
...stream ? { streamItems: [...streamItems, { type: "complete", data: response2, timestamp: Date.now() }] } : {}
|
|
658
|
+
});
|
|
659
|
+
if (await this.resolveRegisteredOrbital(orbital) === void 0) {
|
|
660
|
+
return { ok: false, error: `Orbital not found: ${orbital}`, code: "ORBITAL_NOT_FOUND", status: 404 };
|
|
661
|
+
}
|
|
662
|
+
if (input) {
|
|
663
|
+
if (request.targetTrait === void 0) {
|
|
664
|
+
return { ok: false, error: "program/dispatch: an input request names its trait", code: "NO_TRAIT", status: 400 };
|
|
665
|
+
}
|
|
666
|
+
const response2 = await this.dispatchExternalInput(orbital, {
|
|
667
|
+
targetTrait: request.targetTrait,
|
|
668
|
+
event: request.event,
|
|
669
|
+
...request.payload !== void 0 ? { payload: request.payload } : {},
|
|
670
|
+
...request.entityId !== void 0 ? { entityId: request.entityId } : {}
|
|
671
|
+
}, onPush);
|
|
672
|
+
return answer(response2);
|
|
673
|
+
}
|
|
674
|
+
const refusal = this.refuseInboundOnly(orbital, request);
|
|
675
|
+
if (refusal !== void 0) return answer(refusal);
|
|
676
|
+
const response = await this.processOrbitalEvent(orbital, request, onPush);
|
|
677
|
+
if (response.rejections?.[0]?.code === "locale-not-declared") {
|
|
678
|
+
return { ok: false, error: response.error ?? "the locale is not declared", code: "LOCALE_NOT_DECLARED", status: 400 };
|
|
679
|
+
}
|
|
680
|
+
return answer(response);
|
|
681
|
+
}
|
|
682
|
+
async dispatchExternalInput(orbitalName, request, onPush) {
|
|
683
|
+
return dispatchDeclaredInput(await this.contractEngine(), orbitalName, request, (orbital, req) => this.processOrbitalEvent(orbital, req, onPush));
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* An inbound delivery (`/api/hooks/<name>`): the runtime decides whether the name is served, runs
|
|
687
|
+
* the handler through `processOrbitalEvent` and answers; the host only carries the bytes.
|
|
688
|
+
*/
|
|
689
|
+
/**
|
|
690
|
+
* An event that is an inbound hook's is delivered only by `deliverInbound`: the app's own event
|
|
691
|
+
* route refuses it, as the input channel refuses an event that is no declared input.
|
|
692
|
+
*/
|
|
693
|
+
refuseInboundOnly(orbitalName, request) {
|
|
694
|
+
const only = this.kernelEngine?.inboundOnly(orbitalName, request.targetTrait, request.event);
|
|
695
|
+
if (only === void 0) return void 0;
|
|
696
|
+
const { trait } = only;
|
|
697
|
+
return {
|
|
698
|
+
success: false,
|
|
699
|
+
transitioned: false,
|
|
700
|
+
states: {},
|
|
701
|
+
emittedEvents: [],
|
|
702
|
+
error: only.message,
|
|
703
|
+
rejections: [{ code: "inbound-only-event", trait, event: request.event }]
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
async deliverInbound(name, delivery, onPush) {
|
|
707
|
+
return dispatchInbound(await this.contractEngine(), name, delivery, (orbital, req) => this.processOrbitalEvent(orbital, req, onPush), (credential) => (this.secretPorts()?.secrets ?? createSecretStore()).get(credential, void 0));
|
|
708
|
+
}
|
|
709
|
+
async processOrbitalEvent(orbitalName, request, onPush) {
|
|
710
|
+
try {
|
|
711
|
+
await this.ensureProgramHandlers();
|
|
712
|
+
const registered = await this.resolveRegisteredOrbital(orbitalName);
|
|
713
|
+
if (!registered) {
|
|
714
|
+
return {
|
|
715
|
+
success: false,
|
|
716
|
+
transitioned: false,
|
|
717
|
+
states: {},
|
|
718
|
+
emittedEvents: [],
|
|
719
|
+
error: `Orbital not found: ${orbitalName}`
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
const response = await this.evaluateForOrbital(registered, request, onPush);
|
|
723
|
+
if (request.tick !== void 0 && this.liveBroadcastSink !== null) {
|
|
724
|
+
this.queueTickRelay(orbitalName, request);
|
|
725
|
+
}
|
|
726
|
+
return response;
|
|
727
|
+
} catch (error) {
|
|
728
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
729
|
+
xOrbitalLog.error("processOrbitalEvent:error", {
|
|
730
|
+
orbital: orbitalName,
|
|
731
|
+
event: request.event,
|
|
732
|
+
entityId: request.entityId,
|
|
733
|
+
error: message
|
|
734
|
+
});
|
|
735
|
+
return {
|
|
736
|
+
success: false,
|
|
737
|
+
transitioned: false,
|
|
738
|
+
states: {},
|
|
739
|
+
emittedEvents: [],
|
|
740
|
+
error: message
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* One request evaluated on the kernel, which orders it among every other (EXEC-CONC-2), then its emits relayed
|
|
746
|
+
* to the host sinks.
|
|
747
|
+
*/
|
|
748
|
+
async evaluateForOrbital(registered, request, onPush) {
|
|
749
|
+
const orbitalName = registered.schema.name;
|
|
750
|
+
const payloadRow = request.payload?.["row"];
|
|
751
|
+
const payloadRowAsPayload = payloadRow !== null && typeof payloadRow === "object" && !Array.isArray(payloadRow) ? payloadRow : void 0;
|
|
752
|
+
const payloadRowId = payloadRowAsPayload?.["id"];
|
|
753
|
+
renderLog.debug("processOrbitalEvent:enter", {
|
|
754
|
+
orbital: orbitalName,
|
|
755
|
+
event: request.event,
|
|
756
|
+
hasPayloadRow: payloadRowAsPayload !== void 0,
|
|
757
|
+
payloadRowId: typeof payloadRowId === "string" || typeof payloadRowId === "number" ? payloadRowId : void 0,
|
|
758
|
+
entityId: request.entityId
|
|
759
|
+
});
|
|
760
|
+
busLog.debug("bus:incoming", () => ({
|
|
761
|
+
orbital: orbitalName,
|
|
762
|
+
event: request.event,
|
|
763
|
+
payload: JSON.stringify(request.payload ?? null),
|
|
764
|
+
entityId: request.entityId,
|
|
765
|
+
traitStates: JSON.stringify(this.traitsOf(orbitalName).map((trait) => ({ traitName: trait.name, currentState: this.kernelEngine?.stateOf(trait.name) ?? "" })))
|
|
766
|
+
}));
|
|
767
|
+
xOrbitalLog.debug("processOrbitalEvent:enter", () => ({
|
|
768
|
+
orbital: orbitalName,
|
|
769
|
+
event: request.event,
|
|
770
|
+
traitsInOrbital: this.traitsOf(orbitalName).map((t) => t.name).join(","),
|
|
771
|
+
payloadActiveTraits: JSON.stringify(
|
|
772
|
+
request.payload?.["_activeTraits"] ?? null
|
|
773
|
+
)
|
|
774
|
+
}));
|
|
775
|
+
const response = await evaluateOnKernel(
|
|
776
|
+
{ engine: this.requireKernelEngine(), orbital: registered.schema.name, ...onPush !== void 0 ? { onStream: (item) => {
|
|
777
|
+
if (item.type === "event" || item.type === "effect") onPush(item);
|
|
778
|
+
} } : {} },
|
|
779
|
+
request,
|
|
780
|
+
request.locale
|
|
781
|
+
);
|
|
782
|
+
this.publishKernelResponse(response, void 0, request.clientId);
|
|
783
|
+
return response;
|
|
784
|
+
}
|
|
785
|
+
/**
|
|
786
|
+
* Feed the host sinks from a kernel response: the kernel answers a dispatch whole, so each emit reaches the
|
|
787
|
+
* event bus (the public firehose) and `onPush` once the dispatch is done, in the order the response carries them.
|
|
788
|
+
*/
|
|
789
|
+
publishKernelResponse(response, onPush, originClientId) {
|
|
790
|
+
for (const emitted of response.emittedEvents) {
|
|
791
|
+
this.eventBus.emit(emitted.event, emitted.payload, emitted.source, eventRouteKey(emitted.event, emitted.source?.eventId));
|
|
792
|
+
if (emitted.source?.persistSuccess === true) {
|
|
793
|
+
const { persistSuccess: _mark, ...source } = emitted.source;
|
|
794
|
+
this.publishLiveItem({ event: emitted.event, ...emitted.payload !== void 0 ? { payload: emitted.payload } : {}, source, ...originClientId !== void 0 ? { originClientId } : {}, target: "peers" });
|
|
795
|
+
}
|
|
796
|
+
onPush?.({ type: "event", data: emitted });
|
|
797
|
+
}
|
|
798
|
+
for (const { effect } of response.clientEffectsByTrait ?? []) onPush?.({ type: "effect", data: effect });
|
|
799
|
+
}
|
|
800
|
+
/** This app's in-flight keyed `call-service`s, shared by every transition it runs (`cancel-call`). */
|
|
801
|
+
inFlightCalls = new InFlightCalls();
|
|
802
|
+
// ==========================================================================
|
|
803
|
+
// Direct API (for programmatic use)
|
|
804
|
+
// ==========================================================================
|
|
805
|
+
/**
|
|
806
|
+
* Get the event bus for manual event emission
|
|
807
|
+
*/
|
|
808
|
+
getEventBus() {
|
|
809
|
+
return this.eventBus;
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Get state for a specific orbital/trait
|
|
813
|
+
*/
|
|
814
|
+
getState(orbitalName, traitName) {
|
|
815
|
+
const registered = this.orbitals.get(orbitalName);
|
|
816
|
+
if (!registered) return void 0;
|
|
817
|
+
const kernel = this.kernelEngine;
|
|
818
|
+
if (kernel === null) return void 0;
|
|
819
|
+
const stateOf = (name) => {
|
|
820
|
+
const currentState = kernel.stateOf(name);
|
|
821
|
+
return currentState === "" ? void 0 : { traitName: name, currentState, previousState: null, lastEvent: null, context: {} };
|
|
822
|
+
};
|
|
823
|
+
if (traitName) return stateOf(traitName);
|
|
824
|
+
const states = {};
|
|
825
|
+
for (const trait of this.traitsOf(orbitalName)) {
|
|
826
|
+
const state = stateOf(trait.name);
|
|
827
|
+
if (state !== void 0) states[trait.name] = state;
|
|
828
|
+
}
|
|
829
|
+
return states;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* List registered orbitals
|
|
833
|
+
*/
|
|
834
|
+
listOrbitals() {
|
|
835
|
+
return Array.from(this.orbitals.keys());
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Check if an orbital is registered
|
|
839
|
+
*/
|
|
840
|
+
hasOrbital(name) {
|
|
841
|
+
return this.orbitals.has(name);
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
|
|
845
|
+
export { OrbitalServerRuntime, UnresolvedProgramError };
|