castle-web-cli 0.4.228 → 0.4.229

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.
@@ -0,0 +1,380 @@
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as zlib from 'zlib';
5
+ import * as api from './api.js';
6
+ // Which saved version a folder with no sync record came from. Without this, `source-status
7
+ // --adopt` records the deck's current saved version, which is right for a folder that was
8
+ // fetched from it and wrong for one copied from an older save (the Sep 13-14 legacy-home
9
+ // import left a few dozen such folders behind a save made elsewhere): adopting the current
10
+ // key would let the folder's next save overwrite the newer copy without a word.
11
+ //
12
+ // Every save is kept under its own key, so the folder is compared with the deck's saved
13
+ // versions by identical path + sha256. An older version is adopted only when it matches
14
+ // strictly more files than the current one; a folder that grew, shrank or was reworked since
15
+ // the current save still matches the current save best. Bounded by time and bytes: whatever
16
+ // is not settled within the budget falls back to the current version, as before.
17
+ /** Files that differ between any two copies of the same work: tooling rewrites and metadata. */
18
+ const NOISE_FILES = new Set([
19
+ 'castle.json',
20
+ 'package.json',
21
+ 'package-lock.json',
22
+ 'pnpm-lock.yaml',
23
+ 'pnpm-workspace.yaml',
24
+ 'CLAUDE.md',
25
+ 'AGENTS.md',
26
+ 'fonts.generated.js',
27
+ 'preview.png',
28
+ ]);
29
+ /** Top-level entries the archive leaves out (save-deck SOURCE_ARCHIVE_EXCLUDES). */
30
+ const ARCHIVE_EXCLUDES = new Set(['node_modules', 'dist', '.castle', '.git', 'imports']);
31
+ // Measured from when source-status starts, so its own source query counts too: castle-www's
32
+ // open gives the --adopt and --notify calls 15 s between them.
33
+ export const LINEAGE_BUDGET_MS = 9_000;
34
+ const MAX_VERSIONS_EXAMINED = 20;
35
+ const MAX_ARCHIVE_BYTES_TOTAL = 200 * 1024 * 1024;
36
+ const MAX_UNPACKED_BYTES = 512 * 1024 * 1024;
37
+ const MAX_FOLDER_FILES = 20_000;
38
+ const MAX_FOLDER_BYTES = 512 * 1024 * 1024;
39
+ /** Whether a source path counts toward a match: skips noise, dotfiles at the top, `._*`. */
40
+ export function countsTowardMatch(rel) {
41
+ const parts = rel.split('/');
42
+ if (parts.some((part) => part === '' || part === '.' || part === '..'))
43
+ return false;
44
+ if (parts[0].startsWith('.') || ARCHIVE_EXCLUDES.has(parts[0]))
45
+ return false;
46
+ if (parts.includes('node_modules'))
47
+ return false;
48
+ const base = parts[parts.length - 1];
49
+ if (base.startsWith('._'))
50
+ return false;
51
+ if (parts.length === 1 && NOISE_FILES.has(base))
52
+ return false;
53
+ return true;
54
+ }
55
+ class LineageLimit extends Error {
56
+ }
57
+ const HASH_CHUNK_BYTES = 1024 * 1024;
58
+ function hashFile(file, expired) {
59
+ const hash = crypto.createHash('sha256');
60
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
61
+ try {
62
+ const chunk = Buffer.allocUnsafe(HASH_CHUNK_BYTES);
63
+ for (;;) {
64
+ if (expired())
65
+ throw new LineageLimit('budget');
66
+ const read = fs.readSync(fd, chunk, 0, chunk.length, null);
67
+ if (read === 0)
68
+ break;
69
+ hash.update(chunk.subarray(0, read));
70
+ }
71
+ }
72
+ finally {
73
+ fs.closeSync(fd);
74
+ }
75
+ return hash.digest('hex');
76
+ }
77
+ /**
78
+ * The folder's regular files as the archive would carry them, hashed in chunks; null past the
79
+ * size caps or once `expired` says the time is up.
80
+ */
81
+ export function folderManifest(dir, expired = () => false) {
82
+ const out = new Map();
83
+ let bytes = 0;
84
+ const walk = (rel) => {
85
+ for (const entry of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
86
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
87
+ if (entry.isDirectory()) {
88
+ if (!rel && (ARCHIVE_EXCLUDES.has(entry.name) || entry.name.startsWith('.')))
89
+ continue;
90
+ if (entry.name === 'node_modules')
91
+ continue;
92
+ walk(child);
93
+ }
94
+ else if (entry.isFile() && countsTowardMatch(child)) {
95
+ // Sized before anything is read, so one huge asset cannot run memory or time out.
96
+ bytes += fs.lstatSync(path.join(dir, child)).size;
97
+ if (out.size >= MAX_FOLDER_FILES || bytes > MAX_FOLDER_BYTES)
98
+ throw new LineageLimit('folder');
99
+ out.set(child, hashFile(path.join(dir, child), expired));
100
+ }
101
+ }
102
+ };
103
+ try {
104
+ walk('');
105
+ }
106
+ catch (error) {
107
+ if (error instanceof LineageLimit)
108
+ return null;
109
+ throw error;
110
+ }
111
+ return out;
112
+ }
113
+ function readString(block, start, length) {
114
+ const slice = block.subarray(start, start + length);
115
+ const end = slice.indexOf(0);
116
+ return slice.subarray(0, end === -1 ? slice.length : end).toString('utf-8');
117
+ }
118
+ function readSize(block) {
119
+ const field = block.subarray(124, 136);
120
+ if (field[0] & 0x80) {
121
+ // base-256: a size too big for octal. Nothing a deck saves gets there; refuse it.
122
+ throw new LineageLimit('archive');
123
+ }
124
+ const text = readString(block, 124, 12).trim();
125
+ return text ? parseInt(text, 8) : 0;
126
+ }
127
+ function paxPath(body) {
128
+ let offset = 0;
129
+ let found;
130
+ while (offset < body.length) {
131
+ const space = body.indexOf(0x20, offset);
132
+ if (space === -1)
133
+ break;
134
+ const length = parseInt(body.subarray(offset, space).toString('utf-8'), 10);
135
+ if (!Number.isFinite(length) || length <= 0)
136
+ break;
137
+ const record = body.subarray(space + 1, offset + length - 1).toString('utf-8');
138
+ const eq = record.indexOf('=');
139
+ if (eq !== -1 && record.slice(0, eq) === 'path')
140
+ found = record.slice(eq + 1);
141
+ offset += length;
142
+ }
143
+ return found;
144
+ }
145
+ function normalizeArchivePath(name) {
146
+ let rel = name;
147
+ while (rel.startsWith('./'))
148
+ rel = rel.slice(2);
149
+ return rel.replace(/\/+$/, '');
150
+ }
151
+ /**
152
+ * The regular files of a gzipped tar, hashed as they stream (ustar, pax `path`, GNU long
153
+ * names). Links and everything else are skipped; nothing is written to disk.
154
+ */
155
+ export function archiveManifest(gz, expired = () => false) {
156
+ return new Promise((resolve, reject) => {
157
+ const out = new Map();
158
+ const gunzip = zlib.createGunzip();
159
+ let pending = Buffer.alloc(0);
160
+ let unpacked = 0;
161
+ let done = false;
162
+ // The tar's end blocks were read: the rest is only drained, so gunzip still checks its footer.
163
+ let ended = false;
164
+ // The entry being read: its remaining body bytes, padding, and what to do with them.
165
+ let body = null;
166
+ let nextName;
167
+ const finish = (error) => {
168
+ if (done)
169
+ return;
170
+ done = true;
171
+ if (error) {
172
+ gunzip.destroy();
173
+ reject(error);
174
+ }
175
+ else
176
+ resolve(out);
177
+ };
178
+ const endEntry = () => {
179
+ const entry = body;
180
+ body = null;
181
+ if (entry.kind === 'file' && entry.hash) {
182
+ const rel = normalizeArchivePath(entry.name);
183
+ if (countsTowardMatch(rel))
184
+ out.set(rel, entry.hash.digest('hex'));
185
+ }
186
+ else if (entry.kind === 'pax') {
187
+ nextName = paxPath(Buffer.concat(entry.collect)) ?? nextName;
188
+ }
189
+ else if (entry.kind === 'longname') {
190
+ nextName = readString(Buffer.concat(entry.collect), 0, Number.MAX_SAFE_INTEGER);
191
+ }
192
+ };
193
+ const consume = () => {
194
+ for (;;) {
195
+ if (body) {
196
+ if (body.remaining > 0) {
197
+ if (pending.length === 0)
198
+ return;
199
+ const take = Math.min(body.remaining, pending.length);
200
+ const chunk = pending.subarray(0, take);
201
+ body.hash?.update(chunk);
202
+ body.collect?.push(Buffer.from(chunk));
203
+ body.remaining -= take;
204
+ pending = pending.subarray(take);
205
+ continue;
206
+ }
207
+ if (pending.length < body.padding)
208
+ return;
209
+ pending = pending.subarray(body.padding);
210
+ endEntry();
211
+ continue;
212
+ }
213
+ if (pending.length < 512)
214
+ return;
215
+ const block = pending.subarray(0, 512);
216
+ pending = pending.subarray(512);
217
+ if (block.every((byte) => byte === 0)) {
218
+ ended = true;
219
+ pending = Buffer.alloc(0);
220
+ return;
221
+ }
222
+ const size = readSize(block);
223
+ const type = String.fromCharCode(block[156] || 0x30);
224
+ let name = readString(block, 0, 100);
225
+ if (readString(block, 257, 5) === 'ustar') {
226
+ const prefix = readString(block, 345, 155);
227
+ if (prefix)
228
+ name = `${prefix}/${name}`;
229
+ }
230
+ if (nextName !== undefined && type !== 'x' && type !== 'L') {
231
+ name = nextName;
232
+ nextName = undefined;
233
+ }
234
+ const kind = type === '0' || type === '7' ? 'file' : type === 'x' ? 'pax' : type === 'L' ? 'longname' : 'skip';
235
+ if ((kind === 'pax' || kind === 'longname') && size > 1024 * 1024)
236
+ throw new LineageLimit('archive');
237
+ body = {
238
+ remaining: size,
239
+ padding: (512 - (size % 512)) % 512,
240
+ hash: kind === 'file' ? crypto.createHash('sha256') : null,
241
+ collect: kind === 'pax' || kind === 'longname' ? [] : null,
242
+ kind,
243
+ name,
244
+ };
245
+ }
246
+ };
247
+ gunzip.on('data', (chunk) => {
248
+ if (done)
249
+ return;
250
+ unpacked += chunk.length;
251
+ if (unpacked > MAX_UNPACKED_BYTES) {
252
+ finish(new LineageLimit('archive'));
253
+ return;
254
+ }
255
+ if (expired()) {
256
+ finish(new LineageLimit('budget'));
257
+ return;
258
+ }
259
+ if (ended)
260
+ return;
261
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
262
+ try {
263
+ consume();
264
+ }
265
+ catch (error) {
266
+ finish(error instanceof Error ? error : new Error('unreadable archive'));
267
+ }
268
+ });
269
+ // Complete only with the tar's end blocks and gunzip's verified footer (gunzip errors
270
+ // without it): a cut-off current archive would otherwise lose the comparison unfairly.
271
+ gunzip.on('end', () => finish(ended ? undefined : new Error('truncated archive')));
272
+ gunzip.on('error', (error) => finish(error));
273
+ gunzip.end(gz);
274
+ });
275
+ }
276
+ /** How many files the two copies hold identically. */
277
+ export function matchScore(folder, saved) {
278
+ let score = 0;
279
+ for (const [rel, sha] of saved)
280
+ if (folder.get(rel) === sha)
281
+ score += 1;
282
+ return score;
283
+ }
284
+ async function fetchArchiveBytes(url, timeoutMs) {
285
+ const res = await fetch(url, { signal: AbortSignal.timeout(Math.max(1, timeoutMs)) });
286
+ if (!res.ok)
287
+ throw new Error(`archive fetch failed: HTTP ${res.status}`);
288
+ return Buffer.from(await res.arrayBuffer());
289
+ }
290
+ /**
291
+ * The saved version this folder descends from. Never throws: any failure (an older Ghost,
292
+ * a fetch error, the budget) settles on the current version, which is what adopt recorded
293
+ * before this existed.
294
+ */
295
+ export async function findLineage(dir, deckId, server, deps = {}) {
296
+ const nowMs = deps.nowMs ?? Date.now;
297
+ const deadline = deps.deadlineMs ?? nowMs() + LINEAGE_BUDGET_MS;
298
+ const expired = () => nowMs() >= deadline;
299
+ const fetchArchive = deps.fetchArchive ?? fetchArchiveBytes;
300
+ const current = (reason, examined = 0) => ({ outcome: 'skipped', version: server, examined, reason });
301
+ if (expired())
302
+ return current('budget');
303
+ let versions;
304
+ try {
305
+ versions = await (deps.listVersions ?? api.savedSourceHistory)(deckId, deadline - nowMs());
306
+ }
307
+ catch {
308
+ return current(expired() ? 'budget' : 'history_unavailable');
309
+ }
310
+ const head = versions.find((v) => v.s3Key === server.s3Key);
311
+ if (!head)
312
+ return current('current_not_listed');
313
+ const serverMs = Date.parse(server.updatedAt);
314
+ // Older saves only: a refused save leaves its object behind too, and one newer than the
315
+ // current row was never the saved copy.
316
+ const older = versions
317
+ .filter((v) => v.s3Key !== server.s3Key && Date.parse(v.savedAt) < serverMs)
318
+ .sort((a, b) => Date.parse(b.savedAt) - Date.parse(a.savedAt))
319
+ .slice(0, MAX_VERSIONS_EXAMINED - 1);
320
+ if (older.length === 0)
321
+ return { outcome: 'current', version: server, examined: 0 };
322
+ let folder;
323
+ try {
324
+ folder = folderManifest(dir, expired);
325
+ }
326
+ catch {
327
+ return current('folder_unreadable');
328
+ }
329
+ if (!folder)
330
+ return current(expired() ? 'budget' : 'folder_too_large');
331
+ let bytes = 0;
332
+ const read = async (version) => {
333
+ const remaining = deadline - nowMs();
334
+ bytes += version.bytes;
335
+ if (remaining <= 0 || bytes > MAX_ARCHIVE_BYTES_TOTAL)
336
+ return null;
337
+ try {
338
+ return await archiveManifest(await fetchArchive(version.archiveUrl, remaining), expired);
339
+ }
340
+ catch {
341
+ return null;
342
+ }
343
+ };
344
+ const score = async (version) => {
345
+ const manifest = await read(version);
346
+ return manifest && matchScore(folder, manifest);
347
+ };
348
+ const headManifest = await read(head);
349
+ if (headManifest === null)
350
+ return current(expired() ? 'budget' : 'current_unreadable', 1);
351
+ const headScore = matchScore(folder, headManifest);
352
+ // Everything the current save holds is here unchanged: whatever else the folder has, it
353
+ // is not missing that save's work.
354
+ if (headScore === headManifest.size)
355
+ return { outcome: 'current', version: server, examined: 1 };
356
+ let examined = 1;
357
+ let best = null;
358
+ let reason;
359
+ for (const version of older) {
360
+ const s = await score(version);
361
+ if (s === null) {
362
+ reason = nowMs() >= deadline ? 'budget' : bytes > MAX_ARCHIVE_BYTES_TOTAL ? 'bytes' : 'archive_unreadable';
363
+ if (reason !== 'archive_unreadable')
364
+ break;
365
+ continue;
366
+ }
367
+ examined += 1;
368
+ // Newest first, so a tie keeps the newer of two equally good older saves.
369
+ if (s > headScore && (!best || s > best.score))
370
+ best = { version, score: s };
371
+ }
372
+ if (!best)
373
+ return { outcome: 'current', version: server, examined, ...(reason ? { reason } : {}) };
374
+ return {
375
+ outcome: 'older',
376
+ version: { s3Key: best.version.s3Key, updatedAt: best.version.savedAt },
377
+ examined,
378
+ ...(reason ? { reason } : {}),
379
+ };
380
+ }
@@ -1,3 +1,4 @@
1
+ import type { Lineage, LineageDeps } from './sourceLineage.js';
1
2
  export declare const WEB_SOURCE_SYNC_FILE: string;
2
3
  /** `get-deck --side` copies of the saved source, one folder per saved version. */
3
4
  export declare const SAVED_SOURCE_DIR: string;
@@ -66,6 +67,12 @@ export interface SourceStatusResult {
66
67
  marker: Omit<WebSourceSyncMarker, 'deckId'> | null;
67
68
  server: ServerSourceVersion | null;
68
69
  adopted?: true;
70
+ /** How --adopt chose the version it recorded (sourceLineage.ts). */
71
+ lineage?: {
72
+ outcome: Lineage['outcome'];
73
+ examined: number;
74
+ reason?: string;
75
+ };
69
76
  notified?: true;
70
77
  }
71
78
  export interface SourceStatusOptions {
@@ -73,6 +80,8 @@ export interface SourceStatusOptions {
73
80
  notify?: boolean;
74
81
  /** Injected by tests; defaults to the webDeckSource query. */
75
82
  fetchServer?: (deckId: string) => Promise<ServerSourceVersion | null>;
83
+ /** Injected by tests; defaults to sourceLineage's findLineage. */
84
+ findLineage?: (dir: string, deckId: string, server: ServerSourceVersion, deps: LineageDeps) => Promise<Lineage>;
76
85
  now?: () => Date;
77
86
  }
78
87
  export declare function sourceNewerNotice(dir: string, savedAt: string, syncedAt: string): {
@@ -12,6 +12,8 @@ import { WEB_SOURCE_NEWER_MARKER_FILE } from './cloudGit.js';
12
12
  // It lives in `.castle/agent/`: excluded from the source archive (so it never travels into a
13
13
  // save or a remix), and a durable editor namespace in deck persistence (so a cold resume keeps
14
14
  // it). A missing or malformed marker reads as absent: the folder is then adopted, never refused.
15
+ // `source-status --adopt` records the saved version the folder actually matches
16
+ // (sourceLineage.ts), so a folder copied from an older save is told the saved copy is newer.
15
17
  export const WEB_SOURCE_SYNC_FILE = path.join('.castle', 'agent', 'web-source-sync.json');
16
18
  /** `get-deck --side` copies of the saved source, one folder per saved version. */
17
19
  export const SAVED_SOURCE_DIR = path.join('.castle', 'agent', 'saved-source');
@@ -168,6 +170,7 @@ export async function sourceStatus(dir, opts = {}) {
168
170
  return result;
169
171
  }
170
172
  async function computeSourceStatus(dir, opts) {
173
+ const startedAtMs = Date.now();
171
174
  const projectDir = path.resolve(dir);
172
175
  // An unreadable or missing folder is a real error, unlike a folder that isn't a deck.
173
176
  if (!fs.statSync(projectDir).isDirectory())
@@ -191,18 +194,29 @@ async function computeSourceStatus(dir, opts) {
191
194
  return result;
192
195
  if (!marker) {
193
196
  result.status = 'no-marker';
194
- if (opts.adopt) {
195
- const written = writeSyncMarker(projectDir, deckId, server, 'adopt', opts.now?.());
196
- result.marker = { s3Key: written.s3Key, updatedAt: written.updatedAt, syncedAt: written.syncedAt, via: written.via };
197
- result.adopted = true;
198
- }
199
- return result;
197
+ if (!opts.adopt)
198
+ return result;
199
+ const { findLineage: defaultFindLineage, LINEAGE_BUDGET_MS } = await import('./sourceLineage.js');
200
+ const lineage = await (opts.findLineage ?? defaultFindLineage)(projectDir, deckId, server, {
201
+ deadlineMs: startedAtMs + LINEAGE_BUDGET_MS,
202
+ });
203
+ const written = writeSyncMarker(projectDir, deckId, lineage.version, 'adopt', opts.now?.());
204
+ result.marker = { s3Key: written.s3Key, updatedAt: written.updatedAt, syncedAt: written.syncedAt, via: written.via };
205
+ result.adopted = true;
206
+ result.lineage = {
207
+ outcome: lineage.outcome,
208
+ examined: lineage.examined,
209
+ ...(lineage.reason ? { reason: lineage.reason } : {}),
210
+ };
211
+ // Adopted at an older save: from here on it is an ordinary folder behind the saved copy.
212
+ if (lineage.outcome !== 'older')
213
+ return result;
200
214
  }
201
- result.status = compareSync(marker, server);
215
+ result.status = compareSync(result.marker, server);
202
216
  if (result.status === 'saved-newer' && opts.notify) {
203
217
  const file = path.join(projectDir, WEB_SOURCE_NEWER_MARKER_FILE);
204
218
  fs.mkdirSync(path.dirname(file), { recursive: true });
205
- atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, marker.updatedAt))}\n`);
219
+ atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, result.marker.updatedAt))}\n`);
206
220
  result.notified = true;
207
221
  }
208
222
  return result;
@@ -222,7 +236,8 @@ export function describeSourceStatus(result) {
222
236
  case 'lag':
223
237
  return `The server has not caught up with this folder's last save yet (${humanTime(result.marker.updatedAt)}).`;
224
238
  case 'saved-newer':
225
- return (`The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
239
+ return ((result.adopted ? `This folder matches an older save of deck ${result.deckId}. ` : '') +
240
+ `The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
226
241
  `this folder last synced ${humanTime(result.marker.updatedAt)}).` +
227
242
  (result.notified ? ' The agent has been told.' : ''));
228
243
  }
@@ -82,7 +82,7 @@
82
82
  "title": "base",
83
83
  "deckId": "yRcmH4_aYllE",
84
84
  "cardId": "zkFdingmIm3m",
85
- "publishedVersion": "2026-09-30T05:53:28.406Z",
85
+ "publishedVersion": "2026-10-01T02:24:47.884Z",
86
86
  "provides": [
87
87
  "castle-web-sdk"
88
88
  ]
@@ -189,6 +189,49 @@ leave, and shutdown presence automatically, and `participants.read` reflects
189
189
  those host writes. The SDK never writes participant presence, and there is no
190
190
  public touch method.
191
191
 
192
+ A world-notification template is published copy with named slots; push copy is
193
+ always authored by the deck and is never generated at runtime. Ghost owns
194
+ delivery, muting, expiry, and rate caps, including notifications scheduled for
195
+ later. `notifications.notify` and `notifications.cancel` return counts only, so
196
+ deck code cannot learn which participants were muted or unavailable.
197
+
198
+ ```js
199
+ await session.world.notifications.notify({
200
+ key: "lantern-overdue",
201
+ participantIds: [player.participantId],
202
+ templateId: "lantern_overdue",
203
+ slots: { npc: "Mara" },
204
+ at: "2026-10-01T18:00:00Z",
205
+ });
206
+
207
+ await session.world.notifications.cancel({
208
+ key: "lantern-overdue",
209
+ participantIds: [player.participantId],
210
+ });
211
+ ```
212
+
213
+ A destination can opt into real elapsed time with
214
+ `worldTime: { advance: "wallClock" }`. On boot, `catchUp` reads the latest
215
+ checkpoint, clamps the elapsed duration, and commits the full checkpoint
216
+ returned by `apply`; it retries one revision conflict and never advances an
217
+ authored game clock on its own.
218
+
219
+ The checkpoint marker prevents an elapsed interval from being counted twice
220
+ and never moves backwards if the host clock regresses. If a prior commit landed
221
+ without its acknowledgement being observed, the next boot counts only time
222
+ elapsed after that marker, so `apply` may run again for that new interval; it
223
+ returns `{ applied: false, elapsedMs: 0 }` without calling `apply` only when no
224
+ time has passed since the marker.
225
+
226
+ ```js
227
+ const result = await session.world.catchUp({
228
+ maxElapsedMs: 7 * 24 * 60 * 60 * 1000,
229
+ apply({ elapsedMs, checkpoint }) {
230
+ return advanceWorld(checkpoint, elapsedMs);
231
+ },
232
+ });
233
+ ```
234
+
192
235
  ## Store
193
236
 
194
237
  `Store` saves data one key at a time. It is the storage to use for
@@ -14,7 +14,7 @@ export type { LeaderboardData, LeaderboardEntry, LeaderboardOptions, Leaderboard
14
14
  export { Lifecycle } from "./lifecycle";
15
15
  export type { CastleLifecycleApi } from "./lifecycle";
16
16
  export { Multiplayer } from "./multiplayer";
17
- export type { CastleMultiplayerApi, MultiplayerConnection, MultiplayerConnectionState, MultiplayerDestinationJoinResult, MultiplayerDestinationOptions, MultiplayerJoinHint, MultiplayerJoinOptions, MultiplayerRoster, MultiplayerStateMetadata, } from "./multiplayer";
17
+ export type { CastleMultiplayerApi, MultiplayerConnection, MultiplayerConnectionState, MultiplayerCompleteScheduledBeatCommand, MultiplayerCompleteScheduledBeatResult, MultiplayerDestinationJoinResult, MultiplayerDestinationOptions, MultiplayerEvaluateBeatsCommand, MultiplayerEvaluateBeatsResult, MultiplayerJoinHint, MultiplayerJoinOptions, MultiplayerRoster, MultiplayerScheduledBeatReason, MultiplayerScheduledBeatSelection, MultiplayerStateMetadata, MultiplayerStoryOpportunity, MultiplayerWorldCharacterCommand, MultiplayerWorldCharacterCommandResult, MultiplayerWorldCharacterCommandResultValue, } from "./multiplayer";
18
18
  export type { MultiplayerVoice, VoiceJoinStatus, VoiceListener, VoiceMixEntry, VoiceSpatialOptions, VoiceState, VoiceVector, } from "./multiplayerVoice";
19
19
  export type { MultiplayerDestinationAudience, MultiplayerSoloReason } from "./commands";
20
20
  export { MAX_CLIENT_FRAME_BYTES, MAX_PLAYERS_CAP } from "./multiplayerProtocol";
@@ -79,7 +79,43 @@ export type MultiplayerWorldCharacterCommand = {
79
79
  type: "record_event";
80
80
  eventTypeId: string;
81
81
  data?: Json;
82
+ } | MultiplayerEvaluateBeatsCommand | MultiplayerCompleteScheduledBeatCommand;
83
+ export type MultiplayerStoryOpportunity = {
84
+ type: "approach" | "room_entry" | "world_action";
85
+ id: string;
82
86
  };
87
+ export interface MultiplayerEvaluateBeatsCommand {
88
+ type: "evaluate_beats";
89
+ opportunityId: string;
90
+ opportunity: MultiplayerStoryOpportunity;
91
+ presentCharacterIds: string[];
92
+ }
93
+ export interface MultiplayerCompleteScheduledBeatCommand {
94
+ type: "complete_scheduled_beat";
95
+ deliveryId: string;
96
+ outcomeId: string;
97
+ }
98
+ export interface MultiplayerScheduledBeatSelection {
99
+ deliveryId: string;
100
+ beatId: string;
101
+ characterId: string;
102
+ openingText: string;
103
+ }
104
+ export interface MultiplayerScheduledBeatReason {
105
+ beatId: string;
106
+ status: "selected" | "expired" | "eligible" | "blocked";
107
+ reasonCodes: string[];
108
+ }
109
+ export interface MultiplayerEvaluateBeatsResult {
110
+ selection: MultiplayerScheduledBeatSelection | null;
111
+ reasons?: MultiplayerScheduledBeatReason[];
112
+ }
113
+ export interface MultiplayerCompleteScheduledBeatResult {
114
+ deliveryId: string;
115
+ outcomeId: string;
116
+ completed: true;
117
+ }
118
+ export type MultiplayerWorldCharacterCommandResultValue<Command extends MultiplayerWorldCharacterCommand> = Command extends MultiplayerEvaluateBeatsCommand ? MultiplayerEvaluateBeatsResult : Command extends MultiplayerCompleteScheduledBeatCommand ? MultiplayerCompleteScheduledBeatResult : Json;
83
119
  export type MultiplayerWorldCharacterQuery = {
84
120
  type: "inspect";
85
121
  } | {
@@ -106,11 +142,11 @@ export interface MultiplayerWorldCharacterInspectResult<Gameplay = unknown, Shar
106
142
  }>;
107
143
  sources: Source[];
108
144
  }
109
- export interface MultiplayerWorldCharacterCommandResult {
145
+ export interface MultiplayerWorldCharacterCommandResult<Result = unknown> {
110
146
  operationId: string;
111
147
  status: "applied" | "ineligible";
112
148
  replayed: boolean;
113
- result: unknown;
149
+ result: Result;
114
150
  worldRevision: string;
115
151
  }
116
152
  export interface MultiplayerConnection {
@@ -129,11 +165,11 @@ export interface MultiplayerConnection {
129
165
  requestCharacterTurn(request: MultiplayerCharacterTurnRequest): Promise<MultiplayerCharacterTurnAdmission>;
130
166
  /** Recovers the durable status of a prior operation after reconnecting. */
131
167
  getCharacterTurnStatus(operationId: string): Promise<MultiplayerCharacterTurnStatusResult>;
132
- requestCharacterCommand(request: {
168
+ requestCharacterCommand<Command extends MultiplayerWorldCharacterCommand>(request: {
133
169
  requestId: string;
134
170
  operationId: string;
135
- command: MultiplayerWorldCharacterCommand;
136
- }): Promise<MultiplayerWorldCharacterCommandResult>;
171
+ command: Command;
172
+ }): Promise<MultiplayerWorldCharacterCommandResult<MultiplayerWorldCharacterCommandResultValue<Command>>>;
137
173
  readCharacters(request: {
138
174
  requestId: string;
139
175
  query: {
@@ -781,6 +781,41 @@ function normalizeWorldCharacterCommandRequest(request) {
781
781
  },
782
782
  };
783
783
  }
784
+ if (command.type === "evaluate_beats") {
785
+ const opportunity = command.opportunity;
786
+ if (!opportunity || typeof opportunity !== "object") {
787
+ throw characterError("INVALID_ARGUMENT", "command.opportunity must be an opportunity object.");
788
+ }
789
+ if (opportunity.type !== "approach" &&
790
+ opportunity.type !== "room_entry" &&
791
+ opportunity.type !== "world_action") {
792
+ throw characterError("INVALID_ARGUMENT", "command.opportunity.type is invalid.");
793
+ }
794
+ return {
795
+ requestId,
796
+ operationId,
797
+ command: {
798
+ type: "evaluate_beats",
799
+ opportunityId: boundedCharacterSafeKey(command.opportunityId, "command.opportunityId"),
800
+ opportunity: {
801
+ type: opportunity.type,
802
+ id: boundedCharacterSafeKey(opportunity.id, "command.opportunity.id"),
803
+ },
804
+ presentCharacterIds: boundedCharacterSafeKeys(command.presentCharacterIds, 16, "command.presentCharacterIds"),
805
+ },
806
+ };
807
+ }
808
+ if (command.type === "complete_scheduled_beat") {
809
+ return {
810
+ requestId,
811
+ operationId,
812
+ command: {
813
+ type: "complete_scheduled_beat",
814
+ deliveryId: boundedCharacterSafeKey(command.deliveryId, "command.deliveryId"),
815
+ outcomeId: boundedCharacterSafeKey(command.outcomeId, "command.outcomeId"),
816
+ },
817
+ };
818
+ }
784
819
  throw characterError("INVALID_ARGUMENT", "Unknown shared character command type.");
785
820
  }
786
821
  function normalizeWorldCharacterReadRequest(request) {
@@ -831,6 +866,22 @@ function boundedCharacterIds(value, maxItems, field, maxCharacters = 128) {
831
866
  }
832
867
  return ids;
833
868
  }
869
+ function boundedCharacterSafeKeys(value, maxItems, field) {
870
+ if (!Array.isArray(value) || value.length > maxItems) {
871
+ throw characterError("INVALID_ARGUMENT", `${field} may contain at most ${maxItems} ids.`);
872
+ }
873
+ const ids = value.map((item) => boundedCharacterSafeKey(item, field));
874
+ if (new Set(ids).size !== ids.length) {
875
+ throw characterError("INVALID_ARGUMENT", `${field} may not contain duplicate ids.`);
876
+ }
877
+ return ids;
878
+ }
879
+ function boundedCharacterSafeKey(value, field) {
880
+ if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(value)) {
881
+ throw characterError("INVALID_ARGUMENT", `${field} must be a safe key of at most 64 characters.`);
882
+ }
883
+ return value;
884
+ }
834
885
  function boundedCharacterText(value, maxBytes, field, maxCharacters = maxBytes) {
835
886
  if (typeof value !== "string" ||
836
887
  value.length === 0 ||