@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,481 +0,0 @@
1
- // Session daemon observability (#2003): closes the sk blind spot in
2
- // world-actor observability by mirroring Pi's wiring
3
- // (`.pi/extensions/spellkave/src/extension/run-observability.ts`,
4
- // `main.ts`'s `reducerAttemptTelemetry`) around the daemon's own tool
5
- // dispatch. Two independent pieces, both env-gated by `SPELLKAVE_RUN_EVENTS`:
6
- //
7
- // - `resolveReducerAttemptTelemetry` — the `WorldActorTracer` passed into
8
- // `openSession`'s `actorClientOptions.reducerAttemptTelemetry` (the seam
9
- // #1997/Pi already fills). Built BEFORE `openSession` runs, because the
10
- // actor client needs it at construction time.
11
- // - `createSessionRunObserver` — the `agent-run-events/v1` emitter
12
- // (`run_start`/`tool_call`/`run_end`). Built AFTER `openSession` succeeds
13
- // (#2003 design decision 1: run boundary = daemon lifetime — a daemon
14
- // that never finished starting never lived a run) and closed exactly
15
- // once, from whichever trigger ends the daemon first (shutdown, idle
16
- // timeout, fatal error).
17
- //
18
- // `off` disables BOTH pieces — no emitter, no reducer-attempt tracer, zero
19
- // behavior change from before #2003.
20
-
21
- import { AsyncLocalStorage } from "node:async_hooks";
22
- import { join } from "node:path";
23
-
24
- import {
25
- type AgentRunEventType,
26
- type AgentRunSink,
27
- createOtlpHttpSink,
28
- createRunEmitter,
29
- normalizeWorldActorCausalContext,
30
- type WorldActorCausalContext,
31
- type WorldActorMetrics,
32
- type WorldActorTracer,
33
- worldActorCausalAttributes,
34
- worldActorCausalEventData,
35
- } from "@spellkave/agent-observability";
36
- import {
37
- AGENT_RUN_EVENTS_FILENAME,
38
- createJsonlFileSink,
39
- createWorldActorMetricsFromEnv,
40
- createWorldActorTracerFromEnv,
41
- logSinkResourceAttributesFromEnv,
42
- parseOtelPairs,
43
- serviceVersionFromEnv,
44
- } from "@spellkave/agent-observability/node";
45
- import { PLAYER_TOOL_NAMES } from "@spellkave/tool-contracts";
46
-
47
- import type { SessionBinding } from "../binding.ts";
48
- import { runEventsPath } from "./paths.ts";
49
-
50
- export const SESSION_RUN_DRIVER = "sk-daemon";
51
- const SESSION_RUN_EXPERIMENT_ID = "sk-daemon";
52
- /** Resource `service.name` on session-daemon world-actor metrics so a freshness
53
- * query can tell this process from the npc-host (same heartbeat series). */
54
- export const SESSION_METRICS_SERVICE_NAME = "spellkave-session-daemon";
55
-
56
- /** Master switch env var (#2003 design decision 4). */
57
- export const RUN_EVENTS_ENV = "SPELLKAVE_RUN_EVENTS";
58
- /** OTLP logs projection endpoint — the convention `world-explorer/run-play.ts`
59
- * already established for `createOtlpHttpSink`; reused rather than invented. */
60
- export const RUN_EVENTS_OTLP_ENDPOINT_ENV = "SPELLKAVE_AGENT_OBS_OTLP_ENDPOINT";
61
-
62
- export const RUN_EVENTS_MODES = ["off", "jsonl", "otlp", "jsonl+otlp"] as const;
63
- export type RunEventsMode = (typeof RUN_EVENTS_MODES)[number];
64
-
65
- const DEFAULT_RUN_EVENTS_MODE: RunEventsMode = "jsonl";
66
-
67
- /**
68
- * Parse `SPELLKAVE_RUN_EVENTS`. Unset/empty defaults to `"jsonl"` (cheap,
69
- * local, daemon-lifetime-bounded — ADR-0002 observability-as-surface). An
70
- * UNRECOGNIZED value refuses to start rather than silently falling back to
71
- * `off` — a misconfigured mode must be loud, not a silent observability gap.
72
- */
73
- export function parseRunEventsMode(env: NodeJS.ProcessEnv = process.env): RunEventsMode {
74
- const raw = env[RUN_EVENTS_ENV];
75
- if (raw === undefined || raw.trim() === "") return DEFAULT_RUN_EVENTS_MODE;
76
- const trimmed = raw.trim();
77
- if ((RUN_EVENTS_MODES as readonly string[]).includes(trimmed)) {
78
- return trimmed as RunEventsMode;
79
- }
80
- throw new Error(
81
- `${RUN_EVENTS_ENV}=${JSON.stringify(raw)} is not a recognized observability mode ` +
82
- `(valid: ${RUN_EVENTS_MODES.join(", ")}). Refusing to start rather than silently ` +
83
- "falling back to a different mode.",
84
- );
85
- }
86
-
87
- /** Byte cap for one JSONL run-events file before it rotates to `<path>.1`. */
88
- export const RUN_EVENTS_MAX_BYTES_ENV = "SPELLKAVE_RUN_EVENTS_MAX_BYTES";
89
-
90
- /** A 32 MiB live file and one rotated generation bound each appender. */
91
- export const DEFAULT_RUN_EVENTS_MAX_BYTES = 32 * 1024 * 1024;
92
-
93
- /** Byte budget for the WHOLE transcript tree, enforced by deleting rotated
94
- * generations oldest-first on every rotation. */
95
- export const RUN_EVENTS_ROOT_MAX_BYTES_ENV = "SPELLKAVE_RUN_EVENTS_ROOT_MAX_BYTES";
96
-
97
- /** Hosts with a shared transcript volume can set a budget across all seats. */
98
- export const DEFAULT_RUN_EVENTS_ROOT_MAX_BYTES = undefined;
99
-
100
- /**
101
- * Parse `SPELLKAVE_RUN_EVENTS_ROOT_MAX_BYTES`. Unset/empty and `0` both mean
102
- * no volume bound. Like {@link parseRunEventsMaxBytes}, an unparseable value
103
- * refuses to start rather than silently running unbounded.
104
- */
105
- export function parseRunEventsRootMaxBytes(
106
- env: NodeJS.ProcessEnv = process.env,
107
- ): number | undefined {
108
- const raw = env[RUN_EVENTS_ROOT_MAX_BYTES_ENV];
109
- if (raw === undefined || raw.trim() === "") return DEFAULT_RUN_EVENTS_ROOT_MAX_BYTES;
110
- const parsed = Number(raw.trim());
111
- if (!Number.isSafeInteger(parsed) || parsed < 0) {
112
- throw new Error(
113
- `${RUN_EVENTS_ROOT_MAX_BYTES_ENV}=${JSON.stringify(raw)} is not a non-negative integer ` +
114
- "byte count. Refusing to start rather than silently writing an unbounded transcript tree.",
115
- );
116
- }
117
- return parsed === 0 ? undefined : parsed;
118
- }
119
-
120
- /**
121
- * Parse `SPELLKAVE_RUN_EVENTS_MAX_BYTES`. Unset/empty takes
122
- * `DEFAULT_RUN_EVENTS_MAX_BYTES`; `0` means uncapped (the pre-rotation
123
- * behavior, for a short run that wants one whole artifact). Like
124
- * `parseRunEventsMode`, an unparseable value refuses to start — silently
125
- * running uncapped is the failure this exists to prevent.
126
- */
127
- export function parseRunEventsMaxBytes(env: NodeJS.ProcessEnv = process.env): number | undefined {
128
- const raw = env[RUN_EVENTS_MAX_BYTES_ENV];
129
- if (raw === undefined || raw.trim() === "") return DEFAULT_RUN_EVENTS_MAX_BYTES;
130
- const parsed = Number(raw.trim());
131
- if (!Number.isSafeInteger(parsed) || parsed < 0) {
132
- throw new Error(
133
- `${RUN_EVENTS_MAX_BYTES_ENV}=${JSON.stringify(raw)} is not a non-negative integer byte ` +
134
- "count. Refusing to start rather than silently writing an unbounded transcript.",
135
- );
136
- }
137
- return parsed === 0 ? undefined : parsed;
138
- }
139
-
140
- /**
141
- * The reducer-attempt tracer for `openSession`'s `actorClientOptions`. `off`
142
- * disables it unconditionally; any other mode reuses Pi's own env bootstrap
143
- * (`createWorldActorTracerFromEnv`: standard `OTEL_EXPORTER_OTLP_*` vars,
144
- * `SPELLKAVE_OTEL_DISABLED=1` escape hatch), so a daemon and a Pi session
145
- * pointed at the same collector need no daemon-specific config.
146
- */
147
- export function resolveReducerAttemptTelemetry(options: {
148
- mode: RunEventsMode;
149
- env?: NodeJS.ProcessEnv;
150
- /** Injectable for tests — bypasses the real env bootstrap. */
151
- tracer?: WorldActorTracer;
152
- }): WorldActorTracer | undefined {
153
- if (options.mode === "off") return undefined;
154
- if (options.tracer !== undefined) return options.tracer;
155
- return createWorldActorTracerFromEnv(options.env ?? process.env);
156
- }
157
-
158
- /** Process-owned request metrics. `off` disables them together with the
159
- * other projections; endpoint absence leaves them quietly disabled. */
160
- export function resolveWorldActorMetrics(options: {
161
- mode: RunEventsMode;
162
- env?: NodeJS.ProcessEnv;
163
- metrics?: WorldActorMetrics;
164
- }): WorldActorMetrics | undefined {
165
- if (options.mode === "off") return undefined;
166
- if (options.metrics !== undefined) return options.metrics;
167
- return createWorldActorMetricsFromEnv(options.env ?? process.env, {
168
- allowedToolNames: PLAYER_TOOL_NAMES,
169
- serviceName: SESSION_METRICS_SERVICE_NAME,
170
- });
171
- }
172
-
173
- /** Daemon-request scope shared by the run observer and the SDK tracer. The
174
- * tracer keeps its structural interface while AsyncLocalStorage supplies the
175
- * current request's safe correlation to spans created below tool dispatch. */
176
- export interface SessionCausalTelemetry {
177
- readonly tracer: WorldActorTracer;
178
- run<T>(context: WorldActorCausalContext | undefined, operation: () => Promise<T>): Promise<T>;
179
- }
180
-
181
- export function createSessionCausalTelemetry(tracer: WorldActorTracer): SessionCausalTelemetry {
182
- const storage = new AsyncLocalStorage<WorldActorCausalContext>();
183
- return {
184
- tracer: {
185
- startSpan(name, attributes) {
186
- return tracer.startSpan(name, {
187
- ...worldActorCausalAttributes(storage.getStore()),
188
- ...attributes,
189
- });
190
- },
191
- flush: () => tracer.flush(),
192
- },
193
- run(context, operation) {
194
- const safe = normalizeWorldActorCausalContext(context);
195
- return safe === undefined ? operation() : storage.run(safe, operation);
196
- },
197
- };
198
- }
199
-
200
- /** Where the JSONL run-events file for `runId` lives. Pi's convention:
201
- * `CAMPAIGN_ARTIFACTS_ROOT` root when set, else a package-owned fallback —
202
- * here the daemon's own run dir, next to its log (`paths.ts`'s `runEventsPath`
203
- * derives the SAME per-binding file every time, so successive runs append to
204
- * one file rather than scattering one-per-run directories the way the
205
- * campaign-artifacts tree does; a daemon session has no natural "experiment"
206
- * grouping the way a campaign playthrough does). */
207
- export function sessionRunArtifactPath(options: {
208
- binding: SessionBinding;
209
- runId: string;
210
- env?: NodeJS.ProcessEnv;
211
- }): string {
212
- const root = options.env?.CAMPAIGN_ARTIFACTS_ROOT;
213
- if (root !== undefined && root.length > 0) {
214
- return join(
215
- root,
216
- "experiments",
217
- SESSION_RUN_EXPERIMENT_ID,
218
- "runs",
219
- options.runId,
220
- AGENT_RUN_EVENTS_FILENAME,
221
- );
222
- }
223
- return runEventsPath(options.binding, options.env);
224
- }
225
-
226
- function sessionRunId(now: Date): string {
227
- return `run-${now.toISOString().replaceAll(":", "-").replaceAll(".", "-")}`;
228
- }
229
-
230
- export interface SessionRunObserverStatus {
231
- mode: RunEventsMode;
232
- /** Present only when a JSONL sink is active (`jsonl`/`jsonl+otlp`). */
233
- artifactPath?: string;
234
- /** Configuration only: never includes a collector URL or credentials. */
235
- logsProjection?: "configured" | "disabled";
236
- /** Configuration only: never claims that a collector accepted a span. */
237
- tracesProjection?: "configured" | "disabled";
238
- /** Configuration only: does not claim collector delivery health. */
239
- metricsProjection?: "configured" | "disabled";
240
- }
241
-
242
- /** The daemon-lifetime run observer `serveDaemon`/`SessionDispatcher` wrap
243
- * `invoke` dispatch with. Mirrors `PiRunObserver`'s shape. */
244
- export interface SessionRunObserver {
245
- readonly status: SessionRunObserverStatus;
246
- observeToolCall<T>(
247
- toolName: string,
248
- operation: () => Promise<T>,
249
- causalContext?: WorldActorCausalContext,
250
- ): Promise<T>;
251
- /**
252
- * sk-0m4.120.12: one lifecycle line on the daemon's own run (e.g.
253
- * `subscription_lost {cause}`). Scalars only; best-effort, never throws.
254
- * `end()` itself emits `daemon_exit {reason}` before `run_end`.
255
- */
256
- emitLifecycle(type: AgentRunEventType, data?: Record<string, unknown>): void;
257
- /** Unconditional metrics-exporter liveness. Safe no-op when metrics are off. */
258
- heartbeatMetrics(): void | Promise<void>;
259
- /** Idempotent — safe to call from more than one shutdown trigger. */
260
- end(terminal?: string): Promise<void>;
261
- }
262
-
263
- /** `off`-mode observer: zero behavior change, `status.mode` still reported
264
- * so `status` frames are truthful about ambient config either way. */
265
- export const OFF_SESSION_RUN_OBSERVER: SessionRunObserver = {
266
- status: {
267
- mode: "off",
268
- logsProjection: "disabled",
269
- tracesProjection: "disabled",
270
- metricsProjection: "disabled",
271
- },
272
- observeToolCall: (_toolName, operation) => operation(),
273
- emitLifecycle: () => {},
274
- async heartbeatMetrics() {},
275
- async end() {},
276
- };
277
-
278
- /**
279
- * Request headers for the run-events OTLP logs sink, from the standard OTel
280
- * env pair: `OTEL_EXPORTER_OTLP_LOGS_HEADERS` wins over
281
- * `OTEL_EXPORTER_OTLP_HEADERS`, like the OTel SDKs. The public ingest
282
- * (telemetry.spellkave.com) sits behind Cloudflare Access, so a sink without
283
- * these is refused with 403 at the edge while the traces exporter — which
284
- * reads the same variables on its own — keeps working (sk-0m4.120.9). Shared
285
- * by the daemon sink, the npc host and the MCP gateway so the parse lives
286
- * once. Never log the values: they are the ingest credential.
287
- */
288
- export function otlpLogsHeadersFromEnv(env: NodeJS.ProcessEnv): Record<string, string> {
289
- return parseOtelPairs(env.OTEL_EXPORTER_OTLP_LOGS_HEADERS ?? env.OTEL_EXPORTER_OTLP_HEADERS);
290
- }
291
-
292
- function buildDefaultSinks(options: {
293
- mode: RunEventsMode;
294
- artifactPath: string | undefined;
295
- env: NodeJS.ProcessEnv;
296
- }): AgentRunSink[] {
297
- const sinks: AgentRunSink[] = [];
298
- if (
299
- (options.mode === "jsonl" || options.mode === "jsonl+otlp") &&
300
- options.artifactPath !== undefined
301
- ) {
302
- sinks.push(createJsonlFileSink(options.artifactPath));
303
- }
304
- if (options.mode === "otlp" || options.mode === "jsonl+otlp") {
305
- const endpoint = options.env[RUN_EVENTS_OTLP_ENDPOINT_ENV];
306
- if (endpoint !== undefined && endpoint.trim().length > 0) {
307
- const serviceVersion = serviceVersionFromEnv(options.env);
308
- sinks.push(
309
- createOtlpHttpSink({
310
- endpoint,
311
- headers: otlpLogsHeadersFromEnv(options.env),
312
- ...(serviceVersion === undefined ? {} : { serviceVersion }),
313
- resourceAttributes: logSinkResourceAttributesFromEnv(options.env),
314
- }),
315
- );
316
- }
317
- }
318
- return sinks;
319
- }
320
-
321
- export interface CreateSessionRunObserverOptions {
322
- mode: RunEventsMode;
323
- binding: SessionBinding;
324
- env?: NodeJS.ProcessEnv;
325
- /** Injectable clock for deterministic tests. Defaults to wall clock. */
326
- now?: () => Date;
327
- /** Injectable sinks — bypasses env-driven sink selection (tests). */
328
- sinks?: readonly AgentRunSink[];
329
- /** Request scope shared with the actor-client reducer tracer. */
330
- causalTelemetry?: SessionCausalTelemetry;
331
- /** Process-owned, bounded-label request metrics. */
332
- metrics?: WorldActorMetrics;
333
- }
334
-
335
- /**
336
- * Build the daemon-lifetime run observer. Callers create this AFTER
337
- * `openSession` has already succeeded — see the module comment. `mode ===
338
- * "off"` returns the shared no-op singleton without touching the filesystem
339
- * or network.
340
- */
341
- export function createSessionRunObserver(
342
- options: CreateSessionRunObserverOptions,
343
- ): SessionRunObserver {
344
- if (options.mode === "off") return OFF_SESSION_RUN_OBSERVER;
345
-
346
- const env = options.env ?? process.env;
347
- const worldSlug = env.SPELLKAVE_WORLD_SLUG?.trim() || undefined;
348
- const stableWorldData = worldSlug === undefined ? {} : { world_slug: worldSlug };
349
- const now = options.now ?? (() => new Date());
350
- const startedAt = now();
351
- const runId = sessionRunId(startedAt);
352
- const artifactPath =
353
- options.mode === "otlp"
354
- ? undefined
355
- : sessionRunArtifactPath({ binding: options.binding, runId, env });
356
- const sinks = options.sinks ?? buildDefaultSinks({ mode: options.mode, artifactPath, env });
357
- const logsProjection =
358
- (options.mode === "otlp" || options.mode === "jsonl+otlp") &&
359
- (options.sinks !== undefined || env[RUN_EVENTS_OTLP_ENDPOINT_ENV]?.trim())
360
- ? "configured"
361
- : "disabled";
362
- const tracesProjection =
363
- options.causalTelemetry !== undefined ||
364
- (env.SPELLKAVE_OTEL_DISABLED !== "1" &&
365
- (env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim() || env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim()))
366
- ? "configured"
367
- : "disabled";
368
- const metricsProjection = options.metrics === undefined ? "disabled" : "configured";
369
-
370
- const emitter = createRunEmitter(
371
- {
372
- run_id: runId,
373
- run_kind: "sk_session",
374
- actor_id: options.binding.actorId,
375
- role: "PLAYER",
376
- controller_kind: "human",
377
- driver: SESSION_RUN_DRIVER,
378
- now,
379
- },
380
- sinks,
381
- );
382
- let ended = false;
383
-
384
- emitter.emit("run_start", {
385
- url: options.binding.url,
386
- db: options.binding.db,
387
- ...stableWorldData,
388
- ...(artifactPath === undefined ? {} : { artifact_path: artifactPath }),
389
- });
390
-
391
- return {
392
- status: {
393
- mode: options.mode,
394
- ...(artifactPath === undefined ? {} : { artifactPath }),
395
- logsProjection,
396
- tracesProjection,
397
- metricsProjection,
398
- },
399
- async observeToolCall(toolName, operation, causalContext) {
400
- const toolStartedAt = now().getTime();
401
- const causalData = {
402
- ...worldActorCausalEventData(causalContext),
403
- ...stableWorldData,
404
- };
405
- let requestStatus: "ok" | "error" = "ok";
406
- try {
407
- const result = await (options.causalTelemetry === undefined
408
- ? operation()
409
- : options.causalTelemetry.run(causalContext, operation));
410
- emitter.emit("tool_call", {
411
- tool_name: toolName,
412
- is_error: false,
413
- duration_ms: Math.max(0, now().getTime() - toolStartedAt),
414
- ...causalData,
415
- // sk-0m4.120.42: affordance listing counts (scalars only).
416
- });
417
- return result;
418
- } catch (error) {
419
- requestStatus = "error";
420
- emitter.emit("tool_call", {
421
- tool_name: toolName,
422
- is_error: true,
423
- duration_ms: Math.max(0, now().getTime() - toolStartedAt),
424
- summary: "tool execution failed",
425
- ...causalData,
426
- });
427
- throw error;
428
- } finally {
429
- try {
430
- options.metrics?.recordRequest({
431
- toolName,
432
- durationMs: Math.max(0, now().getTime() - toolStartedAt),
433
- status: requestStatus,
434
- });
435
- } catch {
436
- // Observability cannot change a gameplay result.
437
- }
438
- // Long-lived daemons may never reach the tracer's batch threshold.
439
- // Start export after each request without putting collector latency on
440
- // the gameplay response path; orderly shutdown awaits it below.
441
- void options.causalTelemetry?.tracer.flush().catch(() => {});
442
- }
443
- },
444
- emitLifecycle(type, data = {}) {
445
- if (ended) return;
446
- try {
447
- emitter.emit(type, { ...data, ...stableWorldData });
448
- } catch {
449
- // Observability cannot change a gameplay result.
450
- }
451
- },
452
- async heartbeatMetrics() {
453
- if (ended || options.metrics === undefined) return;
454
- try {
455
- options.metrics.recordExporterHeartbeat?.();
456
- } catch {
457
- // Observability cannot change a gameplay result.
458
- }
459
- await options.metrics.flush().catch(() => {});
460
- },
461
- async end(terminal = "shutdown") {
462
- if (ended) return;
463
- ended = true;
464
- // sk-0m4.120.12: the exit REASON as its own row. `run_end.terminal`
465
- // carries the same word, but a reader filtering `event_type =
466
- // 'daemon_exit'` gets every daemon death — idle, shutdown, world
467
- // loss, crash — without knowing which run kinds end how.
468
- emitter.emit("daemon_exit", { reason: terminal, ...stableWorldData });
469
- emitter.emit("run_end", {
470
- terminal,
471
- duration_ms: Math.max(0, now().getTime() - startedAt.getTime()),
472
- ...stableWorldData,
473
- });
474
- await emitter.close();
475
- await Promise.allSettled([
476
- options.causalTelemetry?.tracer.flush() ?? Promise.resolve(),
477
- options.metrics?.flush() ?? Promise.resolve(),
478
- ]);
479
- },
480
- };
481
- }
package/src/node/paths.ts DELETED
@@ -1,83 +0,0 @@
1
- // Socket + log path derivation for the session daemon (#1990 decision 4/5).
2
- //
3
- // Socket path: `$XDG_RUNTIME_DIR/spellkave/session-<hash12>.sock`, falling
4
- // back to `~/.spellkave/run/` when `XDG_RUNTIME_DIR` is unset (macOS has no
5
- // XDG runtime dir by default). The containing directory is created `0o700`;
6
- // the socket file itself is chmod'd `0o600` once bound (`daemon.ts`) — both
7
- // steps belong here so every caller (daemon, spawn probe, tests) derives the
8
- // same paths and the same permission discipline from one place.
9
-
10
- import { createHash } from "node:crypto";
11
- import { chmodSync, existsSync, mkdirSync } from "node:fs";
12
- import { homedir } from "node:os";
13
- import { dirname, join } from "node:path";
14
-
15
- import { canonicalBindingJson, type SessionBinding } from "../binding.ts";
16
-
17
- const RUN_SUBDIR = "spellkave";
18
-
19
- /** Synchronous sha256 hex digest via `node:crypto` — the Node-bound `Sha256Hex`. */
20
- export function sha256HexNode(input: string): string {
21
- return createHash("sha256").update(input, "utf8").digest("hex");
22
- }
23
-
24
- /**
25
- * Same 12-hex-char digest `hashBinding` (core, async, WebCrypto) produces,
26
- * computed synchronously so socket-path derivation never has to await. Both
27
- * hash the same `canonicalBindingJson` input through sha256 — see
28
- * `__tests__/binding.test.ts` for the cross-check that keeps them from
29
- * silently diverging.
30
- */
31
- export function bindingHash12(binding: SessionBinding): string {
32
- return sha256HexNode(canonicalBindingJson(binding)).slice(0, 12);
33
- }
34
-
35
- /** `$XDG_RUNTIME_DIR/spellkave`, or `~/.spellkave/run` when unset/empty. */
36
- export function runtimeDir(env: NodeJS.ProcessEnv = process.env): string {
37
- const xdg = env.XDG_RUNTIME_DIR;
38
- if (xdg !== undefined && xdg.length > 0) return join(xdg, RUN_SUBDIR);
39
- return join(homedir(), ".spellkave", "run");
40
- }
41
-
42
- /** The unix socket path a binding's daemon listens on. */
43
- export function socketPath(binding: SessionBinding, env?: NodeJS.ProcessEnv): string {
44
- return join(runtimeDir(env), `session-${bindingHash12(binding)}.sock`);
45
- }
46
-
47
- /** Where `spawn.ts` redirects a spawned daemon's stdio (herdr's `*-server.log` convention). */
48
- export function logPath(binding: SessionBinding, env?: NodeJS.ProcessEnv): string {
49
- return join(runtimeDir(env), `session-${bindingHash12(binding)}.log`);
50
- }
51
-
52
- /**
53
- * Fallback `agent-run-events.jsonl` location for the daemon's own run
54
- * (#2003): next to the daemon's log, in the same runtime dir this module
55
- * already owns. `@spellkave/session/node`'s `observability.ts` only reaches
56
- * for this when `CAMPAIGN_ARTIFACTS_ROOT` is unset — the Pi-mirrored default.
57
- */
58
- export function runEventsPath(binding: SessionBinding, env?: NodeJS.ProcessEnv): string {
59
- return join(runtimeDir(env), `session-${bindingHash12(binding)}-run-events.jsonl`);
60
- }
61
-
62
- /**
63
- * Create `path`'s containing directory (`0o700`, recursive) if missing.
64
- * Idempotent — safe to call before every bind/spawn/probe.
65
- */
66
- export function ensureParentDir(path: string): void {
67
- const dir = dirname(path);
68
- if (!existsSync(dir)) {
69
- mkdirSync(dir, { recursive: true, mode: 0o700 });
70
- }
71
- try {
72
- chmodSync(dir, 0o700);
73
- } catch {
74
- // Best-effort: a dir we don't own (unexpected on a per-user runtime
75
- // dir) shouldn't block startup over a permission tightening we can't
76
- // make anyway.
77
- }
78
- }
79
-
80
- /** chmod a just-bound socket file to `0o600` — owner-only, matching the run dir's `0o700`. */
81
- export function restrictSocketPermissions(path: string): void {
82
- chmodSync(path, 0o600);
83
- }
@@ -1,122 +0,0 @@
1
- import { join } from "node:path";
2
-
3
- import { type AgentRunSink, createRunEmitter } from "@spellkave/agent-observability";
4
- import {
5
- AGENT_RUN_EVENTS_FILENAME,
6
- createJsonlFileSink,
7
- } from "@spellkave/agent-observability/node";
8
-
9
- export const PI_AGENT_DRIVER = "pi-dev";
10
- export const PI_AGENT_EXPERIMENT_ID = "pi-agent";
11
-
12
- export interface PlayerRunObserverOptions {
13
- actorId: string;
14
- url: string;
15
- db: string;
16
- cwd: string;
17
- env?: NodeJS.ProcessEnv;
18
- now?: () => Date;
19
- sinks?: readonly AgentRunSink[];
20
- driver?: string;
21
- experimentId?: string;
22
- artifactsRoot?: string;
23
- }
24
-
25
- export interface PlayerRunObserver {
26
- readonly runId: string;
27
- readonly artifactPath: string;
28
- observeToolCall<T>(toolName: string, operation: () => Promise<T>): Promise<T>;
29
- end(terminal?: string): Promise<void>;
30
- }
31
-
32
- export function piAgentRunId(now: Date): string {
33
- return `run-${now.toISOString().replaceAll(":", "-").replaceAll(".", "-")}`;
34
- }
35
-
36
- export function piAgentArtifactPath(options: {
37
- cwd: string;
38
- runId: string;
39
- env?: NodeJS.ProcessEnv;
40
- experimentId?: string;
41
- artifactsRoot?: string;
42
- }): string {
43
- const root =
44
- options.artifactsRoot ??
45
- options.env?.CAMPAIGN_ARTIFACTS_ROOT ??
46
- join(options.cwd, ".local", "campaign-runs");
47
- return join(
48
- root,
49
- "experiments",
50
- options.experimentId ?? PI_AGENT_EXPERIMENT_ID,
51
- "runs",
52
- options.runId,
53
- AGENT_RUN_EVENTS_FILENAME,
54
- );
55
- }
56
-
57
- export function createPlayerRunObserver(options: PlayerRunObserverOptions): PlayerRunObserver {
58
- const now = options.now ?? (() => new Date());
59
- const startedAt = now();
60
- const runId = piAgentRunId(startedAt);
61
- const artifactPath = piAgentArtifactPath({
62
- cwd: options.cwd,
63
- runId,
64
- env: options.env,
65
- experimentId: options.experimentId,
66
- artifactsRoot: options.artifactsRoot,
67
- });
68
- const sinks = options.sinks ?? [createJsonlFileSink(artifactPath)];
69
- const emitter = createRunEmitter(
70
- {
71
- run_id: runId,
72
- run_kind: "campaign_playthrough",
73
- actor_id: options.actorId,
74
- role: "PLAYER",
75
- controller_kind: "llm_player",
76
- driver: options.driver ?? PI_AGENT_DRIVER,
77
- now,
78
- },
79
- sinks,
80
- );
81
- let ended = false;
82
-
83
- emitter.emit("run_start", {
84
- url: options.url,
85
- db: options.db,
86
- artifact_path: artifactPath,
87
- });
88
-
89
- return {
90
- runId,
91
- artifactPath,
92
- async observeToolCall(toolName, operation) {
93
- const toolStartedAt = now().getTime();
94
- try {
95
- const result = await operation();
96
- emitter.emit("tool_call", {
97
- tool_name: toolName,
98
- is_error: false,
99
- duration_ms: Math.max(0, now().getTime() - toolStartedAt),
100
- });
101
- return result;
102
- } catch (error) {
103
- emitter.emit("tool_call", {
104
- tool_name: toolName,
105
- is_error: true,
106
- duration_ms: Math.max(0, now().getTime() - toolStartedAt),
107
- summary: "tool execution failed",
108
- });
109
- throw error;
110
- }
111
- },
112
- async end(terminal = "disconnect") {
113
- if (ended) return;
114
- ended = true;
115
- emitter.emit("run_end", {
116
- terminal,
117
- duration_ms: Math.max(0, now().getTime() - startedAt.getTime()),
118
- });
119
- await emitter.close();
120
- },
121
- };
122
- }