castle-web-cli 0.4.224 → 0.4.226

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.
@@ -59,6 +59,7 @@ const COMMAND_NAMES = [
59
59
  "cauldronStorage.boardSubmit",
60
60
  "cauldronStorage.boardTop",
61
61
  "cauldronStorage.boardGet",
62
+ "cauldronStorage.usage",
62
63
  "lifecycle.restoreState",
63
64
  ];
64
65
  // Platform/capability commands: NOT serviced by graphqlFetch. They're dispatched
@@ -223,6 +224,8 @@ function runCommand(ctx, command, params, caps, options) {
223
224
  return cauldronStorageBoardTop(ctx, params, gql);
224
225
  case "cauldronStorage.boardGet":
225
226
  return cauldronStorageBoardGet(ctx, params, gql);
227
+ case "cauldronStorage.usage":
228
+ return cauldronStorageUsage(ctx, gql);
226
229
  // Platform commands are handled above; listed here to keep the switch
227
230
  // exhaustive over CommandName.
228
231
  case "pass.offer":
@@ -1524,6 +1527,7 @@ function streamAgentReply(oracleStream, body, options) {
1524
1527
  const reply = {
1525
1528
  content: "",
1526
1529
  reasoning: "",
1530
+ reasoningDetails: null,
1527
1531
  toolCalls: [],
1528
1532
  toolCallsSent: 0,
1529
1533
  finishReason: null,
@@ -1677,6 +1681,12 @@ function applyOracleEvent(reply, outbox, event) {
1677
1681
  reply.reasoning += reasoning;
1678
1682
  queueText(outbox, "reasoning", reasoning);
1679
1683
  }
1684
+ if (Array.isArray(delta.reasoning_details)) {
1685
+ reply.reasoningDetails ??= [];
1686
+ for (const piece of delta.reasoning_details) {
1687
+ addReasoningDetail(reply.reasoningDetails, piece);
1688
+ }
1689
+ }
1680
1690
  if (typeof delta.content === "string" && delta.content !== "") {
1681
1691
  reply.content += delta.content;
1682
1692
  queueText(outbox, "text", delta.content);
@@ -1712,6 +1722,37 @@ function reasoningText(delta) {
1712
1722
  }
1713
1723
  return text;
1714
1724
  }
1725
+ // OpenRouter streams each reasoning block in pieces that share its index and
1726
+ // type: text and summaries a few characters at a time, then perhaps a
1727
+ // signature on a piece of its own. Pieces of one block are joined. Blocks of
1728
+ // different types can share an index (Gemini sends its text and its encrypted
1729
+ // signature both at index 0), and an encrypted payload arrives whole, so a
1730
+ // second one, or a different id, starts a new block.
1731
+ function addReasoningDetail(blocks, piece) {
1732
+ if (typeof piece !== "object" || piece === null || Array.isArray(piece)) {
1733
+ return;
1734
+ }
1735
+ const next = piece;
1736
+ const last = blocks[blocks.length - 1];
1737
+ const continues = last !== undefined &&
1738
+ last.type === next.type &&
1739
+ last.index === next.index &&
1740
+ !(typeof last.data === "string" && typeof next.data === "string") &&
1741
+ !(typeof last.id === "string" && typeof next.id === "string" && last.id !== next.id);
1742
+ if (!continues) {
1743
+ blocks.push({ ...next });
1744
+ return;
1745
+ }
1746
+ for (const [key, value] of Object.entries(next)) {
1747
+ const current = last[key];
1748
+ if ((key === "text" || key === "summary") && typeof current === "string" && typeof value === "string") {
1749
+ last[key] = current + value;
1750
+ }
1751
+ else if (value !== null && value !== undefined) {
1752
+ last[key] = value;
1753
+ }
1754
+ }
1755
+ }
1715
1756
  // The first piece of a call carries its id and name; the arguments are a JSON
1716
1757
  // string split across every piece. Calls arrive one after another, so a piece
1717
1758
  // for a later index means every earlier call is complete.
@@ -1766,6 +1807,9 @@ function agentChatResult(reply, outbox) {
1766
1807
  if (toolCalls.length > 0) {
1767
1808
  message.tool_calls = toolCalls;
1768
1809
  }
1810
+ if (reply.reasoningDetails !== null) {
1811
+ message.reasoning_details = reply.reasoningDetails;
1812
+ }
1769
1813
  const result = { status: "ok", message, finishReason: reply.finishReason };
1770
1814
  if (reply.reasoning !== "") {
1771
1815
  result.reasoning = reply.reasoning;
@@ -2005,6 +2049,11 @@ async function cauldronStorageBoardGet(ctx, params, gql) {
2005
2049
  }, "cauldronStorage.boardGet");
2006
2050
  return { entry: data.cauldronStorageBoardGet ?? null };
2007
2051
  }
2052
+ async function cauldronStorageUsage(ctx, gql) {
2053
+ const deckId = requireDeckId(ctx, "cauldronStorage.usage");
2054
+ const data = await graphql(gql, CAULDRON_STORAGE_USAGE_QUERY, { deckId }, "cauldronStorage.usage");
2055
+ return { usage: data.cauldronStorageUsage };
2056
+ }
2008
2057
  const CHARACTER_OPERATION_FIELDS = `
2009
2058
  operationId
2010
2059
  characterId
@@ -2545,6 +2594,14 @@ const CAULDRON_STORAGE_BOARD_TOP_QUERY = `
2545
2594
  }
2546
2595
  }
2547
2596
  `;
2597
+ const CAULDRON_STORAGE_USAGE_QUERY = `
2598
+ query CastleCauldronStorageUsage($deckId: ID!) {
2599
+ cauldronStorageUsage(deckId: $deckId) {
2600
+ player { keyCount keyLimit byteCount byteLimit }
2601
+ shared { keyCount keyLimit byteCount byteLimit }
2602
+ }
2603
+ }
2604
+ `;
2548
2605
  const CAULDRON_STORAGE_BOARD_GET_QUERY = `
2549
2606
  query CastleCauldronStorageBoardGet($deckId: ID!, $board: String!, $subject: ID) {
2550
2607
  cauldronStorageBoardGet(deckId: $deckId, board: $board, subject: $subject) {
@@ -20,7 +20,6 @@ export interface CastleJson {
20
20
  main?: string;
21
21
  agent?: {
22
22
  plan?: 'on' | 'off';
23
- askCalls?: 'on' | 'off';
24
23
  playtest?: 'on' | 'off';
25
24
  };
26
25
  server?: {
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.42';
57
+ const PUBLISHED_SDK_VERSION = '0.4.43';
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.
@@ -1,7 +1,9 @@
1
+ import { type SendDirective } from './taskSteer.js';
1
2
  export interface TaskDirective {
2
3
  title: string;
3
4
  after: string[];
4
5
  item?: string;
6
+ hold?: true;
5
7
  prompt: string;
6
8
  }
7
9
  export interface BoardTask {
@@ -12,12 +14,15 @@ export interface BoardTask {
12
14
  export declare function stripTaskFencePlaceholder(prompt: string): string;
13
15
  export declare function parseTaskFenceBody(body: string): TaskDirective | null;
14
16
  export declare function taskFenceRegex(): RegExp;
15
- export declare function extractDirectives(full: string): {
17
+ export declare function extractDirectives(full: string, opts?: {
18
+ sends?: boolean;
19
+ }): {
16
20
  cleaned: string;
17
21
  directives: TaskDirective[];
18
22
  checkoffs: string[];
19
23
  stops: string[];
20
24
  prefs: string[];
25
+ sends: SendDirective[];
21
26
  plan?: string;
22
27
  };
23
28
  export declare function closedPrefLines(raw: string): string[];
@@ -1,4 +1,5 @@
1
1
  import { TASK_FENCE_PROMPT_EXAMPLE } from './agent-prompts.js';
2
+ import { parseSendFenceBody, sendFenceRegex } from './taskSteer.js';
2
3
  function escapeFlexible(text) {
3
4
  return text
4
5
  .split(/\s+/)
@@ -41,8 +42,8 @@ export function stripTaskFencePlaceholder(prompt) {
41
42
  .replace(/\n[ \t]+/g, '\n')
42
43
  .trim();
43
44
  }
44
- // Parse one ```castle-task fence's body (title line, optional "after:" and
45
- // "item:" lines in either order, then the prompt) into a directive. Shared by
45
+ // Parse one ```castle-task fence's body (title line, optional header lines,
46
+ // then the prompt) into a directive. Shared by
46
47
  // the settle-time full-text extraction below and the mid-stream incremental
47
48
  // scanner (runRouterTurnIn), so a fence spawned early behaves identically to
48
49
  // one spawned at settle.
@@ -53,12 +54,18 @@ export function parseTaskFenceBody(body) {
53
54
  return null;
54
55
  const after = [];
55
56
  let item;
57
+ let hold;
56
58
  while (lines.length > 0) {
57
- const headerMatch = /^(after|item):\s*(.*)$/i.exec((lines[0] ?? '').trim());
59
+ const headerMatch = /^(after|item|hold):\s*(.*)$/i.exec((lines[0] ?? '').trim());
58
60
  if (!headerMatch)
59
61
  break;
60
62
  lines.shift();
61
- if (headerMatch[1].toLowerCase() === 'item') {
63
+ const header = headerMatch[1].toLowerCase();
64
+ if (header === 'hold') {
65
+ hold = true;
66
+ continue;
67
+ }
68
+ if (header === 'item') {
62
69
  const label = headerMatch[2].trim();
63
70
  // `item: -` is the fence saying "chore, no plan item" -- an answer, not
64
71
  // an omission, so it lands the same as no line at all.
@@ -70,7 +77,13 @@ export function parseTaskFenceBody(body) {
70
77
  if (line)
71
78
  after.push(line);
72
79
  }
73
- return { title, after, item, prompt: stripTaskFencePlaceholder(lines.join('\n').trim()) };
80
+ return {
81
+ title,
82
+ after,
83
+ item,
84
+ ...(hold ? { hold } : {}),
85
+ prompt: stripTaskFencePlaceholder(lines.join('\n').trim()),
86
+ };
74
87
  }
75
88
  // A fresh RegExp per call -- this is matched with manual .exec() loops in
76
89
  // TWO independent call sites (settle-time extractDirectives via .replace, and
@@ -95,8 +108,12 @@ function takePlanFence(source) {
95
108
  // Block format: title line, then an optional "after:" line, then the prompt.
96
109
  // castle-done / castle-stop bodies come back one entry per line, still
97
110
  // comma-joined -- see resolveTargets.
98
- export function extractDirectives(full) {
111
+ export function extractDirectives(full,
112
+ // castle-send is a fence only behind CASTLE_TASK_STEER; off, its text stays
113
+ // in the reply like any other code block.
114
+ opts = {}) {
99
115
  const directives = [];
116
+ const sends = [];
100
117
  const checkoffs = [];
101
118
  const stops = [];
102
119
  const prefs = [];
@@ -113,7 +130,15 @@ export function extractDirectives(full) {
113
130
  };
114
131
  const { plan, rest } = takePlanFence(full);
115
132
  const withoutLists = listFence(listFence(listFence(rest, 'castle-done', checkoffs), 'castle-stop', stops), 'castle-pref', prefs);
116
- const cleaned = withoutLists.replace(taskFenceRegex(), (_match, body) => {
133
+ const withoutSends = opts.sends
134
+ ? withoutLists.replace(sendFenceRegex(), (_match, body) => {
135
+ const send = parseSendFenceBody(String(body));
136
+ if (send)
137
+ sends.push(send);
138
+ return '';
139
+ })
140
+ : withoutLists;
141
+ const cleaned = withoutSends.replace(taskFenceRegex(), (_match, body) => {
117
142
  const directive = parseTaskFenceBody(String(body));
118
143
  if (directive)
119
144
  directives.push(directive);
@@ -125,6 +150,7 @@ export function extractDirectives(full) {
125
150
  checkoffs,
126
151
  stops,
127
152
  prefs,
153
+ sends,
128
154
  plan,
129
155
  };
130
156
  }
@@ -0,0 +1,13 @@
1
+ export declare const ROUTER_STOPPED_RESULT = "stopped by the router";
2
+ export interface TaskEndingTarget {
3
+ status: string;
4
+ progress: number;
5
+ updatedAt: string;
6
+ finishedAt?: string;
7
+ resultSummary?: string;
8
+ acknowledged?: boolean;
9
+ failure?: string;
10
+ }
11
+ export declare function platformInterruptionReason(task: TaskEndingTarget): string | undefined;
12
+ export declare function badTaskEndingsSince<T extends TaskEndingTarget>(tasks: T[], lastReplyAtMs: number): T[];
13
+ export declare function withTimeoutReport(error: string | undefined, task: TaskEndingTarget): string | undefined;
@@ -0,0 +1,29 @@
1
+ export const ROUTER_STOPPED_RESULT = 'stopped by the router';
2
+ // A router stop acknowledges the row; a waiting task it halts gets no
3
+ // resultSummary, so the summary alone does not tell it from a platform cut-off.
4
+ export function platformInterruptionReason(task) {
5
+ if (task.status !== 'interrupted' ||
6
+ task.acknowledged ||
7
+ task.resultSummary === ROUTER_STOPPED_RESULT) {
8
+ return undefined;
9
+ }
10
+ return `cut off by the platform at ${task.progress}% -- the workspace/serve restarted or went away while it ran, with no result reported`;
11
+ }
12
+ export function badTaskEndingsSince(tasks, lastReplyAtMs) {
13
+ return tasks.filter((task) => {
14
+ if (task.status !== 'failed' && !platformInterruptionReason(task))
15
+ return false;
16
+ const endedAt = Date.parse(task.finishedAt ?? task.updatedAt);
17
+ // >= because the reply is stamped before its prompt snapshot: an ending in
18
+ // that same millisecond missed the snapshot and would otherwise never show.
19
+ return Number.isFinite(endedAt) && endedAt >= lastReplyAtMs;
20
+ });
21
+ }
22
+ // A timed-out task's resultSummary is the timeout line followed by its wrap-up
23
+ // report, or the killed run's last text when the wrap-up turn itself failed.
24
+ export function withTimeoutReport(error, task) {
25
+ if (task.failure !== 'timeout')
26
+ return error;
27
+ const report = task.resultSummary?.split('\n').slice(1).join(' ').replace(/\s+/g, ' ').trim();
28
+ return report ? `${error} -- its last message before it was stopped: ${report}` : error;
29
+ }
@@ -3,13 +3,23 @@ import { type SavePrecondition } from './webSourceSync.js';
3
3
  export declare const SOURCE_ARCHIVE_EXCLUDES: string[];
4
4
  export declare const SAVE_STAGE_TELEMETRY_PREFIX = "CASTLE_SAVE_TELEMETRY ";
5
5
  export declare const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = "CASTLE_SAVE_COVER_SELECTION ";
6
+ export declare const MAX_SCENE_DATA_BYTES: number;
7
+ export declare const MAX_SOURCE_ARCHIVE_BYTES: number;
6
8
  export type SaveStage = 'bundle' | 'cover' | 'scene_upload_config' | 'scene_upload' | 'content_publish' | 'server_publish' | 'source_archive' | 'source_upload_config' | 'source_upload' | 'source_commit';
7
9
  export declare function runTar(args: string[], opts?: {
8
10
  capture?: boolean;
9
11
  }): Promise<string>;
12
+ export declare function sceneTooLargeMessage(bytes: number): string;
13
+ export declare function sourceTooLargeMessage(bytes: number, largest: {
14
+ file: string;
15
+ bytes: number;
16
+ }[], published?: boolean): string;
10
17
  export declare function archiveSource(projectDir: string): Promise<Buffer>;
11
18
  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>;
19
+ export declare function packSourceForSave(projectDir: string, castleJson: string | null, { published }?: {
20
+ published?: boolean;
21
+ }): Promise<Buffer>;
22
+ export declare function uploadSource(projectDir: string, deckId: string, expectedS3Key?: string | null, archive?: Buffer): Promise<api.WebDeckSource>;
13
23
  export declare function checkSavePrecondition(projectDir: string, deckId: string, force: boolean): Promise<SavePrecondition>;
14
24
  export type SaveVisibility = 'unlisted' | 'private';
15
25
  export interface SaveDeckOptions {
package/dist/save-deck.js CHANGED
@@ -23,6 +23,14 @@ export const SOURCE_ARCHIVE_EXCLUDES = ['node_modules', 'dist', '.castle', '.git
23
23
  // independently deployable.
24
24
  export const SAVE_STAGE_TELEMETRY_PREFIX = 'CASTLE_SAVE_TELEMETRY ';
25
25
  export const SAVE_COVER_SELECTION_TELEMETRY_PREFIX = 'CASTLE_SAVE_COVER_SELECTION ';
26
+ // Ghost's upload ceilings, enforced by S3 in the presigned POST policies (diy.ts
27
+ // MAX_SCENE_DATA_BYTES, webDeckSource.ts MAX_ARCHIVE_BYTES). Mirrored here so an oversized deck
28
+ // is refused before anything is uploaded: past the cap S3 answers only an opaque HTTP 400, and the
29
+ // source upload runs after the deck has already gone live. Keep these in step with ghost.
30
+ export const MAX_SCENE_DATA_BYTES = 50 * 1024 * 1024;
31
+ export const MAX_SOURCE_ARCHIVE_BYTES = 100 * 1024 * 1024;
32
+ // Long enough to move a payload at either cap over a slow uplink (100 MB at ~3 Mbit/s).
33
+ const LARGE_UPLOAD_TIMEOUT_MS = 300_000;
26
34
  function emitSaveStage(stage, outcome, startedAtMs, fields = {}) {
27
35
  if (process.env.CASTLE_SAVE_STAGE_TELEMETRY !== '1')
28
36
  return;
@@ -74,6 +82,55 @@ export function runTar(args, opts = {}) {
74
82
  });
75
83
  });
76
84
  }
85
+ function formatMB(bytes) {
86
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
87
+ }
88
+ // The biggest files the source archive would carry, as a hint for what to shrink. Skips what the
89
+ // archive excludes and never follows a symlink; unreadable entries are left out.
90
+ function largestSourceFiles(projectDir, count) {
91
+ const found = [];
92
+ const walk = (rel) => {
93
+ let entries;
94
+ try {
95
+ entries = fs.readdirSync(path.join(projectDir, rel), { withFileTypes: true });
96
+ }
97
+ catch {
98
+ return;
99
+ }
100
+ for (const entry of entries) {
101
+ const child = rel ? path.join(rel, entry.name) : entry.name;
102
+ if (!rel && SOURCE_ARCHIVE_EXCLUDES.includes(entry.name))
103
+ continue;
104
+ if (entry.isDirectory())
105
+ walk(child);
106
+ else if (entry.isFile()) {
107
+ try {
108
+ found.push({ file: child, bytes: fs.lstatSync(path.join(projectDir, child)).size });
109
+ }
110
+ catch {
111
+ /* vanished mid-walk */
112
+ }
113
+ }
114
+ }
115
+ };
116
+ walk('');
117
+ return found.sort((a, b) => b.bytes - a.bytes).slice(0, count);
118
+ }
119
+ export function sceneTooLargeMessage(bytes) {
120
+ return (`This deck is too large to save: its game bundle is ${formatMB(bytes)}, and Castle accepts at ` +
121
+ `most ${formatMB(MAX_SCENE_DATA_BYTES)}. Nothing was published. Images, audio and models are ` +
122
+ 'packed into the bundle, so shrink or remove the largest assets and save again.');
123
+ }
124
+ export function sourceTooLargeMessage(bytes, largest, published = false) {
125
+ const list = largest.map((f) => `${f.file} (${formatMB(f.bytes)})`).join(', ');
126
+ return (`This deck's source is too large to save: compressed, it is ${formatMB(bytes)}, and Castle ` +
127
+ `accepts at most ${formatMB(MAX_SOURCE_ARCHIVE_BYTES)}. ` +
128
+ (published
129
+ ? 'The playable deck was updated, but its source was not saved.'
130
+ : 'Nothing was published.') +
131
+ (list ? ` Largest files: ${list}.` : '') +
132
+ ' Remove or shrink files the deck does not need and save again.');
133
+ }
77
134
  export async function archiveSource(projectDir) {
78
135
  const tmpFile = path.join(os.tmpdir(), `castle-source-${nanoid(8)}.tar.gz`);
79
136
  const args = ['-czf', tmpFile];
@@ -123,17 +180,57 @@ async function uploadPresignedFile(uploadConfig, file, contentType, timeoutMs, l
123
180
  if (response.status >= 300)
124
181
  throw new Error(`${label} failed: HTTP ${response.status}`);
125
182
  }
183
+ // The source a save uploads, packed (streamed through gzip by tar) and size-checked before
184
+ // anything is published, so the bytes checked are the bytes uploaded. `castleJson` is the
185
+ // castle.json to archive in place of the one on disk: save-deck rewrites that file only after
186
+ // publishing, from the publish result, and the saved source must already carry the new version
187
+ // (a new deck's ids, a new title). The top-level entries are named one by one to leave out only
188
+ // the root castle.json -- an --exclude pattern would also match nested files of that name (bsdtar).
189
+ export async function packSourceForSave(projectDir, castleJson, { published = false } = {}) {
190
+ const stageDir = fs.mkdtempSync(path.join(os.tmpdir(), 'castle-source-'));
191
+ const outFile = path.join(stageDir, 'source.tar.gz');
192
+ try {
193
+ const entries = fs
194
+ .readdirSync(projectDir)
195
+ .filter((name) => !SOURCE_ARCHIVE_EXCLUDES.includes(name))
196
+ .filter((name) => castleJson === null || name !== 'castle.json')
197
+ .sort()
198
+ .map((name) => `./${name}`);
199
+ const args = ['-czf', outFile];
200
+ for (const ex of SOURCE_ARCHIVE_EXCLUDES)
201
+ args.push(`--exclude=./${ex}`);
202
+ // Every name starts with `./`, so none reads as an option.
203
+ args.push('-C', projectDir, ...entries);
204
+ if (castleJson !== null) {
205
+ const castleJsonDir = path.join(stageDir, 'castle-json');
206
+ fs.mkdirSync(castleJsonDir);
207
+ fs.writeFileSync(path.join(castleJsonDir, 'castle.json'), castleJson, 'utf-8');
208
+ // `-C` is positional: it applies to the names after it.
209
+ args.push('-C', castleJsonDir, './castle.json');
210
+ }
211
+ await runTar(args);
212
+ const archive = fs.readFileSync(outFile);
213
+ if (archive.byteLength > MAX_SOURCE_ARCHIVE_BYTES) {
214
+ throw new Error(sourceTooLargeMessage(archive.byteLength, largestSourceFiles(projectDir, 3), published));
215
+ }
216
+ console.log(`Source archive: ${(archive.length / 1024).toFixed(1)}KB`);
217
+ return archive;
218
+ }
219
+ finally {
220
+ fs.rmSync(stageDir, { recursive: true, force: true });
221
+ }
222
+ }
126
223
  // `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) {
129
- const archive = await traceSaveStage('source_archive', () => archiveSource(projectDir), (value) => ({ bytes: value.byteLength }));
130
- const sizeKB = archive.length / 1024;
131
- console.log(`Source archive: ${sizeKB.toFixed(1)}KB`);
224
+ // whose key and time become this folder's sync marker. `archive` is the source save-deck packed
225
+ // before publishing; without it the folder is packed here, as it is on disk.
226
+ export async function uploadSource(projectDir, deckId, expectedS3Key, archive) {
227
+ const source = archive ??
228
+ (await traceSaveStage('source_archive', () => packSourceForSave(projectDir, null, { published: true }), (value) => ({ bytes: value.byteLength })));
132
229
  const uploadConfig = await traceSaveStage('source_upload_config', () => api.createWebDeckSourceUploadConfig(deckId));
133
230
  // FormData expects a Blob; copy the Buffer's bytes so we don't share the underlying ArrayBuffer.
134
- const view = new Uint8Array(archive.byteLength);
135
- view.set(archive);
136
- await traceSaveStage('source_upload', () => uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', 60_000, 'Source upload'));
231
+ const view = new Uint8Array(source.byteLength);
232
+ view.set(source);
233
+ await traceSaveStage('source_upload', () => uploadPresignedFile(uploadConfig, new Blob([view], { type: 'application/gzip' }), 'application/gzip', LARGE_UPLOAD_TIMEOUT_MS, 'Source upload'));
137
234
  return traceSaveStage('source_commit', () => api.saveWebDeckSource(deckId, uploadConfig.uploadId, expectedS3Key));
138
235
  }
139
236
  // Refused: the saved copy is newer than this folder. One machine-readable stdout line (castle-www
@@ -232,6 +329,12 @@ async function uploadLocalCover(projectDir) {
232
329
  return null;
233
330
  }
234
331
  }
332
+ // Preserve any deck-owned config already in castle.json (notably the `editor` block); save-deck
333
+ // only owns the identity fields.
334
+ function castleJsonAfterSave(castleJson, deckId, cardId, title) {
335
+ const next = { ...(castleJson ?? {}), deckId, cardId, title };
336
+ return JSON.stringify(next, null, 2) + '\n';
337
+ }
235
338
  function readCastleJson(dir) {
236
339
  const p = path.join(dir, 'castle.json');
237
340
  if (!fs.existsSync(p))
@@ -298,10 +401,21 @@ export async function saveDeck(dir, opts = {}) {
298
401
  if (sizeKB > 1024) {
299
402
  console.warn(`Warning: Bundle is ${(sizeKB / 1024).toFixed(1)}MB. Large bundles may load slowly.`);
300
403
  }
301
- const sceneData = buildSceneData(bundle);
404
+ // Both of ghost's size caps are checked here, before anything is uploaded: the deck goes live at
405
+ // content_publish, and the source is uploaded only after that.
406
+ const sceneJson = JSON.stringify(buildSceneData(bundle));
407
+ const sceneBytes = Buffer.byteLength(sceneJson);
408
+ if (sceneBytes > MAX_SCENE_DATA_BYTES) {
409
+ // Reported as the stage that would have failed, so castle-www's failed_at stays comparable.
410
+ await traceSaveStage('scene_upload', () => Promise.reject(new Error(sceneTooLargeMessage(sceneBytes))));
411
+ }
302
412
  const isNew = !castleJson;
303
413
  const cardId = castleJson?.cardId ?? nanoid(12);
304
414
  const deckId = castleJson?.deckId ?? nanoid(12);
415
+ const title = opts.title ?? castleJson?.title ?? path.basename(path.resolve(projectDir));
416
+ // Packed now, from the same files as the bundle, with the castle.json this save will write, and
417
+ // uploaded as is after the deck is published.
418
+ const sourceArchive = await traceSaveStage('source_archive', () => packSourceForSave(projectDir, castleJsonAfterSave(castleJson, deckId, cardId, title)), (value) => ({ bytes: value.byteLength }));
305
419
  // Capturing and uploading the cover depends only on the already-running serve. Start it as
306
420
  // soon as the bundle has passed, while the independent scene upload is being authorized and
307
421
  // transferred. The promise is deliberately non-throwing: a thumbnail must never make the
@@ -320,17 +434,16 @@ export async function saveDeck(dir, opts = {}) {
320
434
  for (const [k, v] of Object.entries(uploadConfig.postFields)) {
321
435
  formData.append(k, String(v));
322
436
  }
323
- formData.append('file', new Blob([JSON.stringify(sceneData)]));
437
+ formData.append('file', new Blob([sceneJson]));
324
438
  await traceSaveStage('scene_upload', async () => {
325
439
  const response = await fetch(uploadConfig.postUrl, {
326
440
  method: 'POST',
327
441
  body: formData,
328
- signal: AbortSignal.timeout(30000),
442
+ signal: AbortSignal.timeout(LARGE_UPLOAD_TIMEOUT_MS),
329
443
  });
330
444
  if (response.status >= 300)
331
445
  throw new Error(`Upload failed: HTTP ${response.status}`);
332
446
  });
333
- const title = opts.title ?? castleJson?.title ?? path.basename(path.resolve(projectDir));
334
447
  const deckInput = { deckId, title };
335
448
  // Omitted unless asked for, or the deck is new and needs one: updateDeckV2
336
449
  // only touches visibility when it is sent, so a deck the creator published
@@ -366,20 +479,12 @@ export async function saveDeck(dir, opts = {}) {
366
479
  castleJson !== null && Object.prototype.hasOwnProperty.call(castleJson, 'characterBundle')
367
480
  ? api.updateCardAndDeckV2(deckInput, cardInput, castleJson?.characterBundle ?? null)
368
481
  : api.updateCardAndDeckV2(deckInput, cardInput));
369
- // Preserve any deck-owned config already in castle.json (notably the
370
- // `editor` block); save-deck only owns the identity fields below.
371
- const newCastleJson = {
372
- ...(castleJson ?? {}),
373
- deckId: result.deckId,
374
- cardId: result.cardId,
375
- title,
376
- };
377
482
  // Only write when the bytes actually move. An identical rewrite still bumps
378
483
  // mtime, which the serve's watcher reports as a change like any other -- so
379
484
  // a push that changed nothing here would flip the Play panel to "Changes
380
485
  // available" and put castle.json in the next saved version's diff.
381
486
  const castleJsonPath = path.join(projectDir, 'castle.json');
382
- const nextCastleJson = JSON.stringify(newCastleJson, null, 2) + '\n';
487
+ const nextCastleJson = castleJsonAfterSave(castleJson, result.deckId, result.cardId, title);
383
488
  const onDisk = fs.existsSync(castleJsonPath)
384
489
  ? fs.readFileSync(castleJsonPath, 'utf-8')
385
490
  : null;
@@ -406,7 +511,10 @@ export async function saveDeck(dir, opts = {}) {
406
511
  }
407
512
  console.log('Uploading source archive...');
408
513
  // The precondition only applies to the deck it was checked against.
409
- const saved = await uploadSource(projectDir, result.deckId, result.deckId === existingDeckId ? expectedS3Key : undefined);
514
+ const saved = await uploadSource(projectDir, result.deckId, result.deckId === existingDeckId ? expectedS3Key : undefined,
515
+ // Ghost keeps the ids it is sent, so this is the castle.json packed above; if it ever
516
+ // assigned others, the folder is packed again with the file as written.
517
+ result.deckId === deckId && result.cardId === cardId ? sourceArchive : undefined);
410
518
  console.log('Source archive saved.');
411
519
  try {
412
520
  writeSyncMarker(projectDir, result.deckId, saved, markerVia);
package/dist/serve.js CHANGED
@@ -1341,6 +1341,9 @@ export async function serve(dir, options = {}) {
1341
1341
  pid: process.pid,
1342
1342
  contentPlayUrl: security.localContentOrigin('play'),
1343
1343
  }) + '\n');
1344
+ // After listen and serve.json: a failed startup must not spend a task's
1345
+ // one recovery, and a recovered task may playtest straight away.
1346
+ agentServer.resumeRecovered();
1344
1347
  vite.printUrls();
1345
1348
  }
1346
1349
  // `restart` does a full browser reload, but Vite keeps transformed modules