@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
@@ -1,355 +0,0 @@
1
- /** One isolated caller-authenticated cache; one group, retired before reapplication. */
2
- import { DbConnection, type SubscriptionHandle } from "@spellkave/bindings";
3
- import type { SpellkaveSession } from "@spellkave/sdk";
4
- import type { ScopedReadSource } from "@spellkave/tool-contracts";
5
- import type {
6
- OwnerSnapshot,
7
- ScopedInstanceSnapshot,
8
- ScopedSnapshotPort,
9
- } from "@spellkave/world-author";
10
-
11
- const TABLES = {
12
- visible_manifest_authored_entity: "authoring_authored_entity",
13
- entity: "authoring_entity",
14
- actor: "authoring_actor",
15
- actor_spatial_location: "authoring_actor_spatial_location",
16
- capability: "authoring_capability",
17
- entity_equipment_slot: "authoring_entity_equipment_slot",
18
- entity_containment: "authoring_entity_containment",
19
- entity_tag: "authoring_entity_tag",
20
- object_state: "authoring_object_state",
21
- entity_location: "authoring_entity_location",
22
- entity_description: "authoring_entity_description",
23
- coverage: "authoring_coverage",
24
- binding_context: "visible_role_binding",
25
- binding_inventory: "grant_inventory",
26
- runtime_entity_tag: "visible_entity_tag",
27
- runtime_tag_coverage: "visible_entity_tag_coverage",
28
- pending_request: "pending_arbitration_request",
29
- pending_response: "pending_arbitration_response",
30
- pending_rejection: "pending_arbitration_rejection",
31
- pending_fallback: "pending_arbitration_fallback",
32
- pending_job: "pending_autonomy_job",
33
- pending_coverage: "pending_context_coverage",
34
- } as const;
35
- let nextConnectionEpoch = 0;
36
- const MAX_PENDING_READS = 16;
37
- const KINDS = [
38
- "entities",
39
- "actors",
40
- "actor_spatial_locations",
41
- "actor_capabilities",
42
- "actor_equipment_slots",
43
- "entity_containment",
44
- "entity_tag",
45
- "object_state",
46
- ];
47
- function hex(identity: unknown): string {
48
- if (identity && typeof identity === "object" && "toHexString" in identity) {
49
- return (identity as { toHexString(): string }).toHexString();
50
- }
51
- return String(identity ?? "");
52
- }
53
- function tableRows(
54
- db: Record<string, { iter(): Iterable<Record<string, unknown>> }>,
55
- table: string,
56
- ) {
57
- const handle =
58
- db[table.replace(/_([a-z])/g, (_, char: string) => char.toUpperCase())] ?? db[table];
59
- if (!handle) throw new Error("reader_unavailable: scoped view accessor missing");
60
- return handle.iter();
61
- }
62
- function freeze<T>(value: T): T {
63
- if (value && typeof value === "object") {
64
- for (const child of Object.values(value)) freeze(child);
65
- Object.freeze(value);
66
- }
67
- return value;
68
- }
69
- export function createLiveScopedSnapshotPort(deps: {
70
- session: SpellkaveSession | (() => SpellkaveSession);
71
- world: { url: string; db: string } | (() => { url: string; db: string });
72
- /**
73
- * Additional family name -> server view or public catalog table, read in the
74
- * SAME isolated group and copied in the same `onApplied` (persona exploration).
75
- * Existing callers pass nothing and keep the eight-kind group unchanged.
76
- */
77
- extraTables?: Readonly<Record<string, string>>;
78
- }): ScopedSnapshotPort {
79
- for (const name of Object.keys(deps.extraTables ?? {}))
80
- if (name in TABLES) throw new Error(`extraTables: '${name}' shadows a scoped family`);
81
- const tables: Readonly<Record<string, string>> = { ...TABLES, ...deps.extraTables };
82
- // ci-allow(raw-sql): D-2 isolated scoped authoring snapshot group; names are server-admitted views or public catalogs
83
- const queries = Object.values(tables).map((table) => `SELECT * FROM ${table}`);
84
- const current = () => (typeof deps.session === "function" ? deps.session() : deps.session);
85
- const world = () => (typeof deps.world === "function" ? deps.world() : deps.world);
86
- let connection: DbConnection | undefined;
87
- let handle: SubscriptionHandle | undefined;
88
- let ready: Promise<void> | undefined;
89
- let closed = false;
90
- let ownerKey = "";
91
- let parentConnection: SpellkaveSession["conn"] | undefined;
92
- let connectionEpoch = 0;
93
- let fingerprint = "";
94
- let sourceEpoch = 0;
95
- let queue: Promise<unknown> = Promise.resolve();
96
- let pending = 0;
97
- let failPending: ((error: Error) => void) | undefined;
98
- const unavailable = () =>
99
- new Error("reader_unavailable: isolated caller-scoped snapshot unavailable");
100
- function invalidate(error: Error) {
101
- failPending?.(error);
102
- }
103
- function endConnection() {
104
- invalidate(unavailable());
105
- failPending = undefined;
106
- connectionEpoch = ++nextConnectionEpoch;
107
- const old = connection;
108
- connection = undefined;
109
- handle = undefined;
110
- ready = undefined;
111
- ownerKey = "";
112
- old?.disconnect();
113
- }
114
- function currentKey() {
115
- const endpoint = world();
116
- return JSON.stringify([endpoint.url, endpoint.db, hex(current().authenticatedIdentity)]);
117
- }
118
- async function ensureConnection() {
119
- const session = current();
120
- if (!session.conn.isActive || !session.authenticatedToken) throw unavailable();
121
- const endpoint = world();
122
- const key = currentKey();
123
- if (
124
- key !== ownerKey ||
125
- parentConnection !== session.conn ||
126
- (connection !== undefined && !connection.isActive)
127
- ) {
128
- endConnection();
129
- fingerprint = "";
130
- }
131
- if (!connection) {
132
- ownerKey = key;
133
- parentConnection = session.conn;
134
- connectionEpoch = ++nextConnectionEpoch;
135
- const createdEpoch = connectionEpoch;
136
- ready = new Promise<void>((resolve, reject) => {
137
- failPending = reject;
138
- connection = DbConnection.builder()
139
- .withUri(endpoint.url)
140
- .withDatabaseName(endpoint.db)
141
- .withToken(session.authenticatedToken)
142
- .onConnect((_conn, identity) => {
143
- if (createdEpoch !== connectionEpoch || closed) {
144
- reject(unavailable());
145
- return;
146
- }
147
- if (hex(identity) !== hex(session.authenticatedIdentity)) {
148
- reject(unavailable());
149
- endConnection();
150
- } else {
151
- failPending = undefined;
152
- resolve();
153
- }
154
- })
155
- .onConnectError((_ctx, error) => {
156
- if (createdEpoch !== connectionEpoch) return;
157
- reject(error);
158
- invalidate(error);
159
- })
160
- .onDisconnect(() => {
161
- if (createdEpoch !== connectionEpoch) return;
162
- invalidate(unavailable());
163
- ready = undefined;
164
- handle = undefined;
165
- })
166
- .build();
167
- });
168
- }
169
- await ready;
170
- if (
171
- closed ||
172
- !connection?.isActive ||
173
- ownerKey !== key ||
174
- currentKey() !== key ||
175
- current().conn !== parentConnection
176
- )
177
- throw unavailable();
178
- return {
179
- conn: connection,
180
- key,
181
- identity: hex(session.authenticatedIdentity),
182
- world: `${endpoint.url}/${endpoint.db}`,
183
- };
184
- }
185
- async function capture(): Promise<ScopedInstanceSnapshot> {
186
- if (closed) throw unavailable();
187
- let live = await ensureConnection();
188
- if (handle) {
189
- const old = handle;
190
- handle = undefined;
191
- await new Promise<void>((resolve, reject) => {
192
- failPending = reject;
193
- old.unsubscribeThen(() => {
194
- if (closed || connection !== live.conn) {
195
- reject(unavailable());
196
- return;
197
- }
198
- failPending = undefined;
199
- resolve();
200
- });
201
- });
202
- }
203
- const cache = () =>
204
- live.conn.db as unknown as Record<string, { iter(): Iterable<Record<string, unknown>> }>;
205
- const residue = () =>
206
- Object.values(tables).some((table) => [...tableRows(cache(), table)].length !== 0);
207
- if (residue()) {
208
- // The retired group left rows behind: the SDK cache drifted while the
209
- // group was live ("Deleting a row that was not present in the cache",
210
- // sk-jay0.7.123.20.38). A new connection starts empty, so read there.
211
- endConnection();
212
- live = await ensureConnection();
213
- if (residue()) {
214
- endConnection();
215
- throw unavailable();
216
- }
217
- }
218
- const db = cache();
219
- return new Promise<ScopedInstanceSnapshot>((resolve, reject) => {
220
- failPending = reject;
221
- handle = live.conn
222
- .subscriptionBuilder()
223
- .onError(() => {
224
- if (connection !== live.conn) return;
225
- invalidate(unavailable());
226
- endConnection();
227
- })
228
- .onApplied(() => {
229
- // Installed SDK calls onApplied after applying ALL table updates. Copy
230
- // every family synchronously here, before any table callback can yield.
231
- try {
232
- if (
233
- !current().conn.isActive ||
234
- current().conn !== parentConnection ||
235
- live.key !== ownerKey ||
236
- currentKey() !== live.key ||
237
- !live.conn.isActive ||
238
- closed
239
- )
240
- throw unavailable();
241
- const families: Record<string, readonly Record<string, unknown>[]> = {};
242
- for (const [name, table] of Object.entries(tables))
243
- families[name] = freeze(structuredClone([...tableRows(db, table)]));
244
- const coverageRows = families.coverage;
245
- if (
246
- !coverageRows?.length ||
247
- KINDS.some((kind) => !coverageRows.some((row) => row.kind === kind)) ||
248
- coverageRows.some((row) => row.projectionVersion !== 1)
249
- )
250
- throw unavailable();
251
- const scopes = [...new Set(coverageRows.flatMap((row) => row.scopes as string[]))];
252
- if (scopes.length === 0) throw unavailable();
253
- const next = JSON.stringify(
254
- Object.entries(families).map(([name, rows]) => [
255
- name,
256
- rows
257
- .map((row) =>
258
- JSON.stringify(row, (_key, value) =>
259
- typeof value === "bigint" ? String(value) : value,
260
- ),
261
- )
262
- .sort(),
263
- ]),
264
- (_key, value) => (typeof value === "bigint" ? String(value) : value),
265
- );
266
- if (next !== fingerprint) {
267
- fingerprint = next;
268
- sourceEpoch++;
269
- }
270
- const source: ScopedReadSource = freeze({
271
- reads_as_publisher: false,
272
- identity: live.identity,
273
- world: live.world,
274
- connection_epoch: connectionEpoch,
275
- source_epoch: sourceEpoch,
276
- tick: String(coverageRows[0]?.tick ?? 0),
277
- projection_version: 1,
278
- authorized_scopes: scopes,
279
- read_depths: [
280
- ...new Map(
281
- coverageRows.flatMap((row) =>
282
- ((row.readDepths ?? []) as { bindingId: string; depth: { tag: string } }[]).map(
283
- (item) => {
284
- if (item.depth.tag !== "Internal" && item.depth.tag !== "Hidden")
285
- throw unavailable();
286
- const depth =
287
- item.depth.tag === "Internal"
288
- ? ("internal" as const)
289
- : ("hidden" as const);
290
- return [
291
- `${item.bindingId}:${depth}`,
292
- { binding_id: item.bindingId, depth },
293
- ] as const;
294
- },
295
- ),
296
- ),
297
- ).values(),
298
- ],
299
- authorized_bundles: [
300
- ...new Set(coverageRows.flatMap((row) => row.bundleScopes as string[])),
301
- ],
302
- coverage: Object.fromEntries([
303
- ...coverageRows.map((row) => [String(row.kind), String(row.status)]),
304
- [
305
- "binding_context",
306
- families.binding_inventory?.length &&
307
- families.binding_inventory.every(
308
- (row) => row.protocolVersion === 1 && row.expansionComplete === true,
309
- )
310
- ? "scoped"
311
- : "reader_unavailable",
312
- ],
313
- [
314
- "runtime_entity_tag",
315
- String(families.runtime_tag_coverage?.[0]?.status ?? "reader_unavailable"),
316
- ],
317
- [
318
- "pending_context",
319
- String(families.pending_coverage?.[0]?.status ?? "reader_unavailable"),
320
- ],
321
- ]),
322
- labels: ["authored_entities_only"],
323
- });
324
- const snapshot: OwnerSnapshot = {};
325
- for (const [name, rows] of Object.entries(families))
326
- if (name !== "coverage") snapshot[name] = { iter: () => rows };
327
- failPending = undefined;
328
- resolve({ snapshot: freeze(snapshot), source });
329
- } catch {
330
- reject(unavailable());
331
- if (connection === live.conn) endConnection();
332
- }
333
- })
334
- .subscribe(queries);
335
- });
336
- }
337
- return {
338
- read() {
339
- if (pending >= MAX_PENDING_READS) return Promise.reject(unavailable());
340
- pending++;
341
- const result = queue.then(capture, capture);
342
- queue = result
343
- .finally(() => {
344
- pending--;
345
- })
346
- .catch(() => undefined);
347
- return result;
348
- },
349
- close() {
350
- closed = true;
351
- invalidate(unavailable());
352
- endConnection();
353
- },
354
- };
355
- }
package/src/binding.ts DELETED
@@ -1,125 +0,0 @@
1
- // Session identity (#1990 decision 1): a session **is** the tuple
2
- // `(url, db, identity, actorId)`, not a name or a path — ssh's
3
- // `ControlPath %C` pattern. `identity` is deliberately opaque to this module:
4
- // callers supply whatever string distinguishes "who is connecting" for their
5
- // host (a resolved credential token, a `spacetime login` token, a connected
6
- // `Identity.toHexString()` once known) — `binding.ts` only canonicalizes and
7
- // hashes, it never resolves credentials itself, so it stays isomorphic.
8
- //
9
- // Deviation from the #1990 handover comment's literal `{ url, identity,
10
- // actorId }` shape: `db` is included too. Two databases served from the same
11
- // `url` are different worlds with different affordance caches; dropping `db`
12
- // would hash them onto the same socket and daemon.
13
- //
14
- // Canonicalization matters because two spellings of the same endpoint
15
- // (`http://localhost:3000/` vs `http://127.0.0.1:3000`) must hash to the same
16
- // socket — a session daemon is keyed by where a caller SHOULD attach, not by
17
- // how they happened to type it.
18
-
19
- /** The tuple that identifies one live session. */
20
- export interface SessionBinding {
21
- readonly url: string;
22
- readonly db: string;
23
- readonly identity: string;
24
- readonly actorId: string;
25
- }
26
-
27
- /** `SessionBinding` after canonicalization — every field trimmed/normalized. */
28
- export type CanonicalBinding = Readonly<SessionBinding>;
29
-
30
- /**
31
- * Canonicalize a binding's fields for stable hashing:
32
- * - `url`: lowercase scheme/host, `localhost` folded to `127.0.0.1` (avoids
33
- * IPv4/hostname-resolution ambiguity for the loopback case every local
34
- * dev node uses), trailing slash stripped from the path.
35
- * - `db`/`identity`/`actorId`: trimmed. These are opaque identifiers, not
36
- * URLs — no case-folding, since SpacetimeDB database names and identity
37
- * hex strings are case-sensitive.
38
- */
39
- export function canonicalizeBinding(binding: SessionBinding): CanonicalBinding {
40
- return {
41
- url: canonicalizeUrl(binding.url),
42
- db: binding.db.trim(),
43
- identity: binding.identity.trim(),
44
- actorId: binding.actorId.trim(),
45
- };
46
- }
47
-
48
- function canonicalizeUrl(raw: string): string {
49
- const trimmed = raw.trim();
50
- let parsed: URL;
51
- try {
52
- parsed = new URL(trimmed);
53
- } catch {
54
- // Not a well-formed absolute URL (e.g. a bare host:port some caller
55
- // passed through) — fall back to a best-effort string normalization
56
- // rather than throwing. Binding hashing must never fail a caller who
57
- // only wants a stable socket path.
58
- return trimmed.replace(/\/+$/, "");
59
- }
60
- const host =
61
- parsed.hostname.toLowerCase() === "localhost" ? "127.0.0.1" : parsed.hostname.toLowerCase();
62
- const port = parsed.port.length > 0 ? `:${parsed.port}` : "";
63
- const path = parsed.pathname.replace(/\/+$/, "");
64
- return `${parsed.protocol}//${host}${port}${path}`;
65
- }
66
-
67
- /**
68
- * Canonical JSON representation of a binding, with a fixed key order — the
69
- * hash input. Fixed order matters: `JSON.stringify` on an object literal
70
- * already preserves insertion order for string keys, but this function is the
71
- * ONE place that order is decided, so a future field addition can't silently
72
- * reorder existing hashes.
73
- */
74
- export function canonicalBindingJson(binding: SessionBinding): string {
75
- const canonical = canonicalizeBinding(binding);
76
- return JSON.stringify({
77
- url: canonical.url,
78
- db: canonical.db,
79
- identity: canonical.identity,
80
- actorId: canonical.actorId,
81
- });
82
- }
83
-
84
- /** A sha256-hex digest function. Sync or async, so a host may use WebCrypto or `node:crypto`. */
85
- export type Sha256Hex = (input: string) => string | Promise<string>;
86
-
87
- /** Digest length, in hex chars, of {@link hashBinding}'s result — 12 hex chars = 48 bits. */
88
- export const BINDING_HASH_LENGTH = 12;
89
-
90
- /**
91
- * Derive the stable per-binding hash used to key a session's socket path.
92
- * Same binding (after canonicalization) → same hash, from any host, any hash
93
- * implementation — the hasher is injected so this stays isomorphic; the
94
- * default uses WebCrypto (`globalThis.crypto.subtle`), which every modern
95
- * Node and browser runtime provides. `@spellkave/session/node` additionally
96
- * exposes a synchronous `node:crypto`-backed hasher for callers (like socket
97
- * path derivation) that cannot await.
98
- */
99
- export async function hashBinding(
100
- binding: SessionBinding,
101
- sha256: Sha256Hex = webCryptoSha256Hex,
102
- ): Promise<string> {
103
- const digest = await sha256(canonicalBindingJson(binding));
104
- return digest.slice(0, BINDING_HASH_LENGTH);
105
- }
106
-
107
- /** WebCrypto-backed sha256 hex digest — the isomorphic default hasher. */
108
- export async function webCryptoSha256Hex(input: string): Promise<string> {
109
- const subtle = globalThis.crypto?.subtle;
110
- if (subtle === undefined) {
111
- throw new Error(
112
- "webCryptoSha256Hex requires globalThis.crypto.subtle (WebCrypto); pass a Sha256Hex " +
113
- "override on hosts without it, e.g. @spellkave/session/node's node:crypto-backed hasher",
114
- );
115
- }
116
- const bytes = new TextEncoder().encode(input);
117
- const digest = await subtle.digest("SHA-256", bytes);
118
- return bytesToHex(new Uint8Array(digest));
119
- }
120
-
121
- function bytesToHex(bytes: Uint8Array): string {
122
- let out = "";
123
- for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
124
- return out;
125
- }
package/src/index.ts DELETED
@@ -1,24 +0,0 @@
1
- // Isomorphic core: no `node:*` imports anywhere in this barrel's closure.
2
- // Node-only lifecycle (sockets, spawn, credential/fs resolution) lives behind
3
- // the `@spellkave/session/node` subpath — see `./node/index.ts`.
4
-
5
- export * from "./acting-context";
6
- export {
7
- BINDING_HASH_LENGTH,
8
- type CanonicalBinding,
9
- canonicalBindingJson,
10
- canonicalizeBinding,
11
- hashBinding,
12
- type SessionBinding,
13
- type Sha256Hex,
14
- webCryptoSha256Hex,
15
- } from "./binding.ts";
16
- export {
17
- type LiveSession,
18
- type OpenSessionDeps,
19
- OpenSessionTimeoutError,
20
- openSession,
21
- PLAY_CONNECT_PHASE_TIMEOUT_MS,
22
- SessionClosedError,
23
- type SessionPhase,
24
- } from "./session.ts";