castle-web-cli 0.4.256 → 0.4.257

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.
@@ -23,6 +23,7 @@ export declare function classifyProviderError(text: string | undefined, model?:
23
23
  */
24
24
  export declare function setReaderTimeZone(zone: string): void;
25
25
  export declare function failureLabel(failure: AgentFailure): string;
26
+ export declare function failureOffersCredits(failure: AgentFailure): boolean;
26
27
  export declare function routerTurnRetryable(failure: AgentFailure, opts: {
27
28
  text: string;
28
29
  textIsProviderError: boolean;
@@ -233,6 +233,15 @@ export function failureLabel(failure) {
233
233
  return "transient/upstream-flap";
234
234
  return failure.reason ? `${failure.kind}/${failure.reason}` : failure.kind;
235
235
  }
236
+ // Whether the failure's recovery is buying Castle credits, so the editor puts a
237
+ // Get credits button under the copy instead of leaving castle.xyz/credits as
238
+ // plain text (which the app shell cannot follow at all). Mirrors the order in
239
+ // failureCopy: the free model's own daily cap is not a credits problem.
240
+ export function failureOffersCredits(failure) {
241
+ if (failure.kind !== "limit" || failure.castleFreeModelLimit)
242
+ return false;
243
+ return failure.castleCreditsInsufficient === true || failure.castleCreditsExhausted === true;
244
+ }
236
245
  export function routerTurnRetryable(failure, opts) {
237
246
  const retryableFailure = failure.kind === "exit" || (failure.kind === "transient" && failure.upstreamFlap === true);
238
247
  return retryableFailure && !opts.spawnedTasks && opts.streamedChars === 0 &&
package/dist/agent.d.ts CHANGED
@@ -50,6 +50,7 @@ interface ChatMessage {
50
50
  hideFromUi?: boolean;
51
51
  planUpdated?: boolean;
52
52
  errorDetail?: string;
53
+ offersCredits?: boolean;
53
54
  }
54
55
  interface TaskUsage {
55
56
  input?: number;
@@ -91,6 +92,7 @@ interface TaskRecord {
91
92
  account?: string;
92
93
  errorCopy?: string;
93
94
  errorDetail?: string;
95
+ offersCredits?: boolean;
94
96
  failure?: string;
95
97
  avatar?: string;
96
98
  phase?: string;
@@ -125,6 +127,7 @@ interface AgentRunHandle {
125
127
  spawnfile: string;
126
128
  kill(signal?: NodeJS.Signals): boolean;
127
129
  }
130
+ export declare function claudeActivityTrace(events: Record<string, unknown>[], labelUnknownTools?: boolean): (string | null)[];
128
131
  export declare const TASK_DIRS_KEPT = 200;
129
132
  export declare const TASK_ARCHIVE_BATCH = 250;
130
133
  export declare const TASK_ARCHIVE_SEGMENT_BYTES: number;
package/dist/agent.js CHANGED
@@ -24,6 +24,7 @@ import { isSameOriginUpgrade } from './wsOrigin.js';
24
24
  import { resolveDeckPath } from './ide.js';
25
25
  import { lineRange, uniqueLocators } from './deckLocatorShape.js';
26
26
  import { supportedEffort } from './effortSupport.js';
27
+ import { appendFeedEntry, retryNoticeFor } from './retryNotice.js';
27
28
  import * as fs from 'fs';
28
29
  import * as os from 'os';
29
30
  import * as path from 'path';
@@ -43,7 +44,7 @@ import { readGitIncomingNote, removeGitIncoming } from './gitIncoming.js';
43
44
  import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
44
45
  import { readCastleJson } from './castleJson.js';
45
46
  import { checkOpenrouterKey, checkOpenrouterModel, primeOpenrouterCatalog, } from './openrouter-catalog.js';
46
- import { classifyProviderError, failureCopy, failureLabel, routerTaskError, routerTurnRetryable, routerTurnErrorText, setReaderTimeZone, } from './agent-failures.js';
47
+ import { classifyProviderError, failureCopy, failureOffersCredits, failureLabel, routerTaskError, routerTurnRetryable, routerTurnErrorText, setReaderTimeZone, } from './agent-failures.js';
47
48
  import { castleCreditsExhausted, createBudgetRefreshRetry, createRefreshQueue, fetchAiCredits, fetchBudget, freeRolesFor, freeTierForRoles, meteringHeaders, modelIsFree, newAgentSessionId, spendableMicros, withCustomHeaders, } from './metering.js';
48
49
  import { anthropicKeyHelperCommand, resolveAnthropicAuth, userKey, ANTHROPIC_CREDENTIAL_ENV, ANTHROPIC_PROXY_ENV, CASTLE_USER_KEYS_PATH, } from './byo-auth.js';
49
50
  import { accountsSnapshot, loginProviderFor, watchCredentials, writeCredential, } from './byo-accounts.js';
@@ -1109,6 +1110,7 @@ function createAgentStreamState() {
1109
1110
  needsGap: false,
1110
1111
  pendingTools: new Map(),
1111
1112
  resultMark: 0,
1113
+ retryShowing: false,
1112
1114
  };
1113
1115
  }
1114
1116
  function parseCliUsage(raw) {
@@ -1209,12 +1211,34 @@ function logAgentUsage(label, usage) {
1209
1211
  const output = formatTokenCount(usage.output_tokens);
1210
1212
  console.error(`[agent usage] ${label}: input=${input} cache_read=${read} cache_created=${created} output=${output}`);
1211
1213
  }
1214
+ // Exported for scripts/tests/agent-retry-activity.mjs: the activity calls a
1215
+ // sequence of claude stream-json events produces.
1216
+ export function claudeActivityTrace(events, labelUnknownTools = false) {
1217
+ const trace = [];
1218
+ const handle = makeAgentEventHandler({
1219
+ cwd: '',
1220
+ command: '',
1221
+ args: [],
1222
+ env: {},
1223
+ timeoutMs: 0,
1224
+ children: new Set(),
1225
+ labelUnknownTools,
1226
+ onActivity: (activity) => trace.push(activity),
1227
+ }, createAgentStreamState());
1228
+ for (const ev of events)
1229
+ handle(ev);
1230
+ return trace;
1231
+ }
1212
1232
  // Build the per-run stdout event handler over a shared mutable parser state.
1213
1233
  // Splitting the stream decoding out of runAgentCli keeps each within the
1214
1234
  // max-lines budget. A tool_use block streams its input JSON by block index,
1215
1235
  // accumulated in pendingTools so content_block_stop can label it with the
1216
1236
  // real file / command (and drop progress-file writes).
1217
1237
  function makeAgentEventHandler(opts, state) {
1238
+ const setActivity = (activity, retry = false) => {
1239
+ state.retryShowing = retry;
1240
+ opts.onActivity?.(activity);
1241
+ };
1218
1242
  const emitDelta = (rawDelta) => {
1219
1243
  let delta = rawDelta;
1220
1244
  if (state.needsGap) {
@@ -1225,15 +1249,22 @@ function makeAgentEventHandler(opts, state) {
1225
1249
  }
1226
1250
  state.accumulated += delta;
1227
1251
  opts.onDelta?.(delta);
1228
- opts.onActivity?.(null);
1252
+ setActivity(null);
1229
1253
  };
1230
1254
  const handleClaudeEvent = (ev) => {
1231
1255
  if (ev.type === 'system' && ev.subtype === 'init' && typeof ev.session_id === 'string') {
1232
1256
  state.sessionId = ev.session_id;
1233
1257
  }
1258
+ else if (ev.type === 'system' && ev.subtype === 'api_retry') {
1259
+ setActivity(retryNoticeFor(ev), true);
1260
+ }
1234
1261
  else if (ev.type === 'stream_event') {
1235
1262
  const e = ev.event;
1236
- if (e?.type === 'content_block_start') {
1263
+ if (e?.type === 'message_start') {
1264
+ if (state.retryShowing)
1265
+ setActivity(null);
1266
+ }
1267
+ else if (e?.type === 'content_block_start') {
1237
1268
  if (e.content_block?.type === 'tool_use') {
1238
1269
  state.needsGap = true;
1239
1270
  const name = String(e.content_block.name ?? '');
@@ -1241,7 +1272,7 @@ function makeAgentEventHandler(opts, state) {
1241
1272
  // line isn't stuck on the prior state while the tool runs; the
1242
1273
  // concrete label (with the file) refines it at content_block_stop.
1243
1274
  if (opts.labelUnknownTools)
1244
- opts.onActivity?.(genericClaudeToolLabel(name));
1275
+ setActivity(genericClaudeToolLabel(name));
1245
1276
  // Hold the concrete label until content_block_stop, once the input
1246
1277
  // (file / command) has streamed in, so we can name it concretely.
1247
1278
  state.pendingTools.set(e.index ?? -1, { name, buf: '' });
@@ -1250,7 +1281,7 @@ function makeAgentEventHandler(opts, state) {
1250
1281
  state.needsGap = true;
1251
1282
  // Surface extended thinking as the activity line. The next text delta
1252
1283
  // clears it via emitDelta's onActivity(null); a tool block relabels it.
1253
- opts.onActivity?.('Thinking');
1284
+ setActivity('Thinking');
1254
1285
  }
1255
1286
  }
1256
1287
  else if (e?.type === 'content_block_delta') {
@@ -1282,7 +1313,7 @@ function makeAgentEventHandler(opts, state) {
1282
1313
  }
1283
1314
  const label = claudeToolFeedLabel(pending.name, input);
1284
1315
  if (label)
1285
- opts.onActivity?.(label);
1316
+ setActivity(label);
1286
1317
  }
1287
1318
  }
1288
1319
  }
@@ -2072,7 +2103,7 @@ const TASK_OPTIONAL_STRINGS = [
2072
2103
  const TASK_OPTIONAL_NUMBERS = ['pid', 'costUsd', 'durationApiMs', 'numTurns', 'resumeCount'];
2073
2104
  const TASK_OPTIONAL_OBJECTS = ['usage', 'modelUsage'];
2074
2105
  const TASK_OPTIONAL_BOOLEANS = [
2075
- 'acknowledged', 'rejected', 'durablePending', 'resultSummaryStartsMidWord', 'handoffNoDeckFiles',
2106
+ 'acknowledged', 'rejected', 'durablePending', 'offersCredits', 'resultSummaryStartsMidWord', 'handoffNoDeckFiles',
2076
2107
  ];
2077
2108
  const TASK_OPTIONAL_STRING_LISTS = ['playtestFrames', 'files', 'knobs', 'blockedBy'];
2078
2109
  const isStringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
@@ -3750,6 +3781,7 @@ function startTask(ctx, task) {
3750
3781
  willRetry: false,
3751
3782
  });
3752
3783
  task.errorDetail = failure.detail || result.error;
3784
+ task.offersCredits = failureOffersCredits(failure) || undefined;
3753
3785
  task.failure = failureLabel(failure);
3754
3786
  console.error(`[task ${task.id}] failed (${task.failure}): ${failure.verbose ?? task.errorDetail}`);
3755
3787
  }
@@ -4415,6 +4447,7 @@ function asClientTask(task, signPath) {
4415
4447
  rejected: task.rejected,
4416
4448
  errorCopy: task.errorCopy,
4417
4449
  errorDetail: task.errorDetail,
4450
+ offersCredits: task.offersCredits,
4418
4451
  playtestFrames: (task.playtestFrames ?? []).map((rel) => clientUrl(`${AGENT_PLAYTEST_PREFIX}${task.id}/${path.basename(rel)}`, signPath)),
4419
4452
  steers: task.steers?.length
4420
4453
  ? task.steers.map(({ id, text, state, at, reason, sentOnAs }) => ({ id, text, state, at, reason, sentOnAs }))
@@ -4468,9 +4501,7 @@ function createTaskFeeds(broadcast, tasksDir) {
4468
4501
  }
4469
4502
  if (feed[feed.length - 1] === entry)
4470
4503
  return;
4471
- feed.push(entry);
4472
- if (feed.length > TASK_FEED_CAP)
4473
- feed.splice(0, feed.length - TASK_FEED_CAP);
4504
+ map.set(task.id, appendFeedEntry(feed, entry, TASK_FEED_CAP));
4474
4505
  broadcast({ type: 'task-feed', id: task.id, entry });
4475
4506
  }
4476
4507
  return { map, push, persist };
@@ -4994,6 +5025,7 @@ function runRouterTurnIn(ctx, instruction) {
4994
5025
  message.text = routerTurnErrorText(cleaned, textIsProviderError, copy);
4995
5026
  message.status = 'error';
4996
5027
  message.errorDetail = failure.detail || result.error || 'unknown failure';
5028
+ message.offersCredits = failureOffersCredits(failure) || undefined;
4997
5029
  errorVerbose = failure.verbose;
4998
5030
  console.error(`[router] turn failed (${failureLabel(failure)}): ${failure.verbose ?? message.errorDetail}`);
4999
5031
  }
@@ -5007,6 +5039,7 @@ function runRouterTurnIn(ctx, instruction) {
5007
5039
  status: message.status,
5008
5040
  taskIds: message.taskIds ?? [],
5009
5041
  errorDetail: message.errorDetail,
5042
+ offersCredits: message.offersCredits,
5010
5043
  planUpdated: message.planUpdated,
5011
5044
  // Broadcast-only, never persisted: the client console.errors this so
5012
5045
  // the whole provider response is inspectable without leaving the
@@ -121,7 +121,13 @@ async function handleMessage(data, isBinary) {
121
121
  }
122
122
  function createPlatformHandle(init, platformEvents) {
123
123
  const config = asRecord(init.config);
124
- return {
124
+ const assets = init.sessionAssets === undefined ? {} : asRecord(init.sessionAssets);
125
+ const handle = {
126
+ readAsset(name) {
127
+ const encoded = Object.hasOwn(assets, name) ? assets[name] : undefined;
128
+ const bytes = typeof encoded === 'string' ? new Uint8Array(Buffer.from(encoded, 'base64')) : null;
129
+ return Promise.resolve(bytes);
130
+ },
125
131
  send(connId, text) {
126
132
  send({ protocolVersion: PROTOCOL_VERSION, t: 'sendTo', playerId: connId, d: text });
127
133
  },
@@ -157,6 +163,7 @@ function createPlatformHandle(init, platformEvents) {
157
163
  maxPlayers: Number(config.maxPlayers),
158
164
  }),
159
165
  };
166
+ return Object.defineProperty(handle, 'sessionSecret', { value: init.sessionSecret });
160
167
  }
161
168
  async function dispatch(platformEvents, frame) {
162
169
  switch (frame.t) {
@@ -24,11 +24,17 @@ export interface DevSessionServer {
24
24
  shutdownNow(): void;
25
25
  }
26
26
  export declare function devSessionIdFor(key: string | null): string;
27
+ interface DevSessionFixtures {
28
+ readonly sessionSecret?: string;
29
+ readonly assets?: ReadonlyMap<string, Uint8Array>;
30
+ }
27
31
  export declare function startDevSessionServer(opts: {
28
32
  projectDir: string;
29
33
  log: (level: 'log' | 'error', text: string) => void;
30
34
  /** Tests shorten the empty named-session teardown. */
31
35
  namedSessionIdleMs?: number;
36
+ /** Boot inputs for the local deck's private platform connection. */
37
+ sessionFixtures?: DevSessionFixtures;
32
38
  }): Promise<DevSessionServer>;
33
39
  export declare function serverRestartNeeded(changes: ReadonlyArray<{
34
40
  path: string;
@@ -36,3 +42,4 @@ export declare function serverRestartNeeded(changes: ReadonlyArray<{
36
42
  serverEntry: string;
37
43
  serverDir: string;
38
44
  }): boolean;
45
+ export {};
@@ -32,7 +32,7 @@ export function devSessionIdFor(key) {
32
32
  return key === null ? DEFAULT_SESSION_ID : `${DEFAULT_SESSION_ID}:${key}`;
33
33
  }
34
34
  export async function startDevSessionServer(opts) {
35
- const server = new DevSessionRouter(opts.projectDir, opts.log, opts.namedSessionIdleMs ?? NAMED_SESSION_IDLE_MS);
35
+ const server = new DevSessionRouter(opts.projectDir, opts.log, opts.namedSessionIdleMs ?? NAMED_SESSION_IDLE_MS, opts.sessionFixtures);
36
36
  try {
37
37
  await server.start();
38
38
  return server;
@@ -52,17 +52,19 @@ class DevSessionRouter {
52
52
  projectDir;
53
53
  log;
54
54
  idleMs;
55
+ sessionFixtures;
55
56
  sessionId = DEFAULT_SESSION_ID;
56
57
  port = 0;
57
58
  server = http.createServer((_req, res) => res.writeHead(404).end());
58
59
  defaultSession;
59
60
  named = new Map();
60
61
  closed = false;
61
- constructor(projectDir, log, idleMs) {
62
+ constructor(projectDir, log, idleMs, sessionFixtures) {
62
63
  this.projectDir = projectDir;
63
64
  this.log = log;
64
65
  this.idleMs = idleMs;
65
- this.defaultSession = new DevSessionImpl(projectDir, log, null, () => this.port, () => { });
66
+ this.sessionFixtures = sessionFixtures;
67
+ this.defaultSession = new DevSessionImpl(projectDir, log, null, () => this.port, () => { }, idleMs, sessionFixtures);
66
68
  this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
67
69
  }
68
70
  async start() {
@@ -119,7 +121,7 @@ class DevSessionRouter {
119
121
  // `deck:<name>/<key>` runs another local deck's server, one this deck lists
120
122
  // in `devDecks` (contentPack.ts): a door to a separately built deck.
121
123
  const other = devDeckSessionKey(this.projectDir, key);
122
- const session = new DevSessionImpl(other?.dir ?? this.projectDir, (level, text) => this.log(level, `(${key}) ${text}`), key, () => this.port, () => this.stopIdle(key, session), this.idleMs);
124
+ const session = new DevSessionImpl(other?.dir ?? this.projectDir, (level, text) => this.log(level, `(${key}) ${text}`), key, () => this.port, () => this.stopIdle(key, session), this.idleMs, other ? undefined : this.sessionFixtures);
123
125
  this.named.set(key, session);
124
126
  session.start().catch((error) => {
125
127
  this.log('error', `(${key}) start failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -182,6 +184,7 @@ class DevSessionImpl {
182
184
  port;
183
185
  onIdle;
184
186
  idleMs;
187
+ sessionFixtures;
185
188
  sessionId;
186
189
  clientWss = new WebSocketServer({
187
190
  noServer: true,
@@ -221,13 +224,14 @@ class DevSessionImpl {
221
224
  * `key` null is the default session, which never idles out. A named one calls
222
225
  * `onIdle` once it has had nobody connected for `idleMs`.
223
226
  */
224
- constructor(projectDir, log, key, port, onIdle, idleMs = NAMED_SESSION_IDLE_MS) {
227
+ constructor(projectDir, log, key, port, onIdle, idleMs, sessionFixtures) {
225
228
  this.projectDir = projectDir;
226
229
  this.log = log;
227
230
  this.key = key;
228
231
  this.port = port;
229
232
  this.onIdle = onIdle;
230
233
  this.idleMs = idleMs;
234
+ this.sessionFixtures = sessionFixtures;
231
235
  this.sessionId = devSessionIdFor(key);
232
236
  this.serverEntry = resolveServerConfig(projectDir)?.entry ?? 'server/index.js';
233
237
  this.serverDir = serverDirOf(this.serverEntry);
@@ -516,6 +520,7 @@ class DevSessionImpl {
516
520
  socket.on('close', () => this.runtimeClosed(socket));
517
521
  socket.on('error', () => undefined);
518
522
  const config = this.currentConfig();
523
+ const assets = this.sessionFixtures?.assets;
519
524
  this.sendPlatform({
520
525
  protocolVersion: PROTOCOL_VERSION,
521
526
  t: 'init',
@@ -523,6 +528,8 @@ class DevSessionImpl {
523
528
  deckId: readCastleJson(this.projectDir)?.deckId ?? 'dev',
524
529
  mode: 'named',
525
530
  config: { tickRate: config.tickRate, maxPlayers: config.maxPlayers },
531
+ sessionSecret: this.sessionFixtures?.sessionSecret,
532
+ sessionAssets: assets && Object.fromEntries(Array.from(assets, ([name, bytes]) => [name, Buffer.from(bytes).toString('base64')])),
526
533
  });
527
534
  }
528
535
  handleRuntimeMessage(data, isBinary) {
@@ -0,0 +1,23 @@
1
+ import type { ResolvedServerConfig } from './castleJson.js';
2
+ export declare const WRITER_CHECKS_CAPABILITY = "writerChecksV1";
3
+ export interface FleetCapabilities {
4
+ readyHosts: number;
5
+ capabilities: {
6
+ name: string;
7
+ hosts: number;
8
+ }[];
9
+ }
10
+ /**
11
+ * Whether the published (minified) server bundle passes a writer check
12
+ * (`{ check: { target, writer } }`) on a storage write. The SDK and kits name `check`
13
+ * only in comments and reads (`options.check`), so an object key `check`, the
14
+ * `{ check }` shorthand or an assignment to a `check` property comes from the deck. A heuristic over the built
15
+ * code: an unrelated `check` key also matches, which costs only a warning.
16
+ */
17
+ export declare function bundleUsesWriterChecks(code: string): boolean;
18
+ export declare function usesPersistentWorlds(config: ResolvedServerConfig): boolean;
19
+ export declare function fetchFleetCapabilities(): Promise<FleetCapabilities | null>;
20
+ /** The warning to print, or null when there is nothing to say. */
21
+ export declare function writerCheckFleetWarning(fleet: FleetCapabilities | null): string | null;
22
+ /** Prints the warning for a deck that needs it. Never throws. */
23
+ export declare function warnOnMissingHostFeatures(config: ResolvedServerConfig, code: string, fetchFleet?: () => Promise<FleetCapabilities | null>): Promise<void>;
@@ -0,0 +1,70 @@
1
+ // Warns at save when a deck depends on a host-side Cauldron feature the production
2
+ // fleet does not run yet. Host-agent code ships only in an AMI roll, which can trail a
3
+ // CLI release: on Nov 18 writer-checked saves in persistent worlds were refused as
4
+ // storage unavailable until the hosts were rolled. Warn only, never block, and an
5
+ // unreadable fleet is "unknown", not a failure.
6
+ import * as api from './api.js';
7
+ export const WRITER_CHECKS_CAPABILITY = 'writerChecksV1';
8
+ /**
9
+ * Whether the published (minified) server bundle passes a writer check
10
+ * (`{ check: { target, writer } }`) on a storage write. The SDK and kits name `check`
11
+ * only in comments and reads (`options.check`), so an object key `check`, the
12
+ * `{ check }` shorthand or an assignment to a `check` property comes from the deck. A heuristic over the built
13
+ * code: an unrelated `check` key also matches, which costs only a warning.
14
+ */
15
+ export function bundleUsesWriterChecks(code) {
16
+ return (/[{,]\s*check\s*[:,}]/.test(code) ||
17
+ // options.check = …, options["check"] = …; never the SDK's own `.check === undefined`.
18
+ /(?:\.check|\[\s*["'`]check["'`]\s*\])\s*=(?!=)/.test(code));
19
+ }
20
+ export function usesPersistentWorlds(config) {
21
+ return config.destinations?.some((route) => route.persistence === 'world') === true;
22
+ }
23
+ export async function fetchFleetCapabilities() {
24
+ try {
25
+ const result = await api.graphql(`query CauldronFleetCapabilities {
26
+ cauldronFleetCapabilities(env: "prod") {
27
+ readyHosts
28
+ capabilities { name hosts }
29
+ }
30
+ }`, undefined, { timeoutMs: 5_000 });
31
+ const fleet = result.data?.cauldronFleetCapabilities;
32
+ if (!fleet ||
33
+ typeof fleet.readyHosts !== 'number' ||
34
+ !Array.isArray(fleet.capabilities)) {
35
+ return null;
36
+ }
37
+ return fleet;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ /** The warning to print, or null when there is nothing to say. */
44
+ export function writerCheckFleetWarning(fleet) {
45
+ if (!fleet) {
46
+ return ('This deck uses writer checks in a persistent world, and the Cauldron fleet could not be read, ' +
47
+ `so it is unknown whether production hosts support them (${WRITER_CHECKS_CAPABILITY}). ` +
48
+ 'Where they do not, those saves fail with CAULDRON_STORAGE_UNAVAILABLE.');
49
+ }
50
+ const capable = fleet.capabilities.find((c) => c.name === WRITER_CHECKS_CAPABILITY)?.hosts ?? 0;
51
+ if (fleet.readyHosts > 0 && capable >= fleet.readyHosts)
52
+ return null;
53
+ return (`This deck uses writer checks in a persistent world, but only ${capable} of ${fleet.readyHosts} ` +
54
+ `production Cauldron hosts support them (${WRITER_CHECKS_CAPABILITY}). ` +
55
+ 'Until the rest are updated, a checked save in a world on an older host fails with ' +
56
+ 'CAULDRON_STORAGE_UNAVAILABLE. The deck is saved; nothing was blocked.');
57
+ }
58
+ /** Prints the warning for a deck that needs it. Never throws. */
59
+ export async function warnOnMissingHostFeatures(config, code, fetchFleet = fetchFleetCapabilities) {
60
+ try {
61
+ if (!usesPersistentWorlds(config) || !bundleUsesWriterChecks(code))
62
+ return;
63
+ const warning = writerCheckFleetWarning(await fetchFleet());
64
+ if (warning)
65
+ console.warn(`Warning: ${warning}`);
66
+ }
67
+ catch {
68
+ // A warning must never fail a save.
69
+ }
70
+ }
package/dist/init.js CHANGED
@@ -65,7 +65,7 @@ const BARE_SCAFFOLDS = [
65
65
  // Registry version of castle-web-sdk to inject when scaffolding from a
66
66
  // globally-installed castle-web (not from inside the workspace). Bumped
67
67
  // alongside cli/sdk version bumps.
68
- const PUBLISHED_SDK_VERSION = '0.4.58';
68
+ const PUBLISHED_SDK_VERSION = '0.4.59';
69
69
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
70
70
  // face can ship without a cli release, and a caret range means an existing
71
71
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -5,6 +5,7 @@ export declare const CHARACTER_DOC_REL: string;
5
5
  export declare function everyDeckBullets(deckDir: string): string[];
6
6
  export declare const HOST_LIMIT_BULLETS: string[];
7
7
  export declare const CASTLE_UI_BULLETS: string[];
8
+ export declare const CREATOR_DOCS_BULLETS: string[];
8
9
  export type AgentRole = 'router' | 'task';
9
10
  export declare function roleLoadsClaudeMd(role: AgentRole): boolean;
10
11
  export declare function claudeContextEnv(role: AgentRole): NodeJS.ProcessEnv;
@@ -102,8 +102,19 @@ export const CASTLE_UI_BULLETS = [
102
102
  "- **Upload is not its own button.** Files go into the deck from the Files panel: **New** → **Upload files…**, the last item of that menu. On a phone, switch to the Files panel first. The **Import** button beside New adds another Castle deck as an import; it does not upload files.",
103
103
  "- **Chat attach takes images only.** The attach control under the message box accepts image files. Audio, video, 3D models and any other file go in through Files → New → Upload files…, never through chat.",
104
104
  "- **An imported file opens read-only**, under a banner naming the import it came from. Where the file can be forked (nearly all can; an import's `castle.json` cannot), the banner's **Fork** button (also Fork in that file's menu in the Files panel) gives this deck its own editable copy; **Drop fork** goes back to the import's version.",
105
+ // Docs is in FlowShell's Castle menu (hidden in the mobile app's shell) and in
106
+ // its panel picker (the "+" beside the panel chips, shown everywhere).
107
+ "- **Castle's creator docs open from Docs** in the **+** menu beside the panel tabs at the top of the editor, on the web and in the mobile app; on the web the Castle menu (the Castle mark at the top left) has **Docs** too. It opens the docs outside the editor. Point a creator there for how Castle works.",
105
108
  "- **Describe only the Castle controls named here or in the deck's guide.** If you do not know where something is in Castle's UI, say so -- never name a button, menu or location you have not seen described.",
106
109
  ];
110
+ // Castle's public creator docs (castle-docs). The deck's own references come
111
+ // first because they match the versions it imports; the site covers the rest.
112
+ // Reachability from a production sandbox was checked 2026-11-19 with curl
113
+ // (llms.txt, the Cauldron page and the single-file Markdown all answered 200).
114
+ // The editor's Castle menu and panel picker link the same page (shell/docsUrl.ts).
115
+ export const CREATOR_DOCS_BULLETS = [
116
+ "- **Castle's creator docs are at https://docs.castle.xyz/docs/cauldron.** Before using an SDK or kit feature you are unsure of, read the relevant page: `curl -s https://docs.castle.xyz/llms.txt` is an index of the main pages with a one-line summary each (the Cauldron ones are under `## Cauldron Decks`), and `https://docs.castle.xyz/latest-cauldron-docs.mdx` is all of the Cauldron docs as one Markdown file, so search that when the index has no page for your topic. The references inside this deck (this guide, `imports/castle.base/sdk/README.md`, the kit's `CLAUDE.md`) match the versions it imports, so where the site disagrees with them, they win.",
117
+ ];
107
118
  // The line has to stand on its own to count: this repo's CLAUDE.md names the
108
119
  // path inside a sentence, and prose about the import must not read as a deck
109
120
  // carrying one.
@@ -136,15 +147,16 @@ function deckLoadsGuide(deckDir) {
136
147
  const RESTATEMENT_MARKER = '**Supported media formats are exactly**';
137
148
  // The every-deck bullets after a quick reference that lacks them. Skipped when
138
149
  // the deck's kit is pinned to a version that still restates them, which would
139
- // otherwise say all of it twice. No kit ever restated the Castle UI bullets or
140
- // host limits, so they come either way.
150
+ // otherwise say all of it twice. No kit ever restated the creator docs, Castle
151
+ // UI bullets or host limits, so they come either way.
141
152
  function withEveryDeckBullets(deckDir, quickReference) {
142
153
  const own = quickReference.trim();
143
154
  if (own.includes(RESTATEMENT_MARKER)) {
144
- return `${own}\n\n${[...CASTLE_UI_BULLETS, ...HOST_LIMIT_BULLETS].join('\n')}`;
155
+ return `${own}\n\n${[...CREATOR_DOCS_BULLETS, ...CASTLE_UI_BULLETS, ...HOST_LIMIT_BULLETS].join('\n')}`;
145
156
  }
146
157
  const bullets = [
147
158
  ...everyDeckBullets(deckDir),
159
+ ...CREATOR_DOCS_BULLETS,
148
160
  ...CASTLE_UI_BULLETS,
149
161
  ...HOST_LIMIT_BULLETS,
150
162
  ].join('\n');
@@ -332,6 +344,10 @@ export function platformGuide(deckDir) {
332
344
 
333
345
  ${CHARACTER_POINTER.trimEnd()}
334
346
 
347
+ ## Creator docs
348
+
349
+ ${CREATOR_DOCS_BULLETS.join('\n')}
350
+
335
351
  ## Formats, reloading, editors
336
352
 
337
353
  ${everyDeckBullets(deckDir).filter((b) => !b.includes('PARAMS')).join('\n')}
@@ -0,0 +1,3 @@
1
+ export declare function retryNoticeFor(ev: Record<string, unknown>): string;
2
+ export declare function isFeedRetryNotice(entry: string): boolean;
3
+ export declare function appendFeedEntry(feed: readonly string[], entry: string, cap: number): string[];
@@ -0,0 +1,39 @@
1
+ // The activity line for claude's `system/api_retry` event, shared by the serve
2
+ // (agent.ts builds it) and the shell (task feeds collapse a burst of them).
3
+ const RETRY_SLOW = 'Model is slow to respond, retrying…';
4
+ const RETRY_BUSY = 'Model is busy, retrying…';
5
+ const RETRY_FAILED = 'Model request failed, retrying…';
6
+ // claude emits api_retry before each retry of a model request that failed or
7
+ // timed out (the proxy answers a model that has not started within 45s with a
8
+ // 504). Untrusted JSON, so every field is checked.
9
+ export function retryNoticeFor(ev) {
10
+ const status = ev.error_status;
11
+ let label = RETRY_FAILED;
12
+ if (status === null || status === undefined || status === 504 || status === 408) {
13
+ label = RETRY_SLOW;
14
+ }
15
+ else if (status === 429 || status === 529) {
16
+ label = RETRY_BUSY;
17
+ }
18
+ const attempt = ev.attempt;
19
+ return typeof attempt === 'number' && Number.isInteger(attempt) && attempt > 0
20
+ ? `${label} (attempt ${attempt})`
21
+ : label;
22
+ }
23
+ const FEED_RETRY_RE = new RegExp(`^\\[(?:${[RETRY_SLOW, RETRY_BUSY, RETRY_FAILED]
24
+ .map((l) => l.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
25
+ .join('|')})(?: \\(attempt [1-9]\\d*\\))?\\]$`);
26
+ // A task feed entry that is exactly a retry notice, as the task sink brackets it.
27
+ export function isFeedRetryNotice(entry) {
28
+ return FEED_RETRY_RE.test(entry);
29
+ }
30
+ // The feed after appending `entry`, capped to the newest `cap` entries. A
31
+ // retry notice replaces a retry notice right before it, so a burst of retries
32
+ // takes one slot rather than evicting the task's history.
33
+ export function appendFeedEntry(feed, entry, cap) {
34
+ const last = feed[feed.length - 1];
35
+ const next = last !== undefined && isFeedRetryNotice(entry) && isFeedRetryNotice(last)
36
+ ? [...feed.slice(0, -1), entry]
37
+ : [...feed, entry];
38
+ return next.length > cap ? next.slice(next.length - cap) : next;
39
+ }
package/dist/save-deck.js CHANGED
@@ -11,6 +11,7 @@ import { importChecksFailedMessage, runImportChecks } from './importCheckHook.js
11
11
  import { selectSaveCover } from './saveCover.js';
12
12
  import { COVER_FILE } from './localPaths.js';
13
13
  import { buildServerBundle } from './serverBundle.js';
14
+ import { warnOnMissingHostFeatures } from './hostFeatureCheck.js';
14
15
  import { runSaveExports } from './deckExports.js';
15
16
  import { buildContentPack } from './contentPack.js';
16
17
  import { importRegressionMessage, importRegressions, savedDeckImportPins } from './importRegression.js';
@@ -300,6 +301,7 @@ async function publishServerBundle(projectDir, deckId, pack) {
300
301
  console.log(`Content pack published with it (sha256 ${pack?.sha256}).`);
301
302
  writePublishedServerBundleState(projectDir, { deckId, sha256: bundle.sha256 });
302
303
  console.log(`Server bundle published${saved ? ` as ${saved.version}` : ''} (sha256 ${bundle.sha256}).`);
304
+ await warnOnMissingHostFeatures(serverConfig, bundle.code);
303
305
  }
304
306
  // Checked before anything is bundled or published, so a block Castle would
305
307
  // refuse stops the save while the live deck is still untouched.