castle-web-cli 0.4.219 → 0.4.221
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/dist/agent.js +11 -1
- package/dist/api.d.ts +3 -1
- package/dist/api.js +16 -5
- package/dist/castle-host/host.js +58 -41
- package/dist/cloudGit.d.ts +7 -0
- package/dist/cloudGit.js +13 -1
- package/dist/cloudGitServe.d.ts +25 -0
- package/dist/cloudGitServe.js +62 -21
- package/dist/get-deck.d.ts +17 -0
- package/dist/get-deck.js +149 -0
- package/dist/index.js +15 -2
- package/dist/init.js +1 -1
- package/dist/save-deck.d.ts +6 -1
- package/dist/save-deck.js +66 -6
- package/dist/webSourceSync.d.ts +83 -0
- package/dist/webSourceSync.js +229 -0
- package/kits/base/CLAUDE.md +1 -1
- package/kits/base/castle.json +1 -1
- package/kits/base/package-lock.json +1 -1
- package/kits/base/sdk/README.md +15 -8
- package/kits/base/sdk/agent.js +10 -7
- package/kits/base/sdk/commands.d.ts +1 -1
- package/kits/base/sdk/commands.js +1 -1
- package/kits/base/sdk/server/platformHandle.d.ts +2 -0
- package/kits/base/sdk/server/wrapper.d.ts +34 -0
- package/kits/base/sdk/server/wrapper.js +154 -6
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -155,8 +155,10 @@ function usage() {
|
|
|
155
155
|
castle-web serve [dir] [--port PORT] [--host HOST] [--open] [--detach]
|
|
156
156
|
castle-web restart [--port PORT]
|
|
157
157
|
castle-web screenshot [--out FILE] [--port PORT]
|
|
158
|
-
castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private]
|
|
158
|
+
castle-web save-deck [dir] [--title TITLE] [--caption TEXT] [--visibility unlisted|private] [--force] (--force: save over a newer saved copy)
|
|
159
159
|
castle-web get-deck [dir] [--deck-id ID] [--force] (replaces the source if the deck is already there)
|
|
160
|
+
castle-web get-deck <dir> --side [--deck-id ID] [--json] (fetches the saved copy into <dir>/.castle/agent/saved-source/<stamp>/, touching nothing else)
|
|
161
|
+
castle-web source-status <dir> [--adopt] [--notify] [--json] (whether the deck's saved copy is newer than this folder)
|
|
160
162
|
castle-web list-decks [dir] [--kind mine|saved|kits] (decks this one could import; ids are what add-import takes)
|
|
161
163
|
castle-web add-import <deckId|url|kit> [dir] [--as ALIAS] (adds another deck, or a kit this CLI ships, as a read-only dependency in imports/)
|
|
162
164
|
castle-web fork-import-file <imports/...> [dir] (this deck's own version of one imported file)
|
|
@@ -518,7 +520,7 @@ async function main() {
|
|
|
518
520
|
const title = getFlagValue('--title');
|
|
519
521
|
const caption = getFlagValue('--caption');
|
|
520
522
|
const visibility = getFlagValue('--visibility');
|
|
521
|
-
await saveDeck(dir, { title, caption, visibility });
|
|
523
|
+
await saveDeck(dir, { title, caption, visibility, force: hasFlag('--force') });
|
|
522
524
|
break;
|
|
523
525
|
}
|
|
524
526
|
case 'get-deck': {
|
|
@@ -527,9 +529,20 @@ async function main() {
|
|
|
527
529
|
await getDeck(findPositionalDir(), {
|
|
528
530
|
deckId: getFlagValue('--deck-id'),
|
|
529
531
|
force: hasFlag('--force'),
|
|
532
|
+
side: hasFlag('--side'),
|
|
533
|
+
json: hasFlag('--json'),
|
|
530
534
|
});
|
|
531
535
|
break;
|
|
532
536
|
}
|
|
537
|
+
case 'source-status': {
|
|
538
|
+
const { sourceStatus, describeSourceStatus } = await import('./webSourceSync.js');
|
|
539
|
+
const result = await sourceStatus(findPositionalDir(), {
|
|
540
|
+
adopt: hasFlag('--adopt'),
|
|
541
|
+
notify: hasFlag('--notify'),
|
|
542
|
+
});
|
|
543
|
+
console.log(hasFlag('--json') ? JSON.stringify(result) : describeSourceStatus(result));
|
|
544
|
+
break;
|
|
545
|
+
}
|
|
533
546
|
case 'list-decks': {
|
|
534
547
|
await listDecks(findPositionalDir(), { kind: getFlagValue('--kind') });
|
|
535
548
|
break;
|
package/dist/init.js
CHANGED
|
@@ -54,7 +54,7 @@ if (!(await mountEditorRoute())) startGame(initCard());
|
|
|
54
54
|
// Registry version of castle-web-sdk to inject when scaffolding from a
|
|
55
55
|
// globally-installed castle-web (not from inside the workspace). Bumped
|
|
56
56
|
// alongside cli/sdk version bumps.
|
|
57
|
-
const PUBLISHED_SDK_VERSION = '0.4.
|
|
57
|
+
const PUBLISHED_SDK_VERSION = '0.4.41';
|
|
58
58
|
// Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
|
|
59
59
|
// face can ship without a cli release, and a caret range means an existing
|
|
60
60
|
// deck's next install picks it up. Nothing here has to move when it does.
|
package/dist/save-deck.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as api from './api.js';
|
|
2
|
+
import { type SavePrecondition } from './webSourceSync.js';
|
|
2
3
|
export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
|
|
3
4
|
export declare const SAVE_STAGE_TELEMETRY_PREFIX = "CASTLE_SAVE_TELEMETRY ";
|
|
4
5
|
export declare const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = "CASTLE_SAVE_COVER_SELECTION ";
|
|
@@ -7,11 +8,15 @@ export declare function runTar(args: string[], opts?: {
|
|
|
7
8
|
capture?: boolean;
|
|
8
9
|
}): Promise<string>;
|
|
9
10
|
export declare function archiveSource(projectDir: string): Promise<Buffer>;
|
|
10
|
-
export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string): Promise<string>;
|
|
11
|
+
export declare function downloadSourceArchive(source: api.WebDeckSource, namePrefix: string, log?: (line: string) => void): Promise<string>;
|
|
12
|
+
export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null): Promise<api.WebDeckSource>;
|
|
13
|
+
export declare function checkSavePrecondition(projectDir: string, deckId: string, force: boolean): Promise<SavePrecondition>;
|
|
11
14
|
export type SaveVisibility = 'unlisted' | 'private';
|
|
12
15
|
export interface SaveDeckOptions {
|
|
13
16
|
title?: string;
|
|
14
17
|
caption?: string;
|
|
15
18
|
visibility?: SaveVisibility;
|
|
19
|
+
/** Save even when the deck's saved copy is newer than this folder. */
|
|
20
|
+
force?: boolean;
|
|
16
21
|
}
|
|
17
22
|
export declare function saveDeck(dir: string, opts?: SaveDeckOptions): Promise<void>;
|
package/dist/save-deck.js
CHANGED
|
@@ -10,6 +10,7 @@ import { resolveServerConfig } from './castleJson.js';
|
|
|
10
10
|
import { selectSaveCover } from './saveCover.js';
|
|
11
11
|
import { COVER_FILE } from './localPaths.js';
|
|
12
12
|
import { buildServerBundle } from './serverBundle.js';
|
|
13
|
+
import { decideSavePrecondition, EXIT_SAVED_DECK_NEWER, fetchServerSourceVersion, readSyncMarker, saveRefusedLine, saveRefusedMessage, WEB_DECK_SOURCE_STALE_CODE, writeSyncMarker, } from './webSourceSync.js';
|
|
13
14
|
// `imports/` is derived state like node_modules: a dependency's files belong to
|
|
14
15
|
// the deck that published them, and castle.json's import pins are enough to fetch
|
|
15
16
|
// them again -- so they neither bloat this deck's archive nor get republished as
|
|
@@ -95,14 +96,14 @@ export async function archiveSource(projectDir) {
|
|
|
95
96
|
// Written to tmp and read or untarred out of there, never moved out: in a sandbox
|
|
96
97
|
// the deck is on a different filesystem from tmp, and a rename across that is EXDEV.
|
|
97
98
|
// The caller owns the file it gets back.
|
|
98
|
-
export async function downloadSourceArchive(source, namePrefix) {
|
|
99
|
-
|
|
99
|
+
export async function downloadSourceArchive(source, namePrefix, log = console.log) {
|
|
100
|
+
log(`Fetching ${source.archiveUrl}`);
|
|
100
101
|
const res = await fetch(source.archiveUrl, { signal: AbortSignal.timeout(60000) });
|
|
101
102
|
if (!res.ok) {
|
|
102
103
|
throw new Error(`Archive fetch failed: HTTP ${res.status}`);
|
|
103
104
|
}
|
|
104
105
|
const buf = Buffer.from(await res.arrayBuffer());
|
|
105
|
-
|
|
106
|
+
log(`Archive: ${(buf.length / 1024).toFixed(1)}KB (updated ${source.updatedAt})`);
|
|
106
107
|
const file = path.join(os.tmpdir(), `${namePrefix}-${nanoid(8)}.tar.gz`);
|
|
107
108
|
fs.writeFileSync(file, buf);
|
|
108
109
|
return file;
|
|
@@ -122,7 +123,9 @@ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, l
|
|
|
122
123
|
if (response.status >= 300)
|
|
123
124
|
throw new Error(`${label} failed: HTTP ${response.status}`);
|
|
124
125
|
}
|
|
125
|
-
|
|
126
|
+
// `expectedS3Key` is the save precondition (api.saveWebDeckSource). Returns the saved source,
|
|
127
|
+
// whose key and time become this folder's sync marker.
|
|
128
|
+
export async function uploadSource(projectDir, deckId, expectedS3Key) {
|
|
126
129
|
const archive = await traceSaveStage('source_archive', () => archiveSource(projectDir), (value) => ({ bytes: value.byteLength }));
|
|
127
130
|
const sizeKB = archive.length / 1024;
|
|
128
131
|
console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
|
|
@@ -131,7 +134,24 @@ async function uploadSource(projectDir, deckId) {
|
|
|
131
134
|
const view = new Uint8Array(archive.byteLength);
|
|
132
135
|
view.set(archive);
|
|
133
136
|
await traceSaveStage('source_upload', () => uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload'));
|
|
134
|
-
|
|
137
|
+
return traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId, expectedS3Key));
|
|
138
|
+
}
|
|
139
|
+
// Refused: the saved copy is newer than this folder. One machine-readable stdout line (castle-www
|
|
140
|
+
// turns it into its "saved copy is newer" dialog), the human message on stderr, and a dedicated
|
|
141
|
+
// exit code -- set, not exited with, so a piped stdout is flushed before the process ends. The
|
|
142
|
+
// caller returns straight after.
|
|
143
|
+
function refuseSave(dir, refusal) {
|
|
144
|
+
console.log(saveRefusedLine(refusal));
|
|
145
|
+
console.error(saveRefusedMessage(dir, refusal));
|
|
146
|
+
process.exitCode = EXIT_SAVED_DECK_NEWER;
|
|
147
|
+
}
|
|
148
|
+
// Before anything is uploaded or published: the deck goes live at updateCardAndDeckV2, so a
|
|
149
|
+
// refusal any later would leave it half-published. Only a deck that already has an id is
|
|
150
|
+
// checked; a new deck has no saved copy to overwrite.
|
|
151
|
+
export async function checkSavePrecondition(projectDir, deckId, force) {
|
|
152
|
+
const marker = readSyncMarker(projectDir, deckId);
|
|
153
|
+
const server = await fetchServerSourceVersion(deckId);
|
|
154
|
+
return decideSavePrecondition(marker, server, force);
|
|
135
155
|
}
|
|
136
156
|
const SERVER_BUNDLE_STATE = path.join('.castle', 'published-server-bundle.json');
|
|
137
157
|
function readPublishedServerBundleState(projectDir) {
|
|
@@ -254,6 +274,23 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
254
274
|
process.exit(1);
|
|
255
275
|
}
|
|
256
276
|
const castleJson = readCastleJson(projectDir);
|
|
277
|
+
const existingDeckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : null;
|
|
278
|
+
// A deck without an id is new: the source commit sends no precondition, as before.
|
|
279
|
+
let expectedS3Key;
|
|
280
|
+
let markerVia = 'save-deck';
|
|
281
|
+
if (existingDeckId) {
|
|
282
|
+
const precondition = await checkSavePrecondition(projectDir, existingDeckId, opts.force === true);
|
|
283
|
+
if (precondition.kind === 'refuse') {
|
|
284
|
+
refuseSave(dir, precondition);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
expectedS3Key = precondition.expectedS3Key;
|
|
288
|
+
markerVia = precondition.via;
|
|
289
|
+
if (precondition.adopt) {
|
|
290
|
+
console.error('Note: this folder has no record of which saved copy it came from; adopting it as the ' +
|
|
291
|
+
"deck's saved copy. Later saves are refused if someone else saves this deck in between.");
|
|
292
|
+
}
|
|
293
|
+
}
|
|
257
294
|
console.log('Bundling...');
|
|
258
295
|
const bundle = await traceSaveStage('bundle', () => bundleProject(projectDir), (value) => ({ bytes: Buffer.byteLength(value) }));
|
|
259
296
|
const sizeKB = bundle.length / 1024;
|
|
@@ -368,11 +405,34 @@ export async function saveDeck(dir, opts = {}) {
|
|
|
368
405
|
`"${title}" is live on the new client but its server is unchanged.`);
|
|
369
406
|
}
|
|
370
407
|
console.log('Uploading source archive...');
|
|
371
|
-
|
|
408
|
+
// The precondition only applies to the deck it was checked against.
|
|
409
|
+
const saved = await uploadSource(projectDir, result.deckId, result.deckId === existingDeckId ? expectedS3Key : undefined);
|
|
372
410
|
console.log('Source archive saved.');
|
|
411
|
+
try {
|
|
412
|
+
writeSyncMarker(projectDir, result.deckId, saved, markerVia);
|
|
413
|
+
}
|
|
414
|
+
catch (e) {
|
|
415
|
+
// The save itself succeeded; a missing marker only means the next save adopts again.
|
|
416
|
+
console.error(`Could not record the saved version: ${e instanceof Error ? e.message : String(e)}`);
|
|
417
|
+
}
|
|
373
418
|
}
|
|
374
419
|
catch (e) {
|
|
375
420
|
const code = e?.extensions?.code ?? '';
|
|
421
|
+
if (code === WEB_DECK_SOURCE_STALE_CODE) {
|
|
422
|
+
// Someone saved between the check above and this commit. The game itself is already
|
|
423
|
+
// live; only its saved source was refused. Reported like the check's own refusal.
|
|
424
|
+
const server = existingDeckId
|
|
425
|
+
? await fetchServerSourceVersion(existingDeckId).catch(() => null)
|
|
426
|
+
: null;
|
|
427
|
+
const marker = existingDeckId ? readSyncMarker(projectDir, existingDeckId) : null;
|
|
428
|
+
console.error('The playable deck was updated, but its saved source was not: someone else saved it first.');
|
|
429
|
+
refuseSave(dir, {
|
|
430
|
+
savedAt: server?.updatedAt ?? null,
|
|
431
|
+
syncedAt: marker?.updatedAt ?? null,
|
|
432
|
+
savedS3Key: server?.s3Key ?? null,
|
|
433
|
+
});
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
376
436
|
if (code === 'LOGIN_REQUIRED') {
|
|
377
437
|
console.error('Not logged in. Run `castle-web login` first.');
|
|
378
438
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export declare const WEB_SOURCE_SYNC_FILE: string;
|
|
2
|
+
/** `get-deck --side` copies of the saved source, one folder per saved version. */
|
|
3
|
+
export declare const SAVED_SOURCE_DIR: string;
|
|
4
|
+
export declare const SAVED_SOURCE_KEEP = 2;
|
|
5
|
+
export type SyncVia = 'get-deck' | 'save-deck' | 'adopt' | 'force';
|
|
6
|
+
export interface WebSourceSyncMarker {
|
|
7
|
+
deckId: string;
|
|
8
|
+
s3Key: string;
|
|
9
|
+
updatedAt: string;
|
|
10
|
+
syncedAt: string;
|
|
11
|
+
via: SyncVia;
|
|
12
|
+
}
|
|
13
|
+
export interface ServerSourceVersion {
|
|
14
|
+
s3Key: string;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
}
|
|
17
|
+
/** The folder's marker, or null when missing, malformed, or recorded for another deck. */
|
|
18
|
+
export declare function readSyncMarker(dir: string, deckId?: string): WebSourceSyncMarker | null;
|
|
19
|
+
export declare function writeSyncMarker(dir: string, deckId: string, source: ServerSourceVersion, via: SyncVia, now?: Date): WebSourceSyncMarker;
|
|
20
|
+
/** Removes a `source-status --notify` notice the serve has not consumed yet. */
|
|
21
|
+
export declare function clearSourceNewerNotice(dir: string): void;
|
|
22
|
+
export type SyncComparison = 'in-sync' | 'saved-newer' | 'lag';
|
|
23
|
+
/**
|
|
24
|
+
* The lag rule. `webDeckSource` reads a replica, so right after a save from this folder the
|
|
25
|
+
* server can still show the previous row: a different key alone is not proof of a newer save.
|
|
26
|
+
* Saved-newer only when the keys differ AND the server's save time is strictly newer than the
|
|
27
|
+
* marker's; otherwise it is lag, and the server's own check (primary, under lock) decides.
|
|
28
|
+
*/
|
|
29
|
+
export declare function compareSync(marker: Pick<WebSourceSyncMarker, 's3Key' | 'updatedAt'>, server: ServerSourceVersion): SyncComparison;
|
|
30
|
+
export type SavePrecondition = {
|
|
31
|
+
kind: 'proceed';
|
|
32
|
+
/** undefined: omit the argument (no check); null: expect no saved source; string: expect this key. */
|
|
33
|
+
expectedS3Key: string | null | undefined;
|
|
34
|
+
/** No marker but a saved source exists: this folder is adopted as the deck's saved copy. */
|
|
35
|
+
adopt: boolean;
|
|
36
|
+
via: SyncVia;
|
|
37
|
+
} | {
|
|
38
|
+
kind: 'refuse';
|
|
39
|
+
savedAt: string;
|
|
40
|
+
syncedAt: string;
|
|
41
|
+
savedS3Key: string;
|
|
42
|
+
};
|
|
43
|
+
/** What save-deck does, given the folder's marker and the server's current saved source. */
|
|
44
|
+
export declare function decideSavePrecondition(marker: WebSourceSyncMarker | null, server: ServerSourceVersion | null, force: boolean): SavePrecondition;
|
|
45
|
+
export declare function fetchServerSourceVersion(deckId: string): Promise<ServerSourceVersion | null>;
|
|
46
|
+
/** A save time as people read it: `2026-08-18 13:21 UTC`, or the raw value if unparseable. */
|
|
47
|
+
export declare function humanTime(iso: string): string;
|
|
48
|
+
/** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
|
|
49
|
+
export declare const EXIT_SAVED_DECK_NEWER = 5;
|
|
50
|
+
export declare const SAVE_REFUSED_PREFIX = "CASTLE_SAVE_REFUSED ";
|
|
51
|
+
export declare const SAVED_DECK_NEWER_CODE = "SAVED_DECK_NEWER";
|
|
52
|
+
/** Ghost's code when its own check (primary, under lock) refuses the source commit. */
|
|
53
|
+
export declare const WEB_DECK_SOURCE_STALE_CODE = "WEB_DECK_SOURCE_STALE";
|
|
54
|
+
export interface SaveRefusal {
|
|
55
|
+
savedAt: string | null;
|
|
56
|
+
syncedAt: string | null;
|
|
57
|
+
savedS3Key: string | null;
|
|
58
|
+
}
|
|
59
|
+
/** The single machine-readable stdout line castle-www parses from a refused save. */
|
|
60
|
+
export declare function saveRefusedLine(refusal: SaveRefusal): string;
|
|
61
|
+
export declare function saveRefusedMessage(dir: string, refusal: SaveRefusal): string;
|
|
62
|
+
export type SourceStatus = 'in-sync' | 'saved-newer' | 'lag' | 'no-marker' | 'no-source' | 'no-deck';
|
|
63
|
+
export interface SourceStatusResult {
|
|
64
|
+
deckId: string | null;
|
|
65
|
+
status: SourceStatus;
|
|
66
|
+
marker: Omit<WebSourceSyncMarker, 'deckId'> | null;
|
|
67
|
+
server: ServerSourceVersion | null;
|
|
68
|
+
adopted?: true;
|
|
69
|
+
notified?: true;
|
|
70
|
+
}
|
|
71
|
+
export interface SourceStatusOptions {
|
|
72
|
+
adopt?: boolean;
|
|
73
|
+
notify?: boolean;
|
|
74
|
+
/** Injected by tests; defaults to the webDeckSource query. */
|
|
75
|
+
fetchServer?: (deckId: string) => Promise<ServerSourceVersion | null>;
|
|
76
|
+
now?: () => Date;
|
|
77
|
+
}
|
|
78
|
+
export declare function sourceNewerNotice(dir: string, savedAt: string, syncedAt: string): {
|
|
79
|
+
notice: string;
|
|
80
|
+
instruction: string;
|
|
81
|
+
};
|
|
82
|
+
export declare function sourceStatus(dir: string, opts?: SourceStatusOptions): Promise<SourceStatusResult>;
|
|
83
|
+
export declare function describeSourceStatus(result: SourceStatusResult): string;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as api from './api.js';
|
|
4
|
+
import { atomicWriteFileSync } from './atomicFile.js';
|
|
5
|
+
import { readCastleJson } from './castleJson.js';
|
|
6
|
+
import { WEB_SOURCE_NEWER_MARKER_FILE } from './cloudGit.js';
|
|
7
|
+
// Which saved source a deck folder came from. `web_deck_sources` holds one row per deck and
|
|
8
|
+
// mints a fresh `s3Key` on every save, so the key names one saved version exactly; the folder
|
|
9
|
+
// records the key it last fetched or saved, and a save compares it with the server's before
|
|
10
|
+
// writing over someone else's newer save.
|
|
11
|
+
//
|
|
12
|
+
// It lives in `.castle/agent/`: excluded from the source archive (so it never travels into a
|
|
13
|
+
// save or a remix), and a durable editor namespace in deck persistence (so a cold resume keeps
|
|
14
|
+
// it). A missing or malformed marker reads as absent: the folder is then adopted, never refused.
|
|
15
|
+
export const WEB_SOURCE_SYNC_FILE = path.join('.castle', 'agent', 'web-source-sync.json');
|
|
16
|
+
/** `get-deck --side` copies of the saved source, one folder per saved version. */
|
|
17
|
+
export const SAVED_SOURCE_DIR = path.join('.castle', 'agent', 'saved-source');
|
|
18
|
+
export const SAVED_SOURCE_KEEP = 2;
|
|
19
|
+
const VIAS = ['get-deck', 'save-deck', 'adopt', 'force'];
|
|
20
|
+
/** The folder's marker, or null when missing, malformed, or recorded for another deck. */
|
|
21
|
+
export function readSyncMarker(dir, deckId) {
|
|
22
|
+
let value;
|
|
23
|
+
try {
|
|
24
|
+
value = JSON.parse(fs.readFileSync(path.join(dir, WEB_SOURCE_SYNC_FILE), 'utf-8'));
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
if (!value ||
|
|
30
|
+
typeof value.deckId !== 'string' ||
|
|
31
|
+
typeof value.s3Key !== 'string' ||
|
|
32
|
+
!value.s3Key ||
|
|
33
|
+
typeof value.updatedAt !== 'string' ||
|
|
34
|
+
typeof value.syncedAt !== 'string' ||
|
|
35
|
+
!VIAS.includes(value.via)) {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
if (deckId !== undefined && value.deckId !== deckId)
|
|
39
|
+
return null;
|
|
40
|
+
return {
|
|
41
|
+
deckId: value.deckId,
|
|
42
|
+
s3Key: value.s3Key,
|
|
43
|
+
updatedAt: value.updatedAt,
|
|
44
|
+
syncedAt: value.syncedAt,
|
|
45
|
+
via: value.via,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export function writeSyncMarker(dir, deckId, source, via, now = new Date()) {
|
|
49
|
+
const marker = {
|
|
50
|
+
deckId,
|
|
51
|
+
s3Key: source.s3Key,
|
|
52
|
+
updatedAt: source.updatedAt,
|
|
53
|
+
syncedAt: now.toISOString(),
|
|
54
|
+
via,
|
|
55
|
+
};
|
|
56
|
+
const file = path.join(dir, WEB_SOURCE_SYNC_FILE);
|
|
57
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
58
|
+
atomicWriteFileSync(file, `${JSON.stringify(marker, null, 2)}\n`);
|
|
59
|
+
// The folder now matches a saved version, so a pending "saved copy is newer" notice is moot.
|
|
60
|
+
clearSourceNewerNotice(dir);
|
|
61
|
+
return marker;
|
|
62
|
+
}
|
|
63
|
+
/** Removes a `source-status --notify` notice the serve has not consumed yet. */
|
|
64
|
+
export function clearSourceNewerNotice(dir) {
|
|
65
|
+
fs.rmSync(path.join(dir, WEB_SOURCE_NEWER_MARKER_FILE), { force: true });
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The lag rule. `webDeckSource` reads a replica, so right after a save from this folder the
|
|
69
|
+
* server can still show the previous row: a different key alone is not proof of a newer save.
|
|
70
|
+
* Saved-newer only when the keys differ AND the server's save time is strictly newer than the
|
|
71
|
+
* marker's; otherwise it is lag, and the server's own check (primary, under lock) decides.
|
|
72
|
+
*/
|
|
73
|
+
export function compareSync(marker, server) {
|
|
74
|
+
if (marker.s3Key === server.s3Key)
|
|
75
|
+
return 'in-sync';
|
|
76
|
+
const serverMs = Date.parse(server.updatedAt);
|
|
77
|
+
const markerMs = Date.parse(marker.updatedAt);
|
|
78
|
+
if (Number.isFinite(serverMs) && Number.isFinite(markerMs) && serverMs > markerMs) {
|
|
79
|
+
return 'saved-newer';
|
|
80
|
+
}
|
|
81
|
+
return 'lag';
|
|
82
|
+
}
|
|
83
|
+
/** What save-deck does, given the folder's marker and the server's current saved source. */
|
|
84
|
+
export function decideSavePrecondition(marker, server, force) {
|
|
85
|
+
if (force) {
|
|
86
|
+
// A third writer between this observation and the save still trips the server -- for a
|
|
87
|
+
// marked folder. An unmarked one never sends the precondition (below), forced or not.
|
|
88
|
+
return {
|
|
89
|
+
kind: 'proceed',
|
|
90
|
+
expectedS3Key: marker ? (server?.s3Key ?? null) : undefined,
|
|
91
|
+
adopt: false,
|
|
92
|
+
via: 'force',
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (!marker) {
|
|
96
|
+
// A folder with no marker never sends the precondition: it has nothing to compare, and a
|
|
97
|
+
// server refusal would only arrive after the deck went live. It is adopted (a row exists)
|
|
98
|
+
// or saved as the first source, and guarded from the marker the save writes.
|
|
99
|
+
return { kind: 'proceed', expectedS3Key: undefined, adopt: server !== null, via: 'save-deck' };
|
|
100
|
+
}
|
|
101
|
+
// No row is lag too (a first save the replica hasn't seen yet); the server decides.
|
|
102
|
+
if (server && compareSync(marker, server) === 'saved-newer') {
|
|
103
|
+
return {
|
|
104
|
+
kind: 'refuse',
|
|
105
|
+
savedAt: server.updatedAt,
|
|
106
|
+
syncedAt: marker.updatedAt,
|
|
107
|
+
savedS3Key: server.s3Key,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return { kind: 'proceed', expectedS3Key: marker.s3Key, adopt: false, via: 'save-deck' };
|
|
111
|
+
}
|
|
112
|
+
export async function fetchServerSourceVersion(deckId) {
|
|
113
|
+
const source = await api.webDeckSource(deckId);
|
|
114
|
+
return source ? { s3Key: source.s3Key, updatedAt: source.updatedAt } : null;
|
|
115
|
+
}
|
|
116
|
+
/** A save time as people read it: `2026-08-18 13:21 UTC`, or the raw value if unparseable. */
|
|
117
|
+
export function humanTime(iso) {
|
|
118
|
+
const ms = Date.parse(iso);
|
|
119
|
+
if (!Number.isFinite(ms))
|
|
120
|
+
return iso;
|
|
121
|
+
return `${new Date(ms).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
|
|
122
|
+
}
|
|
123
|
+
// --- save-deck refusal --------------------------------------------------------
|
|
124
|
+
/** save-deck's exit code when the saved copy is newer than this folder (1-4 are taken). */
|
|
125
|
+
export const EXIT_SAVED_DECK_NEWER = 5;
|
|
126
|
+
export const SAVE_REFUSED_PREFIX = 'CASTLE_SAVE_REFUSED ';
|
|
127
|
+
export const SAVED_DECK_NEWER_CODE = 'SAVED_DECK_NEWER';
|
|
128
|
+
/** Ghost's code when its own check (primary, under lock) refuses the source commit. */
|
|
129
|
+
export const WEB_DECK_SOURCE_STALE_CODE = 'WEB_DECK_SOURCE_STALE';
|
|
130
|
+
/** The single machine-readable stdout line castle-www parses from a refused save. */
|
|
131
|
+
export function saveRefusedLine(refusal) {
|
|
132
|
+
return `${SAVE_REFUSED_PREFIX}${JSON.stringify({
|
|
133
|
+
event: 'castle_web_save_refused',
|
|
134
|
+
code: SAVED_DECK_NEWER_CODE,
|
|
135
|
+
savedAt: refusal.savedAt,
|
|
136
|
+
syncedAt: refusal.syncedAt,
|
|
137
|
+
savedS3Key: refusal.savedS3Key,
|
|
138
|
+
})}`;
|
|
139
|
+
}
|
|
140
|
+
export function saveRefusedMessage(dir, refusal) {
|
|
141
|
+
const saved = refusal.savedAt ? `saved ${humanTime(refusal.savedAt)}` : 'saved from elsewhere';
|
|
142
|
+
const synced = refusal.syncedAt
|
|
143
|
+
? `this folder last synced ${humanTime(refusal.syncedAt)}`
|
|
144
|
+
: 'this folder never synced with it';
|
|
145
|
+
return [
|
|
146
|
+
`Not saved: the saved copy of this deck is newer than this folder (${saved}; ${synced}).`,
|
|
147
|
+
'Saving now would overwrite changes made elsewhere. Either:',
|
|
148
|
+
` castle-web get-deck ${dir} --side fetch the saved copy beside this one (.castle/agent/saved-source/) to compare`,
|
|
149
|
+
` castle-web save-deck ${dir} --force overwrite the saved copy with this folder`,
|
|
150
|
+
].join('\n');
|
|
151
|
+
}
|
|
152
|
+
export function sourceNewerNotice(dir, savedAt, syncedAt) {
|
|
153
|
+
const notice = `The saved copy of this deck is newer than this workspace (saved ${humanTime(savedAt)}; ` +
|
|
154
|
+
`this workspace last synced ${humanTime(syncedAt)}). Ask before saving over it.`;
|
|
155
|
+
const instruction = [
|
|
156
|
+
`[Castle] The saved copy of this deck was saved at ${savedAt}, after this workspace last synced with it (${syncedAt}): someone saved this deck from somewhere else since, and this workspace does not have those changes.`,
|
|
157
|
+
`Do not run \`castle-web save-deck\` (and never \`save-deck --force\`) over the saved copy without the user's explicit OK: it would overwrite those changes.`,
|
|
158
|
+
`To compare, \`castle-web get-deck ${dir} --side\` fetches the saved copy into .castle/agent/saved-source/<stamp>/ without touching this workspace; diff it against the workspace and tell the user what differs.`,
|
|
159
|
+
'Tell the user about this in one or two sentences and ask how they want to proceed.',
|
|
160
|
+
].join('\n');
|
|
161
|
+
return { notice, instruction };
|
|
162
|
+
}
|
|
163
|
+
export async function sourceStatus(dir, opts = {}) {
|
|
164
|
+
const result = await computeSourceStatus(dir, opts);
|
|
165
|
+
// Whatever a notice said no longer holds unless the saved copy is still newer.
|
|
166
|
+
if (result.status !== 'saved-newer')
|
|
167
|
+
clearSourceNewerNotice(path.resolve(dir));
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
async function computeSourceStatus(dir, opts) {
|
|
171
|
+
const projectDir = path.resolve(dir);
|
|
172
|
+
// An unreadable or missing folder is a real error, unlike a folder that isn't a deck.
|
|
173
|
+
if (!fs.statSync(projectDir).isDirectory())
|
|
174
|
+
throw new Error(`Not a directory: ${projectDir}`);
|
|
175
|
+
fs.readdirSync(projectDir);
|
|
176
|
+
const deckId = readCastleJson(projectDir)?.deckId;
|
|
177
|
+
if (typeof deckId !== 'string' || !deckId) {
|
|
178
|
+
return { deckId: null, status: 'no-deck', marker: null, server: null };
|
|
179
|
+
}
|
|
180
|
+
const marker = readSyncMarker(projectDir, deckId);
|
|
181
|
+
const server = await (opts.fetchServer ?? fetchServerSourceVersion)(deckId);
|
|
182
|
+
const result = {
|
|
183
|
+
deckId,
|
|
184
|
+
status: 'no-source',
|
|
185
|
+
marker: marker
|
|
186
|
+
? { s3Key: marker.s3Key, updatedAt: marker.updatedAt, syncedAt: marker.syncedAt, via: marker.via }
|
|
187
|
+
: null,
|
|
188
|
+
server,
|
|
189
|
+
};
|
|
190
|
+
if (!server)
|
|
191
|
+
return result;
|
|
192
|
+
if (!marker) {
|
|
193
|
+
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;
|
|
200
|
+
}
|
|
201
|
+
result.status = compareSync(marker, server);
|
|
202
|
+
if (result.status === 'saved-newer' && opts.notify) {
|
|
203
|
+
const file = path.join(projectDir, WEB_SOURCE_NEWER_MARKER_FILE);
|
|
204
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
205
|
+
atomicWriteFileSync(file, `${JSON.stringify(sourceNewerNotice(dir, server.updatedAt, marker.updatedAt))}\n`);
|
|
206
|
+
result.notified = true;
|
|
207
|
+
}
|
|
208
|
+
return result;
|
|
209
|
+
}
|
|
210
|
+
export function describeSourceStatus(result) {
|
|
211
|
+
switch (result.status) {
|
|
212
|
+
case 'no-deck':
|
|
213
|
+
return 'Not a saved deck (castle.json has no deckId).';
|
|
214
|
+
case 'no-source':
|
|
215
|
+
return `Deck ${result.deckId} has no saved source yet.`;
|
|
216
|
+
case 'no-marker':
|
|
217
|
+
return result.adopted
|
|
218
|
+
? `Adopted this folder as deck ${result.deckId}'s saved copy (saved ${humanTime(result.server.updatedAt)}).`
|
|
219
|
+
: `This folder has no sync record for deck ${result.deckId}; the saved copy is from ${humanTime(result.server.updatedAt)}.`;
|
|
220
|
+
case 'in-sync':
|
|
221
|
+
return `In sync with the saved copy (saved ${humanTime(result.server.updatedAt)}).`;
|
|
222
|
+
case 'lag':
|
|
223
|
+
return `The server has not caught up with this folder's last save yet (${humanTime(result.marker.updatedAt)}).`;
|
|
224
|
+
case 'saved-newer':
|
|
225
|
+
return (`The saved copy is newer than this folder (saved ${humanTime(result.server.updatedAt)}; ` +
|
|
226
|
+
`this folder last synced ${humanTime(result.marker.updatedAt)}).` +
|
|
227
|
+
(result.notified ? ' The agent has been told.' : ''));
|
|
228
|
+
}
|
|
229
|
+
}
|
package/kits/base/CLAUDE.md
CHANGED
|
@@ -15,7 +15,7 @@ that framework provides. This one is true either way.
|
|
|
15
15
|
<!-- Injected into Castle's create assistant every turn; keep this compact and factual. -->
|
|
16
16
|
|
|
17
17
|
- `import { setup, initCard } from 'castle-web-sdk'`. Call `setup()` first, once; `initCard()` returns the element to render into (a React tree mounted at `#root` needs no `initCard`). Castle services — `Store`, `Leaderboard`, `Time`, `User`, `Haptics`, `Pass`, `Snapshot`, `Portal`, `Multiplayer`, `Lifecycle` — come from the same package. `Store` is how a deck saves anything; the older `Storage`/`SharedStorage` still work but should not be used in new decks; the full reference is `imports/castle.base/sdk/README.md`.
|
|
18
|
-
- `Agent.chat({ messages, tools?, toolChoice?, model?, maxTokens?, reasoning?, onDelta?, signal? })` gets one chat completion from a language model (OpenAI message and tool format, default model `meta/muse-spark-1.3`) through Castle's
|
|
18
|
+
- `Agent.chat({ messages, tools?, toolChoice?, model?, maxTokens?, reasoning?, onDelta?, signal? })` gets one chat completion from a language model (OpenAI message and tool format, default model `meta/muse-spark-1.3-contributor`; also `meta/muse-spark-1.3` or `openai/gpt-4.1-mini`) through Castle's deck-agent service, paid from the player's daily play allowance that characters share. `onDelta` streams text and reasoning pieces and each finished tool call; `signal` cancels; `reasoning: { effort: 'minimal' | 'low' | 'medium' | 'high' }` sets how hard the model thinks, and minimal answers soonest. It resolves with the whole `message`: the deck runs any `tool_calls` itself, appends the message and the `tool` results, and calls again. Admin only: other players get `refused`; a player whose allowance for the day is spent gets `allowance_exhausted` (it resets at midnight UTC).
|
|
19
19
|
- `Decks.mine({ limit? })` and `Decks.saved({ limit? })` list decks a portal can lead to (the player's published decks; their bookmarks and playlists) as `{ deckId, title, creator, coverUrl }`, with `coverUrl` a `data:` url. Use them to offer a portal destination picker. Admin only: other players get a `PERMISSION_DENIED` error.
|
|
20
20
|
- What each service cannot do is in that README beside the service: `Store` / `Storage` size caps (no media in storage), the Castle app build a command needs (older builds reject it with `UNKNOWN_COMMAND`), no clipboard command, no call that sets the deck's cover. Read it before telling someone a service can or cannot do something.
|
|
21
21
|
- The SDK is a file of this import, not an npm package: `castle-web-sdk` resolves here. Nothing needs installing, and nothing in a deck's `package.json` names it.
|
package/kits/base/castle.json
CHANGED
package/kits/base/sdk/README.md
CHANGED
|
@@ -731,9 +731,11 @@ be coalesced, so it's safe to call on frequent events.
|
|
|
731
731
|
## Agent
|
|
732
732
|
|
|
733
733
|
`Agent` asks a language model for one chat completion. The host sends it
|
|
734
|
-
through Castle's
|
|
735
|
-
|
|
736
|
-
player
|
|
734
|
+
through Castle's deck-agent service, so the deck holds no key. Castle pays
|
|
735
|
+
for each player's calls out of a daily play allowance, which Castle
|
|
736
|
+
characters draw from too; once a player has used it up, calls resolve
|
|
737
|
+
`'allowance_exhausted'` until it resets at midnight UTC. Agent.chat is
|
|
738
|
+
limited to Castle admins for now; every other player gets `'refused'`.
|
|
737
739
|
|
|
738
740
|
### `Agent.chat(params): Promise<AgentChatResult>`
|
|
739
741
|
|
|
@@ -745,9 +747,11 @@ player gets `'refused'`.
|
|
|
745
747
|
- `tools` — optional function tools, in the OpenAI function-tool schema.
|
|
746
748
|
- `toolChoice` — optional: `'auto'` (the default), `'none'`, `'required'`,
|
|
747
749
|
or `{ type: 'function', function: { name } }` to force one tool.
|
|
748
|
-
- `model` — optional OpenRouter model id.
|
|
749
|
-
`'meta/muse-spark-1.3'`.
|
|
750
|
-
|
|
750
|
+
- `model` — optional OpenRouter model id: `'meta/muse-spark-1.3-contributor'`
|
|
751
|
+
(the default), `'meta/muse-spark-1.3'` or `'openai/gpt-4.1-mini'`. Any
|
|
752
|
+
other model resolves `'error'`.
|
|
753
|
+
- `maxTokens` — optional cap on the reply's length. Defaults to 4096; the
|
|
754
|
+
service caps it at 16384.
|
|
751
755
|
- `reasoning` — optional `{ effort: 'minimal' | 'low' | 'medium' | 'high' }`,
|
|
752
756
|
how hard the model thinks before it answers. Lower effort answers sooner.
|
|
753
757
|
Left out, the model uses its own default. Muse can't turn reasoning off;
|
|
@@ -819,9 +823,12 @@ for (let round = 0; round < 8; round++) {
|
|
|
819
823
|
`'tool_calls'` or `'length'`. `usage` carries `prompt_tokens`,
|
|
820
824
|
`completion_tokens` and `total_tokens`.
|
|
821
825
|
- `'refused'` — the player is not a Castle admin. The model was not called.
|
|
822
|
-
- `'
|
|
826
|
+
- `'allowance_exhausted'` — the player's play allowance for the day is used
|
|
827
|
+
up. The model was not called. It resets at midnight UTC.
|
|
828
|
+
- `'unavailable'` — this host has no route to the deck-agent service, or
|
|
829
|
+
the service is down.
|
|
823
830
|
- `'cancelled'` — the call's `signal` was aborted.
|
|
824
|
-
- `'error'` — the
|
|
831
|
+
- `'error'` — the service or the model failed; `reason` says how.
|
|
825
832
|
|
|
826
833
|
Every status but `'ok'` carries a `reason`.
|
|
827
834
|
|
package/kits/base/sdk/agent.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
// Agent — one chat completion from a language model, run
|
|
2
|
-
// Castle
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
1
|
+
// Agent — one chat completion from a language model, run through Castle's
|
|
2
|
+
// deck-agent service. Castle funds each player's calls from a daily play
|
|
3
|
+
// allowance that characters share. Messages and tools follow the OpenAI chat
|
|
4
|
+
// completions format. The reply streams: `onDelta` gets text and reasoning as
|
|
5
|
+
// they arrive and each tool call once its arguments are complete, and the
|
|
6
|
+
// promise resolves with the whole message. A deck runs any tool calls itself
|
|
7
|
+
// and calls Agent.chat again with the results.
|
|
7
8
|
//
|
|
8
9
|
// Agent.chat is limited to Castle admins for now: every other player gets
|
|
9
|
-
// `refused`. A
|
|
10
|
+
// `refused`. A player whose allowance for the day is spent gets
|
|
11
|
+
// `allowance_exhausted`. A host with no route to the service answers
|
|
12
|
+
// `unavailable`.
|
|
10
13
|
import { CastleError } from "./errors";
|
|
11
14
|
import { hostRequest } from "./transport";
|
|
12
15
|
async function chat(params) {
|
|
@@ -255,7 +255,7 @@ export type AgentChatResult = {
|
|
|
255
255
|
finishReason: string | null;
|
|
256
256
|
usage?: AgentUsage;
|
|
257
257
|
} | {
|
|
258
|
-
status: "unavailable" | "refused" | "error" | "cancelled";
|
|
258
|
+
status: "unavailable" | "refused" | "allowance_exhausted" | "error" | "cancelled";
|
|
259
259
|
reason: string;
|
|
260
260
|
};
|
|
261
261
|
export interface DeckSummary {
|
|
@@ -15,7 +15,7 @@ export const COMMAND_TIMEOUTS_MS = {
|
|
|
15
15
|
"decks.saved": 30_000,
|
|
16
16
|
};
|
|
17
17
|
// Once a host streams a command, each stream envelope restarts the wait at this
|
|
18
|
-
// length instead. The
|
|
18
|
+
// length instead. The deck-agent service sends a heartbeat every 15 seconds, and the host
|
|
19
19
|
// passes each one on.
|
|
20
20
|
export const STREAM_IDLE_TIMEOUT_MS = 60_000;
|
|
21
21
|
export function isResponseEnvelope(value) {
|
|
@@ -53,6 +53,8 @@ export interface PlatformHandle {
|
|
|
53
53
|
worldCharacterSend?(grantId: string): Promise<string>;
|
|
54
54
|
worldCharacterCommand?(grantId: string): Promise<string>;
|
|
55
55
|
worldCharacterRead?(grantId: string): Promise<string>;
|
|
56
|
+
worldCharacterRuntimeCreate?(argsJson: string): Promise<string>;
|
|
57
|
+
worldCharacterRuntimeList?(): Promise<string>;
|
|
56
58
|
worldCharacterReject?(grantId: string, code?: string): void;
|
|
57
59
|
readonly config: PlatformSessionConfig;
|
|
58
60
|
}
|