@spellkave/session 0.0.0-bootstrap → 0.0.0-stage

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 (45) hide show
  1. package/README.md +3 -0
  2. package/package.json +4 -58
  3. package/LICENSE +0 -89
  4. package/bin/spellkave-session-daemon.js +0 -5
  5. package/src/acting-context.ts +0 -222
  6. package/src/authoring/caller-tools.ts +0 -227
  7. package/src/authoring/index.ts +0 -28
  8. package/src/authoring/live-applyset-port.ts +0 -432
  9. package/src/authoring/live-author-target.ts +0 -995
  10. package/src/authoring/live-can-i-port.ts +0 -152
  11. package/src/authoring/live-exploration-port.ts +0 -274
  12. package/src/authoring/live-grants-port.ts +0 -172
  13. package/src/authoring/live-scenes-port.ts +0 -84
  14. package/src/authoring/live-scoped-instance-port.ts +0 -355
  15. package/src/binding.ts +0 -125
  16. package/src/index.ts +0 -24
  17. package/src/live/discovery-closure-walk.ts +0 -318
  18. package/src/live/kernel-convergence-support.ts +0 -122
  19. package/src/live/seed.ts +0 -37
  20. package/src/live/support.ts +0 -82
  21. package/src/node/client.ts +0 -233
  22. package/src/node/connection-controller.ts +0 -469
  23. package/src/node/daemon-entry.ts +0 -57
  24. package/src/node/daemon.ts +0 -629
  25. package/src/node/index.ts +0 -110
  26. package/src/node/live-delta.ts +0 -229
  27. package/src/node/observability.ts +0 -481
  28. package/src/node/paths.ts +0 -83
  29. package/src/node/player-run-observer.ts +0 -122
  30. package/src/node/protocol.ts +0 -200
  31. package/src/node/spawn.ts +0 -225
  32. package/src/node/world-events.ts +0 -270
  33. package/src/player-tools/delta-tracker.ts +0 -1
  34. package/src/player-tools/index.ts +0 -10
  35. package/src/player-tools/node-adapter.ts +0 -9
  36. package/src/player-tools/observation.ts +0 -1
  37. package/src/player-tools/player-host.ts +0 -92
  38. package/src/player-tools/push-events.ts +0 -1
  39. package/src/player-tools/query-protocol.ts +0 -1
  40. package/src/player-tools/refusal-prose.ts +0 -1
  41. package/src/player-tools/resolution.ts +0 -1
  42. package/src/player-tools/tool-registry.ts +0 -1
  43. package/src/player-tools/tools.ts +0 -42
  44. package/src/player-tools/world-events.ts +0 -119
  45. package/src/session.ts +0 -604
package/src/session.ts DELETED
@@ -1,604 +0,0 @@
1
- // Isomorphic session lifecycle: resolve -> connect -> bind identity/actor ->
2
- // subscribe-on-connect -> return a handle. This is the ONE place that
3
- // sequence happens (#1990 decision 4) — the daemon, the Pi extension, and any
4
- // future browser host are meant to call `openSession` instead of re-spelling
5
- // `@spellkave/sdk`'s connect/createActorClient/subscribe call chain, which
6
- // today is hand-rolled at ~110 call sites (walkthrough scripts, world-explorer
7
- // probes, live twin tests, wanderer.ts).
8
- //
9
- // "Resolve" is deliberately NOT a step this module performs: profile/
10
- // credential resolution (`resolveConnection`, `resolveCredential`) needs
11
- // `node:fs`, so it lives one layer up, in the Node-only caller that builds a
12
- // `SessionBinding` + token before calling `openSession` (see
13
- // `@spellkave/session/node`'s `daemon.ts`). This module starts from an
14
- // already-resolved binding, exactly like `.pi/extensions/spellkave`'s
15
- // `connection-controller.ts` does at its own `connectSession` seam.
16
- //
17
- // Connection subscription is the SELECT-* table subscription built centrally
18
- // by `connect()` (`buildSubscribeSet`, `packages/spellkave-sdk/src/connection.ts`).
19
- // The actor-scoped factual context is materialised by the server lifecycle;
20
- // opening a session never invokes a cache reducer.
21
- //
22
- // CONTRACT NON-GOALS (#2001 — decided, not deferred; NON-GOAL 4 revised by
23
- // ADR-0103 D-3 / sk-dms.46). The package-adoption pass (#1996) listed four
24
- // shapes. (1) and (3) still stand, each with exactly one caller that keeps
25
- // its hand-rolled chain ON PURPOSE. (2) was retired when a second caller
26
- // appeared. (4) now allows one setup step on the session's own connection:
27
- //
28
- // 1. Caller-supplied actor resolution (body-swap): `binding.actorId` IS the
29
- // actor this session resolves. `wanderer.ts`'s `actorPrincipalId` branch
30
- // (resolve a different acting body than the connected actor) stays
31
- // hand-rolled in `@spellkave/agent-scenarios`.
32
- // 2. Custom `readerManifests` — RETIRED (sk-dms.1, srd-cc backlog #BL-9): a
33
- // SECOND caller appeared (`@spellkave/npc`'s NPC host, `src/host/host.ts`)
34
- // — per this doc's own "if a SECOND caller ever appears... extend
35
- // deliberately then" escape valve, `readerManifests` is now a first-class
36
- // `OpenSessionDeps` field, forwarded to `connect()`'s own
37
- // `buildSubscribeSet` verbatim. A per-seat manifest is exactly how a host
38
- // widens one NPC's live subscriptions without touching every other seat's
39
- // (or the registry-derived default) subscribe set. `undefined` (the
40
- // default) is unchanged behavior: `connect()` falls back to
41
- // `READER_SCOPED_TABLES` ∪ the registered-reader union, same as before
42
- // this field existed.
43
- // 3. Subscribe-less passive observer: always-subscribe, always-an-ActorClient
44
- // is the point of this seam (#1987) — a session that never subscribes is
45
- // not an `openSession` variant. A passive observer in a live test is a
46
- // scene hero connection that never gets an action client.
47
- // 4. `openSession` still resolves an already-controlled actor; a caller may
48
- // run ONE setup step on the session's own connection before resolution
49
- // (claim, bind, self-grant). Dual-identity test flows remain a
50
- // composition.
51
- //
52
- // If a SECOND caller ever appears for (1), that is the moment to revisit —
53
- // extend deliberately then, not speculatively now.
54
-
55
- import {
56
- type ActorClient,
57
- type ActorClientOptions,
58
- asEntityRef,
59
- connect,
60
- createActorClient,
61
- defaultReaderManifest,
62
- type ReaderManifest,
63
- type ResolvedActor,
64
- readManipulationContext,
65
- resolveActor,
66
- type SpellkaveSession,
67
- snapshot,
68
- snapshotDb,
69
- } from "@spellkave/sdk";
70
-
71
- import { AUTHORITY_TOOL_READER_MANIFEST, callerActingContexts } from "./acting-context";
72
- import type { SessionBinding } from "./binding.ts";
73
-
74
- /**
75
- * Shared default for `setupTimeoutMs` and `resolveTimeoutMs` (ADR-0103 D-3).
76
- * Unchanged by sk-jay0.6.38.25 — these two steps run against an already-open
77
- * connection and stay tight.
78
- */
79
- const DEFAULT_OPEN_SESSION_TIMEOUT_MS = 4_000;
80
-
81
- /**
82
- * Recommended bound for `readyTimeoutMs`/`factualContextTimeoutMs`
83
- * (sk-jay0.6.38.25, made OPT-IN by the #3477 RUM-lane review). Neither field
84
- * is applied automatically any more: `undefined` (the default) leaves
85
- * `session.ready`/factual-context readiness unbounded, the behavior every
86
- * caller had before sk-jay0.6.38.25 first shipped a blanket 30s default that
87
- * silently applied to every `openSession` caller, including the Pi/MCP
88
- * session daemon, npc-brains' drive loop, `orient-adventure`, and the NPC
89
- * seat — none of which asked for a bound, and a cold or throttled world
90
- * (e.g. right after a roll plus world re-load) would have turned their
91
- * previously-patient awaits into a hard startup failure.
92
- *
93
- * Play (`apps/play/src/lib/play-session.ts`) is the one caller that opts in,
94
- * passing this constant explicitly for both fields. The #3464 headless/hosted
95
- * repros measured a *healthy* connect completing in under 2s, but a live
96
- * `play.spellkave.com` run during the original review measured ~10s
97
- * wall-clock end to end, and `openSession`'s other caller (`@spellkave/npc`'s
98
- * host) cold-connects under CPU throttling with a known reconnect-storm
99
- * history (`npc-host-storm-cpu-and-reconnect`) — 30s gives ample headroom
100
- * above the ~10s observed worst case for a caller that wants a bound at all.
101
- */
102
- export const PLAY_CONNECT_PHASE_TIMEOUT_MS = 30_000;
103
-
104
- /**
105
- * Which `openSession` step is in flight or failed. Attached to every error
106
- * this function throws after `connect()` returns (sk-jay0.6.38.25), so a
107
- * caller (or its telemetry) can tell "the WS never opened" apart from "the
108
- * WS opened but the affordance-cache subscribe never replied" without
109
- * parsing error text.
110
- */
111
- export type SessionPhase = "ready" | "setup" | "resolve_actor" | "factual_context";
112
-
113
- /**
114
- * Thrown when a bounded `openSession` phase does not complete in time. The
115
- * message stays the same shape prior callers already match on
116
- * (`"<label> timed out after <ms>ms"`); `phase`/`timeoutMs` are additive.
117
- */
118
- export class OpenSessionTimeoutError extends Error {
119
- readonly phase: SessionPhase;
120
- readonly timeoutMs: number;
121
- constructor(phase: SessionPhase, timeoutMs: number, message: string) {
122
- super(message);
123
- this.name = "OpenSessionTimeoutError";
124
- this.phase = phase;
125
- this.timeoutMs = timeoutMs;
126
- }
127
- }
128
-
129
- /** Tags any thrown `Error` with the `openSession` phase it failed in, without
130
- * altering its message — callers that already assert on error text (e.g. the
131
- * unchanged "not found in live actor_spatial_location" message) keep passing. */
132
- function withPhase(err: unknown, phase: SessionPhase): unknown {
133
- if (err instanceof Error) (err as Error & { phase?: SessionPhase }).phase = phase;
134
- return err;
135
- }
136
-
137
- export interface OpenSessionDeps {
138
- /** Auth token for the connection. `undefined` connects anonymously. */
139
- token?: string;
140
- /** Optional JSONL diagnostic sink, forwarded to `connect()`. */
141
- onDiagnostic?: (line: object) => void;
142
- /** Optional transport error hook, forwarded to `connect()`. */
143
- onError?: (err: Error) => void;
144
- /** Optional disconnect hook, forwarded to `connect()`. */
145
- onDisconnect?: (err: Error | undefined) => void;
146
- /** Optional cache-mutation hook, forwarded to `connect()`. Receives the
147
- * moved table name (or `__applied`); nullary listeners remain valid. */
148
- onUpdate?: (table?: string) => void;
149
- /** Extra `ActorClient` options (e.g. custom timeouts); `successOnProvenance` is always set. */
150
- actorClientOptions?: ActorClientOptions;
151
- /** Optional reader profile narrowing/widening this session's live subscribe
152
- * set, forwarded to `connect()`'s own `readerManifests` (`buildSubscribeSet`)
153
- * verbatim. `undefined` (the default) is unchanged behavior — `connect()`
154
- * falls back to its own registry-derived default. See this module's
155
- * CONTRACT NON-GOALS comment (item 2) for why this field exists now: a
156
- * second caller (`@spellkave/npc`'s NPC host) needs a per-seat widened
157
- * subscription, the same shape a `ReaderManifest[]` already describes. */
158
- readerManifests?: readonly ReaderManifest[];
159
- /** Opt in to public role catalogs and caller-redacting bindings for authority tools. */
160
- authorityTools?: boolean;
161
- /**
162
- * Runs on the session's OWN connection after `session.ready` and BEFORE
163
- * actor resolution (ADR-0103 D-3 / sk-dms.46). Any throw or timeout
164
- * closes the connection and rethrows — no partially-open state.
165
- */
166
- setup?: (session: SpellkaveSession) => Promise<void>;
167
- /**
168
- * Bound for `setup`. Defaults to the same default as `resolveTimeoutMs`
169
- * (`DEFAULT_OPEN_SESSION_TIMEOUT_MS`).
170
- */
171
- setupTimeoutMs?: number;
172
- /**
173
- * Bound for the check-then-wait `resolveActor` path. The common case
174
- * (controlled-actor row already present at `ready`/`setup`) pays zero
175
- * extra latency. Default `DEFAULT_OPEN_SESSION_TIMEOUT_MS`.
176
- */
177
- resolveTimeoutMs?: number;
178
- /**
179
- * Bound for `await session.ready` (sk-jay0.6.38.25 — added to investigate
180
- * the #3464 "Connecting to SpacetimeDB WS…" stall). **OPT-IN** (#3477
181
- * RUM-lane review): `undefined` (the default) leaves this await unbounded,
182
- * matching every caller's behavior before sk-jay0.6.38.25. Play passes
183
- * `PLAY_CONNECT_PHASE_TIMEOUT_MS` (30s) explicitly; the Pi/MCP session
184
- * daemon, npc-brains' drive loop, `orient-adventure`, and the NPC seat do
185
- * not set this and keep waiting indefinitely, same as before #3477.
186
- */
187
- readyTimeoutMs?: number;
188
- /**
189
- * Reserved opt-in bound for observing the server-materialised factual
190
- * context. The current lifecycle emits this phase after actor resolution;
191
- * callers that need an action context read it through the SDK reader.
192
- */
193
- factualContextTimeoutMs?: number;
194
- /**
195
- * Runs after each phase below completes successfully, in order: `ready`,
196
- * `setup` (only if `deps.setup` is set), `resolve_actor`,
197
- * `factual_context`. `elapsedMs` covers only that phase. A host uses this
198
- * to observe connect progress (e.g. mark "connected" once
199
- * `factual_context` fires) without console-logging every phase itself.
200
- * Never called on failure — the thrown error's `.phase` covers that.
201
- */
202
- onPhase?(phase: SessionPhase, elapsedMs: number): void;
203
- }
204
-
205
- /**
206
- * A live, subscribed session bound to one binding. `close()` is idempotent —
207
- * a caller wiring shutdown from multiple triggers (idle timeout, explicit
208
- * `shutdown` op, transport disconnect) never has to guard against a double
209
- * `disconnect()`.
210
- */
211
- export interface LiveSession {
212
- readonly binding: SessionBinding;
213
- readonly session: SpellkaveSession;
214
- /** Resolved body entity id from `resolveActor`. Named `actorId` because hosts (`@spellkave/npc` seats, daemon wiring) consume this field; renaming would leak. */
215
- readonly actorId: string;
216
- readonly actorClient: ActorClient;
217
- /**
218
- * Replace this connection's reader set without reconnecting or re-claiming
219
- * the actor. The next set overlaps the old one until its snapshot applies.
220
- * Callers own the semantic transition: this API does not decide whether an
221
- * NPC is safe to make passive.
222
- */
223
- replaceReaderManifests(manifests: readonly ReaderManifest[]): Promise<void>;
224
- /**
225
- * T25: register a listener for the same underlying cache-mutation signal
226
- * the constructor-time `deps.onUpdate` callback already receives. Returns
227
- * an unsubscribe function. Both fire on every update — this is additive,
228
- * not a replacement for the constructor callback.
229
- *
230
- * Exists because a consumer that builds something OVER an already-open
231
- * `LiveSession` (the NPC seat's `"async"` mode being the first, `@spellkave/npc`'s
232
- * `supervisor.ts`) cannot supply its listener at `openSession()` call time —
233
- * the thing that needs to react to updates isn't constructed yet. Before
234
- * this, every such host reproduced a mutable-closure workaround (`let
235
- * notify: (() => void) | undefined` filled in after the fact); this
236
- * registry makes that indirection unnecessary — wire in natural order
237
- * instead: `openSession()` → build the consumer → `live.onUpdate((table) =>
238
- * consumer.notify(table))`. Each event carries the single moved table
239
- * (or `__applied`); listeners that ignore the argument stay valid.
240
- */
241
- onUpdate(listener: (table?: string) => void): () => void;
242
- /**
243
- * Monotonic cache-mutation revision. Incremented inside the same
244
- * constructor-time `onUpdate` fan-out registered listeners already
245
- * receive. Starts at 0 (no mutations observed yet). An NPC seat uses
246
- * this to skip `perceive()` when nothing in the subscribed cache has
247
- * changed (sk-dms.34).
248
- */
249
- revision(): number;
250
- close(): void;
251
- }
252
-
253
- /**
254
- * Thrown when an async operation on an `ActorClient` is aborted or attempted
255
- * after its owning `LiveSession` has closed (sk-jay0.6.15.56.16.12.3).
256
- */
257
- export class SessionClosedError extends Error {
258
- constructor(message = "Session is closed") {
259
- super(message);
260
- this.name = "SessionClosedError";
261
- }
262
- }
263
-
264
- /**
265
- * Open a session for `binding`: connect, await `ready`, run optional `setup`
266
- * on this connection, validate the actor is directly controlled (bounded
267
- * wait on the cache-mutation fan-out if the row is not yet present), build
268
- * an `ActorClient`, and wait for its actor-scoped factual context before
269
- * returning.
270
- * Rejects (and disconnects) if any step fails — there is no partially-open
271
- * state a caller could observe.
272
- */
273
- export async function openSession(
274
- binding: SessionBinding,
275
- deps: OpenSessionDeps = {},
276
- ): Promise<LiveSession> {
277
- const listeners = new Set<(table?: string) => void>();
278
- let cacheRevision = 0;
279
- function onUpdate(listener: (table?: string) => void): () => void {
280
- listeners.add(listener);
281
- return () => listeners.delete(listener);
282
- }
283
- function revision(): number {
284
- return cacheRevision;
285
- }
286
-
287
- const session = await connect(
288
- {
289
- url: binding.url,
290
- db: binding.db,
291
- token: deps.token,
292
- connectedActorId: binding.actorId,
293
- ...(deps.onDiagnostic === undefined ? {} : { onDiagnostic: deps.onDiagnostic }),
294
- ...(deps.authorityTools
295
- ? {
296
- readerManifests: [
297
- ...(deps.readerManifests ?? [defaultReaderManifest()]),
298
- AUTHORITY_TOOL_READER_MANIFEST,
299
- ],
300
- }
301
- : deps.readerManifests === undefined
302
- ? {}
303
- : { readerManifests: deps.readerManifests }),
304
- },
305
- {
306
- onError: deps.onError ?? (() => {}),
307
- onDisconnect: deps.onDisconnect ?? (() => {}),
308
- onUpdate: (table) => {
309
- cacheRevision += 1;
310
- deps.onUpdate?.(table);
311
- for (const listener of listeners) listener(table);
312
- },
313
- },
314
- );
315
-
316
- let closed = false;
317
- const inFlightRejections = new Set<(err: Error) => void>();
318
-
319
- const abortWaits = new Set<(err: Error) => void>();
320
-
321
- function close(): void {
322
- if (closed) return;
323
- closed = true;
324
- session.disconnect();
325
- const closeErr = new SessionClosedError("Session is closed");
326
- for (const reject of inFlightRejections) {
327
- reject(closeErr);
328
- }
329
- inFlightRejections.clear();
330
- for (const reject of abortWaits) {
331
- reject(closeErr);
332
- }
333
- abortWaits.clear();
334
- }
335
-
336
- function wrapActorClient(raw: ActorClient): ActorClient {
337
- return new Proxy(raw, {
338
- get(target, prop, receiver) {
339
- const value = Reflect.get(target, prop, receiver);
340
- if (typeof value !== "function") {
341
- return value;
342
- }
343
- if (prop === "withDriverToken") {
344
- return (...args: unknown[]) => wrapActorClient(Reflect.apply(value, target, args));
345
- }
346
- return function (this: unknown, ...args: unknown[]) {
347
- const thisArg = this === receiver ? target : this;
348
- const result = Reflect.apply(value, thisArg, args);
349
- if (
350
- result !== null &&
351
- typeof result === "object" &&
352
- typeof (result as PromiseLike<unknown>).then === "function"
353
- ) {
354
- if (closed) {
355
- return Promise.reject(new SessionClosedError("Session is closed"));
356
- }
357
- return new Promise((resolve, reject) => {
358
- const rejectInFlight = (err: Error) => {
359
- reject(err);
360
- };
361
- inFlightRejections.add(rejectInFlight);
362
- Promise.resolve(result).then(
363
- (val) => {
364
- inFlightRejections.delete(rejectInFlight);
365
- resolve(val);
366
- },
367
- (err) => {
368
- inFlightRejections.delete(rejectInFlight);
369
- reject(err);
370
- },
371
- );
372
- });
373
- }
374
- return result;
375
- };
376
- },
377
- });
378
- }
379
-
380
- const resolveTimeoutMs = deps.resolveTimeoutMs ?? DEFAULT_OPEN_SESSION_TIMEOUT_MS;
381
- const setupTimeoutMs = deps.setupTimeoutMs ?? DEFAULT_OPEN_SESSION_TIMEOUT_MS;
382
- // Opt-in (#3477 RUM-lane review): `undefined` stays unbounded — see the
383
- // two fields' own JSDoc above and `PLAY_CONNECT_PHASE_TIMEOUT_MS`.
384
- const readyTimeoutMs = deps.readyTimeoutMs;
385
- const factualContextTimeoutMs = deps.factualContextTimeoutMs;
386
-
387
- try {
388
- let phaseStartedAt = Date.now();
389
- await awaitWithTimeout(
390
- session.ready,
391
- readyTimeoutMs,
392
- `openSession: session.ready timed out after ${readyTimeoutMs}ms`,
393
- "ready",
394
- );
395
- deps.onPhase?.("ready", Date.now() - phaseStartedAt);
396
-
397
- if (deps.setup !== undefined) {
398
- phaseStartedAt = Date.now();
399
- await awaitWithTimeout(
400
- deps.setup(session),
401
- setupTimeoutMs,
402
- `OpenSessionDeps.setup timed out after ${setupTimeoutMs}ms`,
403
- "setup",
404
- );
405
- deps.onPhase?.("setup", Date.now() - phaseStartedAt);
406
- }
407
- phaseStartedAt = Date.now();
408
- const presence = callerActingContexts(session).find(
409
- (choice) => choice.kind === "presence" && choice.bodyId === binding.actorId,
410
- );
411
- const resolved =
412
- presence === undefined
413
- ? await resolveControlledActor(binding.actorId, session, listeners, resolveTimeoutMs)
414
- : { body_entity_id: presence.bodyId };
415
- deps.onPhase?.("resolve_actor", Date.now() - phaseStartedAt);
416
- const rawActorClient = createActorClient(session, resolved.body_entity_id, {
417
- // Generic session hosts (the daemon, the Pi extension) cannot supply
418
- // a world-state predicate for every authored action; the server's
419
- // provenance is authoritative — same rationale as
420
- // `connection-controller.ts`'s `createActorClient` wiring.
421
- successOnProvenance: true,
422
- ...deps.actorClientOptions,
423
- });
424
- const actorClient = wrapActorClient(rawActorClient);
425
- phaseStartedAt = Date.now();
426
- if (presence === undefined)
427
- await awaitFactualContext(
428
- resolved.body_entity_id,
429
- session,
430
- listeners,
431
- factualContextTimeoutMs,
432
- abortWaits,
433
- );
434
- deps.onPhase?.("factual_context", Date.now() - phaseStartedAt);
435
- return {
436
- binding,
437
- session,
438
- actorId: resolved.body_entity_id,
439
- actorClient,
440
- replaceReaderManifests: (manifests) => session.replaceReaderManifests(manifests),
441
- onUpdate,
442
- revision,
443
- close,
444
- };
445
- } catch (err) {
446
- close();
447
- throw err;
448
- }
449
- }
450
-
451
- /**
452
- * The context header is the server's atomic readiness witness: `ready` means
453
- * that the subscribed target/action/participant fact generation is coherent.
454
- * As with actor resolution, check first to avoid adding an event wait in the
455
- * warm case and only listen when the initial snapshot is still catching up.
456
- */
457
- function awaitFactualContext(
458
- actorId: string,
459
- session: SpellkaveSession,
460
- listeners: Set<(table?: string) => void>,
461
- timeoutMs: number | undefined,
462
- abortWaits: Set<(err: Error) => void>,
463
- ): Promise<void> {
464
- const ready = (): boolean =>
465
- readManipulationContext(snapshotDb(session), asEntityRef(actorId)).status === "ready";
466
- if (ready()) return Promise.resolve();
467
-
468
- return new Promise((resolve, reject) => {
469
- let settled = false;
470
- let timer: ReturnType<typeof setTimeout> | undefined;
471
- const finish = (fn: () => void): void => {
472
- if (settled) return;
473
- settled = true;
474
- if (timer !== undefined) clearTimeout(timer);
475
- listeners.delete(onUpdate);
476
- abortWaits.delete(onAbort);
477
- fn();
478
- };
479
- const attempt = (): void => {
480
- if (ready()) finish(resolve);
481
- };
482
- const onUpdate = (): void => attempt();
483
- const onAbort = (err: Error): void => finish(() => reject(err));
484
- listeners.add(onUpdate);
485
- abortWaits.add(onAbort);
486
- if (timeoutMs !== undefined) {
487
- timer = setTimeout(() => {
488
- if (ready()) finish(resolve);
489
- else {
490
- finish(() =>
491
- reject(
492
- new OpenSessionTimeoutError(
493
- "factual_context",
494
- timeoutMs,
495
- `openSession: factual context timed out after ${timeoutMs}ms`,
496
- ),
497
- ),
498
- );
499
- }
500
- }, timeoutMs);
501
- }
502
- attempt();
503
- });
504
- }
505
-
506
- function isMissingControlledActor(err: unknown): boolean {
507
- return err instanceof Error && err.message.includes("not found in live actor_spatial_location");
508
- }
509
-
510
- function tryResolveActor(actorId: string, session: SpellkaveSession): ResolvedActor {
511
- return resolveActor(actorId, snapshot(session.conn).controlledActors);
512
- }
513
-
514
- /**
515
- * Check-then-wait (ADR-0103 D-3): run `resolveActor` once immediately. Only
516
- * if the controlled-actor row is absent do we subscribe to the same
517
- * cache-mutation fan-out `LiveSession.onUpdate` uses and re-check on each
518
- * event until `timeoutMs`. The common case pays zero extra latency and zero
519
- * extra event round trips. Deadline failure rethrows `resolveActor`'s own
520
- * error (unchanged text).
521
- */
522
- function resolveControlledActor(
523
- actorId: string,
524
- session: SpellkaveSession,
525
- listeners: Set<(table?: string) => void>,
526
- timeoutMs: number,
527
- ): Promise<ResolvedActor> {
528
- try {
529
- return Promise.resolve(tryResolveActor(actorId, session));
530
- } catch (err) {
531
- if (!isMissingControlledActor(err)) return Promise.reject(withPhase(err, "resolve_actor"));
532
- }
533
-
534
- return new Promise((resolve, reject) => {
535
- let settled = false;
536
- const finish = (fn: () => void): void => {
537
- if (settled) return;
538
- settled = true;
539
- clearTimeout(timer);
540
- listeners.delete(onCacheUpdate);
541
- fn();
542
- };
543
- const attempt = (): boolean => {
544
- try {
545
- const resolved = tryResolveActor(actorId, session);
546
- finish(() => resolve(resolved));
547
- return true;
548
- } catch (err) {
549
- if (!isMissingControlledActor(err)) {
550
- finish(() => reject(withPhase(err, "resolve_actor")));
551
- return true;
552
- }
553
- return false;
554
- }
555
- };
556
- const onCacheUpdate = (): void => {
557
- attempt();
558
- };
559
- listeners.add(onCacheUpdate);
560
- const timer = setTimeout(() => {
561
- try {
562
- const resolved = tryResolveActor(actorId, session);
563
- finish(() => resolve(resolved));
564
- } catch (err) {
565
- finish(() => reject(withPhase(err, "resolve_actor")));
566
- }
567
- }, timeoutMs);
568
- attempt();
569
- });
570
- }
571
-
572
- /** `timeoutMs === undefined` runs `work` with no bound at all (no timer is
573
- * even created) — the compat default for `readyTimeoutMs`/
574
- * `factualContextTimeoutMs` (#3477 RUM-lane review). */
575
- async function awaitWithTimeout<T>(
576
- work: Promise<T>,
577
- timeoutMs: number | undefined,
578
- message: string,
579
- phase: SessionPhase,
580
- ): Promise<T> {
581
- if (timeoutMs === undefined) {
582
- try {
583
- return await work;
584
- } catch (err) {
585
- throw withPhase(err, phase);
586
- }
587
- }
588
- let timer: ReturnType<typeof setTimeout> | undefined;
589
- try {
590
- return await Promise.race([
591
- work,
592
- new Promise<T>((_, reject) => {
593
- timer = setTimeout(
594
- () => reject(new OpenSessionTimeoutError(phase, timeoutMs, message)),
595
- timeoutMs,
596
- );
597
- }),
598
- ]);
599
- } catch (err) {
600
- throw withPhase(err, phase);
601
- } finally {
602
- if (timer !== undefined) clearTimeout(timer);
603
- }
604
- }