@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.
- package/LICENSE +89 -0
- package/bin/spellkave-session-daemon.js +5 -0
- package/package.json +58 -4
- package/src/acting-context.ts +222 -0
- package/src/authoring/caller-tools.ts +227 -0
- package/src/authoring/index.ts +28 -0
- package/src/authoring/live-applyset-port.ts +432 -0
- package/src/authoring/live-author-target.ts +995 -0
- package/src/authoring/live-can-i-port.ts +152 -0
- package/src/authoring/live-exploration-port.ts +274 -0
- package/src/authoring/live-grants-port.ts +172 -0
- package/src/authoring/live-scenes-port.ts +84 -0
- package/src/authoring/live-scoped-instance-port.ts +355 -0
- package/src/binding.ts +125 -0
- package/src/index.ts +24 -0
- package/src/live/discovery-closure-walk.ts +318 -0
- package/src/live/kernel-convergence-support.ts +122 -0
- package/src/live/seed.ts +37 -0
- package/src/live/support.ts +82 -0
- package/src/node/client.ts +233 -0
- package/src/node/connection-controller.ts +469 -0
- package/src/node/daemon-entry.ts +57 -0
- package/src/node/daemon.ts +629 -0
- package/src/node/index.ts +110 -0
- package/src/node/live-delta.ts +229 -0
- package/src/node/observability.ts +481 -0
- package/src/node/paths.ts +83 -0
- package/src/node/player-run-observer.ts +122 -0
- package/src/node/protocol.ts +200 -0
- package/src/node/spawn.ts +225 -0
- package/src/node/world-events.ts +270 -0
- package/src/player-tools/delta-tracker.ts +1 -0
- package/src/player-tools/index.ts +10 -0
- package/src/player-tools/node-adapter.ts +9 -0
- package/src/player-tools/observation.ts +1 -0
- package/src/player-tools/player-host.ts +92 -0
- package/src/player-tools/push-events.ts +1 -0
- package/src/player-tools/query-protocol.ts +1 -0
- package/src/player-tools/refusal-prose.ts +1 -0
- package/src/player-tools/resolution.ts +1 -0
- package/src/player-tools/tool-registry.ts +1 -0
- package/src/player-tools/tools.ts +42 -0
- package/src/player-tools/world-events.ts +119 -0
- package/src/session.ts +604 -0
- package/README.md +0 -3
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// JSONL wire protocol over the session daemon's unix socket (#1990 decision
|
|
2
|
+
// 3): one generic `invoke` frame plus a tiny control plane. No tool names
|
|
3
|
+
// appear anywhere in this file — the registry decided the shape
|
|
4
|
+
// (`defineTool` + typebox schema + JSON args -> transport-neutral result), so the
|
|
5
|
+
// wire protocol only needs to pass a tool NAME through, never enumerate one.
|
|
6
|
+
//
|
|
7
|
+
// -> {"id":1,"op":"invoke","tool":"<name>","args":{...}}
|
|
8
|
+
// <- {"id":1,"ok":true,"result":{...}}
|
|
9
|
+
// <- {"id":1,"ok":false,"error":{"message":"...","code":"..."}}
|
|
10
|
+
// <- {"id":1,"ok":true,"result":{...},"pushes":[...]}
|
|
11
|
+
//
|
|
12
|
+
// Control ops: `hello` (protocol version + binding echo), `status` (binding,
|
|
13
|
+
// uptime, subscribed, and — #2003 — the active `observability` mode/artifact
|
|
14
|
+
// path), `shutdown` (clean close), `drain_pushes` (sk-0m4.22: drain the
|
|
15
|
+
// daemon's ONE WorldEventBuilder without running a PLAYER tool). Each
|
|
16
|
+
// request/response is framed as one JSON object per line (JSONL, ADR-0002's
|
|
17
|
+
// own wire convention).
|
|
18
|
+
//
|
|
19
|
+
// `pushes` is ADDITIVE (sk-0m4.22): pending WorldEvents piggyback on every
|
|
20
|
+
// response so a PLAYER driving the world through `sk` sees incoming hits,
|
|
21
|
+
// damage dealt, XP, and turn transitions without a protocol-version bump or
|
|
22
|
+
// unsolicited daemon→client frames. Existing consumers that ignore unknown
|
|
23
|
+
// fields keep working. Omitted (not `[]`) when the daemon has no feed — the
|
|
24
|
+
// fake-registry test seam — so those tests stay byte-stable.
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
normalizeWorldActorCausalContext,
|
|
28
|
+
type WorldActorCausalContext,
|
|
29
|
+
} from "@spellkave/agent-observability";
|
|
30
|
+
|
|
31
|
+
export const PROTOCOL_VERSION = 1;
|
|
32
|
+
|
|
33
|
+
export interface InvokeRequest {
|
|
34
|
+
id: number;
|
|
35
|
+
op: "invoke";
|
|
36
|
+
tool: string;
|
|
37
|
+
args: unknown;
|
|
38
|
+
/** Optional non-secret observability context beside (never inside) tool args. */
|
|
39
|
+
causal_context?: WorldActorCausalContext;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface HelloRequest {
|
|
43
|
+
id: number;
|
|
44
|
+
op: "hello";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface StatusRequest {
|
|
48
|
+
id: number;
|
|
49
|
+
op: "status";
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ShutdownRequest {
|
|
53
|
+
id: number;
|
|
54
|
+
op: "shutdown";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface DrainPushesRequest {
|
|
58
|
+
id: number;
|
|
59
|
+
op: "drain_pushes";
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ListToolsRequest {
|
|
63
|
+
id: number;
|
|
64
|
+
op: "list_tools";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export type Request =
|
|
68
|
+
| ListToolsRequest
|
|
69
|
+
| InvokeRequest
|
|
70
|
+
| HelloRequest
|
|
71
|
+
| StatusRequest
|
|
72
|
+
| ShutdownRequest
|
|
73
|
+
| DrainPushesRequest;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* sk-uglp: an out-of-band session-lifecycle notice a gateway attaches to the
|
|
77
|
+
* next response after something happened to the WORLD SESSION itself (not to
|
|
78
|
+
* the world): today only `world_reset` — the session daemon behind this
|
|
79
|
+
* caller died (world connection lost after a wipe/redeploy) and a fresh one
|
|
80
|
+
* was attached. Additive, same discipline as `pushes`; clients that ignore
|
|
81
|
+
* unknown fields keep working.
|
|
82
|
+
*/
|
|
83
|
+
export interface SessionNotice {
|
|
84
|
+
kind: "world_reset";
|
|
85
|
+
text: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface OkResponse<R = unknown> {
|
|
89
|
+
id: number;
|
|
90
|
+
ok: true;
|
|
91
|
+
result: R;
|
|
92
|
+
/** Pending WorldEvents drained from the daemon's one session-lifetime
|
|
93
|
+
* builder (sk-0m4.22). Omitted when the daemon has no feed, or when the
|
|
94
|
+
* drain produced nothing. Never an empty array. */
|
|
95
|
+
pushes?: readonly unknown[];
|
|
96
|
+
/** sk-uglp: see {@link SessionNotice}. Omitted when there is nothing to say. */
|
|
97
|
+
notices?: readonly SessionNotice[];
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export interface ErrorDetail {
|
|
101
|
+
message: string;
|
|
102
|
+
code?: string;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export interface ErrResponse {
|
|
106
|
+
id: number;
|
|
107
|
+
ok: false;
|
|
108
|
+
error: ErrorDetail;
|
|
109
|
+
/** Same piggyback as {@link OkResponse.pushes} — a tool_error must not
|
|
110
|
+
* swallow events that accumulated before the throw. */
|
|
111
|
+
pushes?: readonly unknown[];
|
|
112
|
+
/** sk-uglp: see {@link SessionNotice}. */
|
|
113
|
+
notices?: readonly SessionNotice[];
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export type Response<R = unknown> = OkResponse<R> | ErrResponse;
|
|
117
|
+
|
|
118
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
119
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function hasNumericId(
|
|
123
|
+
value: Record<string, unknown>,
|
|
124
|
+
): value is Record<string, unknown> & { id: number } {
|
|
125
|
+
return typeof value.id === "number" && Number.isFinite(value.id);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Type guard for a well-formed request frame. Rejects anything the codec can't safely dispatch. */
|
|
129
|
+
export function isRequest(value: unknown): value is Request {
|
|
130
|
+
if (!isPlainObject(value) || !hasNumericId(value)) return false;
|
|
131
|
+
switch (value.op) {
|
|
132
|
+
case "list_tools":
|
|
133
|
+
case "hello":
|
|
134
|
+
case "status":
|
|
135
|
+
case "shutdown":
|
|
136
|
+
case "drain_pushes":
|
|
137
|
+
return true;
|
|
138
|
+
case "invoke":
|
|
139
|
+
return (
|
|
140
|
+
typeof value.tool === "string" &&
|
|
141
|
+
value.tool.length > 0 &&
|
|
142
|
+
"args" in value &&
|
|
143
|
+
(value.causal_context === undefined ||
|
|
144
|
+
normalizeWorldActorCausalContext(value.causal_context) !== undefined)
|
|
145
|
+
);
|
|
146
|
+
default:
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Best-effort id extraction from a frame that failed {@link isRequest} — for error replies. */
|
|
152
|
+
export function requestId(value: unknown): number | undefined {
|
|
153
|
+
if (isPlainObject(value) && typeof value.id === "number" && Number.isFinite(value.id)) {
|
|
154
|
+
return value.id;
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function isOkResponse(value: unknown): value is OkResponse {
|
|
160
|
+
return isPlainObject(value) && hasNumericId(value) && value.ok === true && "result" in value;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function isErrResponse(value: unknown): value is ErrResponse {
|
|
164
|
+
if (!isPlainObject(value) || !hasNumericId(value) || value.ok !== false) return false;
|
|
165
|
+
const error = value.error;
|
|
166
|
+
return isPlainObject(error) && typeof error.message === "string";
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function isResponse(value: unknown): value is Response {
|
|
170
|
+
return isOkResponse(value) || isErrResponse(value);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Encode one frame as a newline-terminated JSON line — the unit this codec writes to the socket. */
|
|
174
|
+
export function encodeFrame(value: unknown): string {
|
|
175
|
+
return `${JSON.stringify(value)}\n`;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Incremental JSONL decoder: feed raw socket chunks in, get back the frames
|
|
180
|
+
* (parsed, but NOT yet validated as `Request`/`Response` — callers apply the
|
|
181
|
+
* type guards above) that completed since the last call. Blank lines are
|
|
182
|
+
* skipped rather than erroring, matching ADR-0002's JSONL convention
|
|
183
|
+
* elsewhere in the repo.
|
|
184
|
+
*/
|
|
185
|
+
export class JsonlFrameDecoder {
|
|
186
|
+
private buffer = "";
|
|
187
|
+
|
|
188
|
+
push(chunk: string): unknown[] {
|
|
189
|
+
this.buffer += chunk;
|
|
190
|
+
const frames: unknown[] = [];
|
|
191
|
+
let newlineIndex = this.buffer.indexOf("\n");
|
|
192
|
+
while (newlineIndex !== -1) {
|
|
193
|
+
const line = this.buffer.slice(0, newlineIndex).trim();
|
|
194
|
+
this.buffer = this.buffer.slice(newlineIndex + 1);
|
|
195
|
+
if (line.length > 0) frames.push(JSON.parse(line));
|
|
196
|
+
newlineIndex = this.buffer.indexOf("\n");
|
|
197
|
+
}
|
|
198
|
+
return frames;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// `ensureDaemon` — probe / stale-socket-unlink / spawn / poll-ready / attach
|
|
2
|
+
// (#1990 decision 4). Modeled on herdr's `src/server/autodetect.rs`:
|
|
3
|
+
// `is_server_listening_at` (connect-probe; a socket file with nobody
|
|
4
|
+
// listening reads as `ConnectionRefused`/`ENOENT`, both "stale"),
|
|
5
|
+
// `spawn_server_daemon` (detached, stdio redirected to a log file),
|
|
6
|
+
// `wait_for_server_socket` (poll at a fixed interval up to a timeout).
|
|
7
|
+
|
|
8
|
+
import { type ChildProcess, spawn as spawnChildProcess } from "node:child_process";
|
|
9
|
+
import { closeSync, existsSync, openSync, unlinkSync } from "node:fs";
|
|
10
|
+
import * as net from "node:net";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
|
|
13
|
+
import type { SessionBinding } from "../binding.ts";
|
|
14
|
+
import {
|
|
15
|
+
logPath as deriveLogPath,
|
|
16
|
+
socketPath as deriveSocketPath,
|
|
17
|
+
ensureParentDir,
|
|
18
|
+
} from "./paths.ts";
|
|
19
|
+
|
|
20
|
+
const DEFAULT_READY_TIMEOUT_MS = 15_000;
|
|
21
|
+
const DEFAULT_POLL_INTERVAL_MS = 50;
|
|
22
|
+
const DEFAULT_PROBE_TIMEOUT_MS = 500;
|
|
23
|
+
|
|
24
|
+
const BINDING_ENV = "SPELLKAVE_SESSION_BINDING";
|
|
25
|
+
const SOCKET_ENV = "SPELLKAVE_SESSION_SOCKET";
|
|
26
|
+
const TOKEN_ENV = "SPELLKAVE_SESSION_TOKEN";
|
|
27
|
+
const IDLE_TIMEOUT_ENV = "SPELLKAVE_SESSION_IDLE_TIMEOUT_MS";
|
|
28
|
+
const WORLD_SLUG_ENV = "SPELLKAVE_WORLD_SLUG";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* This package's own `tsx`-shebang'd daemon entry — the default spawn
|
|
32
|
+
* target, same shape as `packages/spellkave-cli/bin/sk.js`. Relies on `tsx`
|
|
33
|
+
* being resolvable on the spawned child's `PATH` (true under `pnpm`/`just`,
|
|
34
|
+
* which put each workspace package's `node_modules/.bin` on `PATH`). A host
|
|
35
|
+
* that spawns `ensureDaemon` outside such an environment — or that wants to
|
|
36
|
+
* respawn itself instead (e.g. `sk session start`, #1990 slice 3) — should
|
|
37
|
+
* pass an explicit `command` override rather than rely on this default.
|
|
38
|
+
*/
|
|
39
|
+
const DEFAULT_DAEMON_BIN = fileURLToPath(
|
|
40
|
+
new URL("../../bin/spellkave-session-daemon.js", import.meta.url),
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
export interface DaemonCommand {
|
|
44
|
+
command: string;
|
|
45
|
+
args: string[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Minimal shape `ensureDaemon` needs from a spawned child — narrower than `ChildProcess` so tests can fake it. */
|
|
49
|
+
export interface SpawnedProcessLike {
|
|
50
|
+
unref(): void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type SpawnDaemonFn = (
|
|
54
|
+
command: string,
|
|
55
|
+
args: string[],
|
|
56
|
+
options: { detached: boolean; stdio: ["ignore", number, number]; env: NodeJS.ProcessEnv },
|
|
57
|
+
) => SpawnedProcessLike;
|
|
58
|
+
|
|
59
|
+
export interface EnsureDaemonOptions {
|
|
60
|
+
token?: string;
|
|
61
|
+
/** Stable catalog identity for this daemon's single world. */
|
|
62
|
+
worldSlug?: string;
|
|
63
|
+
idleTimeoutMs?: number;
|
|
64
|
+
readyTimeoutMs?: number;
|
|
65
|
+
pollIntervalMs?: number;
|
|
66
|
+
probeTimeoutMs?: number;
|
|
67
|
+
/** Override the derived socket path. Defaults to `socketPath(binding)`; tests point this at a temp dir. */
|
|
68
|
+
socketPath?: string;
|
|
69
|
+
/** Override the spawned daemon process. Defaults to this package's own entry via `tsx`. */
|
|
70
|
+
command?: DaemonCommand;
|
|
71
|
+
/** Injectable for tests — avoids spawning a real process. */
|
|
72
|
+
spawnFn?: SpawnDaemonFn;
|
|
73
|
+
/** Injectable probe for tests — avoids touching a real socket. */
|
|
74
|
+
probeFn?: (path: string) => Promise<boolean>;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface DaemonAttachment {
|
|
78
|
+
socketPath: string;
|
|
79
|
+
/** `true` when this call spawned a new daemon; `false` when it attached to one already listening. */
|
|
80
|
+
spawned: boolean;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Attach to `binding`'s daemon, spawning one first if none is listening.
|
|
85
|
+
* A socket FILE that exists but refuses connections (a crashed daemon's
|
|
86
|
+
* leftover) is unlinked before respawning — never mistaken for "already
|
|
87
|
+
* running".
|
|
88
|
+
*/
|
|
89
|
+
export async function ensureDaemon(
|
|
90
|
+
binding: SessionBinding,
|
|
91
|
+
options: EnsureDaemonOptions = {},
|
|
92
|
+
): Promise<DaemonAttachment> {
|
|
93
|
+
const path = options.socketPath ?? deriveSocketPath(binding);
|
|
94
|
+
const probe =
|
|
95
|
+
options.probeFn ??
|
|
96
|
+
((p: string) => probeSocket(p, options.probeTimeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS));
|
|
97
|
+
|
|
98
|
+
if (await probe(path)) {
|
|
99
|
+
return { socketPath: path, spawned: false };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
await unlinkStaleSocket(path, probe);
|
|
103
|
+
spawnDaemonProcess(binding, path, options);
|
|
104
|
+
await waitForReady(
|
|
105
|
+
path,
|
|
106
|
+
probe,
|
|
107
|
+
options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS,
|
|
108
|
+
options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,
|
|
109
|
+
);
|
|
110
|
+
return { socketPath: path, spawned: true };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Connect-probe a unix socket path. `false` covers both "no file" and "file present, nobody listening". */
|
|
114
|
+
export function probeSocket(path: string, timeoutMs = DEFAULT_PROBE_TIMEOUT_MS): Promise<boolean> {
|
|
115
|
+
if (!existsSync(path)) return Promise.resolve(false);
|
|
116
|
+
return new Promise((resolve) => {
|
|
117
|
+
const socket = net.createConnection(path);
|
|
118
|
+
let settled = false;
|
|
119
|
+
const finish = (result: boolean): void => {
|
|
120
|
+
if (settled) return;
|
|
121
|
+
settled = true;
|
|
122
|
+
clearTimeout(timer);
|
|
123
|
+
socket.removeAllListeners();
|
|
124
|
+
socket.destroy();
|
|
125
|
+
resolve(result);
|
|
126
|
+
};
|
|
127
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
128
|
+
socket.once("connect", () => finish(true));
|
|
129
|
+
socket.once("error", () => finish(false));
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function unlinkStaleSocket(
|
|
134
|
+
path: string,
|
|
135
|
+
probe: (p: string) => Promise<boolean>,
|
|
136
|
+
): Promise<void> {
|
|
137
|
+
if (!existsSync(path)) return;
|
|
138
|
+
// Re-probe: a concurrent `ensureDaemon` caller may have started listening
|
|
139
|
+
// between our own probe above and this call.
|
|
140
|
+
if (await probe(path)) return;
|
|
141
|
+
try {
|
|
142
|
+
unlinkSync(path);
|
|
143
|
+
} catch (err) {
|
|
144
|
+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function spawnDaemonProcess(
|
|
149
|
+
binding: SessionBinding,
|
|
150
|
+
socketPathValue: string,
|
|
151
|
+
options: EnsureDaemonOptions,
|
|
152
|
+
): void {
|
|
153
|
+
ensureParentDir(socketPathValue);
|
|
154
|
+
const log = deriveLogPath(binding);
|
|
155
|
+
ensureParentDir(log);
|
|
156
|
+
const logFd = openSync(log, "a");
|
|
157
|
+
try {
|
|
158
|
+
const spawnFn = options.spawnFn ?? defaultSpawnFn;
|
|
159
|
+
const command = options.command ?? { command: DEFAULT_DAEMON_BIN, args: [] };
|
|
160
|
+
// `...process.env` is the spawn-time config snapshot (#2003): the child
|
|
161
|
+
// inherits `SPELLKAVE_RUN_EVENTS`, `CAMPAIGN_ARTIFACTS_ROOT`,
|
|
162
|
+
// `SPELLKAVE_AGENT_OBS_OTLP_ENDPOINT`, and the standard `OTEL_EXPORTER_OTLP_*`
|
|
163
|
+
// vars exactly as they read HERE, once, never re-read afterward — a
|
|
164
|
+
// binding-keyed daemon's env is fixed at spawn; changing observability
|
|
165
|
+
// config means `sk session stop` + respawn, same as any other daemon env.
|
|
166
|
+
const env: NodeJS.ProcessEnv = {
|
|
167
|
+
...process.env,
|
|
168
|
+
[BINDING_ENV]: JSON.stringify(binding),
|
|
169
|
+
[SOCKET_ENV]: socketPathValue,
|
|
170
|
+
...(options.token === undefined ? {} : { [TOKEN_ENV]: options.token }),
|
|
171
|
+
...(options.worldSlug?.trim() ? { [WORLD_SLUG_ENV]: options.worldSlug.trim() } : {}),
|
|
172
|
+
...(options.idleTimeoutMs === undefined
|
|
173
|
+
? {}
|
|
174
|
+
: { [IDLE_TIMEOUT_ENV]: String(options.idleTimeoutMs) }),
|
|
175
|
+
};
|
|
176
|
+
const child = spawnFn(command.command, command.args, {
|
|
177
|
+
detached: true,
|
|
178
|
+
stdio: ["ignore", logFd, logFd],
|
|
179
|
+
env,
|
|
180
|
+
});
|
|
181
|
+
child.unref();
|
|
182
|
+
} finally {
|
|
183
|
+
closeSync(logFd);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function defaultSpawnFn(
|
|
188
|
+
command: string,
|
|
189
|
+
args: string[],
|
|
190
|
+
options: { detached: boolean; stdio: ["ignore", number, number]; env: NodeJS.ProcessEnv },
|
|
191
|
+
): ChildProcess {
|
|
192
|
+
return spawnChildProcess(command, args, options);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function waitForReady(
|
|
196
|
+
path: string,
|
|
197
|
+
probe: (p: string) => Promise<boolean>,
|
|
198
|
+
timeoutMs: number,
|
|
199
|
+
intervalMs: number,
|
|
200
|
+
): Promise<void> {
|
|
201
|
+
const deadline = Date.now() + timeoutMs;
|
|
202
|
+
// Sequential polling is the point here — each iteration must observe the
|
|
203
|
+
// previous probe's outcome before retrying.
|
|
204
|
+
while (Date.now() < deadline) {
|
|
205
|
+
if (await probe(path)) return;
|
|
206
|
+
await delay(intervalMs);
|
|
207
|
+
}
|
|
208
|
+
throw new Error(
|
|
209
|
+
`session daemon did not become ready within ${timeoutMs}ms (socket: ${path}). ` +
|
|
210
|
+
"It may still be starting; check the daemon log next to the socket.",
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function delay(ms: number): Promise<void> {
|
|
215
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Env var names `daemon-entry.ts` reads — exported so tests/spawn stay in sync with the entry point. */
|
|
219
|
+
export const DAEMON_ENV = {
|
|
220
|
+
binding: BINDING_ENV,
|
|
221
|
+
socket: SOCKET_ENV,
|
|
222
|
+
token: TOKEN_ENV,
|
|
223
|
+
worldSlug: WORLD_SLUG_ENV,
|
|
224
|
+
idleTimeoutMs: IDLE_TIMEOUT_ENV,
|
|
225
|
+
} as const;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Session-daemon push feed (sk-0m4.22): drains the session's ONE world-event
|
|
2
|
+
// cursor (`session.worldEvents` — one per session, SDK-owned, see
|
|
3
|
+
// `ledger/designs/session-owns-the-world-event-cursor.md`) on demand so a
|
|
4
|
+
// PLAYER driving the world through `sk` finally sees incoming hits, damage
|
|
5
|
+
// dealt, XP, and turn transitions.
|
|
6
|
+
//
|
|
7
|
+
// Mirrors `.pi/extensions/spellkave/src/extension/world-events.ts` (sk-dms.16)
|
|
8
|
+
// — same ADR-0093 D-2 vocabulary, same D-5 recreate-trap contract. Before the
|
|
9
|
+
// cursor moved onto the session, this feed constructed its own builder;
|
|
10
|
+
// recreating one per `invoke` would be finding #98: a freshly constructed
|
|
11
|
+
// builder primes quiet on its first `diffAndAdvance()` and silently drops
|
|
12
|
+
// everything that happened between calls. That risk is now structural, not
|
|
13
|
+
// discipline-enforced — `createSessionWorldEventFeed` takes the session's
|
|
14
|
+
// cursor as its `builder` (`startDaemon` passes `live.session.worldEvents`),
|
|
15
|
+
// and the daemon holds one session for its whole process lifetime, so there
|
|
16
|
+
// is no per-invoke construction left to get wrong.
|
|
17
|
+
//
|
|
18
|
+
// THE PROTOCOL DOES NOT BREAK: pending events ride an additive `pushes`
|
|
19
|
+
// field on every response (`protocol.ts`). No unsolicited daemon→client
|
|
20
|
+
// frames, no `PROTOCOL_VERSION` bump. A drain that throws must never turn a
|
|
21
|
+
// working tool call into a failed one — events are a courtesy channel; the
|
|
22
|
+
// tool's own result is the contract (same posture as the pi feed).
|
|
23
|
+
//
|
|
24
|
+
// PRIMING happens at construction, not on the first invoke: `startDaemon`
|
|
25
|
+
// only builds this feed after `openSession` has subscribed, so the snapshot
|
|
26
|
+
// is live. Leaving the first `diffAndAdvance()` to the first `sk act` would
|
|
27
|
+
// swallow that act's own dealt_hit / self_hit as "already true".
|
|
28
|
+
|
|
29
|
+
import type { WorldActorTracer } from "@spellkave/agent-observability";
|
|
30
|
+
import { type EntityRef, resolveEntityId, type SnapshotDb } from "@spellkave/sdk";
|
|
31
|
+
import { readRecentTraces } from "@spellkave/sdk/readers";
|
|
32
|
+
import {
|
|
33
|
+
createWorldEventBuilder,
|
|
34
|
+
type WorldEvent,
|
|
35
|
+
type WorldEventBuilder,
|
|
36
|
+
} from "../player-tools/push-events.ts";
|
|
37
|
+
|
|
38
|
+
const MAX_TRACKED_WORLD_EVENT_IDS = 1_024;
|
|
39
|
+
const TRACE_SCAN_WINDOW = 200;
|
|
40
|
+
|
|
41
|
+
type WorldEventIdentityKind = "trace_id" | "event_id";
|
|
42
|
+
|
|
43
|
+
interface WorldEventIdentity {
|
|
44
|
+
kind: WorldEventIdentityKind;
|
|
45
|
+
id: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
interface WorldEventAnomaly {
|
|
49
|
+
name: "world_event_duplicate" | "world_event_unreported";
|
|
50
|
+
identity: WorldEventIdentity;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
class BoundedStringSet {
|
|
54
|
+
private readonly values = new Set<string>();
|
|
55
|
+
|
|
56
|
+
constructor(private readonly capacity: number) {}
|
|
57
|
+
|
|
58
|
+
has(value: string): boolean {
|
|
59
|
+
return this.values.has(value);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
add(value: string): void {
|
|
63
|
+
if (this.values.delete(value)) this.values.add(value);
|
|
64
|
+
else {
|
|
65
|
+
this.values.add(value);
|
|
66
|
+
if (this.values.size > this.capacity) {
|
|
67
|
+
const oldest = this.values.values().next().value;
|
|
68
|
+
if (oldest !== undefined) this.values.delete(oldest);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
delete(value: string): void {
|
|
74
|
+
this.values.delete(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
entries(): string[] {
|
|
78
|
+
return [...this.values];
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function eventIdentity(event: WorldEvent): WorldEventIdentity | undefined {
|
|
83
|
+
const record = event as unknown as Record<string, unknown>;
|
|
84
|
+
if (typeof record.trace_id === "string" && record.trace_id.length > 0) {
|
|
85
|
+
return { kind: "trace_id", id: record.trace_id };
|
|
86
|
+
}
|
|
87
|
+
// Honor a source event id structurally when a projection supplies one. This
|
|
88
|
+
// keeps the failsafe log-only: it never adds identifiers to delivery payloads.
|
|
89
|
+
if (typeof record.event_id === "string" && record.event_id.length > 0) {
|
|
90
|
+
return { kind: "event_id", id: record.event_id };
|
|
91
|
+
}
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function identityKey(identity: WorldEventIdentity): string {
|
|
96
|
+
return `${identity.kind}:${identity.id}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface SessionWorldEventFeedDeps {
|
|
100
|
+
/** Live snapshot of the daemon's open session. */
|
|
101
|
+
db: () => SnapshotDb;
|
|
102
|
+
/** The connected body entity ref (branded at the daemon / fixture door). */
|
|
103
|
+
actorId: () => EntityRef | undefined;
|
|
104
|
+
/** Existing world-actor OTLP tracer; no new telemetry projection/table. */
|
|
105
|
+
telemetry?: WorldActorTracer;
|
|
106
|
+
/** Injectable builder for live-node-free failsafe tests. */
|
|
107
|
+
builder?: WorldEventBuilder;
|
|
108
|
+
/** Injectable bound for eviction tests; production defaults to 1,024 ids. */
|
|
109
|
+
maxTrackedIds?: number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface SessionWorldEventDrainOptions {
|
|
113
|
+
/** Compare visible reportable traces with delivered ids on an orient drain. */
|
|
114
|
+
auditVisibleTraces?: boolean;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export interface SessionWorldEventFeed {
|
|
118
|
+
/**
|
|
119
|
+
* Drain whatever the world has done to this actor since the last drain
|
|
120
|
+
* (or since construction-time priming). Returns `[]` whenever nothing
|
|
121
|
+
* happened and when the snapshot read races a disconnect — the common
|
|
122
|
+
* case, so callers can attach the result unconditionally.
|
|
123
|
+
*/
|
|
124
|
+
drain(options?: SessionWorldEventDrainOptions): WorldEvent[];
|
|
125
|
+
/**
|
|
126
|
+
* sk-0m4.73: the SAME underlying `WorldEventBuilder` `drain()` calls
|
|
127
|
+
* `diffAndAdvance()` on — exposed so `startDaemon` can inject it into the
|
|
128
|
+
* companion tools' `conversation.builder` option (the `communicate` reply
|
|
129
|
+
* window). MUST NOT be used to construct a second builder; there is only
|
|
130
|
+
* ever this one for the daemon's whole lifetime (module header).
|
|
131
|
+
*/
|
|
132
|
+
readonly builder: WorldEventBuilder;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Construct the daemon's ONE builder. Call this exactly once per
|
|
137
|
+
* `startDaemon` lifetime and hand the returned feed to the dispatcher —
|
|
138
|
+
* never call `createWorldEventBuilder` again for the same live actor.
|
|
139
|
+
*/
|
|
140
|
+
export function createSessionWorldEventFeed(
|
|
141
|
+
deps: SessionWorldEventFeedDeps,
|
|
142
|
+
): SessionWorldEventFeed {
|
|
143
|
+
const rawBuilder: WorldEventBuilder =
|
|
144
|
+
deps.builder ??
|
|
145
|
+
createWorldEventBuilder(
|
|
146
|
+
() => deps.db(),
|
|
147
|
+
() => deps.actorId(),
|
|
148
|
+
);
|
|
149
|
+
const capacity = Math.max(1, deps.maxTrackedIds ?? MAX_TRACKED_WORLD_EVENT_IDS);
|
|
150
|
+
const deliveredIds = new BoundedStringSet(capacity);
|
|
151
|
+
const knownVisibleTraceIds = new BoundedStringSet(capacity);
|
|
152
|
+
const pendingVisibleTraceIds = new BoundedStringSet(capacity);
|
|
153
|
+
|
|
154
|
+
function visibleReportableTraceIds(): string[] {
|
|
155
|
+
try {
|
|
156
|
+
const currentDb = deps.db();
|
|
157
|
+
const currentActorId = deps.actorId();
|
|
158
|
+
const ownEntityId =
|
|
159
|
+
currentActorId === undefined ? undefined : resolveEntityId(currentDb, currentActorId);
|
|
160
|
+
return readRecentTraces(currentDb, TRACE_SCAN_WINDOW)
|
|
161
|
+
.filter(
|
|
162
|
+
(trace) =>
|
|
163
|
+
trace.inscribed_by !== String(ownEntityId) &&
|
|
164
|
+
typeof trace.payload === "object" &&
|
|
165
|
+
trace.payload !== null &&
|
|
166
|
+
typeof (trace.payload as { text?: unknown }).text === "string",
|
|
167
|
+
)
|
|
168
|
+
.map((trace) => trace.trace_id);
|
|
169
|
+
} catch {
|
|
170
|
+
return [];
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
for (const traceId of visibleReportableTraceIds()) knownVisibleTraceIds.add(traceId);
|
|
175
|
+
|
|
176
|
+
function emitAnomalies(anomalies: readonly WorldEventAnomaly[]): void {
|
|
177
|
+
if (anomalies.length === 0) return;
|
|
178
|
+
try {
|
|
179
|
+
const span = deps.telemetry?.startSpan("spellkave.world_event_delivery", {
|
|
180
|
+
"spellkave.actor_id": deps.actorId() ?? "",
|
|
181
|
+
});
|
|
182
|
+
for (const anomaly of anomalies) {
|
|
183
|
+
try {
|
|
184
|
+
span?.addEvent(anomaly.name, {
|
|
185
|
+
"spellkave.cause_kind": anomaly.identity.kind,
|
|
186
|
+
"spellkave.cause_id": anomaly.identity.id,
|
|
187
|
+
});
|
|
188
|
+
} catch {
|
|
189
|
+
// A failing projection loses only its own diagnostic event.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
span?.end("error");
|
|
194
|
+
} catch {
|
|
195
|
+
// Observability cannot change world-event delivery.
|
|
196
|
+
}
|
|
197
|
+
} catch {
|
|
198
|
+
// Same optional-observability posture as observeReducerAttempt.
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function observeReturnedEvents(
|
|
203
|
+
events: WorldEvent[],
|
|
204
|
+
options: SessionWorldEventDrainOptions = {},
|
|
205
|
+
): WorldEvent[] {
|
|
206
|
+
const anomalies: WorldEventAnomaly[] = [];
|
|
207
|
+
for (const event of events) {
|
|
208
|
+
const identity = eventIdentity(event);
|
|
209
|
+
if (identity === undefined) continue;
|
|
210
|
+
const key = identityKey(identity);
|
|
211
|
+
if (deliveredIds.has(key)) anomalies.push({ name: "world_event_duplicate", identity });
|
|
212
|
+
deliveredIds.add(key);
|
|
213
|
+
if (identity.kind === "trace_id") pendingVisibleTraceIds.delete(identity.id);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
for (const traceId of visibleReportableTraceIds()) {
|
|
217
|
+
if (knownVisibleTraceIds.has(traceId)) continue;
|
|
218
|
+
knownVisibleTraceIds.add(traceId);
|
|
219
|
+
if (!deliveredIds.has(identityKey({ kind: "trace_id", id: traceId }))) {
|
|
220
|
+
pendingVisibleTraceIds.add(traceId);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (options.auditVisibleTraces === true) {
|
|
224
|
+
for (const traceId of pendingVisibleTraceIds.entries()) {
|
|
225
|
+
anomalies.push({
|
|
226
|
+
name: "world_event_unreported",
|
|
227
|
+
identity: { kind: "trace_id", id: traceId },
|
|
228
|
+
});
|
|
229
|
+
pendingVisibleTraceIds.delete(traceId);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
emitAnomalies(anomalies);
|
|
233
|
+
return events;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// Proxy both builder entry points. Companion tools consume takeWhere()
|
|
237
|
+
// directly for synchronous replies/consequences; observing only daemon
|
|
238
|
+
// drains would falsely call those deliberately-taken events unreported.
|
|
239
|
+
const builder: WorldEventBuilder = {
|
|
240
|
+
diffAndAdvance: () => observeReturnedEvents(rawBuilder.diffAndAdvance()),
|
|
241
|
+
takeWhere: (predicate) => observeReturnedEvents(rawBuilder.takeWhere(predicate)),
|
|
242
|
+
};
|
|
243
|
+
// Prime NOW, not on the first invoke. `startDaemon` only constructs this
|
|
244
|
+
// feed after `openSession` has subscribed, so the snapshot is live. If we
|
|
245
|
+
// left priming to the first `sk act`, that act's own dealt_hit / self_hit
|
|
246
|
+
// would be swallowed as "already true" — the exact player-visible gap
|
|
247
|
+
// this change exists to close. The world as it stands at daemon start is
|
|
248
|
+
// not news; everything after this call is.
|
|
249
|
+
try {
|
|
250
|
+
rawBuilder.diffAndAdvance();
|
|
251
|
+
} catch {
|
|
252
|
+
// Same courtesy-channel posture as drain(): a snapshot race at
|
|
253
|
+
// construction must not refuse to start the daemon. The next drain
|
|
254
|
+
// will be the priming call in that case.
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return {
|
|
258
|
+
drain(options: SessionWorldEventDrainOptions = {}): WorldEvent[] {
|
|
259
|
+
try {
|
|
260
|
+
return observeReturnedEvents(rawBuilder.diffAndAdvance(), options);
|
|
261
|
+
} catch {
|
|
262
|
+
// A drain must never turn a working invoke into a failed one: the
|
|
263
|
+
// events are a courtesy channel, the tool's own result is the contract.
|
|
264
|
+
// A disconnect racing the drain is the expected case here.
|
|
265
|
+
return [];
|
|
266
|
+
}
|
|
267
|
+
},
|
|
268
|
+
builder,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "@spellkave/tool-player";
|