@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,233 @@
1
+ // Host-neutral client for the binding-keyed session daemon. Hosts attach by
2
+ // SessionBinding, then speak the generic JSONL protocol; PLAYER tool membership
3
+ // remains in session-owned player-tools and never appears here.
4
+
5
+ import * as net from "node:net";
6
+ import {
7
+ normalizeWorldActorCausalContext,
8
+ type WorldActorCausalContext,
9
+ } from "@spellkave/agent-observability";
10
+ import type { SessionBinding } from "../binding.ts";
11
+ import {
12
+ type ErrResponse,
13
+ encodeFrame,
14
+ isOkResponse,
15
+ isResponse,
16
+ JsonlFrameDecoder,
17
+ type Request,
18
+ type Response,
19
+ } from "./protocol.ts";
20
+ import { type DaemonAttachment, type EnsureDaemonOptions, ensureDaemon } from "./spawn.ts";
21
+
22
+ export const DEFAULT_SESSION_REQUEST_TIMEOUT_MS = 15_000;
23
+
24
+ export type EnsureDaemon = (
25
+ binding: SessionBinding,
26
+ options?: EnsureDaemonOptions,
27
+ ) => Promise<DaemonAttachment>;
28
+
29
+ export interface SendSessionRequestOptions {
30
+ timeoutMs?: number;
31
+ }
32
+
33
+ export interface AttachSessionDaemonOptions extends EnsureDaemonOptions {
34
+ /** Injectable attach/spawn seam for tests and hosts with their own process supervisor. */
35
+ ensureDaemonFn?: EnsureDaemon;
36
+ requestTimeoutMs?: number;
37
+ }
38
+
39
+ export interface SessionDaemonHello {
40
+ protocol: number;
41
+ binding: SessionBinding;
42
+ }
43
+
44
+ export interface SessionDaemonStatus {
45
+ binding: SessionBinding;
46
+ uptimeMs: number;
47
+ subscribed: boolean;
48
+ observability: {
49
+ mode: string;
50
+ artifactPath?: string;
51
+ logsProjection?: "configured" | "disabled";
52
+ tracesProjection?: "configured" | "disabled";
53
+ metricsProjection?: "configured" | "disabled";
54
+ };
55
+ }
56
+
57
+ export class SessionDaemonResponseError extends Error {
58
+ readonly code: string | undefined;
59
+ readonly requestId: number;
60
+
61
+ constructor(response: ErrResponse) {
62
+ super(response.error.message);
63
+ this.name = "SessionDaemonResponseError";
64
+ this.code = response.error.code;
65
+ this.requestId = response.id;
66
+ }
67
+ }
68
+
69
+ export class SessionDaemonProtocolError extends Error {
70
+ constructor(message: string) {
71
+ super(message);
72
+ this.name = "SessionDaemonProtocolError";
73
+ }
74
+ }
75
+
76
+ export class SessionDaemonTransportError extends Error {
77
+ readonly socketPath: string;
78
+ readonly transportCode: string | undefined;
79
+
80
+ constructor(socketPath: string, message: string, cause?: unknown) {
81
+ super(`session daemon request failed at ${socketPath}: ${message}`, { cause });
82
+ this.name = "SessionDaemonTransportError";
83
+ this.socketPath = socketPath;
84
+ this.transportCode =
85
+ typeof cause === "object" && cause !== null && "code" in cause
86
+ ? String((cause as { code: unknown }).code)
87
+ : undefined;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * One validated request/response round trip over an already-listening daemon
93
+ * socket. The returned daemon error frame is intentionally not thrown so a
94
+ * host can map its stable code into its own protocol without losing detail.
95
+ */
96
+ export function sendSessionRequest<R = unknown>(
97
+ socketPath: string,
98
+ request: Request,
99
+ options: SendSessionRequestOptions = {},
100
+ ): Promise<Response<R>> {
101
+ return new Promise((resolve, reject) => {
102
+ const socket = net.createConnection(socketPath);
103
+ const decoder = new JsonlFrameDecoder();
104
+ const timeoutMs = options.timeoutMs ?? DEFAULT_SESSION_REQUEST_TIMEOUT_MS;
105
+ let settled = false;
106
+
107
+ const finish = (operation: () => void): void => {
108
+ if (settled) return;
109
+ settled = true;
110
+ clearTimeout(timer);
111
+ socket.removeAllListeners();
112
+ socket.destroy();
113
+ operation();
114
+ };
115
+ const failTransport = (message: string, cause?: unknown): void =>
116
+ finish(() => reject(new SessionDaemonTransportError(socketPath, message, cause)));
117
+ const timer = setTimeout(() => failTransport(`timed out after ${timeoutMs}ms`), timeoutMs);
118
+
119
+ socket.setEncoding("utf8");
120
+ socket.once("connect", () => socket.write(encodeFrame(request)));
121
+ socket.on("data", (chunk: string) => {
122
+ let frames: unknown[];
123
+ try {
124
+ frames = decoder.push(chunk);
125
+ } catch (error) {
126
+ failTransport("received malformed JSON", error);
127
+ return;
128
+ }
129
+ if (frames.length === 0) return;
130
+ const response = frames[0];
131
+ if (!isResponse(response)) {
132
+ finish(() =>
133
+ reject(new SessionDaemonProtocolError("daemon returned a malformed response")),
134
+ );
135
+ return;
136
+ }
137
+ if (response.id !== request.id) {
138
+ finish(() =>
139
+ reject(
140
+ new SessionDaemonProtocolError(
141
+ `daemon response id ${response.id} does not match request id ${request.id}`,
142
+ ),
143
+ ),
144
+ );
145
+ return;
146
+ }
147
+ finish(() => resolve(response as Response<R>));
148
+ });
149
+ socket.once("error", (error) => failTransport(error.message, error));
150
+ socket.once("end", () => failTransport("connection ended before a response"));
151
+ });
152
+ }
153
+
154
+ export function requireSessionResult<R>(response: Response<R>): R {
155
+ if (isOkResponse(response)) return response.result as R;
156
+ throw new SessionDaemonResponseError(response);
157
+ }
158
+
159
+ /** A lightweight host client; each call opens one socket while the daemon keeps the session alive. */
160
+ export class SessionDaemonClient {
161
+ readonly attachment: DaemonAttachment;
162
+ private readonly requestTimeoutMs: number;
163
+ private nextId = 1;
164
+
165
+ constructor(attachment: DaemonAttachment, requestTimeoutMs = DEFAULT_SESSION_REQUEST_TIMEOUT_MS) {
166
+ this.attachment = attachment;
167
+ this.requestTimeoutMs = requestTimeoutMs;
168
+ }
169
+
170
+ request<R = unknown>(request: Request): Promise<Response<R>> {
171
+ return sendSessionRequest<R>(this.attachment.socketPath, request, {
172
+ timeoutMs: this.requestTimeoutMs,
173
+ });
174
+ }
175
+
176
+ hello(): Promise<Response<SessionDaemonHello>> {
177
+ return this.request({ id: this.requestId(), op: "hello" });
178
+ }
179
+
180
+ async toolNames(): Promise<Response<string[]>> {
181
+ const response = await this.request<string[]>({ id: this.requestId(), op: "list_tools" });
182
+ // A v1 predecessor refuses this additive operation. Gateway-first rollback
183
+ // preserves its shipped PLAYER surface without inferring elevated rights.
184
+ if (!response.ok && response.error.code === "bad_request") {
185
+ const { PLAYER_TOOL_NAMES } = await import("@spellkave/tool-contracts");
186
+ return { id: response.id, ok: true, result: [...PLAYER_TOOL_NAMES] };
187
+ }
188
+ return response;
189
+ }
190
+
191
+ status(): Promise<Response<SessionDaemonStatus>> {
192
+ return this.request({ id: this.requestId(), op: "status" });
193
+ }
194
+
195
+ invoke<R = unknown>(
196
+ tool: string,
197
+ args: unknown,
198
+ causalContext?: WorldActorCausalContext,
199
+ ): Promise<Response<R>> {
200
+ const causal_context = normalizeWorldActorCausalContext(causalContext);
201
+ return this.request({
202
+ id: this.requestId(),
203
+ op: "invoke",
204
+ tool,
205
+ args,
206
+ ...(causal_context === undefined ? {} : { causal_context }),
207
+ });
208
+ }
209
+
210
+ drainPushes(): Promise<Response<Record<string, never>>> {
211
+ return this.request({ id: this.requestId(), op: "drain_pushes" });
212
+ }
213
+
214
+ shutdown(): Promise<Response<Record<string, never>>> {
215
+ return this.request({ id: this.requestId(), op: "shutdown" });
216
+ }
217
+
218
+ private requestId(): number {
219
+ const id = this.nextId;
220
+ this.nextId += 1;
221
+ return id;
222
+ }
223
+ }
224
+
225
+ /** Attach or spawn by binding; callers can issue `hello()` when they need the binding echo. */
226
+ export async function attachSessionDaemon(
227
+ binding: SessionBinding,
228
+ options: AttachSessionDaemonOptions = {},
229
+ ): Promise<SessionDaemonClient> {
230
+ const { ensureDaemonFn = ensureDaemon, requestTimeoutMs, ...ensureOptions } = options;
231
+ const attachment = await ensureDaemonFn(binding, ensureOptions);
232
+ return new SessionDaemonClient(attachment, requestTimeoutMs);
233
+ }
@@ -0,0 +1,469 @@
1
+ import {
2
+ type ActorClient,
3
+ checkedProfileFile,
4
+ type PersonaProfile,
5
+ type ReducerAttemptTelemetry,
6
+ type SpellkaveSession,
7
+ } from "@spellkave/sdk";
8
+ import {
9
+ loadProfileFromDisk,
10
+ readLastUsedProfile,
11
+ resolveCliPaths,
12
+ resolveConnection,
13
+ resolveCredential,
14
+ resolveSpacetimeLoginToken,
15
+ writeLastUsedProfile,
16
+ } from "@spellkave/sdk/node";
17
+ import { type Static, Type } from "typebox";
18
+ import { openSession, type SessionBinding } from "../index.ts";
19
+ import { sha256HexNode } from "./paths.ts";
20
+
21
+ const BUILT_IN_URL = "http://127.0.0.1:3000";
22
+ const BUILT_IN_DB = "spellkave-dev";
23
+ const CONFIG_ERROR = "Connection configuration or credential reference could not be resolved.";
24
+ const CONNECT_ERROR = "Spellkave connection failed before activation.";
25
+ export const NO_VALID_PROFILE_RECOVERY =
26
+ "No valid player profile. Pass `profile` (or url, db, and actor) to spellkave_connect, or run `just play-stage <adventure>` so a seat is staged. Clear a stale last-used pointer with `spellkave profile forget-last-used`.";
27
+
28
+ function deadActorRecovery(actor: string, db: string, profile?: string): string {
29
+ const from = profile === undefined ? "" : ` (profile '${profile}')`;
30
+ return (
31
+ `Actor '${actor}' is not in database '${db}'${from}. That pointer is from a previous adventure. ` +
32
+ "Pass a current `profile` to spellkave_connect or run `just play-stage <adventure>`."
33
+ );
34
+ }
35
+
36
+ function isMissingActorError(error: unknown): boolean {
37
+ const message = error instanceof Error ? error.message : String(error);
38
+ return message.includes("not found in live actor_spatial_location");
39
+ }
40
+
41
+ /** BSATN / bindings-vs-module mismatch often surfaces as uncaughtException and kills Pi (#1260 class). */
42
+ function isSchemaMismatchError(error: unknown): boolean {
43
+ const message = error instanceof Error ? error.message : String(error);
44
+ const name = error instanceof Error ? error.name : "";
45
+ return (
46
+ name === "RangeError" || /byte\(s\)|BSATN|deserializ|Tried to read \d+ byte/i.test(message)
47
+ );
48
+ }
49
+
50
+ function schemaMismatchMessage(error: unknown): string {
51
+ const detail = error instanceof Error ? error.message : String(error);
52
+ return (
53
+ `Spellkave connection failed: client bindings/schema mismatch while reading the module (${detail}). ` +
54
+ "The campaign DB was likely provisioned with an older server.wasm than this worktree. " +
55
+ "Fix: spellkave_campaign_rebuild_reset { run_id, confirm: true } " +
56
+ "(or just campaign-host-rebuild && just campaign-reset <new-run-id>)."
57
+ );
58
+ }
59
+
60
+ /**
61
+ * Route connect-time SDK throws (async onmessage / uncaughtException) onto the
62
+ * connect promise instead of killing the Pi process. Mirrors connectTestWorld's
63
+ * #1260 failfast, plus uncaughtException (the live crash we hit on campaign connect).
64
+ */
65
+ async function withConnectFailfast<T>(run: () => Promise<T>): Promise<T> {
66
+ return await new Promise<T>((resolve, reject) => {
67
+ let settled = false;
68
+ const cleanup = () => {
69
+ process.off("uncaughtException", onUncaught);
70
+ process.off("unhandledRejection", onRejection);
71
+ };
72
+ const fail = (reason: unknown) => {
73
+ if (settled) return;
74
+ settled = true;
75
+ cleanup();
76
+ if (isSchemaMismatchError(reason)) {
77
+ reject(new Error(schemaMismatchMessage(reason)));
78
+ return;
79
+ }
80
+ reject(reason instanceof Error ? reason : new Error(String(reason)));
81
+ };
82
+ const onUncaught = (err: Error) => fail(err);
83
+ const onRejection = (reason: unknown) => fail(reason);
84
+ process.on("uncaughtException", onUncaught);
85
+ process.on("unhandledRejection", onRejection);
86
+ void run().then(
87
+ (value) => {
88
+ if (settled) return;
89
+ settled = true;
90
+ cleanup();
91
+ resolve(value);
92
+ },
93
+ (error) => fail(error),
94
+ );
95
+ });
96
+ }
97
+
98
+ const CREDENTIAL_REFERENCE = Type.Union([
99
+ Type.Object({
100
+ source: Type.Literal("env_var"),
101
+ name: Type.String({ minLength: 1 }),
102
+ }),
103
+ Type.Object({
104
+ source: Type.Literal("file"),
105
+ path: Type.String({ minLength: 1 }),
106
+ }),
107
+ Type.Object({ source: Type.Literal("spacetime_login") }),
108
+ ]);
109
+
110
+ export const CONNECT_PARAMETERS = Type.Object({
111
+ profile: Type.Optional(Type.String({ minLength: 1 })),
112
+ url: Type.Optional(Type.String({ minLength: 1 })),
113
+ db: Type.Optional(Type.String({ minLength: 1 })),
114
+ actor: Type.Optional(Type.String({ minLength: 1 })),
115
+ credential: Type.Optional(CREDENTIAL_REFERENCE),
116
+ });
117
+
118
+ export const DISCONNECT_PARAMETERS = Type.Object({});
119
+
120
+ export type ConnectToolInput = Static<typeof CONNECT_PARAMETERS>;
121
+
122
+ export interface SessionPort {
123
+ conn: unknown;
124
+ ready: Promise<void>;
125
+ /** Present on real SDK sessions; optional so controller unit fakes stay minimal. */
126
+ estimator?: SpellkaveSession["estimator"];
127
+ /** Present on real SDK sessions; optional so controller unit fakes stay minimal. */
128
+ worldEvents?: SpellkaveSession["worldEvents"];
129
+ disconnect(): void;
130
+ }
131
+
132
+ /**
133
+ * The result of opening one connect -> resolve-actor -> actor-client ->
134
+ * subscribe-affordance-cache sequence — `@spellkave/session`'s `openSession`
135
+ * bundled into a single deps seam. `createSdkConnectionController` delegates
136
+ * to `openSession` for this (#1990/#1983); tests inject a fake.
137
+ */
138
+ export interface OpenedConnection {
139
+ session: SessionPort;
140
+ onUpdate?: (notify: (table?: string) => void) => () => void;
141
+ /** The resolved actor id — same value as the requested `actor`, after direct-control validation. */
142
+ actorId: string;
143
+ actorClient: ActorClient;
144
+ }
145
+
146
+ export interface ConnectionControllerDeps {
147
+ resolveSharedConnection(input: { profile?: string; url?: string; db?: string }): {
148
+ url: string;
149
+ db: string;
150
+ profile?: string;
151
+ };
152
+ loadProfile(name: string): PersonaProfile;
153
+ resolveCredential(
154
+ ref:
155
+ | { kind: "env_var"; name: string }
156
+ | { kind: "file"; path: string }
157
+ | { kind: "inline"; value: string },
158
+ ): string;
159
+ resolveHostLogin(): string;
160
+ openConnection(
161
+ input: { url: string; db: string; actor: string; token?: string },
162
+ callbacks: { onDisconnect(error?: Error): void },
163
+ ): Promise<OpenedConnection>;
164
+ rememberProfile(name: string): void;
165
+ }
166
+
167
+ export interface ActiveConnection {
168
+ session: SessionPort;
169
+ onUpdate?: (notify: (table?: string) => void) => () => void;
170
+ actor: string;
171
+ actorClient: ActorClient;
172
+ url: string;
173
+ db: string;
174
+ profile?: string;
175
+ }
176
+
177
+ export type ConnectionResult =
178
+ | { ok: true; actor: string; url: string; db: string; profile?: string }
179
+ | { ok: false; error: string };
180
+
181
+ export interface ConnectionController {
182
+ connect(input: ConnectToolInput): Promise<ConnectionResult>;
183
+ disconnect(): Promise<void>;
184
+ active(): ActiveConnection | undefined;
185
+ onDisconnected(listener: () => void): () => void;
186
+ }
187
+
188
+ interface EffectiveConnection {
189
+ url: string;
190
+ db: string;
191
+ actor: string;
192
+ token: string;
193
+ profile?: string;
194
+ }
195
+
196
+ export function createConnectionController(deps: ConnectionControllerDeps): ConnectionController {
197
+ let current: ActiveConnection | undefined;
198
+ let candidate: SessionPort | undefined;
199
+ let nextAttempt = 0;
200
+ let pendingAttempt: number | undefined;
201
+ const closed = new WeakSet<object>();
202
+ const disconnectedListeners = new Set<() => void>();
203
+
204
+ function notifyDisconnected(): void {
205
+ for (const listener of disconnectedListeners) listener();
206
+ }
207
+
208
+ function close(session: SessionPort): void {
209
+ if (closed.has(session)) return;
210
+ closed.add(session);
211
+ session.disconnect();
212
+ }
213
+
214
+ function clearOwned(session: SessionPort): void {
215
+ const owned = candidate === session || current?.session === session;
216
+ if (candidate === session) candidate = undefined;
217
+ if (current?.session === session) current = undefined;
218
+ close(session);
219
+ if (owned) notifyDisconnected();
220
+ }
221
+
222
+ function resolveEffective(input: ConnectToolInput): EffectiveConnection {
223
+ const directOnly =
224
+ input.url !== undefined &&
225
+ input.db !== undefined &&
226
+ input.actor !== undefined &&
227
+ input.profile === undefined;
228
+ if (directOnly) {
229
+ return {
230
+ url: input.url!,
231
+ db: input.db!,
232
+ actor: input.actor!,
233
+ token: resolveInputCredential(input, deps),
234
+ };
235
+ }
236
+
237
+ const resolved = deps.resolveSharedConnection({
238
+ ...(input.profile === undefined ? {} : { profile: input.profile }),
239
+ ...(input.url === undefined ? {} : { url: input.url }),
240
+ ...(input.db === undefined ? {} : { db: input.db }),
241
+ });
242
+ if (resolved.profile === undefined) {
243
+ throw new Error(NO_VALID_PROFILE_RECOVERY);
244
+ }
245
+ const selected = deps.loadProfile(resolved.profile);
246
+ const actor = input.actor ?? selected.identity.in_world_self;
247
+ const token =
248
+ input.credential === undefined
249
+ ? selected.identity.credential === undefined
250
+ ? deps.resolveHostLogin()
251
+ : deps.resolveCredential(selected.identity.credential)
252
+ : resolveInputCredential(input, deps);
253
+ return {
254
+ url: resolved.url,
255
+ db: resolved.db,
256
+ actor,
257
+ token,
258
+ profile: resolved.profile,
259
+ };
260
+ }
261
+
262
+ return {
263
+ async connect(input) {
264
+ if (current !== undefined || candidate !== undefined || pendingAttempt !== undefined) {
265
+ return {
266
+ ok: false,
267
+ error: "Disconnect the active Spellkave session before connecting again.",
268
+ };
269
+ }
270
+
271
+ const attempt = ++nextAttempt;
272
+ pendingAttempt = attempt;
273
+ let effective: EffectiveConnection;
274
+ try {
275
+ effective = resolveEffective(input);
276
+ } catch (error) {
277
+ if (pendingAttempt === attempt) pendingAttempt = undefined;
278
+ const message = error instanceof Error ? error.message : String(error);
279
+ if (message === NO_VALID_PROFILE_RECOVERY) {
280
+ return { ok: false, error: NO_VALID_PROFILE_RECOVERY };
281
+ }
282
+ return { ok: false, error: CONFIG_ERROR };
283
+ }
284
+
285
+ let opened: OpenedConnection | undefined;
286
+ let disconnectedBeforeOwnership = false;
287
+ try {
288
+ opened = await withConnectFailfast(() =>
289
+ deps.openConnection(
290
+ {
291
+ url: effective.url,
292
+ db: effective.db,
293
+ actor: effective.actor,
294
+ token: effective.token,
295
+ },
296
+ {
297
+ onDisconnect: () => {
298
+ if (opened === undefined) {
299
+ disconnectedBeforeOwnership = true;
300
+ return;
301
+ }
302
+ clearOwned(opened.session);
303
+ },
304
+ },
305
+ ),
306
+ );
307
+ if (pendingAttempt !== attempt) {
308
+ close(opened.session);
309
+ return { ok: false, error: CONNECT_ERROR };
310
+ }
311
+ candidate = opened.session;
312
+ if (disconnectedBeforeOwnership) throw new Error("transport disconnected during connect");
313
+
314
+ current = {
315
+ session: opened.session,
316
+ onUpdate: opened.onUpdate,
317
+ actor: opened.actorId,
318
+ actorClient: opened.actorClient,
319
+ url: effective.url,
320
+ db: effective.db,
321
+ ...(effective.profile === undefined ? {} : { profile: effective.profile }),
322
+ };
323
+ candidate = undefined;
324
+ if (effective.profile !== undefined) {
325
+ try {
326
+ deps.rememberProfile(effective.profile);
327
+ } catch {
328
+ // Remembered profile is convenience state, never connection authority.
329
+ }
330
+ }
331
+ return {
332
+ ok: true,
333
+ actor: opened.actorId,
334
+ url: effective.url,
335
+ db: effective.db,
336
+ ...(effective.profile === undefined ? {} : { profile: effective.profile }),
337
+ };
338
+ } catch (error) {
339
+ if (opened !== undefined) clearOwned(opened.session);
340
+ if (isMissingActorError(error)) {
341
+ return {
342
+ ok: false,
343
+ error: deadActorRecovery(effective.actor, effective.db, effective.profile),
344
+ };
345
+ }
346
+ return {
347
+ ok: false,
348
+ error: isSchemaMismatchError(error)
349
+ ? schemaMismatchMessage(error)
350
+ : error instanceof Error && error.message.startsWith("Spellkave connection failed:")
351
+ ? error.message
352
+ : CONNECT_ERROR,
353
+ };
354
+ } finally {
355
+ if (pendingAttempt === attempt) pendingAttempt = undefined;
356
+ }
357
+ },
358
+
359
+ async disconnect() {
360
+ pendingAttempt = undefined;
361
+ const owned = current?.session ?? candidate;
362
+ current = undefined;
363
+ candidate = undefined;
364
+ if (owned !== undefined) {
365
+ close(owned);
366
+ notifyDisconnected();
367
+ }
368
+ },
369
+
370
+ active() {
371
+ return current;
372
+ },
373
+
374
+ onDisconnected(listener) {
375
+ disconnectedListeners.add(listener);
376
+ return () => disconnectedListeners.delete(listener);
377
+ },
378
+ };
379
+ }
380
+
381
+ function resolveInputCredential(input: ConnectToolInput, deps: ConnectionControllerDeps): string {
382
+ const ref = input.credential;
383
+ if (ref === undefined || ref.source === "spacetime_login") {
384
+ return deps.resolveHostLogin();
385
+ }
386
+ if (ref.source === "env_var") {
387
+ return deps.resolveCredential({ kind: "env_var", name: ref.name });
388
+ }
389
+ return deps.resolveCredential({ kind: "file", path: ref.path });
390
+ }
391
+
392
+ function lastUsedProfileIsUsable(name: string, paths: ReturnType<typeof resolveCliPaths>): boolean {
393
+ try {
394
+ const selected = loadProfileFromDisk(checkedProfileFile(paths, name));
395
+ if (selected.identity.credential !== undefined) {
396
+ resolveCredential(selected.identity.credential);
397
+ }
398
+ return true;
399
+ } catch {
400
+ return false;
401
+ }
402
+ }
403
+
404
+ export function createSdkConnectionController(
405
+ options: { reducerAttemptTelemetry?: ReducerAttemptTelemetry } = {},
406
+ ): ConnectionController {
407
+ const paths = resolveCliPaths();
408
+ return createConnectionController({
409
+ resolveSharedConnection(input) {
410
+ let lastUsed = input.profile === undefined ? readLastUsedProfile(paths) : undefined;
411
+ if (lastUsed !== undefined && !lastUsedProfileIsUsable(lastUsed, paths)) {
412
+ lastUsed = undefined;
413
+ }
414
+ const resolved = resolveConnection(input, {
415
+ paths,
416
+ built_in_url: BUILT_IN_URL,
417
+ built_in_db: BUILT_IN_DB,
418
+ last_used_profile: lastUsed,
419
+ });
420
+ return {
421
+ url: resolved.url,
422
+ db: resolved.db,
423
+ ...(resolved.profile === undefined ? {} : { profile: resolved.profile }),
424
+ };
425
+ },
426
+ loadProfile(name) {
427
+ return loadProfileFromDisk(checkedProfileFile(paths, name));
428
+ },
429
+ resolveCredential,
430
+ resolveHostLogin: resolveSpacetimeLoginToken,
431
+ async openConnection(input, callbacks) {
432
+ // Credential/profile resolution happened above this seam (resolveEffective,
433
+ // deps.resolveCredential/resolveHostLogin) — `@spellkave/session`'s
434
+ // `openSession` deliberately excludes it (see `binding.ts`'s module
435
+ // comment) and starts from an already-resolved binding + token, exactly
436
+ // what this deps function builds. Convention (#1992, mirrored in
437
+ // `packages/spellkave-cli`'s `resolveLiveToken` wiring): `binding.identity`
438
+ // is the sha256 hex of the resolved token, never the raw secret — the
439
+ // binding is a value object any future consumer may echo, hash, or log.
440
+ // The raw token still flows separately via `token` below.
441
+ const binding: SessionBinding = {
442
+ url: input.url,
443
+ db: input.db,
444
+ identity: input.token === undefined ? "anonymous" : sha256HexNode(input.token),
445
+ actorId: input.actor,
446
+ };
447
+ const live = await openSession(binding, {
448
+ authorityTools: true,
449
+ token: input.token,
450
+ onDisconnect: callbacks.onDisconnect,
451
+ actorClientOptions: {
452
+ // Generic PLAYER tools cannot provide a world-state predicate for
453
+ // every authored action; the server's successful provenance is
454
+ // authoritative — `openSession` already sets `successOnProvenance`.
455
+ reducerAttemptTelemetry: options.reducerAttemptTelemetry,
456
+ },
457
+ });
458
+ return {
459
+ session: live.session,
460
+ onUpdate: (notify) => live.onUpdate(notify),
461
+ actorId: live.actorId,
462
+ actorClient: live.actorClient,
463
+ };
464
+ },
465
+ rememberProfile(name) {
466
+ writeLastUsedProfile(paths, name);
467
+ },
468
+ });
469
+ }