@spellkave/session 0.0.0-bootstrap

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 (44) hide show
  1. package/LICENSE +89 -0
  2. package/bin/spellkave-session-daemon.js +5 -0
  3. package/package.json +60 -0
  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
@@ -0,0 +1,57 @@
1
+ // Process entry point for the session daemon (#1990). Spawned by
2
+ // `spawn.ts`'s `ensureDaemon` (default command) via
3
+ // `bin/spellkave-session-daemon.js`. Reads its binding from the ENVIRONMENT,
4
+ // never argv — `spawn.ts` sets these vars itself, so a token never appears in
5
+ // a `ps`-visible command line.
6
+
7
+ import type { SessionBinding } from "../binding.ts";
8
+ import { startDaemon } from "./daemon.ts";
9
+ import { DAEMON_ENV } from "./spawn.ts";
10
+
11
+ function readBinding(): SessionBinding {
12
+ const raw = process.env[DAEMON_ENV.binding];
13
+ if (raw === undefined || raw.length === 0) {
14
+ throw new Error(`${DAEMON_ENV.binding} is required to start the session daemon`);
15
+ }
16
+ return JSON.parse(raw) as SessionBinding;
17
+ }
18
+
19
+ async function main(): Promise<void> {
20
+ const binding = readBinding();
21
+ const socketPath = process.env[DAEMON_ENV.socket];
22
+ const token = process.env[DAEMON_ENV.token];
23
+ const idleTimeoutRaw = process.env[DAEMON_ENV.idleTimeoutMs];
24
+ const handle = await startDaemon({
25
+ binding,
26
+ ...(socketPath === undefined ? {} : { socketPath }),
27
+ ...(token === undefined ? {} : { token }),
28
+ ...(idleTimeoutRaw === undefined ? {} : { idleTimeoutMs: Number(idleTimeoutRaw) }),
29
+ // sk-uglp: the daemon already closed its socket + session; nothing
30
+ // useful is left in this process. Exit so the next attach spawns fresh.
31
+ onWorldConnectionLost: () => {
32
+ process.stderr.write(
33
+ "spellkave-session-daemon: world connection lost (reset/redeploy?) — exiting so the next attach starts fresh\n",
34
+ );
35
+ process.exit(0);
36
+ },
37
+ });
38
+
39
+ // #2003: a run observer opened by `startDaemon` must get a terminal
40
+ // "error" status even when the daemon dies from something neither the
41
+ // `shutdown` op nor the idle-check loop caught — a crash, not a clean
42
+ // lifecycle end. Best-effort: `handle.close` never throws (its own
43
+ // `observability.end`/`onClose` swallow their own failures).
44
+ function crash(kind: string, err: unknown): void {
45
+ const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
46
+ process.stderr.write(`spellkave-session-daemon: ${kind}: ${message}\n`);
47
+ void handle.close("error").finally(() => process.exit(1));
48
+ }
49
+ process.on("uncaughtException", (err) => crash("uncaught exception", err));
50
+ process.on("unhandledRejection", (reason) => crash("unhandled rejection", reason));
51
+ }
52
+
53
+ main().catch((err: unknown) => {
54
+ const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
55
+ process.stderr.write(`spellkave-session-daemon: ${message}\n`);
56
+ process.exitCode = 1;
57
+ });
@@ -0,0 +1,629 @@
1
+ // Session daemon host (#1990 decision 3/4): one process, one binding, one
2
+ // live session, dispatching `invoke` frames against the PLAYER tool registry
3
+ // over a unix socket. Split into two layers so the protocol logic is
4
+ // testable without a live SpacetimeDB node:
5
+ //
6
+ // - `SessionDispatcher` — pure frame-in/response-out + idle bookkeeping.
7
+ // No `node:net`, no live session. Tests drive it directly.
8
+ // - `serveDaemon` — binds the socket, wires `JsonlFrameDecoder` to the
9
+ // dispatcher, and owns the idle-check loop. Accepts an already-built
10
+ // tool list, so tests can prove the real IPC roundtrip over a real
11
+ // temp-dir unix socket with a FAKE tool registry — no live node.
12
+ // - `startDaemon` — the production entry point: opens ONE session (core
13
+ // `openSession`), builds the shared PLAYER tools from it, and
14
+ // delegates to `serveDaemon`.
15
+ //
16
+ // CRITICAL invariant (mirrors `packages/spellkave-cli`'s
17
+ // `registry-parity.test.ts`): no registry tool name may appear as a string
18
+ // literal anywhere in this file. Every tool this daemon can invoke comes from
19
+ // `createPlayerFacingTools`'s own registration order — adding a tool to that
20
+ // registry makes it callable here with zero edits, exactly like `sk`.
21
+
22
+ import { unlinkSync } from "node:fs";
23
+ import * as net from "node:net";
24
+
25
+ import { asEntityRef, snapshotDb } from "@spellkave/sdk";
26
+ import { PLAYER_TOOL_NAMES } from "@spellkave/tool-contracts";
27
+ import type { TSchema } from "typebox";
28
+ import { Check as typeboxCheck, Errors as typeboxErrors } from "typebox/value";
29
+
30
+ import { createCallerSessionTools } from "../authoring/caller-tools";
31
+ import type { SessionBinding } from "../binding.ts";
32
+ import type { ToolResult } from "../player-tools/tool-registry.ts";
33
+ import { type OpenSessionDeps, openSession } from "../session.ts";
34
+ import {
35
+ createSessionCausalTelemetry,
36
+ createSessionRunObserver,
37
+ OFF_SESSION_RUN_OBSERVER,
38
+ parseRunEventsMode,
39
+ resolveReducerAttemptTelemetry,
40
+ resolveWorldActorMetrics,
41
+ type SessionRunObserver,
42
+ } from "./observability.ts";
43
+ import {
44
+ socketPath as deriveSocketPath,
45
+ ensureParentDir,
46
+ restrictSocketPermissions,
47
+ } from "./paths.ts";
48
+ import {
49
+ encodeFrame,
50
+ type InvokeRequest,
51
+ isRequest,
52
+ JsonlFrameDecoder,
53
+ PROTOCOL_VERSION,
54
+ type Response,
55
+ requestId,
56
+ } from "./protocol.ts";
57
+ import { createSessionWorldEventFeed, type SessionWorldEventFeed } from "./world-events.ts";
58
+
59
+ /** Default idle window: no frame handled for this long -> clean close (ssh ControlPersist's equivalent). */
60
+ export const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60 * 1000;
61
+ /** How often a live daemon ships `exporter_heartbeats_total` with no player request. */
62
+ export const DEFAULT_METRICS_HEARTBEAT_INTERVAL_MS = 15_000;
63
+
64
+ // The contract roster is ordered and has been frozen by the pre-cut baseline;
65
+ // derive the orient audit target from it instead of importing a companion
66
+ // schema/name constant. This keeps session protocol routing tied to the same
67
+ // canonical descriptor source MCP publishes.
68
+ const PLAYER_ORIENT_TOOL_NAME = PLAYER_TOOL_NAMES[0] ?? "";
69
+
70
+ /**
71
+ * The minimal shape the dispatcher needs from a registry tool. `execute`'s
72
+ * `params` type is deliberately `never` rather than `unknown` — this is the
73
+ * same escape hatch used by heterogeneous runtime `BoundTool` registries:
74
+ * `never` is assignable to each concrete tool parameter under
75
+ * contravariance. The dispatcher
76
+ * still only ever calls `execute` after validating `params` against the
77
+ * tool's own `parameters` schema, so no unvalidated JSON reaches a tool body.
78
+ */
79
+ export interface InvokableTool {
80
+ readonly name: string;
81
+ readonly parameters: TSchema;
82
+ execute(toolCallId: string, params: never): Promise<ToolResult<unknown>>;
83
+ }
84
+
85
+ export interface DispatcherOptions {
86
+ binding: SessionBinding;
87
+ tools: readonly InvokableTool[] | (() => readonly InvokableTool[]);
88
+ idleTimeoutMs?: number;
89
+ /** Injectable clock for tests. Defaults to `Date.now`. */
90
+ now?: () => number;
91
+ /** Invoked once, after a `shutdown` op has been accepted and responded to. */
92
+ onShutdown?: () => void;
93
+ /** Session-run observability (#2003): `invoke` dispatch is wrapped with the
94
+ * observer's `tool_call` events, and its `status` is echoed in the `status`
95
+ * frame. Defaults to the `off` no-op so callers that don't care (most
96
+ * existing tests) see no behavior change. */
97
+ observability?: SessionRunObserver;
98
+ /** sk-0m4.22: the daemon's ONE WorldEventBuilder, constructed by
99
+ * `startDaemon` and held for the whole process lifetime. Tests that don't
100
+ * care (the fake-registry IPC suite) omit this and get no `pushes` field. */
101
+ pushes?: SessionWorldEventFeed;
102
+ /** sk-uglp: whether the live world connection behind these tools is still
103
+ * up. Echoed as `status.subscribed`; defaults to always-true for the
104
+ * fake-registry test seam. */
105
+ connected?: () => boolean;
106
+ }
107
+
108
+ /**
109
+ * Pure protocol dispatch: given a decoded frame, produce a response. Tracks
110
+ * last-activity for the idle timeout independently of any transport — a
111
+ * caller (test or `serveDaemon`) drives it by calling `handle()`.
112
+ */
113
+ export class SessionDispatcher {
114
+ readonly binding: SessionBinding;
115
+ readonly idleTimeoutMs: number;
116
+ private readonly tools: readonly InvokableTool[] | (() => readonly InvokableTool[]);
117
+ private readonly now: () => number;
118
+ private readonly startedAt: number;
119
+ private readonly onShutdown: (() => void) | undefined;
120
+ private readonly observability: SessionRunObserver;
121
+ private readonly pushFeed: SessionWorldEventFeed | undefined;
122
+ private readonly connected: () => boolean;
123
+ private lastActivityAt: number;
124
+ /** One serial PLAYER execution lane, shared by every socket frame. */
125
+ private invokeTail: Promise<void> = Promise.resolve();
126
+
127
+ constructor(options: DispatcherOptions) {
128
+ this.binding = options.binding;
129
+ this.tools = options.tools;
130
+ this.idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
131
+ this.now = options.now ?? Date.now;
132
+ this.onShutdown = options.onShutdown;
133
+ this.observability = options.observability ?? OFF_SESSION_RUN_OBSERVER;
134
+ this.pushFeed = options.pushes;
135
+ this.connected = options.connected ?? (() => true);
136
+ this.startedAt = this.now();
137
+ this.lastActivityAt = this.startedAt;
138
+ }
139
+
140
+ /** Milliseconds since the last frame this dispatcher handled. */
141
+ idleForMs(): number {
142
+ return this.now() - this.lastActivityAt;
143
+ }
144
+
145
+ isIdle(): boolean {
146
+ return this.idleForMs() >= this.idleTimeoutMs;
147
+ }
148
+
149
+ async handle(raw: unknown): Promise<Response> {
150
+ this.lastActivityAt = this.now();
151
+ if (!isRequest(raw)) {
152
+ return {
153
+ id: requestId(raw) ?? -1,
154
+ ok: false,
155
+ error: { message: "malformed request frame", code: "bad_request" },
156
+ };
157
+ }
158
+ switch (raw.op) {
159
+ case "list_tools":
160
+ return { id: raw.id, ok: true, result: this.currentTools().map((tool) => tool.name) };
161
+ case "hello":
162
+ return {
163
+ id: raw.id,
164
+ ok: true,
165
+ result: { protocol: PROTOCOL_VERSION, binding: this.binding },
166
+ };
167
+ case "status":
168
+ return {
169
+ id: raw.id,
170
+ ok: true,
171
+ result: {
172
+ binding: this.binding,
173
+ uptimeMs: this.now() - this.startedAt,
174
+ // True once `startDaemon` built this dispatcher (after
175
+ // `openSession`'s subscribe-on-connect resolved) — UNTIL the
176
+ // world connection drops (sk-uglp): a daemon that lost its
177
+ // world closes itself, but a `status` racing that close must
178
+ // not report a live subscription.
179
+ subscribed: this.connected(),
180
+ // #2003: ambient observability config must be visible, not just
181
+ // inferable — same posture as the #2002 profile announce. Additive
182
+ // field only; every existing `status` consumer keeps working.
183
+ observability: this.observability.status,
184
+ },
185
+ };
186
+ case "shutdown": {
187
+ // Respond before tearing down, on the next microtask — the ack must
188
+ // land on the wire before `serveDaemon` closes the socket under it.
189
+ queueMicrotask(() => this.onShutdown?.());
190
+ return this.withPushes({ id: raw.id, ok: true, result: {} });
191
+ }
192
+ case "drain_pushes":
193
+ // Explicit drain (sk-0m4.22 bonus): same piggyback as every other
194
+ // op, with an empty result so `sk events --drain` has a dedicated
195
+ // request that does not invent a PLAYER tool name.
196
+ return this.withPushes({ id: raw.id, ok: true, result: {} });
197
+ case "invoke":
198
+ return this.enqueueInvoke(raw);
199
+ }
200
+ }
201
+
202
+ /**
203
+ * The daemon, not an HTTP adapter, owns PLAYER serialization. This keeps
204
+ * reducer/event ordering stable when two clients send frames concurrently;
205
+ * `invoke()` drains/takes WorldEvents before releasing the next tool.
206
+ *
207
+ * sk-0m4.121: a tool may hand the lock back EARLY through
208
+ * {@link releaseCurrentInvoke} once its ordering-relevant work is done —
209
+ * the `communicate` reply window (`tool-player`'s `awaitConversationReply`)
210
+ * does, after the reducer settled, so a read that arrives during the window
211
+ * is served instead of queueing behind it into the gateway's fast-fail.
212
+ * The lock holder is unambiguous by construction (one invoke body at a
213
+ * time), so a single field, not per-call plumbing, identifies it.
214
+ */
215
+ private async enqueueInvoke(request: InvokeRequest): Promise<Response> {
216
+ const previous = this.invokeTail;
217
+ let release: (() => void) | undefined;
218
+ this.invokeTail = new Promise<void>((resolve) => {
219
+ release = resolve;
220
+ });
221
+ await previous;
222
+ this.currentInvokeRelease = release;
223
+ try {
224
+ return await this.invoke(request);
225
+ } finally {
226
+ // Idempotent: a no-op if the tool already released via
227
+ // `releaseCurrentInvoke`, and never clears a SUCCESSOR's release.
228
+ if (this.currentInvokeRelease === release) this.currentInvokeRelease = undefined;
229
+ release?.();
230
+ }
231
+ }
232
+
233
+ /** Release function of the invoke currently holding the serialisation
234
+ * lock; `undefined` between invokes or after an early release. */
235
+ private currentInvokeRelease: (() => void) | undefined;
236
+
237
+ /**
238
+ * sk-0m4.121: let the NEXT queued invoke run while the current tool body
239
+ * is still finishing. Safe only once the caller has no ordering-relevant
240
+ * work left (no reducer call, no consequence take) — its remaining reads
241
+ * of the shared `WorldEventBuilder` are single-threaded and each
242
+ * `takeWhere`/`drain` is atomic, so interleaving with the next invoke's
243
+ * drain is zero-loss (the `takeWhere` carry contract). A second call
244
+ * before the next invoke acquires the lock is a no-op.
245
+ */
246
+ releaseCurrentInvoke(): void {
247
+ const release = this.currentInvokeRelease;
248
+ this.currentInvokeRelease = undefined;
249
+ release?.();
250
+ }
251
+
252
+ /** Attach pending WorldEvents as an additive `pushes` field. Omitted when
253
+ * there is no feed (test seam) or the drain is empty — never `[]`. */
254
+ private withPushes(response: Response, auditVisibleTraces = false): Response {
255
+ const pushes = this.drainPushes(auditVisibleTraces);
256
+ if (pushes === undefined) return response;
257
+ return { ...response, pushes };
258
+ }
259
+
260
+ private drainPushes(auditVisibleTraces: boolean): readonly unknown[] | undefined {
261
+ if (this.pushFeed === undefined) return undefined;
262
+ const pushes = this.pushFeed.drain({ auditVisibleTraces });
263
+ return pushes.length === 0 ? undefined : pushes;
264
+ }
265
+
266
+ private currentTools(): readonly InvokableTool[] {
267
+ return typeof this.tools === "function" ? this.tools() : this.tools;
268
+ }
269
+
270
+ private async invoke(request: InvokeRequest): Promise<Response> {
271
+ const tool = this.currentTools().find((candidate) => candidate.name === request.tool);
272
+ if (tool === undefined) {
273
+ return this.withPushes({
274
+ id: request.id,
275
+ ok: false,
276
+ error: { message: `unknown tool ${request.tool}`, code: "unknown_tool" },
277
+ });
278
+ }
279
+ if (!typeboxCheck(tool.parameters, request.args)) {
280
+ const errors = [...typeboxErrors(tool.parameters, request.args)];
281
+ return this.withPushes({
282
+ id: request.id,
283
+ ok: false,
284
+ error: {
285
+ message: `invalid parameters for ${request.tool}: ${errors
286
+ .map((e) => `${e.instancePath || "/"} ${e.message}`)
287
+ .join("; ")}`,
288
+ code: "bad_request",
289
+ },
290
+ });
291
+ }
292
+ try {
293
+ const result = await this.observability.observeToolCall(
294
+ request.tool,
295
+ () => tool.execute(String(request.id), request.args as never),
296
+ request.causal_context,
297
+ );
298
+ return this.withPushes(
299
+ { id: request.id, ok: true, result },
300
+ request.tool === PLAYER_ORIENT_TOOL_NAME,
301
+ );
302
+ } catch (err) {
303
+ return this.withPushes(
304
+ {
305
+ id: request.id,
306
+ ok: false,
307
+ error: {
308
+ message: err instanceof Error ? err.message : String(err),
309
+ code:
310
+ err instanceof Error && "code" in err && typeof err.code === "string"
311
+ ? err.code
312
+ : "tool_error",
313
+ },
314
+ },
315
+ request.tool === PLAYER_ORIENT_TOOL_NAME,
316
+ );
317
+ }
318
+ }
319
+ }
320
+
321
+ export interface DaemonHandle {
322
+ readonly socketPath: string;
323
+ readonly dispatcher: SessionDispatcher;
324
+ /**
325
+ * Idempotent. Closes the socket, cancels the idle timer, ends the run
326
+ * observer with `terminal` (default `"shutdown"`), and runs `onClose`
327
+ * (session teardown).
328
+ */
329
+ close(terminal?: string): Promise<void>;
330
+ }
331
+
332
+ export interface ServeDaemonOptions {
333
+ binding: SessionBinding;
334
+ tools: readonly InvokableTool[] | (() => readonly InvokableTool[]);
335
+ socketPath: string;
336
+ idleTimeoutMs?: number;
337
+ now?: () => number;
338
+ /** How often the idle check re-arms; defaults to the idle timeout itself. */
339
+ idleCheckIntervalMs?: number;
340
+ /** How often to ship an unconditional metrics heartbeat; `0` disables. */
341
+ metricsHeartbeatIntervalMs?: number;
342
+ /** Torn down exactly once, from whichever trigger closes the daemon first. */
343
+ onClose?: () => void;
344
+ /** #2003: forwarded to the dispatcher and ended exactly once on close. */
345
+ observability?: SessionRunObserver;
346
+ /** sk-0m4.22: forwarded to the dispatcher. Production `startDaemon` always
347
+ * supplies one; the fake-registry test seam omits it. */
348
+ pushes?: SessionWorldEventFeed;
349
+ /** sk-uglp: forwarded to the dispatcher's `status.subscribed`. */
350
+ connected?: () => boolean;
351
+ }
352
+
353
+ /**
354
+ * Bind `socketPath`, wire JSONL framing to a `SessionDispatcher`, and run the
355
+ * idle-check loop. Takes an already-built tool list — the live-node-free
356
+ * seam `@spellkave/session-node-tests` exercises with a fake registry.
357
+ */
358
+ export function serveDaemon(options: ServeDaemonOptions): Promise<DaemonHandle> {
359
+ ensureParentDir(options.socketPath);
360
+ removeSocketFileIfPresent(options.socketPath);
361
+
362
+ let closed = false;
363
+ let idleTimer: ReturnType<typeof setTimeout> | undefined;
364
+ let metricsHeartbeatTimer: ReturnType<typeof setInterval> | undefined;
365
+
366
+ const dispatcher = new SessionDispatcher({
367
+ binding: options.binding,
368
+ tools: options.tools,
369
+ ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }),
370
+ ...(options.now === undefined ? {} : { now: options.now }),
371
+ ...(options.observability === undefined ? {} : { observability: options.observability }),
372
+ ...(options.pushes === undefined ? {} : { pushes: options.pushes }),
373
+ ...(options.connected === undefined ? {} : { connected: options.connected }),
374
+ onShutdown: () => {
375
+ void close("shutdown");
376
+ },
377
+ });
378
+
379
+ const server = net.createServer((socket) => {
380
+ const decoder = new JsonlFrameDecoder();
381
+ socket.setEncoding("utf8");
382
+ socket.on("data", (chunk: string) => {
383
+ for (const frame of decoder.push(chunk)) {
384
+ void dispatcher.handle(frame).then((response) => {
385
+ if (!socket.destroyed) socket.write(encodeFrame(response));
386
+ });
387
+ }
388
+ });
389
+ // A peer that vanishes mid-write is not a daemon-lifecycle event on its
390
+ // own — the idle timer, not a single connection's socket error, decides
391
+ // whether this daemon keeps running (other clients may still be live).
392
+ socket.on("error", () => {});
393
+ });
394
+
395
+ async function close(terminal = "shutdown"): Promise<void> {
396
+ if (closed) return;
397
+ closed = true;
398
+ if (idleTimer !== undefined) clearTimeout(idleTimer);
399
+ if (metricsHeartbeatTimer !== undefined) clearInterval(metricsHeartbeatTimer);
400
+ await new Promise<void>((resolve) => server.close(() => resolve()));
401
+ removeSocketFileIfPresent(options.socketPath);
402
+ await options.observability?.end(terminal);
403
+ options.onClose?.();
404
+ }
405
+
406
+ function scheduleIdleCheck(): void {
407
+ const interval = options.idleCheckIntervalMs ?? dispatcher.idleTimeoutMs;
408
+ idleTimer = setTimeout(() => {
409
+ if (dispatcher.isIdle()) {
410
+ void close("idle_timeout");
411
+ return;
412
+ }
413
+ scheduleIdleCheck();
414
+ }, interval);
415
+ idleTimer.unref?.();
416
+ }
417
+
418
+ function startMetricsHeartbeat(): void {
419
+ const observer = options.observability;
420
+ if (observer === undefined) return;
421
+ const interval = options.metricsHeartbeatIntervalMs ?? DEFAULT_METRICS_HEARTBEAT_INTERVAL_MS;
422
+ if (interval <= 0) return;
423
+ void observer.heartbeatMetrics();
424
+ metricsHeartbeatTimer = setInterval(() => {
425
+ void observer.heartbeatMetrics();
426
+ }, interval);
427
+ metricsHeartbeatTimer.unref?.();
428
+ }
429
+
430
+ return new Promise<DaemonHandle>((resolve, reject) => {
431
+ server.once("error", reject);
432
+ server.listen(options.socketPath, () => {
433
+ restrictSocketPermissions(options.socketPath);
434
+ scheduleIdleCheck();
435
+ startMetricsHeartbeat();
436
+ resolve({ socketPath: options.socketPath, dispatcher, close });
437
+ });
438
+ });
439
+ }
440
+
441
+ function removeSocketFileIfPresent(path: string): void {
442
+ try {
443
+ unlinkSync(path);
444
+ } catch (err) {
445
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
446
+ }
447
+ }
448
+
449
+ export interface StartDaemonOptions {
450
+ binding: SessionBinding;
451
+ /** Select events only when the client has a suitable event return channel. */
452
+ replyDelivery?: "bundled" | "events";
453
+ token?: string;
454
+ idleTimeoutMs?: number;
455
+ socketPath?: string;
456
+ onDiagnostic?: OpenSessionDeps["onDiagnostic"];
457
+ /** Source of `SPELLKAVE_RUN_EVENTS`/`CAMPAIGN_ARTIFACTS_ROOT`/OTLP env vars
458
+ * (#2003); defaults to `process.env`. `spawn.ts` snapshots the daemon's
459
+ * whole environment at spawn time, so this reflects that snapshot. */
460
+ env?: NodeJS.ProcessEnv;
461
+ /** sk-uglp: invoked once, AFTER the daemon closed itself because its world
462
+ * connection was lost (wipe/redeploy/host restart). The process entry uses
463
+ * it to exit, so nothing keeps a dead session's process alive. */
464
+ onWorldConnectionLost?: () => void;
465
+ }
466
+
467
+ /**
468
+ * sk-0m4.73: the daemon-level override for the companion `communicate` reply
469
+ * window. `SPELLKAVE_REPLY_WINDOW_MS` (a positive finite number of
470
+ * milliseconds) wins when set. Otherwise this returns `undefined`, leaving
471
+ * the companion layer to compute its tick-scaled fallback from the live
472
+ * session estimator.
473
+ */
474
+ export function resolveReplyWindowMs(env: NodeJS.ProcessEnv): number | undefined {
475
+ const raw = env.SPELLKAVE_REPLY_WINDOW_MS;
476
+ if (raw !== undefined && raw.trim() !== "") {
477
+ const parsed = Number(raw);
478
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
479
+ }
480
+ return undefined;
481
+ }
482
+
483
+ /**
484
+ * sk-0m4.121: upper bound on the DEFAULT (tick-scaled) `communicate` reply
485
+ * window — for THIS host only. The hosted gateway fast-fails every daemon
486
+ * invoke at `SESSION_INVOKE_FAST_FAIL_MS` (12 s,
487
+ * `packages/spellkave-mcp/src/runtime.ts`); a synchronous wait longer than
488
+ * that never reaches the player anyway — the gateway has already answered
489
+ * `awaiting_response=true` and the reply lands as a `speech_heard` world event
490
+ * on the next call. A slow world can yield a tick-scaled timeout of roughly 100 seconds
491
+ * (2 × tick interval), so every act wedged the invoke queue for the whole
492
+ * window. 8 s leaves framing headroom under 12 s.
493
+ *
494
+ * In-process hosts (pi extension, the adventure story recorder) never go
495
+ * through the daemon and keep the full tick-scaled default — the cap is not
496
+ * a tool-player default.
497
+ */
498
+ export const DAEMON_REPLY_WINDOW_CAP_MS = 8_000;
499
+
500
+ /**
501
+ * The daemon's reply-window slice of `SpellkaveWorldEventsContext`: an
502
+ * explicit `SPELLKAVE_REPLY_WINDOW_MS` wins, uncapped; otherwise only the cap
503
+ * is passed and tool-player bounds its tick-scaled default by it.
504
+ */
505
+ export function resolveReplyWindowOptions(
506
+ env: NodeJS.ProcessEnv,
507
+ ): { replyWindowMs: number } | { replyWindowCapMs: number } {
508
+ const replyWindowMs = resolveReplyWindowMs(env);
509
+ return replyWindowMs === undefined
510
+ ? { replyWindowCapMs: DAEMON_REPLY_WINDOW_CAP_MS }
511
+ : { replyWindowMs };
512
+ }
513
+
514
+ /**
515
+ * Production entry point: open ONE session for `binding`, bind its PLAYER
516
+ * tools, and serve them over the binding's derived socket. This is what
517
+ * `daemon-entry.ts` (the process `spawn.ts` launches) calls.
518
+ *
519
+ * Observability (#2003): `SPELLKAVE_RUN_EVENTS` is parsed FIRST — an
520
+ * unrecognized value refuses to start before a session is even opened. The
521
+ * reducer-attempt tracer must exist before `openSession` (the actor client
522
+ * needs it at construction); the run-events emitter is built AFTER
523
+ * `openSession` succeeds, so a daemon that never finished starting never
524
+ * leaves behind a half-open run.
525
+ */
526
+ export async function startDaemon(options: StartDaemonOptions): Promise<DaemonHandle> {
527
+ const env = options.env ?? process.env;
528
+ const runEventsMode = parseRunEventsMode(env);
529
+ const reducerAttemptTelemetry = resolveReducerAttemptTelemetry({ mode: runEventsMode, env });
530
+ const metrics = resolveWorldActorMetrics({ mode: runEventsMode, env });
531
+ const causalTelemetry =
532
+ reducerAttemptTelemetry === undefined
533
+ ? undefined
534
+ : createSessionCausalTelemetry(reducerAttemptTelemetry);
535
+ // sk-uglp: a daemon whose WORLD connection dies must die with it. The SDK
536
+ // never reconnects (`connect()` is one-shot), so a daemon that ignored
537
+ // `onDisconnect` kept listening on a healthy socket over a dead world —
538
+ // every reattach found "something listening" and re-joined the corpse,
539
+ // every tool call hung into the 3s fast-fail, and read-only tools served
540
+ // the pre-wipe client cache as if live. Closing here unlinks the socket, so
541
+ // the next `ensureDaemon` spawns a fresh process against the fresh world.
542
+ let handle: DaemonHandle | undefined;
543
+ const replyLifetime = new AbortController();
544
+ let worldLost = false;
545
+ // Assigned after `openSession` resolves (the observer needs a live session);
546
+ // a `const` here would hit the TDZ if the world dropped mid-startup.
547
+ let observabilityRef: SessionRunObserver | undefined;
548
+ const onWorldLost = (): void => {
549
+ replyLifetime.abort(new Error("World connection lost"));
550
+ if (worldLost) return;
551
+ worldLost = true;
552
+ // sk-0m4.120.12: name the cause on the daemon's own run BEFORE close()
553
+ // ends it — the row a triager needs to tell "subscription dropped" from
554
+ // "pod restarted" (both leave the same doctor snapshot).
555
+ observabilityRef?.emitLifecycle("subscription_lost", { cause: "world_connection_lost" });
556
+ const current = handle;
557
+ if (current === undefined) return; // still starting up; see below
558
+ void current.close("world_connection_lost").finally(() => options.onWorldConnectionLost?.());
559
+ };
560
+ const live = await openSession(options.binding, {
561
+ authorityTools: true,
562
+ ...(options.token === undefined ? {} : { token: options.token }),
563
+ ...(options.onDiagnostic === undefined ? {} : { onDiagnostic: options.onDiagnostic }),
564
+ ...(causalTelemetry === undefined
565
+ ? {}
566
+ : { actorClientOptions: { reducerAttemptTelemetry: causalTelemetry.tracer } }),
567
+ onDisconnect: () => onWorldLost(),
568
+ });
569
+ const observability = createSessionRunObserver({
570
+ mode: runEventsMode,
571
+ binding: options.binding,
572
+ env,
573
+ ...(causalTelemetry === undefined ? {} : { causalTelemetry }),
574
+ ...(metrics === undefined ? {} : { metrics }),
575
+ });
576
+ observabilityRef = observability;
577
+ // The session's ONE cursor (finding #98 / ADR-0093 D-5), not a
578
+ // daemon-constructed builder: `live.session.worldEvents` is the SDK's
579
+ // lazily-memoized fanout, one per session, primed here at construction
580
+ // (see the module header). Built BEFORE the tools below — sk-0m4.73's
581
+ // communicate reply window (and sk-0m4.74's consequences register) needs
582
+ // the SAME builder instance injected as `worldEvents.builder`, so the
583
+ // tools can no longer be constructed first.
584
+ const pushes = createSessionWorldEventFeed({
585
+ db: () => snapshotDb(live.session),
586
+ actorId: () => asEntityRef(live.actorId),
587
+ builder: live.session.worldEvents,
588
+ ...(causalTelemetry === undefined ? {} : { telemetry: causalTelemetry.tracer }),
589
+ });
590
+ const callerTools = createCallerSessionTools(live, {
591
+ controlReducers: live.session.conn.reducers,
592
+ db: () => snapshotDb(live.session),
593
+ act: {
594
+ actorId: () => live.actorId,
595
+ actorClient: () => live.actorClient,
596
+ },
597
+ worldEvents: {
598
+ builder: pushes.builder,
599
+ replyDelivery: options.replyDelivery ?? "bundled",
600
+ onUpdate: (notify) => live.onUpdate(notify),
601
+ replySignal: replyLifetime.signal,
602
+ estimator: live.session.estimator,
603
+ ...resolveReplyWindowOptions(env),
604
+ // sk-0m4.121: late-bound — the dispatcher only exists once
605
+ // `serveDaemon` below returns, and the tools must be built first.
606
+ releaseInvokeLock: () => handle?.dispatcher.releaseCurrentInvoke(),
607
+ },
608
+ });
609
+ handle = await serveDaemon({
610
+ binding: options.binding,
611
+ tools: callerTools.tools,
612
+ socketPath: options.socketPath ?? deriveSocketPath(options.binding),
613
+ ...(options.idleTimeoutMs === undefined ? {} : { idleTimeoutMs: options.idleTimeoutMs }),
614
+ observability,
615
+ pushes,
616
+ connected: () => !worldLost,
617
+ onClose: () => {
618
+ replyLifetime.abort(new Error("Session closed"));
619
+ callerTools.close();
620
+ return live.close();
621
+ },
622
+ });
623
+ // The world may have dropped us between `openSession` resolving and the
624
+ // socket binding — close now rather than serve a dead session.
625
+ if (worldLost) {
626
+ void handle.close("world_connection_lost").finally(() => options.onWorldConnectionLost?.());
627
+ }
628
+ return handle;
629
+ }