@spellkave/sdk 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.
- package/README.md +2 -155
- package/package.json +4 -63
- package/LICENSE +0 -89
- package/src/binding_rows.ts +0 -186
- package/src/connection.ts +0 -964
- package/src/core/actor.ts +0 -62
- package/src/core/actor_control.ts +0 -193
- package/src/core/actor_control_query_methods.ts +0 -101
- package/src/core/actor_control_reaction_methods.ts +0 -79
- package/src/core/actor_control_sense_methods.ts +0 -81
- package/src/core/actor_control_source.ts +0 -57
- package/src/core/actor_session_methods.ts +0 -226
- package/src/core/binding_drift.ts +0 -301
- package/src/core/credential.ts +0 -259
- package/src/core/driver_control.ts +0 -54
- package/src/core/effective_environment_state.ts +0 -71
- package/src/core/factored_manipulation_attempt.ts +0 -158
- package/src/core/ids.ts +0 -60
- package/src/core/interaction/canonical.ts +0 -15
- package/src/core/interaction/fingerprint.ts +0 -118
- package/src/core/interaction/index.ts +0 -31
- package/src/core/interaction/intent.ts +0 -284
- package/src/core/interaction/outcome.ts +0 -67
- package/src/core/interaction/rejection_ledger.ts +0 -108
- package/src/core/kernel_contract.generated.ts +0 -10
- package/src/core/log.ts +0 -23
- package/src/core/movement.ts +0 -111
- package/src/core/node-io.ts +0 -208
- package/src/core/paths.ts +0 -220
- package/src/core/profile.ts +0 -270
- package/src/core/profiles.ts +0 -9
- package/src/core/provenance_buffer.ts +0 -102
- package/src/core/readers/_helpers.ts +0 -273
- package/src/core/readers/action_description.ts +0 -17
- package/src/core/readers/action_economy_events.ts +0 -149
- package/src/core/readers/actor_body_swaps.ts +0 -62
- package/src/core/readers/actor_snapshot.ts +0 -197
- package/src/core/readers/actor_states.ts +0 -163
- package/src/core/readers/actors_and_bodies.ts +0 -179
- package/src/core/readers/affordance_cue.ts +0 -59
- package/src/core/readers/affordance_defaults.ts +0 -158
- package/src/core/readers/affordance_group_membership.ts +0 -67
- package/src/core/readers/affordance_input.ts +0 -129
- package/src/core/readers/affordance_reference.ts +0 -41
- package/src/core/readers/apply_consequences.ts +0 -54
- package/src/core/readers/audience_trace_presentation.ts +0 -62
- package/src/core/readers/bounded_collection.ts +0 -29
- package/src/core/readers/bundle_definitions.ts +0 -74
- package/src/core/readers/bundle_entities.ts +0 -62
- package/src/core/readers/co_location.ts +0 -71
- package/src/core/readers/combat_session.ts +0 -124
- package/src/core/readers/combat_session_active.ts +0 -44
- package/src/core/readers/combat_session_feedback.ts +0 -37
- package/src/core/readers/combat_session_grid.ts +0 -117
- package/src/core/readers/combat_session_roster.ts +0 -98
- package/src/core/readers/combat_session_types.ts +0 -51
- package/src/core/readers/condition_deltas.ts +0 -53
- package/src/core/readers/container_contents.ts +0 -92
- package/src/core/readers/dialogue_guide.ts +0 -99
- package/src/core/readers/dialogue_prompt_presentation.ts +0 -90
- package/src/core/readers/driver_control.ts +0 -64
- package/src/core/readers/entity_art.ts +0 -219
- package/src/core/readers/entity_containment.ts +0 -119
- package/src/core/readers/equipment.ts +0 -99
- package/src/core/readers/intervention_windows.ts +0 -136
- package/src/core/readers/inventory_query.ts +0 -145
- package/src/core/readers/item_detail.ts +0 -198
- package/src/core/readers/location_snapshot.ts +0 -216
- package/src/core/readers/manifest_apply_provenance.ts +0 -32
- package/src/core/readers/manifest_export.ts +0 -81
- package/src/core/readers/manipulation_context.ts +0 -475
- package/src/core/readers/map_layers.ts +0 -49
- package/src/core/readers/metadata_rows.ts +0 -56
- package/src/core/readers/object_state.ts +0 -124
- package/src/core/readers/observer_knowledge.ts +0 -41
- package/src/core/readers/observer_place_knowledge.ts +0 -37
- package/src/core/readers/observer_trace_knowledge.ts +0 -45
- package/src/core/readers/outcome_template.ts +0 -41
- package/src/core/readers/place_topology.ts +0 -109
- package/src/core/readers/reaction_options.ts +0 -156
- package/src/core/readers/resource_deltas.ts +0 -47
- package/src/core/readers/scene.ts +0 -275
- package/src/core/readers/seats.ts +0 -33
- package/src/core/readers/self.ts +0 -245
- package/src/core/readers/self_capabilities.ts +0 -159
- package/src/core/readers/self_economy.ts +0 -101
- package/src/core/readers/self_economy_budget.ts +0 -93
- package/src/core/readers/self_evaluations.ts +0 -128
- package/src/core/readers/self_identity.ts +0 -104
- package/src/core/readers/sense_context.ts +0 -112
- package/src/core/readers/session.ts +0 -207
- package/src/core/readers/session_detail.ts +0 -211
- package/src/core/readers/session_status.ts +0 -68
- package/src/core/readers/spatial_environment_state.ts +0 -74
- package/src/core/readers/spatial_niche_attachments.ts +0 -28
- package/src/core/readers/substrate_definitions.ts +0 -27
- package/src/core/readers/suggest_next_action.ts +0 -72
- package/src/core/readers/surface_membership.ts +0 -78
- package/src/core/readers/tag_reads.ts +0 -54
- package/src/core/readers/trace_query.ts +0 -120
- package/src/core/readers/trace_response.ts +0 -80
- package/src/core/readers/traces.ts +0 -124
- package/src/core/readers/travel_session.ts +0 -88
- package/src/core/readers/turn_state.ts +0 -34
- package/src/core/readers/world_events.ts +0 -43
- package/src/core/readers/world_status.ts +0 -63
- package/src/core/reducers/manipulation_args.ts +0 -239
- package/src/core/reducers/manipulation_receipt.ts +0 -66
- package/src/core/reducers/r_actor_wake_up.ts +0 -32
- package/src/core/reducers/r_inscribe_trace.ts +0 -109
- package/src/core/reducers/r_manipulate.ts +0 -163
- package/src/core/reducers/r_move.ts +0 -155
- package/src/core/reducers/r_react.ts +0 -143
- package/src/core/reducers/r_release_claim.ts +0 -81
- package/src/core/reducers/r_sense.ts +0 -84
- package/src/core/reducers/r_session_close.ts +0 -130
- package/src/core/reducers/r_session_move.ts +0 -116
- package/src/core/reducers/r_session_open.ts +0 -91
- package/src/core/reducers/session_lookup.ts +0 -64
- package/src/core/reducers/tick.ts +0 -65
- package/src/core/reducers/trace_lookup.ts +0 -29
- package/src/core/reducers/transport.ts +0 -84
- package/src/core/resolve.ts +0 -228
- package/src/core/shape_telemetry.ts +0 -146
- package/src/core/snapshot_rows.ts +0 -109
- package/src/core/tick_cadence.ts +0 -61
- package/src/core/types.ts +0 -501
- package/src/core/watch_provenance.ts +0 -113
- package/src/core/world-contract/classify.ts +0 -38
- package/src/core/world-contract/index.ts +0 -12
- package/src/core/world-contract/normalise.ts +0 -574
- package/src/core/world-contract/runtime.ts +0 -144
- package/src/core/world-contract/served.ts +0 -173
- package/src/core/world-contract/strict-reducers.ts +0 -14
- package/src/core/world-contract/typetext.ts +0 -94
- package/src/core/world_time.ts +0 -22
- package/src/index.ts +0 -262
- package/src/manifest-apply.ts +0 -497
- package/src/provenance.ts +0 -568
- package/src/reader-manifest.ts +0 -338
- package/src/readers.ts +0 -392
- package/src/replay.ts +0 -515
- package/src/watch-buffer.ts +0 -438
- package/src/world-events/builder.ts +0 -1042
package/src/connection.ts
DELETED
|
@@ -1,964 +0,0 @@
|
|
|
1
|
-
import { STRICT_REDUCERS } from "./core/world-contract/strict-reducers.ts";
|
|
2
|
-
// SpacetimeDB connection lifecycle for the pi extension.
|
|
3
|
-
//
|
|
4
|
-
// Wraps the generated TypeScript bindings in a small typed seam so the rest
|
|
5
|
-
// of the extension code can subscribe, snapshot, and disconnect without
|
|
6
|
-
// re-spelling the SDK's builder chain at every callsite. Stays well inside
|
|
7
|
-
// ADR-0009 D-2 wrapper discipline by limiting itself to:
|
|
8
|
-
// * connection lifecycle (build / disconnect)
|
|
9
|
-
// * the canonical first-slice subscription set
|
|
10
|
-
// * a `snapshot()` that copies live tables into the actor/movement reader
|
|
11
|
-
// shapes consumed by `src/core/{actor,movement}.ts`
|
|
12
|
-
//
|
|
13
|
-
// Reducer invocation lives in `tool.ts` next to the LLM tool definition so
|
|
14
|
-
// this file stays read-side only.
|
|
15
|
-
|
|
16
|
-
// Generated bindings ship as the workspace `@spellkave/bindings` package
|
|
17
|
-
// (source-of-truth produced by `just generate`); pi extension consumes the
|
|
18
|
-
// barrel export rather than reaching into the file layout.
|
|
19
|
-
import { DbConnection, type SubscriptionHandle } from "@spellkave/bindings";
|
|
20
|
-
// `@spellkave/world-events` is zero-dep and browser-gated (see the package's
|
|
21
|
-
// own header) — this is the one new edge B1/B2 add to the SDK's package
|
|
22
|
-
// graph, per `ledger/designs/session-owns-the-world-event-cursor.md`.
|
|
23
|
-
import { createWorldEventFanout, type WorldEventFanout } from "@spellkave/world-events";
|
|
24
|
-
|
|
25
|
-
import type {
|
|
26
|
-
ActorSpatialLocationRow,
|
|
27
|
-
EvaluationProvenanceRow,
|
|
28
|
-
PlaceEdgeRow,
|
|
29
|
-
PlaceNodeRow,
|
|
30
|
-
WorldTimeRow,
|
|
31
|
-
} from "./binding_rows";
|
|
32
|
-
import type { LiveActorReader } from "./core/actor";
|
|
33
|
-
import {
|
|
34
|
-
BindingDriftError,
|
|
35
|
-
BindingShapeError,
|
|
36
|
-
compareServedShape,
|
|
37
|
-
fetchServerSchema,
|
|
38
|
-
} from "./core/binding_drift";
|
|
39
|
-
import { asEntityId, type EntityId } from "./core/ids";
|
|
40
|
-
import { KERNEL_CONTRACT, KERNEL_CONTRACT_EPOCH } from "./core/kernel_contract.generated";
|
|
41
|
-
import type { LiveMovementReader } from "./core/movement";
|
|
42
|
-
import { type ProvenanceBufferConfig, ProvenanceRingBuffer } from "./core/provenance_buffer";
|
|
43
|
-
import {
|
|
44
|
-
CONTRACT_SHAPE_MISMATCH,
|
|
45
|
-
exportShapeMismatches,
|
|
46
|
-
shapeMismatchEvents,
|
|
47
|
-
shapeMismatchFields,
|
|
48
|
-
shapeTelemetryDriver,
|
|
49
|
-
unreportedShapeMismatches,
|
|
50
|
-
} from "./core/shape_telemetry";
|
|
51
|
-
import { TickIntervalEstimator } from "./core/tick_cadence";
|
|
52
|
-
import { MANIFEST_APPLY_WAIT_TABLES } from "./manifest-apply";
|
|
53
|
-
import {
|
|
54
|
-
CONNECTION_BASELINE,
|
|
55
|
-
getRegisteredReaderTables,
|
|
56
|
-
READER_SCOPED_TABLES,
|
|
57
|
-
type ReaderManifest,
|
|
58
|
-
STRICT_TABLES,
|
|
59
|
-
} from "./reader-manifest";
|
|
60
|
-
import type { SnapshotDb } from "./replay";
|
|
61
|
-
import { createWorldEventBuilder } from "./world-events/builder.ts";
|
|
62
|
-
|
|
63
|
-
export {
|
|
64
|
-
CONNECTION_BASELINE,
|
|
65
|
-
defaultReaderManifest,
|
|
66
|
-
findUndeclaredBaselineTables,
|
|
67
|
-
getRegisteredReaderTables,
|
|
68
|
-
READER_SCOPED_TABLES,
|
|
69
|
-
type ReaderManifest,
|
|
70
|
-
type RequiredTables,
|
|
71
|
-
registerReaderManifest,
|
|
72
|
-
STRICT_TABLES,
|
|
73
|
-
SUBSCRIBED_TABLES,
|
|
74
|
-
type TableName,
|
|
75
|
-
} from "./reader-manifest";
|
|
76
|
-
export {
|
|
77
|
-
captureSnapshotFrame,
|
|
78
|
-
type SnapshotCaptureFrame,
|
|
79
|
-
type SnapshotDb,
|
|
80
|
-
type SnapshotFixtureTables,
|
|
81
|
-
snapshotDbFromCaptureFrame,
|
|
82
|
-
snapshotDbFromFixture,
|
|
83
|
-
} from "./replay";
|
|
84
|
-
|
|
85
|
-
type PromiseWithResolversResult<T> = {
|
|
86
|
-
promise: Promise<T>;
|
|
87
|
-
resolve: (value: T | PromiseLike<T>) => void;
|
|
88
|
-
reject: (reason?: unknown) => void;
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
function ensurePromiseWithResolvers(): void {
|
|
92
|
-
const PromiseCtor = Promise as PromiseConstructor & {
|
|
93
|
-
withResolvers?: <T>() => PromiseWithResolversResult<T>;
|
|
94
|
-
};
|
|
95
|
-
if (typeof PromiseCtor.withResolvers === "function") return;
|
|
96
|
-
|
|
97
|
-
PromiseCtor.withResolvers = <T>() => {
|
|
98
|
-
let resolve!: (value: T | PromiseLike<T>) => void;
|
|
99
|
-
let reject!: (reason?: unknown) => void;
|
|
100
|
-
const promise = new Promise<T>((resolveFn, rejectFn) => {
|
|
101
|
-
resolve = resolveFn;
|
|
102
|
-
reject = rejectFn;
|
|
103
|
-
});
|
|
104
|
-
return { promise, resolve, reject };
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Raw evaluation_provenance, target_condition, object_state, world_event, entity_tag,
|
|
109
|
-
// arbitration context and autonomy jobs
|
|
110
|
-
// are private server state. Clients subscribe the per-caller visible_* views
|
|
111
|
-
// instead.
|
|
112
|
-
/**
|
|
113
|
-
* Raw world-state tables the publisher may subscribe (ADR-0150).
|
|
114
|
-
* Add a table here only with a live row, and only when no ADR makes that
|
|
115
|
-
* table's view the only client read. This set bypasses `buildSubscribeSet()`
|
|
116
|
-
* and its filter on purpose: private base names are stripped on the
|
|
117
|
-
* ordinary reader route.
|
|
118
|
-
*/
|
|
119
|
-
export const OWNER_SUBSCRIPTION_TABLES = [
|
|
120
|
-
"operator_manifest_authored_entity",
|
|
121
|
-
"entity_tag",
|
|
122
|
-
"autonomy_job",
|
|
123
|
-
"arbitration_request",
|
|
124
|
-
"arbitration_response",
|
|
125
|
-
"arbitration_rejection",
|
|
126
|
-
"arbitration_fallback",
|
|
127
|
-
"entity_containment",
|
|
128
|
-
"entity_location",
|
|
129
|
-
"object_state",
|
|
130
|
-
"capability",
|
|
131
|
-
"actor_identity",
|
|
132
|
-
"actor_spatial_location",
|
|
133
|
-
"entity_equipment_slot",
|
|
134
|
-
"target_condition",
|
|
135
|
-
] as const;
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Test-only probe. Not a `ConnectArgs` field and not part of the public
|
|
139
|
-
* connect contract. A live proof sets `appendBogusTable` so the owner
|
|
140
|
-
* subscription is refused at subscribe time.
|
|
141
|
-
*/
|
|
142
|
-
export const ownerSubscriptionTestProbe = { appendBogusTable: false };
|
|
143
|
-
|
|
144
|
-
export const FILTERED_SUBSCRIPTION_TABLES = [
|
|
145
|
-
"manifest_applyset",
|
|
146
|
-
"manifest_applyset_part",
|
|
147
|
-
"manifest_applyset_export_hash",
|
|
148
|
-
"manifest_authored_entity",
|
|
149
|
-
"entity_tag",
|
|
150
|
-
"autonomy_job",
|
|
151
|
-
"arbitration_request",
|
|
152
|
-
"arbitration_response",
|
|
153
|
-
"arbitration_rejection",
|
|
154
|
-
"arbitration_fallback",
|
|
155
|
-
"actor_identity",
|
|
156
|
-
"actor_driver_control",
|
|
157
|
-
"actor_control_transition",
|
|
158
|
-
"control_continuation",
|
|
159
|
-
"control_continuation_refusal",
|
|
160
|
-
"event_steering",
|
|
161
|
-
"evaluation_provenance",
|
|
162
|
-
"object_state",
|
|
163
|
-
"target_condition",
|
|
164
|
-
// sk-jay0.6.15.56.16.12.5.2.1: the turn singleton is private; a caller
|
|
165
|
-
// reads `visible_turn_state` (its own session's rotation only).
|
|
166
|
-
"turn_state",
|
|
167
|
-
"world_event",
|
|
168
|
-
] as const;
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* Compute the SELECT-* subscribe set: CONNECTION_BASELINE ∪ reader-union,
|
|
172
|
-
* minus any tables that use filtered subscriptions.
|
|
173
|
-
* Falls back to READER_SCOPED_TABLES when registry is empty so Phase 1
|
|
174
|
-
* behavior is preserved until Phase 2 readers register their manifests.
|
|
175
|
-
*/
|
|
176
|
-
export function buildSubscribeSet(manifests?: readonly ReaderManifest[]): string[] {
|
|
177
|
-
const readerTables =
|
|
178
|
-
manifests === undefined
|
|
179
|
-
? [...READER_SCOPED_TABLES, ...getRegisteredReaderTables()]
|
|
180
|
-
: manifests.flatMap((manifest) => manifest.requiredTables);
|
|
181
|
-
const optional = new Set<string>(OPTIONAL_SATELLITE_TABLES);
|
|
182
|
-
|
|
183
|
-
return Array.from(new Set([...CONNECTION_BASELINE, ...readerTables])).filter(
|
|
184
|
-
(t) => !(FILTERED_SUBSCRIPTION_TABLES as readonly string[]).includes(t) && !optional.has(t),
|
|
185
|
-
);
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Public catalog satellites a module may predate. Each is subscribed only when
|
|
190
|
-
* the live server surface lists it, so new bindings still connect to an older
|
|
191
|
-
* module. `session_turn_eligibility`: ADR-0143 D-5 (the live author target
|
|
192
|
-
* reconstructs `session_definitions.turn_eligibility_pred` from it).
|
|
193
|
-
*/
|
|
194
|
-
export const OPTIONAL_SATELLITE_TABLES = [
|
|
195
|
-
"condition_definition_description",
|
|
196
|
-
"session_turn_eligibility",
|
|
197
|
-
// ADR-0149: the export view. A module published before this change does
|
|
198
|
-
// not list it. Subscribing it unconditionally would fail that connect.
|
|
199
|
-
"visible_observed_container_content",
|
|
200
|
-
"visible_observed_container_coverage",
|
|
201
|
-
"visible_manifest_export_result",
|
|
202
|
-
"visible_clock_pacer",
|
|
203
|
-
"visible_event_pace_time",
|
|
204
|
-
"visible_manifest_apply_provenance",
|
|
205
|
-
"manipulation_contract",
|
|
206
|
-
] as const;
|
|
207
|
-
|
|
208
|
-
export function subscribeSetForSurface(
|
|
209
|
-
serverSurface: { tables: readonly string[] },
|
|
210
|
-
manifests?: readonly ReaderManifest[],
|
|
211
|
-
): string[] {
|
|
212
|
-
const optional = new Set<string>(OPTIONAL_SATELLITE_TABLES);
|
|
213
|
-
const tables = buildSubscribeSet(manifests).filter((table) => !optional.has(table));
|
|
214
|
-
for (const satellite of OPTIONAL_SATELLITE_TABLES) {
|
|
215
|
-
if (serverSurface.tables.includes(satellite) && !tables.includes(satellite)) {
|
|
216
|
-
tables.push(satellite);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
return tables;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
export interface ConnectArgs {
|
|
223
|
-
url: string;
|
|
224
|
-
db: string;
|
|
225
|
-
/** Auth token. `undefined` permits the host's SPELLKAVE_CONNECT_TOKEN
|
|
226
|
-
* default; `null` explicitly connects anonymously. */
|
|
227
|
-
token: string | null | undefined;
|
|
228
|
-
/** The in-world actor id bound to this session. Used for filtered provenance subscriptions. */
|
|
229
|
-
connectedActorId: string;
|
|
230
|
-
/** Optional JSONL diagnostic sink (D-C). Called with structured log lines.
|
|
231
|
-
* Defaults to `console.warn(JSON.stringify(line))` when omitted. */
|
|
232
|
-
onDiagnostic?: (line: object) => void;
|
|
233
|
-
/** Ring buffer size config (D3). Defaults: connectedCap=512, perSubjectCap=200. */
|
|
234
|
-
provenanceBufferSize?: Partial<ProvenanceBufferConfig>;
|
|
235
|
-
/** Optional reader profile for callers that only need a narrowed live-cache slice. */
|
|
236
|
-
readerManifests?: readonly ReaderManifest[];
|
|
237
|
-
/**
|
|
238
|
-
* When true, and only when this connection's identity is the module
|
|
239
|
-
* publisher, open a second subscription over `OWNER_SUBSCRIPTION_TABLES`
|
|
240
|
-
* after the reader subscription applies (ADR-0150). Default false. `sk`
|
|
241
|
-
* is the one production caller.
|
|
242
|
-
*/
|
|
243
|
-
ownerTables?: boolean;
|
|
244
|
-
/**
|
|
245
|
-
* Connect-time shape check mode (sk-jay0.7.389.3). `"strict"` (default:
|
|
246
|
-
* CI, tests, local dev): throw {@link BindingShapeError} when the served
|
|
247
|
-
* world module breaks a consumed row or reducer shape. `"warn"` (hosted
|
|
248
|
-
* apps and services opt in explicitly): connect anyway and emit one
|
|
249
|
-
* `contract_shape_mismatch` diagnostic per mismatch, plus the same event to
|
|
250
|
-
* OpenObserve when the host has `SPELLKAVE_AGENT_OBS_OTLP_ENDPOINT`. See
|
|
251
|
-
* {@link resolveShapeCheck} for the global and environment fallbacks.
|
|
252
|
-
*/
|
|
253
|
-
shapeCheck?: ShapeCheckMode;
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
export type ShapeCheckMode = "strict" | "warn";
|
|
257
|
-
|
|
258
|
-
/**
|
|
259
|
-
* The shape-check mode: the `shapeCheck` option; else `globalThis.SPELLKAVE_SHAPE_CHECK`
|
|
260
|
-
* (a browser app sets it at start-up from its build configuration, e.g. Play's
|
|
261
|
-
* `VITE_SPELLKAVE_SHAPE_CHECK`); else the `SPELLKAVE_SHAPE_CHECK` environment
|
|
262
|
-
* variable where a process env exists. Only the exact value `"warn"` relaxes
|
|
263
|
-
* it; anything else, absence included, is `"strict"`.
|
|
264
|
-
*/
|
|
265
|
-
export function resolveShapeCheck(option: ConnectArgs["shapeCheck"]): ShapeCheckMode {
|
|
266
|
-
const g = globalThis as {
|
|
267
|
-
SPELLKAVE_SHAPE_CHECK?: unknown;
|
|
268
|
-
process?: { env?: Record<string, string | undefined> };
|
|
269
|
-
};
|
|
270
|
-
const sources: [string, unknown][] = [
|
|
271
|
-
["connect({ shapeCheck })", option],
|
|
272
|
-
["globalThis.SPELLKAVE_SHAPE_CHECK", g.SPELLKAVE_SHAPE_CHECK],
|
|
273
|
-
["SPELLKAVE_SHAPE_CHECK", g.process?.env?.SPELLKAVE_SHAPE_CHECK],
|
|
274
|
-
];
|
|
275
|
-
for (const [source, value] of sources) {
|
|
276
|
-
if (value === undefined || value === null || value === "") continue;
|
|
277
|
-
if (value === "strict" || value === "warn") return value;
|
|
278
|
-
throw new ShapeCheckConfigError(source, value);
|
|
279
|
-
}
|
|
280
|
-
return "strict";
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/** An unknown shape-check mode: a configuration error in every mode, never a guess. */
|
|
284
|
-
export class ShapeCheckConfigError extends Error {
|
|
285
|
-
constructor(source: string, value: unknown) {
|
|
286
|
-
super(`${source} must be "strict" or "warn", got ${JSON.stringify(value)}`);
|
|
287
|
-
this.name = "ShapeCheckConfigError";
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
export interface SpellkaveSession {
|
|
292
|
-
readonly grantProtocolSupported?: boolean;
|
|
293
|
-
readonly handOverProtocolSupported?: boolean;
|
|
294
|
-
conn: DbConnection;
|
|
295
|
-
/** Resolves on first `onApplied`; rejects if the connection ends before then. */
|
|
296
|
-
ready: Promise<void>;
|
|
297
|
-
disconnect(): void;
|
|
298
|
-
/** Per-session tick-interval estimator (D7). Updated on every world_time mutation. */
|
|
299
|
-
estimator: TickIntervalEstimator;
|
|
300
|
-
/** Latest world_time.tick from the live cache; 0n if cache empty (Phase 5.2 fails-closed on this). */
|
|
301
|
-
currentWorldTick(): bigint;
|
|
302
|
-
/** The in-world actor id bound at connect time. */
|
|
303
|
-
readonly connectedActorId: string;
|
|
304
|
-
/** Identity returned by the SDK authentication callback for this connection. */
|
|
305
|
-
readonly authenticatedIdentity: DbConnection["identity"];
|
|
306
|
-
/** Token returned by the SDK authentication callback for this connection. */
|
|
307
|
-
readonly authenticatedToken: string | undefined;
|
|
308
|
-
/** Per-session provenance ring buffer (D3). Populated via onInsert hooks. */
|
|
309
|
-
readonly provenanceBuffer: ProvenanceRingBuffer;
|
|
310
|
-
/** True when the published module lists `visible_manifest_export_result`. */
|
|
311
|
-
readonly exportViewSubscribed: boolean;
|
|
312
|
-
/**
|
|
313
|
-
* Replace the live reader set without replacing this connection. The next
|
|
314
|
-
* subscription is applied before the previous one is removed, so callers
|
|
315
|
-
* retain an overlap while their cache hydrates. This is transport/cache
|
|
316
|
-
* lifecycle only; callers still decide when it is safe to change profiles.
|
|
317
|
-
*/
|
|
318
|
-
replaceReaderManifests(manifests: readonly ReaderManifest[]): Promise<void>;
|
|
319
|
-
/**
|
|
320
|
-
* The one world-event cursor for this session (one per session, lazily
|
|
321
|
-
* memoized on first access). First access CONSTRUCTS the builder; it does
|
|
322
|
-
* NOT prime it. Access after `ready`, then prime once with
|
|
323
|
-
* `diffAndAdvance()` at the moment your host considers itself "arrived" —
|
|
324
|
-
* that moment is a host decision the SDK cannot make for you. See
|
|
325
|
-
* `ledger/designs/session-owns-the-world-event-cursor.md`.
|
|
326
|
-
*/
|
|
327
|
-
readonly worldEvents: WorldEventFanout;
|
|
328
|
-
/** True only after the owner subscription's `onApplied`. */
|
|
329
|
-
readonly readsAsPublisher: boolean;
|
|
330
|
-
/** Last subscribe-time error of the owner subscription, if any. */
|
|
331
|
-
readonly ownerSubscriptionError: Error | null;
|
|
332
|
-
/**
|
|
333
|
-
* Resolves when the owner subscription applies, or at once when the
|
|
334
|
-
* option is off or the identity is not the publisher. Rejects on a
|
|
335
|
-
* subscribe-time owner error, which is stored in `ownerSubscriptionError`.
|
|
336
|
-
* If still pending when the connection ends, it rejects as a connection
|
|
337
|
-
* failure and that rejection is not stored in `ownerSubscriptionError`.
|
|
338
|
-
* An error after the owner subscription has applied disconnects the whole
|
|
339
|
-
* connection and cannot be attributed to this query
|
|
340
|
-
* (`db_connection_impl.ts:1019-1031`, `:1390`, tag `v2.10.0`). A settled
|
|
341
|
-
* promise is not settled again. The SDK attaches a no-op `catch`.
|
|
342
|
-
* `ready` does not wait for this.
|
|
343
|
-
*/
|
|
344
|
-
readonly ownerRowsReady: Promise<void>;
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
/**
|
|
348
|
-
* Open a connection, subscribe to the first-slice table set, and resolve
|
|
349
|
-
* `ready` once the initial snapshot has applied. Errors propagate to the
|
|
350
|
-
* `onError` callback and reject `ready` if they occur before first apply.
|
|
351
|
-
*
|
|
352
|
-
* Async (D-B): fetches the live schema before opening the WebSocket. Strict
|
|
353
|
-
* name mismatch → throws BindingDriftError before .build(). A consumed row,
|
|
354
|
-
* argument or type shape this client cannot decode or call (against the
|
|
355
|
-
* generated KERNEL_CONTRACT, connect-time rules) → throws BindingShapeError
|
|
356
|
-
* before .build() in "strict" mode (the default); in "warn" mode it connects
|
|
357
|
-
* and emits one `contract_shape_mismatch` per change (diagnostic, plus OTLP
|
|
358
|
-
* when configured). Other shape differences are a `binding_shape_diagnostic`.
|
|
359
|
-
*/
|
|
360
|
-
export async function connect(
|
|
361
|
-
args: ConnectArgs,
|
|
362
|
-
callbacks: {
|
|
363
|
-
onError: (err: Error) => void;
|
|
364
|
-
onDisconnect: (err: Error | undefined) => void;
|
|
365
|
-
/** Cache mutation. Per-table hooks pass the snake_case table name; the initial (and later) subscription `onApplied` path passes {@link CACHE_APPLIED_MARKER}. Nullary listeners remain valid. */
|
|
366
|
-
onUpdate: (table?: string) => void;
|
|
367
|
-
},
|
|
368
|
-
): Promise<SpellkaveSession> {
|
|
369
|
-
ensurePromiseWithResolvers();
|
|
370
|
-
const diagnostic = args.onDiagnostic ?? ((line: object) => console.warn(JSON.stringify(line)));
|
|
371
|
-
|
|
372
|
-
const shapeMode = resolveShapeCheck(args.shapeCheck);
|
|
373
|
-
const served = await fetchServerSchema(args.url, args.db);
|
|
374
|
-
const serverSurface = served.surface;
|
|
375
|
-
const expected = {
|
|
376
|
-
tables: [...STRICT_TABLES].sort(),
|
|
377
|
-
reducers: [...STRICT_REDUCERS].sort(),
|
|
378
|
-
};
|
|
379
|
-
const expectedTableSet: ReadonlySet<string> = new Set(expected.tables);
|
|
380
|
-
const expectedReducerSet: ReadonlySet<string> = new Set(expected.reducers);
|
|
381
|
-
const actualStrict = {
|
|
382
|
-
tables: serverSurface.tables.filter((t) => expectedTableSet.has(t)),
|
|
383
|
-
reducers: serverSurface.reducers.filter((r) => expectedReducerSet.has(r)),
|
|
384
|
-
};
|
|
385
|
-
const missingTables = expected.tables.filter((t) => !serverSurface.tables.includes(t));
|
|
386
|
-
if (missingTables.length > 0) {
|
|
387
|
-
throw new BindingDriftError(expected, actualStrict, "table");
|
|
388
|
-
}
|
|
389
|
-
const missingReducers = expected.reducers.filter((r) => !serverSurface.reducers.includes(r));
|
|
390
|
-
if (missingReducers.length > 0) {
|
|
391
|
-
throw new BindingDriftError(expected, actualStrict, "reducer");
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
const shape = compareServedShape(served.schema, KERNEL_CONTRACT);
|
|
395
|
-
const line = (c: { item: string; detail: string }) => `${c.item}: ${c.detail}`;
|
|
396
|
-
if (shape.breaking.length > 0) {
|
|
397
|
-
if (shapeMode === "strict") {
|
|
398
|
-
throw new BindingShapeError(expected, actualStrict, shape.breaking, KERNEL_CONTRACT_EPOCH);
|
|
399
|
-
}
|
|
400
|
-
const mismatches = unreportedShapeMismatches(
|
|
401
|
-
shapeMismatchFields(shape.breaking, args.db, KERNEL_CONTRACT_EPOCH),
|
|
402
|
-
);
|
|
403
|
-
for (const fields of mismatches) diagnostic({ kind: CONTRACT_SHAPE_MISMATCH, ...fields });
|
|
404
|
-
void exportShapeMismatches(
|
|
405
|
-
shapeMismatchEvents(mismatches, {
|
|
406
|
-
runId: `contract-check-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
407
|
-
actorId: args.connectedActorId,
|
|
408
|
-
driver: shapeTelemetryDriver(),
|
|
409
|
-
now: new Date(),
|
|
410
|
-
}),
|
|
411
|
-
);
|
|
412
|
-
}
|
|
413
|
-
if (shape.diagnostics.length > 0 || shape.unchecked.length > 0) {
|
|
414
|
-
diagnostic({
|
|
415
|
-
kind: "binding_shape_diagnostic",
|
|
416
|
-
client_epoch: KERNEL_CONTRACT_EPOCH,
|
|
417
|
-
changes: shape.diagnostics.map(line),
|
|
418
|
-
unchecked: shape.unchecked.map((u) => `${u.item}: ${u.error}`),
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
const additiveTables = serverSurface.tables.filter((t) => !expectedTableSet.has(t));
|
|
423
|
-
const additiveReducers = serverSurface.reducers.filter((r) => !expectedReducerSet.has(r));
|
|
424
|
-
if (additiveTables.length > 0 || additiveReducers.length > 0) {
|
|
425
|
-
diagnostic({
|
|
426
|
-
kind: "binding_drift_additive",
|
|
427
|
-
additions: {
|
|
428
|
-
tables: additiveTables,
|
|
429
|
-
reducers: additiveReducers,
|
|
430
|
-
},
|
|
431
|
-
});
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
let resolveReady: () => void;
|
|
435
|
-
let rejectReady: (err: Error) => void;
|
|
436
|
-
const ready = new Promise<void>((resolve, reject) => {
|
|
437
|
-
resolveReady = resolve;
|
|
438
|
-
rejectReady = reject;
|
|
439
|
-
});
|
|
440
|
-
let resolveOwnerReady: () => void;
|
|
441
|
-
let rejectOwnerReady: (err: Error) => void;
|
|
442
|
-
const ownerRowsReady = new Promise<void>((resolve, reject) => {
|
|
443
|
-
resolveOwnerReady = resolve;
|
|
444
|
-
rejectOwnerReady = reject;
|
|
445
|
-
});
|
|
446
|
-
// An unobserved rejection must not end the process.
|
|
447
|
-
ownerRowsReady.catch(() => {});
|
|
448
|
-
let ownerSettled = false;
|
|
449
|
-
const settleOwnerReady = (): void => {
|
|
450
|
-
if (ownerSettled) return;
|
|
451
|
-
ownerSettled = true;
|
|
452
|
-
resolveOwnerReady();
|
|
453
|
-
};
|
|
454
|
-
const rejectOwnerWait = (error: Error, attributedToOwnerQuery: boolean): void => {
|
|
455
|
-
if (ownerSettled) return;
|
|
456
|
-
ownerSettled = true;
|
|
457
|
-
if (attributedToOwnerQuery) ownerSubscriptionError = error;
|
|
458
|
-
readsAsPublisher = false;
|
|
459
|
-
rejectOwnerReady(error);
|
|
460
|
-
};
|
|
461
|
-
const failOwnerConnection = (err: unknown): void => {
|
|
462
|
-
if (!args.ownerTables) return;
|
|
463
|
-
rejectOwnerWait(
|
|
464
|
-
err instanceof Error
|
|
465
|
-
? err
|
|
466
|
-
: new Error(String(err ?? "connection ended before owner rows were ready")),
|
|
467
|
-
false,
|
|
468
|
-
);
|
|
469
|
-
};
|
|
470
|
-
let readsAsPublisher = false;
|
|
471
|
-
let ownerSubscriptionError: Error | null = null;
|
|
472
|
-
let ownerOpened = false;
|
|
473
|
-
if (!args.ownerTables) settleOwnerReady();
|
|
474
|
-
|
|
475
|
-
let applied = false;
|
|
476
|
-
const failInitialConnection = (error?: Error): void => {
|
|
477
|
-
if (!applied)
|
|
478
|
-
rejectReady(error ?? new Error("connection ended before initial subscription was ready"));
|
|
479
|
-
};
|
|
480
|
-
let conn: DbConnection | undefined;
|
|
481
|
-
let activeSubscription: SubscriptionHandle | undefined;
|
|
482
|
-
let subscriptionTail: Promise<void> = Promise.resolve();
|
|
483
|
-
let authenticatedIdentity: DbConnection["identity"];
|
|
484
|
-
let authenticatedToken: string | undefined;
|
|
485
|
-
const estimator = new TickIntervalEstimator();
|
|
486
|
-
const provenanceBuffer = new ProvenanceRingBuffer(
|
|
487
|
-
args.connectedActorId,
|
|
488
|
-
args.provenanceBufferSize ?? {},
|
|
489
|
-
);
|
|
490
|
-
|
|
491
|
-
const subscribe = (
|
|
492
|
-
live: DbConnection,
|
|
493
|
-
manifests: readonly ReaderManifest[] | undefined,
|
|
494
|
-
onApplied: () => void,
|
|
495
|
-
onError: (ctx: unknown, err?: unknown) => void,
|
|
496
|
-
): SubscriptionHandle =>
|
|
497
|
-
live
|
|
498
|
-
.subscriptionBuilder()
|
|
499
|
-
.onApplied(onApplied)
|
|
500
|
-
.onError(onError)
|
|
501
|
-
.subscribe(
|
|
502
|
-
subscribeSetForSurface(serverSurface, manifests).map(
|
|
503
|
-
// ci-allow(raw-sql): canonical SDK derivation from validated reader manifests and the published surface.
|
|
504
|
-
(t) => `SELECT * FROM ${t}`,
|
|
505
|
-
),
|
|
506
|
-
);
|
|
507
|
-
|
|
508
|
-
const openOwnerSubscription = (live: DbConnection): void => {
|
|
509
|
-
if (!args.ownerTables || ownerOpened) return;
|
|
510
|
-
ownerOpened = true;
|
|
511
|
-
if (!isPublisherIdentity(live, authenticatedIdentity)) {
|
|
512
|
-
settleOwnerReady();
|
|
513
|
-
return;
|
|
514
|
-
}
|
|
515
|
-
const tables: string[] = [...OWNER_SUBSCRIPTION_TABLES];
|
|
516
|
-
if (ownerSubscriptionTestProbe.appendBogusTable) {
|
|
517
|
-
tables.push("spellkave_owner_probe_missing_table");
|
|
518
|
-
}
|
|
519
|
-
live
|
|
520
|
-
.subscriptionBuilder()
|
|
521
|
-
.onApplied(() => {
|
|
522
|
-
if (ownerSettled) return;
|
|
523
|
-
readsAsPublisher = true;
|
|
524
|
-
settleOwnerReady();
|
|
525
|
-
})
|
|
526
|
-
.onError((_ctx: unknown, err?: unknown) => {
|
|
527
|
-
rejectOwnerWait(toSubscriptionError(err ?? _ctx), true);
|
|
528
|
-
})
|
|
529
|
-
.subscribe(
|
|
530
|
-
tables.map(
|
|
531
|
-
// ci-allow(raw-sql): ADR-0150 owner set bypasses buildSubscribeSet and its filter on purpose.
|
|
532
|
-
(table) => `SELECT * FROM ${table}`,
|
|
533
|
-
),
|
|
534
|
-
);
|
|
535
|
-
};
|
|
536
|
-
|
|
537
|
-
const replaceReaderManifests = (manifests: readonly ReaderManifest[]): Promise<void> => {
|
|
538
|
-
const operation = subscriptionTail.then(
|
|
539
|
-
() =>
|
|
540
|
-
new Promise<void>((resolve, reject) => {
|
|
541
|
-
const live = conn ?? built;
|
|
542
|
-
const previous = activeSubscription;
|
|
543
|
-
let next: SubscriptionHandle | undefined;
|
|
544
|
-
let settled = false;
|
|
545
|
-
next = subscribe(
|
|
546
|
-
live,
|
|
547
|
-
manifests,
|
|
548
|
-
() => {
|
|
549
|
-
// The upstream callback is normally asynchronous, but defer one
|
|
550
|
-
// turn so a synchronous test/client callback still sees the
|
|
551
|
-
// handle returned by subscribe before it becomes active.
|
|
552
|
-
queueMicrotask(() => {
|
|
553
|
-
if (settled) return;
|
|
554
|
-
settled = true;
|
|
555
|
-
activeSubscription = next;
|
|
556
|
-
previous?.unsubscribe();
|
|
557
|
-
callbacks.onUpdate(CACHE_APPLIED_MARKER);
|
|
558
|
-
resolve();
|
|
559
|
-
});
|
|
560
|
-
},
|
|
561
|
-
(ctx, err) => {
|
|
562
|
-
if (settled) return;
|
|
563
|
-
settled = true;
|
|
564
|
-
const error =
|
|
565
|
-
err instanceof Error
|
|
566
|
-
? err
|
|
567
|
-
: ctx instanceof Error
|
|
568
|
-
? ctx
|
|
569
|
-
: new Error(String(err ?? ctx ?? "subscription replacement failed"));
|
|
570
|
-
callbacks.onError(error);
|
|
571
|
-
reject(error);
|
|
572
|
-
},
|
|
573
|
-
);
|
|
574
|
-
}),
|
|
575
|
-
);
|
|
576
|
-
subscriptionTail = operation.then(
|
|
577
|
-
() => undefined,
|
|
578
|
-
() => undefined,
|
|
579
|
-
);
|
|
580
|
-
return operation;
|
|
581
|
-
};
|
|
582
|
-
|
|
583
|
-
// SpacetimeDB 2.10.0 WebsocketDecompressAdapter can deliver an
|
|
584
|
-
// uncompressed frame before an earlier gzip frame, corrupting caches.
|
|
585
|
-
// Repro: src/__tests__/connection_transport.test.ts (no timing controls).
|
|
586
|
-
// Re-enable only after an upstream ordering fix and this regression passes
|
|
587
|
-
// with compression on. Correct subscription state takes priority over bytes.
|
|
588
|
-
const builder = DbConnection.builder()
|
|
589
|
-
.withCompression("none")
|
|
590
|
-
.withUri(args.url)
|
|
591
|
-
.withDatabaseName(args.db)
|
|
592
|
-
.onConnect((live, identity, token) => {
|
|
593
|
-
conn = live;
|
|
594
|
-
authenticatedIdentity = identity;
|
|
595
|
-
authenticatedToken = token;
|
|
596
|
-
activeSubscription = subscribe(
|
|
597
|
-
live,
|
|
598
|
-
args.readerManifests,
|
|
599
|
-
() => {
|
|
600
|
-
if (!applied) {
|
|
601
|
-
applied = true;
|
|
602
|
-
resolveReady();
|
|
603
|
-
openOwnerSubscription(live);
|
|
604
|
-
}
|
|
605
|
-
callbacks.onUpdate(CACHE_APPLIED_MARKER);
|
|
606
|
-
},
|
|
607
|
-
(ctx: unknown, err?: unknown) => {
|
|
608
|
-
const error =
|
|
609
|
-
err instanceof Error
|
|
610
|
-
? err
|
|
611
|
-
: ctx instanceof Error
|
|
612
|
-
? ctx
|
|
613
|
-
: new Error(String(err ?? ctx ?? "subscription failed"));
|
|
614
|
-
callbacks.onError(error);
|
|
615
|
-
if (!applied) rejectReady(error);
|
|
616
|
-
},
|
|
617
|
-
);
|
|
618
|
-
// Re-render on any cache mutation across the subscribed tables. The
|
|
619
|
-
// callback receives the moved table so a consumer (NPC seat) can
|
|
620
|
-
// ignore baseline-only churn; a nullary widget listener still works.
|
|
621
|
-
installRefreshHooks(live, callbacks.onUpdate);
|
|
622
|
-
// Feed world_time updates into the per-session tick-interval estimator (D7).
|
|
623
|
-
installTickEstimatorHook(live, estimator);
|
|
624
|
-
// Feed evaluation_provenance inserts into the per-session ring buffer (D3).
|
|
625
|
-
installProvenanceBufferHook(live, provenanceBuffer);
|
|
626
|
-
})
|
|
627
|
-
.onConnectError((_ctx, err) => {
|
|
628
|
-
callbacks.onError(err);
|
|
629
|
-
if (!applied) rejectReady(err);
|
|
630
|
-
failOwnerConnection(err);
|
|
631
|
-
})
|
|
632
|
-
.onDisconnect((_ctx, err) => {
|
|
633
|
-
failInitialConnection(err);
|
|
634
|
-
callbacks.onDisconnect(err);
|
|
635
|
-
failOwnerConnection(err);
|
|
636
|
-
});
|
|
637
|
-
|
|
638
|
-
const token = args.token === null ? undefined : (args.token ?? resolveConnectTokenFromEnv());
|
|
639
|
-
if (token !== undefined) {
|
|
640
|
-
builder.withToken(token);
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
const built = builder.build();
|
|
644
|
-
|
|
645
|
-
// Memoized lazily by the `worldEvents` getter below — first access
|
|
646
|
-
// constructs the one cursor for this session; every later access returns
|
|
647
|
-
// the same object. See the interface doc comment and
|
|
648
|
-
// `ledger/designs/session-owns-the-world-event-cursor.md`.
|
|
649
|
-
let worldEvents: WorldEventFanout | undefined;
|
|
650
|
-
|
|
651
|
-
const session: SpellkaveSession = {
|
|
652
|
-
connectedActorId: args.connectedActorId,
|
|
653
|
-
grantProtocolSupported: serverSurface.tables.includes("grant_inventory"),
|
|
654
|
-
handOverProtocolSupported:
|
|
655
|
-
serverSurface.tables.includes("role_binding_hand_over_context") &&
|
|
656
|
-
serverSurface.tables.includes("visible_role_binding_transfer"),
|
|
657
|
-
get authenticatedIdentity(): DbConnection["identity"] {
|
|
658
|
-
return authenticatedIdentity ?? (conn ?? built).identity;
|
|
659
|
-
},
|
|
660
|
-
get authenticatedToken(): string | undefined {
|
|
661
|
-
return authenticatedToken ?? (conn ?? built).token;
|
|
662
|
-
},
|
|
663
|
-
get conn(): DbConnection {
|
|
664
|
-
// Returns the live connection only after onConnect — callers should
|
|
665
|
-
// await `ready` first. We surface the post-connect handle by closure
|
|
666
|
-
// so `tool.ts` can reach `conn.reducers`.
|
|
667
|
-
return conn ?? built;
|
|
668
|
-
},
|
|
669
|
-
ready,
|
|
670
|
-
replaceReaderManifests,
|
|
671
|
-
disconnect() {
|
|
672
|
-
failInitialConnection();
|
|
673
|
-
failOwnerConnection(new Error("connection ended before owner rows were ready"));
|
|
674
|
-
try {
|
|
675
|
-
(conn ?? built).disconnect();
|
|
676
|
-
} catch {
|
|
677
|
-
// ignore disconnect-after-disconnect
|
|
678
|
-
}
|
|
679
|
-
},
|
|
680
|
-
estimator,
|
|
681
|
-
provenanceBuffer,
|
|
682
|
-
exportViewSubscribed: serverSurface.tables.includes("visible_manifest_export_result"),
|
|
683
|
-
currentWorldTick(): bigint {
|
|
684
|
-
if (!conn) return 0n;
|
|
685
|
-
const db = conn.db as unknown as Record<string, TableHandle | undefined>;
|
|
686
|
-
const handle = db.worldTime ?? db.world_time;
|
|
687
|
-
if (!handle) return 0n;
|
|
688
|
-
for (const row of handle.iter()) {
|
|
689
|
-
const r = row as unknown as WorldTimeRow;
|
|
690
|
-
return typeof r.tick === "bigint" ? r.tick : BigInt(String(r.tick ?? 0));
|
|
691
|
-
}
|
|
692
|
-
return 0n;
|
|
693
|
-
},
|
|
694
|
-
get readsAsPublisher(): boolean {
|
|
695
|
-
return readsAsPublisher;
|
|
696
|
-
},
|
|
697
|
-
get ownerSubscriptionError(): Error | null {
|
|
698
|
-
return ownerSubscriptionError;
|
|
699
|
-
},
|
|
700
|
-
ownerRowsReady,
|
|
701
|
-
get worldEvents(): WorldEventFanout {
|
|
702
|
-
// CONSTRUCTS only — never primes. Priming is a host decision (see
|
|
703
|
-
// the doc comment on `SpellkaveSession.worldEvents`).
|
|
704
|
-
if (worldEvents === undefined) {
|
|
705
|
-
worldEvents = createWorldEventFanout(
|
|
706
|
-
createWorldEventBuilder(
|
|
707
|
-
() => snapshotDb(session),
|
|
708
|
-
() => session.connectedActorId,
|
|
709
|
-
),
|
|
710
|
-
);
|
|
711
|
-
}
|
|
712
|
-
return worldEvents;
|
|
713
|
-
},
|
|
714
|
-
};
|
|
715
|
-
return session;
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
function toSubscriptionError(value: unknown): Error {
|
|
719
|
-
if (value instanceof Error) return value;
|
|
720
|
-
return new Error(String(value ?? "owner subscription failed"));
|
|
721
|
-
}
|
|
722
|
-
|
|
723
|
-
function identityHex(value: unknown): string {
|
|
724
|
-
if (typeof value === "string") return value.replace(/^0x/i, "").toLowerCase();
|
|
725
|
-
if (value && typeof value === "object" && "toHexString" in value) {
|
|
726
|
-
const hex = (value as { toHexString?: () => string }).toHexString;
|
|
727
|
-
if (typeof hex === "function") return hex.call(value).replace(/^0x/i, "").toLowerCase();
|
|
728
|
-
}
|
|
729
|
-
return "";
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
function isPublisherIdentity(live: DbConnection, authenticated: unknown): boolean {
|
|
733
|
-
const mine = identityHex(authenticated);
|
|
734
|
-
if (mine.length === 0) return false;
|
|
735
|
-
const db = live.db as unknown as {
|
|
736
|
-
config?: { iter?: () => Iterable<{ operatorIdentity?: unknown; operator_identity?: unknown }> };
|
|
737
|
-
};
|
|
738
|
-
const handle = db.config;
|
|
739
|
-
if (!handle?.iter) return false;
|
|
740
|
-
for (const row of handle.iter()) {
|
|
741
|
-
const owner = identityHex(row.operatorIdentity ?? row.operator_identity);
|
|
742
|
-
return owner.length > 0 && owner === mine;
|
|
743
|
-
}
|
|
744
|
-
return false;
|
|
745
|
-
}
|
|
746
|
-
|
|
747
|
-
function resolveConnectTokenFromEnv(): string | undefined {
|
|
748
|
-
if (typeof process === "undefined") return undefined;
|
|
749
|
-
const token = process.env.SPELLKAVE_CONNECT_TOKEN;
|
|
750
|
-
return token !== undefined && token.length > 0 ? token : undefined;
|
|
751
|
-
}
|
|
752
|
-
|
|
753
|
-
/**
|
|
754
|
-
* Wire world_time mutations into the per-session TickIntervalEstimator (D7).
|
|
755
|
-
* Called once from onConnect so the estimator accumulates deltas from the
|
|
756
|
-
* moment the subscription applies.
|
|
757
|
-
*/
|
|
758
|
-
function installTickEstimatorHook(conn: DbConnection, estimator: TickIntervalEstimator): void {
|
|
759
|
-
const db = conn.db as unknown as Record<string, TableHandle | undefined>;
|
|
760
|
-
const handle = db.worldTime ?? db.world_time;
|
|
761
|
-
if (!handle) return;
|
|
762
|
-
|
|
763
|
-
const sample = (): void => {
|
|
764
|
-
for (const row of handle.iter()) {
|
|
765
|
-
const r = row as unknown as WorldTimeRow;
|
|
766
|
-
const tick = typeof r.tick === "bigint" ? r.tick : BigInt(String(r.tick ?? 0));
|
|
767
|
-
estimator.record(tick, Date.now());
|
|
768
|
-
return; // world_time is a singleton — first row is the only row
|
|
769
|
-
}
|
|
770
|
-
};
|
|
771
|
-
|
|
772
|
-
handle.onInsert?.(sample);
|
|
773
|
-
handle.onUpdate?.(sample);
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
/**
|
|
777
|
-
* Wire visible_evaluation_provenance inserts into the per-session ring buffer (D3).
|
|
778
|
-
* Updates are not wired — provenance rows are immutable once written.
|
|
779
|
-
*/
|
|
780
|
-
function installProvenanceBufferHook(conn: DbConnection, buffer: ProvenanceRingBuffer): void {
|
|
781
|
-
const db = conn.db as unknown as Record<string, TableHandle | undefined>;
|
|
782
|
-
const handle =
|
|
783
|
-
db.visibleEvaluationProvenance ??
|
|
784
|
-
db.visible_evaluation_provenance ??
|
|
785
|
-
db.evaluationProvenance ??
|
|
786
|
-
db.evaluation_provenance;
|
|
787
|
-
if (!handle) return;
|
|
788
|
-
|
|
789
|
-
handle.onInsert?.(() => {
|
|
790
|
-
for (const raw of handle.iter()) {
|
|
791
|
-
const r = raw as unknown as EvaluationProvenanceRow;
|
|
792
|
-
buffer.insert({
|
|
793
|
-
id: r.provenanceId,
|
|
794
|
-
kind: tagString(r.kind),
|
|
795
|
-
status: tagString(r.status),
|
|
796
|
-
subject_id: r.subjectId,
|
|
797
|
-
failure_kind: r.failureKind,
|
|
798
|
-
failure_detail: r.failureDetail,
|
|
799
|
-
selected_template_ids: Array.isArray(r.selectedTemplateIds)
|
|
800
|
-
? r.selectedTemplateIds.map(String)
|
|
801
|
-
: [],
|
|
802
|
-
created_at_tick: r.createdAtTick,
|
|
803
|
-
bundle_id: r.bundleId,
|
|
804
|
-
});
|
|
805
|
-
}
|
|
806
|
-
});
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
function tagString(v: unknown): string {
|
|
810
|
-
if (typeof v === "string") return v;
|
|
811
|
-
if (v && typeof v === "object") {
|
|
812
|
-
const tag = (v as { tag?: unknown }).tag;
|
|
813
|
-
if (typeof tag === "string") return tag;
|
|
814
|
-
}
|
|
815
|
-
return String(v ?? "");
|
|
816
|
-
}
|
|
817
|
-
|
|
818
|
-
/** Distinct marker `onApplied` reports — never a real table name. Consumers
|
|
819
|
-
* that filter wakes treat this as always-observable (the snapshot is new). */
|
|
820
|
-
export const CACHE_APPLIED_MARKER = "__applied";
|
|
821
|
-
|
|
822
|
-
/**
|
|
823
|
-
* Wire `onUpdate` to fire whenever any subscribed table mutates. Passes the
|
|
824
|
-
* snake_case table name so a consumer can filter; a nullary listener still
|
|
825
|
-
* compiles. Wrapping is required — the SDK's `onInsert`/`onUpdate`/`onDelete`
|
|
826
|
-
* invoke with `(ctx, row)`, which must not leak into `onUpdate`'s table arg.
|
|
827
|
-
*/
|
|
828
|
-
export function installRefreshHooks(conn: DbConnection, onUpdate: (table: string) => void): void {
|
|
829
|
-
// The SDK's table accessors live under `conn.db`. Each accessor exposes
|
|
830
|
-
// `onInsert/onUpdate/onDelete`. We dispatch by name so we don't depend on
|
|
831
|
-
// the exact camelCased accessor identifiers being unique to this slice.
|
|
832
|
-
const db = conn.db as unknown as Record<string, TableHandle | undefined>;
|
|
833
|
-
// Apply bookkeeping is deliberately outside the PLAYER reader baseline.
|
|
834
|
-
// An elevated caller subscribing it still needs seal/failure notifications.
|
|
835
|
-
for (const t of [
|
|
836
|
-
...CONNECTION_BASELINE,
|
|
837
|
-
...READER_SCOPED_TABLES,
|
|
838
|
-
...MANIFEST_APPLY_WAIT_TABLES,
|
|
839
|
-
...OPTIONAL_SATELLITE_TABLES,
|
|
840
|
-
]) {
|
|
841
|
-
const handle = db[toCamel(t)] ?? db[t];
|
|
842
|
-
if (!handle) continue;
|
|
843
|
-
const fire = (): void => onUpdate(t);
|
|
844
|
-
handle.onInsert?.(fire);
|
|
845
|
-
handle.onDelete?.(fire);
|
|
846
|
-
handle.onUpdate?.(fire);
|
|
847
|
-
}
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
interface TableHandle {
|
|
851
|
-
iter(): Iterable<Record<string, unknown>>;
|
|
852
|
-
onInsert?: (cb: () => void) => void;
|
|
853
|
-
onDelete?: (cb: () => void) => void;
|
|
854
|
-
onUpdate?: (cb: () => void) => void;
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
function toCamel(snake: string): string {
|
|
858
|
-
return snake.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
|
|
859
|
-
}
|
|
860
|
-
|
|
861
|
-
/** Public live-cache view for read-model helpers. */
|
|
862
|
-
export function snapshotDb(session: SpellkaveSession): SnapshotDb {
|
|
863
|
-
return session.conn.db as unknown as SnapshotDb;
|
|
864
|
-
}
|
|
865
|
-
|
|
866
|
-
/**
|
|
867
|
-
* Build the readers consumed by `core/actor.ts` and `core/movement.ts` from
|
|
868
|
-
* the live SDK caches. Called every time the widget re-renders.
|
|
869
|
-
*/
|
|
870
|
-
export function snapshot(conn: DbConnection): {
|
|
871
|
-
actors: LiveActorReader;
|
|
872
|
-
controlledActors: LiveActorReader;
|
|
873
|
-
movement: LiveMovementReader;
|
|
874
|
-
} {
|
|
875
|
-
return snapshotFromDb(conn.db as unknown as SnapshotDb);
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
export function snapshotFromDb(db: SnapshotDb): {
|
|
879
|
-
actors: LiveActorReader;
|
|
880
|
-
controlledActors: LiveActorReader;
|
|
881
|
-
movement: LiveMovementReader;
|
|
882
|
-
} {
|
|
883
|
-
const locationsHandle = db.visibleActorSpatialLocation ?? db.visible_actor_spatial_location;
|
|
884
|
-
const controlledLocationsHandle =
|
|
885
|
-
db.directlyControlledActorSpatialLocation ?? db.directly_controlled_actor_spatial_location;
|
|
886
|
-
const authoredEntityHandle =
|
|
887
|
-
db.visibleManifestAuthoredEntity ?? db.visible_manifest_authored_entity;
|
|
888
|
-
const edgesHandle = db.visiblePlaceEdge ?? db.visible_place_edge;
|
|
889
|
-
const nodesHandle = db.visiblePlaceNode ?? db.visible_place_node;
|
|
890
|
-
const entityAliases = new Map<string, string[]>();
|
|
891
|
-
const mappingCoverage = [
|
|
892
|
-
...((
|
|
893
|
-
db.visibleManifestAuthoredEntityCoverage ?? db.visible_manifest_authored_entity_coverage
|
|
894
|
-
)?.iter() ?? []),
|
|
895
|
-
] as Array<{ status?: string; projectionVersion?: number }>;
|
|
896
|
-
const mappingComplete =
|
|
897
|
-
mappingCoverage.length === 1 &&
|
|
898
|
-
mappingCoverage[0]?.status === "complete" &&
|
|
899
|
-
mappingCoverage[0]?.projectionVersion === 1;
|
|
900
|
-
for (const r of mappingComplete ? (authoredEntityHandle?.iter() ?? []) : []) {
|
|
901
|
-
const row = r as unknown as { entityId?: bigint | number; manifestKey?: string };
|
|
902
|
-
if (row.entityId === undefined || row.manifestKey === undefined) continue;
|
|
903
|
-
const alias = row.manifestKey.includes(":")
|
|
904
|
-
? row.manifestKey.slice(row.manifestKey.indexOf(":") + 1)
|
|
905
|
-
: row.manifestKey;
|
|
906
|
-
const key = String(row.entityId);
|
|
907
|
-
const aliases = entityAliases.get(key) ?? [];
|
|
908
|
-
aliases.push(alias);
|
|
909
|
-
entityAliases.set(key, aliases);
|
|
910
|
-
}
|
|
911
|
-
|
|
912
|
-
const actorReader = (handle: TableHandle | undefined): LiveActorReader => ({
|
|
913
|
-
locations: () =>
|
|
914
|
-
Array.from(handle?.iter() ?? []).map((r) => {
|
|
915
|
-
const row = r as unknown as ActorSpatialLocationRow;
|
|
916
|
-
const entityId = String(row.entityId);
|
|
917
|
-
const out: {
|
|
918
|
-
entity_id: EntityId;
|
|
919
|
-
aliases?: string[];
|
|
920
|
-
node_id: string | undefined;
|
|
921
|
-
} = {
|
|
922
|
-
entity_id: asEntityId(entityId),
|
|
923
|
-
node_id: optionalString(row.placeNodeId),
|
|
924
|
-
};
|
|
925
|
-
const aliases = entityAliases.get(entityId);
|
|
926
|
-
if (aliases !== undefined && aliases.length > 0) out.aliases = aliases;
|
|
927
|
-
return out;
|
|
928
|
-
}),
|
|
929
|
-
});
|
|
930
|
-
|
|
931
|
-
return {
|
|
932
|
-
// Broad scene/perception projection: includes direct, extent, and co-located bodies.
|
|
933
|
-
actors: actorReader(locationsHandle as TableHandle | undefined),
|
|
934
|
-
// Strict server-attested control projection for connection activation.
|
|
935
|
-
controlledActors: actorReader(controlledLocationsHandle as TableHandle | undefined),
|
|
936
|
-
movement: {
|
|
937
|
-
// `visible_place_edge.edgeId` is `u64` in the generated table, but `r_move`
|
|
938
|
-
// accepts a string `edgeId` in its reducer schema (see
|
|
939
|
-
// `@spellkave/bindings`: `visible_place_edge_table.ts`, `r_move_reducer.ts`).
|
|
940
|
-
// Stringify here so widget display, LLM tool input, and reducer call
|
|
941
|
-
// all share one identifier shape.
|
|
942
|
-
edges: () =>
|
|
943
|
-
Array.from(edgesHandle?.iter() ?? []).map((r) => {
|
|
944
|
-
const row = r as unknown as PlaceEdgeRow;
|
|
945
|
-
return {
|
|
946
|
-
edge_id: String(row.edgeId),
|
|
947
|
-
from_node_id: row.fromNodeId,
|
|
948
|
-
to_node_id: row.toNodeId,
|
|
949
|
-
};
|
|
950
|
-
}),
|
|
951
|
-
nodes: () =>
|
|
952
|
-
Array.from(nodesHandle?.iter() ?? []).map((r) => {
|
|
953
|
-
const row = r as unknown as PlaceNodeRow;
|
|
954
|
-
return { node_id: row.nodeId };
|
|
955
|
-
}),
|
|
956
|
-
},
|
|
957
|
-
};
|
|
958
|
-
}
|
|
959
|
-
|
|
960
|
-
function optionalString(v: unknown): string | undefined {
|
|
961
|
-
if (v === undefined || v === null) return undefined;
|
|
962
|
-
const s = String(v);
|
|
963
|
-
return s.length > 0 ? s : undefined;
|
|
964
|
-
}
|