@spellkave/session 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +89 -0
  2. package/bin/spellkave-session-daemon.js +5 -0
  3. package/package.json +58 -4
  4. package/src/acting-context.ts +222 -0
  5. package/src/authoring/caller-tools.ts +227 -0
  6. package/src/authoring/index.ts +28 -0
  7. package/src/authoring/live-applyset-port.ts +432 -0
  8. package/src/authoring/live-author-target.ts +995 -0
  9. package/src/authoring/live-can-i-port.ts +152 -0
  10. package/src/authoring/live-exploration-port.ts +274 -0
  11. package/src/authoring/live-grants-port.ts +172 -0
  12. package/src/authoring/live-scenes-port.ts +84 -0
  13. package/src/authoring/live-scoped-instance-port.ts +355 -0
  14. package/src/binding.ts +125 -0
  15. package/src/index.ts +24 -0
  16. package/src/live/discovery-closure-walk.ts +318 -0
  17. package/src/live/kernel-convergence-support.ts +122 -0
  18. package/src/live/seed.ts +37 -0
  19. package/src/live/support.ts +82 -0
  20. package/src/node/client.ts +233 -0
  21. package/src/node/connection-controller.ts +469 -0
  22. package/src/node/daemon-entry.ts +57 -0
  23. package/src/node/daemon.ts +629 -0
  24. package/src/node/index.ts +110 -0
  25. package/src/node/live-delta.ts +229 -0
  26. package/src/node/observability.ts +481 -0
  27. package/src/node/paths.ts +83 -0
  28. package/src/node/player-run-observer.ts +122 -0
  29. package/src/node/protocol.ts +200 -0
  30. package/src/node/spawn.ts +225 -0
  31. package/src/node/world-events.ts +270 -0
  32. package/src/player-tools/delta-tracker.ts +1 -0
  33. package/src/player-tools/index.ts +10 -0
  34. package/src/player-tools/node-adapter.ts +9 -0
  35. package/src/player-tools/observation.ts +1 -0
  36. package/src/player-tools/player-host.ts +92 -0
  37. package/src/player-tools/push-events.ts +1 -0
  38. package/src/player-tools/query-protocol.ts +1 -0
  39. package/src/player-tools/refusal-prose.ts +1 -0
  40. package/src/player-tools/resolution.ts +1 -0
  41. package/src/player-tools/tool-registry.ts +1 -0
  42. package/src/player-tools/tools.ts +42 -0
  43. package/src/player-tools/world-events.ts +119 -0
  44. package/src/session.ts +604 -0
  45. package/README.md +0 -3
@@ -0,0 +1,110 @@
1
+ // Node-only lifecycle: sockets, spawn, and the daemon process. Subpath
2
+ // export `@spellkave/session/node` — the isomorphic core lives at the
3
+ // package root (`@spellkave/session`, `../index.ts`).
4
+
5
+ export {
6
+ type AttachSessionDaemonOptions,
7
+ attachSessionDaemon,
8
+ DEFAULT_SESSION_REQUEST_TIMEOUT_MS,
9
+ type EnsureDaemon,
10
+ requireSessionResult,
11
+ type SendSessionRequestOptions,
12
+ SessionDaemonClient,
13
+ type SessionDaemonHello,
14
+ SessionDaemonProtocolError,
15
+ SessionDaemonResponseError,
16
+ type SessionDaemonStatus,
17
+ SessionDaemonTransportError,
18
+ sendSessionRequest,
19
+ } from "./client.ts";
20
+ export * from "./connection-controller.ts";
21
+ export {
22
+ type DaemonHandle,
23
+ DEFAULT_IDLE_TIMEOUT_MS,
24
+ DEFAULT_METRICS_HEARTBEAT_INTERVAL_MS,
25
+ type DispatcherOptions,
26
+ type InvokableTool,
27
+ type ServeDaemonOptions,
28
+ SessionDispatcher,
29
+ type StartDaemonOptions,
30
+ serveDaemon,
31
+ startDaemon,
32
+ } from "./daemon.ts";
33
+ export {
34
+ type ApplyLiveDeltaOptions,
35
+ applyLiveDelta,
36
+ connectSetupSession,
37
+ isManifestAlreadyApplied,
38
+ } from "./live-delta.ts";
39
+ export {
40
+ type CreateSessionRunObserverOptions,
41
+ createSessionCausalTelemetry,
42
+ createSessionRunObserver,
43
+ DEFAULT_RUN_EVENTS_MAX_BYTES,
44
+ DEFAULT_RUN_EVENTS_ROOT_MAX_BYTES,
45
+ OFF_SESSION_RUN_OBSERVER,
46
+ otlpLogsHeadersFromEnv,
47
+ parseRunEventsMaxBytes,
48
+ parseRunEventsMode,
49
+ parseRunEventsRootMaxBytes,
50
+ RUN_EVENTS_ENV,
51
+ RUN_EVENTS_MAX_BYTES_ENV,
52
+ RUN_EVENTS_MODES,
53
+ RUN_EVENTS_OTLP_ENDPOINT_ENV,
54
+ RUN_EVENTS_ROOT_MAX_BYTES_ENV,
55
+ type RunEventsMode,
56
+ resolveReducerAttemptTelemetry,
57
+ SESSION_METRICS_SERVICE_NAME,
58
+ SESSION_RUN_DRIVER,
59
+ type SessionCausalTelemetry,
60
+ type SessionRunObserver,
61
+ type SessionRunObserverStatus,
62
+ sessionRunArtifactPath,
63
+ } from "./observability.ts";
64
+ export {
65
+ bindingHash12,
66
+ ensureParentDir,
67
+ logPath,
68
+ restrictSocketPermissions,
69
+ runEventsPath,
70
+ runtimeDir,
71
+ sha256HexNode,
72
+ socketPath,
73
+ } from "./paths.ts";
74
+ export * from "./player-run-observer.ts";
75
+ export {
76
+ type DrainPushesRequest,
77
+ type ErrorDetail,
78
+ type ErrResponse,
79
+ encodeFrame,
80
+ type HelloRequest,
81
+ type InvokeRequest,
82
+ isErrResponse,
83
+ isOkResponse,
84
+ isRequest,
85
+ isResponse,
86
+ JsonlFrameDecoder,
87
+ type OkResponse,
88
+ PROTOCOL_VERSION,
89
+ type Request,
90
+ type Response,
91
+ requestId,
92
+ type SessionNotice,
93
+ type ShutdownRequest,
94
+ type StatusRequest,
95
+ } from "./protocol.ts";
96
+ export {
97
+ DAEMON_ENV,
98
+ type DaemonAttachment,
99
+ type DaemonCommand,
100
+ type EnsureDaemonOptions,
101
+ ensureDaemon,
102
+ probeSocket,
103
+ type SpawnDaemonFn,
104
+ type SpawnedProcessLike,
105
+ } from "./spawn.ts";
106
+ export {
107
+ createSessionWorldEventFeed,
108
+ type SessionWorldEventFeed,
109
+ type SessionWorldEventFeedDeps,
110
+ } from "./world-events.ts";
@@ -0,0 +1,229 @@
1
+ // Shared live-delta transport (#1968 "new tests use the verb tools and
2
+ // mutate the LIVE server, not a seed each time" — the operator's test rule,
3
+ // made consequent). Every fast-lane/us9-act/doc-contract world used to be
4
+ // built OFFLINE (an in-memory verb-call harness rendering a scratch
5
+ // manifest.toml) then materialized via a SEPARATE `just seed <file>` step
6
+ // (`r_apply_world_manifest`, the whole-bundle CLI path). This module is the
7
+ // replacement half: connect the SAME persisted local dev credential
8
+ // `just seed`'s own genesis apply uses (`liveNodeToken()`), then submit the
9
+ // already-built, already-validated manifest as ONE live
10
+ // `r_apply_manifest_delta` call (ADR-0085, upsert semantics) — exercising the
11
+ // delta pipeline on every caller's run instead of only in dedicated
12
+ // delta-authoring proofs (US5-7, `sandbox/sk-sndbx-unified-authoring/
13
+ // user-stories/us-live-dungeon.ts`).
14
+ //
15
+ // The VERB-AUTHORING half (`spellkave_author_place`/`spellkave_write_rows`/
16
+ // `spellkave_define_resource`/...) is UNCHANGED and stays fully OFFLINE —
17
+ // each caller still drives an in-memory `memoryWorkspace()` through
18
+ // `createAuthorFacingTools`, exactly as before the port. Only the LAST step
19
+ // (what used to be "write the rendered TOML to `.local/**` and require a
20
+ // separate `just seed <file>`") is replaced by this module's
21
+ // `applyLiveDelta`, which rides the SAME `createLiveAuthorTarget`
22
+ // (`@spellkave/session/authoring`, #1968 "connection-level target" decision) the Pi
23
+ // extension's own `spellkave_apply_manifest_delta` tool uses live —
24
+ // `applyBatch` dispatches through `r_apply_manifest_delta`. After enqueue it
25
+ // waits via `@spellkave/sdk`'s `waitForManifestApplyVerdict` (sk-0m4.45) —
26
+ // the same waiter CLI / sk / Pi / test-lab use — until a new digest seals
27
+ // or a `manifest_apply_outcome` failure row appears. Digest + outcome are
28
+ // not in CONNECTION_BASELINE; this session additively subscribes them.
29
+ //
30
+ // SEAL-WAIT TRANSPORT (#1968 delta seal-poll-floor tuning, 2026-07-24):
31
+ // `waitForManifestSeal` used to poll via `spacetimeSql` — a spawned
32
+ // `spacetime sql` CLI subprocess — on a flat 300ms interval. Baseline
33
+ // measurement (this same issue) found the SERVER side of the drain already
34
+ // seals within roughly one poll cycle for a small delta (the CLI's own
35
+ // `await_manifest_drain`, which reads the LOCAL subscribed cache instead of
36
+ // shelling out, resolves a whole enqueue+drain+seal round trip in ~60-100ms
37
+ // against a core-only world) — the 300ms fixed interval was ADDING latency,
38
+ // not bounding real work. This session now additively subscribes
39
+ // `manifest_apply_digest` once at connect time (mirroring
40
+ // `client/src/cli/manifest.rs`'s own subscribed-cache read and
41
+ // `@spellkave/test-lab`'s `src/live.ts`'s `waitForManifestDrain`) so
42
+ // the wait loop reads the LOCAL cache — no subprocess, no network round trip
43
+ // per poll — at a tight adaptive-backoff interval instead. The TOCTOU note
44
+ // below (ANY new digest, not necessarily this call's own) is unchanged by
45
+ // this transport swap; it was never about polling mechanism.
46
+ //
47
+ // AUTHORITY NOTE: each mechanics fixture authors an explicit system-author
48
+ // binding of the setup identity over its root graph. Publisher/genesis applies
49
+ // realise that independent presence; later deltas use its apply capability.
50
+ // Character identity rows are separate, so character release or takeover does
51
+ // not transfer the setup principal's authority.
52
+ //
53
+ // CANONICAL HOME (#1968 recorded-debt cleanup): the former in-package
54
+ // script/test helper copies have been consolidated into this Node session
55
+ // transport. It owns the live SDK connection and seal wait; session/authoring
56
+ // owns `createLiveAuthorTarget`, while tool-node owns the local credential.
57
+ import {
58
+ connect,
59
+ digestSetFromHandle,
60
+ formatManifestApplyFailure,
61
+ outcomesFromHandle,
62
+ type SpellkaveSession,
63
+ snapshotDb,
64
+ subscribeManifestApplyWait,
65
+ verdictFromManifestApplySnapshots,
66
+ waitForManifestApplyVerdict,
67
+ } from "@spellkave/sdk";
68
+ import { liveNodeToken } from "@spellkave/tool-node";
69
+ import { createLiveAuthorTarget } from "../authoring/index.ts";
70
+
71
+ const URL = process.env.SPELLKAVE_URL ?? "http://127.0.0.1:3000";
72
+ const DB = process.env.SPELLKAVE_DB ?? "spellkave-dev";
73
+ const NOOP_CALLBACKS = { onError: () => {}, onDisconnect: () => {}, onUpdate: () => {} };
74
+ // Drain wait lives in `@spellkave/sdk` (`waitForManifestApplyVerdict`, sk-0m4.45).
75
+
76
+ /**
77
+ * Connect the ONE identity every live-delta caller submits deltas as —
78
+ * `liveNodeToken()`, the persisted local dev credential `just seed`'s own
79
+ * genesis apply used (`src/__tests__/helpers/multiplayer-twin.ts`).
80
+ * `connectedActorId` is provenance-buffer bookkeeping only
81
+ * (`packages/spellkave-sdk/src/connection.ts`) — it need not resolve to a
82
+ * live actor at connect time, since a caller submits manifest deltas, it
83
+ * does not act as anyone. Additively subscribes `manifest_apply_digest`
84
+ * (#1968) so `waitForManifestSeal` can read the local cache instead of
85
+ * shelling out to `spacetime sql` on every poll.
86
+ */
87
+ export async function connectSetupSession(connectedActorId: string): Promise<SpellkaveSession> {
88
+ const session = await connect(
89
+ { url: URL, db: DB, token: liveNodeToken(), connectedActorId },
90
+ NOOP_CALLBACKS,
91
+ );
92
+ await session.ready;
93
+ await subscribeManifestApplyDigest(session);
94
+ return session;
95
+ }
96
+
97
+ /**
98
+ * `manifest_apply_digest` is not in `@spellkave/sdk`'s `CONNECTION_BASELINE`
99
+ * (deliberately — see this file's header); add it to THIS session's own
100
+ * subscription set rather than widening the shared baseline for every
101
+ * caller. One extra round trip paid once at connect time, not per delta.
102
+ */
103
+ async function subscribeManifestApplyDigest(session: SpellkaveSession): Promise<void> {
104
+ await subscribeManifestApplyWait(session.conn.subscriptionBuilder());
105
+ }
106
+
107
+ /**
108
+ * Read `manifest_apply_digest` off the local subscribed cache (no network
109
+ * round trip) — finding ledger entry #5
110
+ * (`packages/spellkave-srd-cc/ledger/findings.md`): the accessor is
111
+ * snake_case on the generated `DbConnection.db` (verified against
112
+ * `@spellkave/bindings`'s schema — table accessors are keyed verbatim by
113
+ * their snake_case schema name, never camelCase), NOT the camelCase-falling-
114
+ * back-to-snake pattern this function used to mirror from
115
+ * `packages/spellkave-sdk/src/connection.ts`. Throws (never silently treats
116
+ * the digest set as empty) if the accessor is entirely missing — a missing
117
+ * `manifest_apply_digest` handle on an already-subscribed session means the
118
+ * table name is wrong, not that no digest has sealed yet, and the caller's
119
+ * seal-wait poll would otherwise spin to its timeout looking like a stalled
120
+ * drain instead of a wiring bug.
121
+ */
122
+ function localManifestDigestSet(session: SpellkaveSession): Set<string> {
123
+ const db = snapshotDb(session);
124
+ const handle = db.manifest_apply_digest;
125
+ if (handle === undefined) {
126
+ throw new Error(
127
+ 'localManifestDigestSet: no accessor "manifest_apply_digest" on the connected db — ' +
128
+ "the live SDK exposes snake_case table names only (never camelCase); check the table name " +
129
+ "against the schema and that this session subscribed it.",
130
+ );
131
+ }
132
+ return digestSetFromHandle(handle);
133
+ }
134
+
135
+ function localManifestOutcomes(session: SpellkaveSession) {
136
+ return outcomesFromHandle(snapshotDb(session).manifest_apply_outcome);
137
+ }
138
+
139
+ /** Opt-in per-phase timing (#1968 seal-poll-floor measurement), gated the
140
+ * same way `@spellkave/test-lab`'s `src/live.ts`'s own
141
+ * `SPELLKAVE_SRD_RUNNER_TIMINGS` is — silent by default, `console.error` (not
142
+ * `.log`, so it never lands in a caller's stdout-parsed output) when enabled. */
143
+ function liveDeltaTiming(label: string, started: number): number {
144
+ const now = Date.now();
145
+ if (process.env.SPELLKAVE_LIVE_DELTA_TIMINGS === "1") {
146
+ console.error(`[live-delta-timing] ${label}: ${now - started}ms`);
147
+ }
148
+ return now;
149
+ }
150
+
151
+ async function waitForManifestSeal(
152
+ session: SpellkaveSession,
153
+ before: Set<string>,
154
+ label: string,
155
+ ): Promise<void> {
156
+ const beforeOutcomes = new Set(localManifestOutcomes(session).map((row) => row.applyId));
157
+ const verdict = await waitForManifestApplyVerdict(
158
+ () =>
159
+ verdictFromManifestApplySnapshots({
160
+ beforeDigests: before,
161
+ currentDigests: localManifestDigestSet(session),
162
+ beforeOutcomeIds: beforeOutcomes,
163
+ currentOutcomes: localManifestOutcomes(session),
164
+ }),
165
+ { label },
166
+ );
167
+ if (verdict.status === "failed") {
168
+ throw new Error(
169
+ `live-delta: [${label}] ${formatManifestApplyFailure(verdict.code, verdict.message)}`,
170
+ );
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Submit `toml` (already offline-validated by the caller) as ONE live
176
+ * `r_apply_manifest_delta` call over `session`, then wait for the drain to
177
+ * seal before returning. Rides `createLiveAuthorTarget` from session/authoring
178
+ * purely for its `applyBatch` semantics — no read-side ref-checks are needed
179
+ * here, the authoring phase that built `toml` already ran fully offline
180
+ * against its own scratch workspace.
181
+ *
182
+ * Throws on a genuine apply failure. Exact-digest resubmits can opt into
183
+ * treating `MF-APPLY-012` as an idempotent success; the default remains
184
+ * fail-loud so existing callers keep their current contract.
185
+ */
186
+ export interface ApplyLiveDeltaOptions {
187
+ tolerateAlreadyApplied?: boolean;
188
+ }
189
+
190
+ /** Pure error classifier kept beside the transport so tolerance is testable
191
+ * without a live node. SpacetimeDB's SenderError string carries the stable
192
+ * server code; the prose fallback covers wrapped errors that retain only the
193
+ * server message. */
194
+ export function isManifestAlreadyApplied(error: unknown): boolean {
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ return message.includes("MF-APPLY-012") || message.includes("manifest already applied");
197
+ }
198
+
199
+ export async function applyLiveDelta(
200
+ session: SpellkaveSession,
201
+ toml: string,
202
+ label: string,
203
+ options: ApplyLiveDeltaOptions = {},
204
+ ): Promise<void> {
205
+ const target = createLiveAuthorTarget({
206
+ db: () => snapshotDb(session),
207
+ applyDelta: async (deltaToml) => {
208
+ let t = Date.now();
209
+ const before = localManifestDigestSet(session);
210
+ try {
211
+ await session.conn.reducers.rApplyManifestDelta({ toml: deltaToml });
212
+ } catch (error) {
213
+ if (options.tolerateAlreadyApplied && isManifestAlreadyApplied(error)) {
214
+ return { ok: true };
215
+ }
216
+ throw error;
217
+ }
218
+ t = liveDeltaTiming(`[${label}] enqueue`, t);
219
+ await waitForManifestSeal(session, before, label);
220
+ liveDeltaTiming(`[${label}] seal-wait`, t);
221
+ return { ok: true };
222
+ },
223
+ });
224
+ const result = await target.applyBatch(toml);
225
+ if (!result.ok) {
226
+ throw new Error(`live-delta: [${label}] apply failed — ${result.detail ?? "unknown error"}`);
227
+ }
228
+ console.log(`[live-delta] [${label}] applied live (${toml.split("\n").length} lines).`);
229
+ }