castle-web-cli 0.4.226 → 0.4.227

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.
@@ -141,11 +141,16 @@ export interface PromptRef {
141
141
  field?: string;
142
142
  fragment?: string;
143
143
  }
144
+ export interface FlattenedAttachment {
145
+ view: string;
146
+ original: string;
147
+ }
144
148
  export declare function userTurnInstruction(opts: {
145
149
  messages: string[];
146
150
  interruptedDraft?: string;
147
151
  attachments?: string[];
148
152
  marked?: string[];
153
+ flattened?: FlattenedAttachment[];
149
154
  refs?: PromptRef[];
150
155
  }): string;
151
156
  export declare function buildTaskPrompt(opts: {
@@ -59,7 +59,7 @@ function baseRouterRules(playtest, playtestPref, steer = false) {
59
59
  : playtest
60
60
  ? `\n${PLAYTEST_ROUTER_RULE}`
61
61
  : '';
62
- const modelsRule = `\n- You cannot change which models run. Both are set in the model chip under the message box (Agent & model settings): Operator model and Operator effort set the model you, this chat, run on; Task model and Task effort set the model new tasks run on. A change applies to what starts after it, not to anything already running. When the user asks which model you or their tasks run on, asks to switch to or use a model or effort, or says they have switched: answer from == models == (and, when relevant, the model on the rows they mean), which always shows the current settings; trust it over anything said earlier in this chat, which may be wrong. If it does not show what they say they picked, tell them that setting has not changed yet. Point them to the matching row; never say you switched it or that it has changed when == models == does not show it. If the same message asks for work they want done on a model or effort == models == does not show yet, do not spawn that work yet: tell them to change the setting and send the request again. When == models == already shows it, spawn the work as usual${steer ? STEER_MODEL_CLAUSE : '.'} Apart from a usage-limit failure (above), do not bring up models when the user did not.`;
62
+ const modelsRule = `\n- You cannot change which models run. Both are set in the model chip under the message box (Agent & model settings): Operator model and Operator effort set the model you, this chat, run on; Task model and Task effort set the model new tasks run on. A change applies to what starts after it, not to anything already running. When the user asks which model you or their tasks run on, asks to switch to or use a model or effort, or says they have switched: answer from == models == (and, when relevant, the model on the rows they mean), which always shows the current settings; trust it over anything said earlier in this chat, which may be wrong. The tool you run inside calls itself Claude Code; that names the tool, not you. Your model is the one == models == names for this chat: answer whether you are Claude, or any model, from it. When it names a model that is not Claude (${CLAUDE_FAMILY} are Claude), you are not Claude: say so plainly. If it does not show what they say they picked, tell them that setting has not changed yet. Point them to the matching row; never say you switched it or that it has changed when == models == does not show it. If the same message asks for work they want done on a model or effort == models == does not show yet, do not spawn that work yet: tell them to change the setting and send the request again. When == models == already shows it, spawn the work as usual${steer ? STEER_MODEL_CLAUSE : '.'} Apart from a usage-limit failure (above), do not bring up models when the user did not.`;
63
63
  return `You are Castle's create assistant: the fast conversational router for a game-making session. The deck (game project) lives in the current directory and runs live in a pane right next to this chat.
64
64
 
65
65
  What a deck is: a normal web project served by vite -- index.html plus plain JS/JSX modules, with real npm dependencies (more can be installed), the castle-web-sdk package, and usually a kit framework whose engine, behaviors, scenes, editors, and drawings are ordinary files in this directory. The web platform is fully available (DOM, canvas, npm libraries like react, three, etc.). The deck's Quick reference and file list below describe its setup; the full CLAUDE.md / AGENTS.md has deeper detail. NEVER claim something is impossible or unsupported on the platform without checking that context (or, for specifics it doesn't cover, the deck's files) first.
@@ -189,7 +189,7 @@ now- food-hauling
189
189
  - THE USER SHAPING THE GAME IS AN INFLECTION POINT. A mechanic, a rule, an entity, a mood, a difficulty they ask for is taste, not a chore: it goes in with \`decide+\` quoting the words they used, in the same reply that spawns the work. Early on nearly every ask is one of these, and a plan that holds only what is in flight has kept nothing.
190
190
  - A bare number, a knob setting, or a bug they want gone is not taste -- just do the tweak. The REASON they give for one is: "make the islands bigger, it's already pretty hard" is a \`decide+\` about the difficulty they want, not about island size. A line about a value someone tuned names the intent and the knob, never the number: \`decide+ gentle-start: the first wave should feel easy -- spawnRate ("go easy at the start" -- user)\`, not \`... spawnRate at 0.4\`. A number inside the quote stays, since the quote is their words verbatim; your own sentence never carries one. The number lives in one place, the \`PARAMS\` object of the file that uses it, and a plan line repeating it becomes a second answer the moment anyone moves the slider.
191
191
  - Put the fence AFTER your task fences: tasks spawn the moment their fence closes.
192
- - NOTHING in \`## Open questions\` may be answered by anything else in the same reply, fence or task: asking and deciding are different acts. A probe IS the top open question, asked in its own words.
192
+ - NOTHING in \`## Open questions\` may be answered by anything else in the same reply, fence or task: asking and deciding are different acts.
193
193
  - An open question you have asked outright twice, and the user passed over both times, is TABLED: \`open- <label>\` it in that reply's fence and stop asking it. Passing over it twice is their answer about the question. It comes back only if they bring it up.
194
194
  - An ask that goes against a \`## Decisions\` line: say what was decided and why in one sentence BEFORE you build it. They may well have changed their mind -- that is theirs to say, and the line is yours to raise.
195
195
  - No plan.md yet and the deck is getting work? Open one here with the ops the moment supports: an \`identity:\` line, the \`## Now\` items you are spawning, an \`open+\` for what you are guessing at. SPARSE AND TRUE, and never in place of their actual ask.
@@ -830,10 +830,6 @@ export function renderPlanDigest(plan, tasks) {
830
830
  }
831
831
  return parts.join("\n\n");
832
832
  }
833
- // The non-empty lines of `## Open questions`, for the runtime's agenda nudge
834
- // (agent.ts): a standing question the router keeps not asking gets named in a
835
- // notice, since five wordings of a prompt rule for the same behavior all
836
- // measured 0 (26-08-18) while the notice-shaped close rule measured real.
837
833
  export function planOpenQuestionLines(fileText) {
838
834
  const section = parsePlanSections(fileText).find((s) => s.key === "open questions");
839
835
  return (section?.lines ?? []).map((l) => l.trim()).filter(Boolean);
@@ -887,6 +883,7 @@ export function renderTaskPlanSlice(fileText, item, finishedWork) {
887
883
  // settings rather than a provider slug. "Muse" is the chip's name for a model
888
884
  // Castle pays for, which only the budget's free prefixes decide.
889
885
  const CLAUDE_MODEL_LABELS = { sonnet: "Sonnet", opus: "Opus", fable: "Fable" };
886
+ const CLAUDE_FAMILY = Object.values(CLAUDE_MODEL_LABELS).join(", ").replace(/, ([^,]*)$/, " and $1");
890
887
  const noFreeModels = () => false;
891
888
  export function modelLabel(model, isFreeModel) {
892
889
  const trimmed = model.trim();
@@ -1058,7 +1055,10 @@ export function userTurnInstruction(opts) {
1058
1055
  const markNote = marked.length > 0
1059
1056
  ? ` ${marked.join(", ")} ${marked.length === 1 ? "carries" : "carry"} the user's marks drawn on top of the game in red; numbered pins match the numbered lines in their message.`
1060
1057
  : "";
1061
- parts.push(`The user attached image file(s), saved in the deck at: ${opts.attachments.join(", ")}. Open them with your read tool. Take them into account; pass the paths along to task agents that need them.${markNote}`);
1058
+ const flatNote = (opts.flattened ?? [])
1059
+ .map(({ view, original }) => ` ${view} is ${original} flattened onto white, because its transparent areas would show to you as black; ${original} keeps the transparency, so pass that one to a task that puts the image in the game.`)
1060
+ .join("");
1061
+ parts.push(`The user attached image file(s), saved in the deck at: ${opts.attachments.join(", ")}. Open them with your read tool. Take them into account; pass the paths along to task agents that need them.${markNote}${flatNote}`);
1062
1062
  }
1063
1063
  if (opts.refs && opts.refs.length > 0) {
1064
1064
  parts.push(`The user pointed at: ${opts.refs.map(refPhrase).join(", ")}. Read them with your read tool if you need them to reply. When you spawn a task one of these concerns, name it the same way in that task's prompt -- the path and the lines, or the path and the param -- so the agent reads that place; do not mention it to tasks it does not concern.`);
package/dist/agent.d.ts CHANGED
@@ -143,6 +143,7 @@ export declare function createTaskStore(opts: {
143
143
  onRetry: (task: TaskRecord, attempt: number) => void;
144
144
  onFeed: (task: TaskRecord, entry: string) => void;
145
145
  }): TaskStore;
146
+ export declare function attachmentViewName(fileName: string): string;
146
147
  export declare function computeSettingsWarnings(settings: AgentSettings): Promise<SettingsWarnings>;
147
148
  export interface AgentServer {
148
149
  /** Start tasks recovered from a restart; call once the serve is listening. */
package/dist/agent.js CHANGED
@@ -37,7 +37,7 @@ import { badTaskEndingsSince, platformInterruptionReason, ROUTER_STOPPED_RESULT,
37
37
  import { accountForRun, closingMessageOf } from './taskAccount.js';
38
38
  import { atomicWriteFileSync } from './atomicFile.js';
39
39
  import { AGENT_ATTACHMENT_PREFIX, AGENT_PLAYTEST_PREFIX, PLAN_FILE } from './localPaths.js';
40
- import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, planOpenQuestionLines, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
40
+ import { applyPlanOps, buildRouterPromptParts, buildTaskPrompt, parsePlanOps, truncateToBytes, userTurnInstruction, CLAUDE_TASK_SYSTEM_REMINDER, modelTaskAddendum, isMuseModel, } from './agent-prompts.js';
41
41
  import { readCastleJson } from './castleJson.js';
42
42
  import { checkOpenrouterKey, checkOpenrouterModel, primeOpenrouterCatalog, } from './openrouter-catalog.js';
43
43
  import { classifyProviderError, failureCopy, failureLabel, routerTaskError, setReaderTimeZone, } from './agent-failures.js';
@@ -647,8 +647,6 @@ function planSession(deckDir) {
647
647
  const session = {
648
648
  enabled: declared === 'on' ? true : declared === 'off' ? false : planDefault(),
649
649
  notices: [],
650
- asyncNotices: [],
651
- quietBuildTurns: 0,
652
650
  };
653
651
  planSessions.set(deckDir, session);
654
652
  return session;
@@ -744,9 +742,8 @@ function routerPlanOpts(deckDir, snapshot, nominations, tasks) {
744
742
  const session = planSession(deckDir);
745
743
  if (!session.enabled)
746
744
  return undefined;
747
- const notices = [...session.notices, ...session.asyncNotices].slice(0, PLAN_NOTICE_LIMIT);
745
+ const notices = session.notices.slice(0, PLAN_NOTICE_LIMIT);
748
746
  session.notices = [];
749
- session.asyncNotices = [];
750
747
  return {
751
748
  fileText: snapshot.text,
752
749
  pendingDurables: nominations.map((t) => ({
@@ -758,32 +755,6 @@ function routerPlanOpts(deckDir, snapshot, nominations, tasks) {
758
755
  notices,
759
756
  };
760
757
  }
761
- // The agenda nudge. A reply that spawned work, asked nothing (no probe chips,
762
- // no question mark), while `## Open questions` holds a standing line, is a
763
- // quiet build turn; the second in a row queues a notice naming the top line.
764
- // Counting quiet turns and naming the line is exactly what five wordings of a
765
- // prompt rule could not get the router to do for itself (0 across 14 samples,
766
- // 26-08-18) and what the notice-shaped close rule showed it does do when told.
767
- function trackStandingQuestions(ctx, cleaned, spawnedWork) {
768
- const session = planSession(ctx.deckDir);
769
- if (!session.enabled)
770
- return;
771
- const askedSomething = /\[\[[^\]\n]+\]\]/.test(cleaned) || cleaned.includes('?');
772
- if (askedSomething || !spawnedWork) {
773
- session.quietBuildTurns = 0;
774
- return;
775
- }
776
- const standing = planOpenQuestionLines(readPlanSnapshot(ctx.deckDir).raw ?? '');
777
- if (standing.length === 0) {
778
- session.quietBuildTurns = 0;
779
- return;
780
- }
781
- session.quietBuildTurns += 1;
782
- if (session.quietBuildTurns < 2)
783
- return;
784
- session.quietBuildTurns = 0;
785
- session.asyncNotices.push(`the plan's top open question has now sat through two build turns with nothing asked -- this is the turn to ask it, in its own words, while work spawns anyway: ${standing[0]}`);
786
- }
787
758
  function taskPlanOpts(deckDir, item, finishedWork) {
788
759
  if (!planSession(deckDir).enabled)
789
760
  return undefined;
@@ -3285,13 +3256,21 @@ const ATTACHMENT_MIME = {
3285
3256
  gif: 'image/gif',
3286
3257
  webp: 'image/webp',
3287
3258
  };
3259
+ // The copy of an attachment the model is shown: the composer's `view`, the
3260
+ // picture flattened onto white because the model sees transparency as black.
3261
+ export function attachmentViewName(fileName) {
3262
+ return fileName.replace(/\.[^.]+$/, '') + '-view.jpg';
3263
+ }
3264
+ const VIEW_DATA_URL = /^data:image\/jpeg;base64,([A-Za-z0-9+/=]+)$/;
3288
3265
  // Decode pasted/attached images (data URLs) into .castle/agent/attachments/.
3289
- // Returns the saved file names, and which of them carry the user's marks.
3266
+ // Returns the saved file names, which of them carry the user's marks, and
3267
+ // which have a flattened view saved beside them (attachmentViewName).
3290
3268
  function saveAttachments(attachmentsDir, messageId, images) {
3291
3269
  const saved = [];
3292
3270
  const marked = [];
3271
+ const viewed = [];
3293
3272
  if (!Array.isArray(images))
3294
- return { saved, marked };
3273
+ return { saved, marked, viewed };
3295
3274
  for (const [index, image] of images.slice(0, MAX_ATTACHMENTS).entries()) {
3296
3275
  const dataUrl = image?.dataUrl;
3297
3276
  if (typeof dataUrl !== 'string' || dataUrl.length > MAX_ATTACHMENT_BYTES * 1.4)
@@ -3310,9 +3289,23 @@ function saveAttachments(attachmentsDir, messageId, images) {
3310
3289
  }
3311
3290
  catch {
3312
3291
  /* disk trouble -- skip this image */
3292
+ continue;
3293
+ }
3294
+ const view = image.view;
3295
+ const viewMatch = typeof view === 'string' && view.length <= MAX_ATTACHMENT_BYTES * 1.4
3296
+ ? VIEW_DATA_URL.exec(view)
3297
+ : null;
3298
+ if (!viewMatch)
3299
+ continue;
3300
+ try {
3301
+ atomicWriteFileSync(path.join(attachmentsDir, attachmentViewName(fileName)), Buffer.from(viewMatch[1], 'base64'));
3302
+ viewed.push(fileName);
3303
+ }
3304
+ catch {
3305
+ /* the model reads the faithful file instead */
3313
3306
  }
3314
3307
  }
3315
- return { saved, marked };
3308
+ return { saved, marked, viewed };
3316
3309
  }
3317
3310
  function isExistingFile(abs) {
3318
3311
  try {
@@ -3993,7 +3986,6 @@ function runRouterTurnIn(ctx, instruction) {
3993
3986
  if (result.ok) {
3994
3987
  message.text = cleaned;
3995
3988
  message.status = 'done';
3996
- trackStandingQuestions(ctx, cleaned, taskIds.length > 0);
3997
3989
  }
3998
3990
  else {
3999
3991
  const failure = resolveFailure(result);
@@ -4346,12 +4338,19 @@ function handleStopTask(taskStore, socket, msg) {
4346
4338
  }
4347
4339
  }
4348
4340
  // A mirror on disk is not evidence: only names that are also this send's
4349
- // attachments count as marked.
4341
+ // attachments count as marked or viewed.
4342
+ function attachmentSubset(item, names) {
4343
+ if (!Array.isArray(names))
4344
+ return [];
4345
+ return names.filter((name) => typeof name === 'string' && item.attachments.includes(name));
4346
+ }
4350
4347
  function markedOf(item) {
4351
- if (!Array.isArray(item.marked))
4352
- return {};
4353
- const marked = item.marked.filter((name) => typeof name === 'string' && item.attachments.includes(name));
4354
- return marked.length > 0 ? { marked } : {};
4348
+ const marked = attachmentSubset(item, item.marked);
4349
+ const viewed = attachmentSubset(item, item.viewed);
4350
+ return {
4351
+ ...(marked.length > 0 ? { marked } : {}),
4352
+ ...(viewed.length > 0 ? { viewed } : {}),
4353
+ };
4355
4354
  }
4356
4355
  // Restart recovery: load the durable queue mirror, keeping only well-formed
4357
4356
  // sends that never reached the message log. A send whose id is already in
@@ -4474,6 +4473,7 @@ function commitDrainedSends(drained, log) {
4474
4473
  const texts = [];
4475
4474
  const attachmentPaths = [];
4476
4475
  const markedPaths = [];
4476
+ const flattened = [];
4477
4477
  const refs = [];
4478
4478
  for (const item of drained) {
4479
4479
  if (!item.logged) {
@@ -4495,14 +4495,20 @@ function commitDrainedSends(drained, log) {
4495
4495
  if (item.text.trim())
4496
4496
  texts.push(item.text);
4497
4497
  for (const name of item.attachments) {
4498
- const attachmentPath = path.join('.castle', 'agent', 'attachments', name);
4499
- attachmentPaths.push(attachmentPath);
4498
+ const original = path.join('.castle', 'agent', 'attachments', name);
4499
+ const view = item.viewed?.includes(name)
4500
+ ? path.join('.castle', 'agent', 'attachments', attachmentViewName(name))
4501
+ : null;
4502
+ const listed = view ?? original;
4503
+ attachmentPaths.push(listed);
4504
+ if (view)
4505
+ flattened.push({ view, original });
4500
4506
  if (item.marked?.includes(name))
4501
- markedPaths.push(attachmentPath);
4507
+ markedPaths.push(listed);
4502
4508
  }
4503
4509
  refs.push(...item.refs);
4504
4510
  }
4505
- return { texts, attachmentPaths, markedPaths, refs: uniqueLocators(refs) };
4511
+ return { texts, attachmentPaths, markedPaths, flattened, refs: uniqueLocators(refs) };
4506
4512
  }
4507
4513
  // Drain the queue into the log as real user messages and start one follow-up
4508
4514
  // turn addressing them all (a burst batches into a single turn). A pending
@@ -4524,7 +4530,7 @@ function maybeStartRouterQueueTurn(ctx) {
4524
4530
  for (const send of drained)
4525
4531
  if (!send.hideFromUi)
4526
4532
  ctx.taskStore.releaseHeld(send.text);
4527
- const { texts, attachmentPaths, markedPaths, refs } = commitDrainedSends(drained, ctx.log);
4533
+ const { texts, attachmentPaths, markedPaths, flattened, refs } = commitDrainedSends(drained, ctx.log);
4528
4534
  // The queue is now committed to messages.json; clear its durable mirror.
4529
4535
  persistPendingSends(ctx);
4530
4536
  const draft = state.pendingInterruptedDraft;
@@ -4536,6 +4542,7 @@ function maybeStartRouterQueueTurn(ctx) {
4536
4542
  interruptedDraft: draft || undefined,
4537
4543
  attachments: attachmentPaths,
4538
4544
  marked: markedPaths,
4545
+ flattened,
4539
4546
  refs,
4540
4547
  }));
4541
4548
  }
@@ -4615,12 +4622,13 @@ function handleQueueUserMessage(ctx, text, images, refs, clientId, hideFromUi) {
4615
4622
  return;
4616
4623
  }
4617
4624
  const id = sentId ?? nanoid(8);
4618
- const { saved: attachments, marked } = saveAttachments(ctx.attachmentsDir, id, images);
4625
+ const { saved: attachments, marked, viewed } = saveAttachments(ctx.attachmentsDir, id, images);
4619
4626
  state.pendingSends.push({
4620
4627
  id,
4621
4628
  text,
4622
4629
  attachments,
4623
4630
  ...(marked.length > 0 ? { marked } : {}),
4631
+ ...(viewed.length > 0 ? { viewed } : {}),
4624
4632
  refs: validMessageRefs(ctx.deckDir, refs),
4625
4633
  ...(hideFromUi ? { hideFromUi: true } : {}),
4626
4634
  });
package/dist/api.d.ts CHANGED
@@ -176,6 +176,9 @@ export interface DeckMeta {
176
176
  creator: {
177
177
  username: string;
178
178
  } | null;
179
+ initialCard: {
180
+ type: string | null;
181
+ } | null;
179
182
  }
180
183
  export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
181
184
  export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
package/dist/api.js CHANGED
@@ -273,12 +273,12 @@ export async function saveCauldronServerBundle(deckId, uploadId, serverConfig) {
273
273
  handleAPIError(data);
274
274
  return pickData(data, 'saveCauldronServerBundle');
275
275
  }
276
- // Title + author, for naming an import. Readable without auth for the same decks
277
- // webDeckSource is (unlisted ones), so this works in a sandbox with no login.
276
+ // Metadata for naming an import and distinguishing classic decks. Readable
277
+ // without auth for the same decks webDeckSource is, including unlisted ones.
278
278
  export async function deckMeta(deckId) {
279
279
  const data = await graphql(`query($deckId: ID!) {
280
280
  deck(deckId: $deckId) {
281
- deckId title creator { username }
281
+ deckId title creator { username } initialCard { type }
282
282
  }
283
283
  }`, { deckId });
284
284
  return data?.data?.deck ?? null;
package/dist/get-deck.js CHANGED
@@ -110,7 +110,10 @@ export async function getDeck(dir, options = {}) {
110
110
  }
111
111
  }
112
112
  fs.mkdirSync(targetDir, { recursive: true });
113
- await runTar(['-xzf', tmpFile, '-C', targetDir]);
113
+ // --no-same-owner: an archive saved on a laptop records the laptop's uid, and tar
114
+ // run as root (a cloud sandbox) keeps it; git then refuses the deck as "dubious
115
+ // ownership" and the cloud git attach fails. Same for every unpack of a deck archive.
116
+ await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', targetDir]);
114
117
  }
115
118
  finally {
116
119
  try {
@@ -247,7 +250,7 @@ async function getDeckSide(dir, options) {
247
250
  const staging = path.join(root, `.partial-${nanoid(8)}`);
248
251
  try {
249
252
  fs.mkdirSync(staging, { recursive: true });
250
- await runTar(['-xzf', tmpFile, '-C', staging]);
253
+ await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', staging]);
251
254
  fs.rmSync(dest, { recursive: true, force: true });
252
255
  fs.renameSync(staging, dest);
253
256
  }
@@ -18,7 +18,7 @@ import * as api from './api.js';
18
18
  import * as config from './config.js';
19
19
  import { runTar } from './save-deck.js';
20
20
  import { readCastleJson } from './castleJson.js';
21
- import { ImportError, addImportTo, importedDeckIds, parseDeckRef } from './imports.js';
21
+ import { ImportError, addImportTo, importedDeckIds, resolveDeckRef as resolveImportDeckRef, } from './imports.js';
22
22
  import { errorMessage, readRequestBody, sendJson } from './httpJson.js';
23
23
  export const IMPORT_API_PREFIX = '/__castle/import/';
24
24
  // Rows per list, and how many decks we are willing to ask the source question
@@ -136,13 +136,10 @@ export async function listImportable(deckDir, tab) {
136
136
  // NOT hide a deck with no source -- naming a specific deck and getting nothing
137
137
  // back says less than naming it and being told it was never saved.
138
138
  export async function resolveDeckRef(deckDir, ref) {
139
- const deckId = parseDeckRef(ref);
139
+ const deckId = await resolveImportDeckRef(ref);
140
140
  if (!deckId) {
141
141
  throw new ImportError('bad-deck-ref', `Not a deck id or a castle deck link: ${ref}`);
142
142
  }
143
- if (readCastleJson(deckDir)?.deckId === deckId) {
144
- throw new ImportError('self-import', `That is this deck -- a deck can't import itself.`);
145
- }
146
143
  const [rows, source] = await Promise.all([
147
144
  api.deckRows([deckId]),
148
145
  api.webDeckSource(deckId).catch(() => null),
@@ -150,7 +147,11 @@ export async function resolveDeckRef(deckDir, ref) {
150
147
  const row = rows[0];
151
148
  if (!row)
152
149
  throw new ImportError('bad-deck-ref', `No deck ${deckId} on the server.`);
153
- return stampImported(deckDir, [toCandidate(row, source !== null)])[0];
150
+ if (readCastleJson(deckDir)?.deckId === row.deckId) {
151
+ throw new ImportError('self-import', `That is this deck -- a deck can't import itself.`);
152
+ }
153
+ const canonicalSource = source ?? (row.deckId !== deckId ? await api.webDeckSource(row.deckId).catch(() => null) : null);
154
+ return stampImported(deckDir, [toCandidate(row, canonicalSource !== null)])[0];
154
155
  }
155
156
  // How many files a deck's source holds. Not on any list query, so it is counted
156
157
  // from the archive itself -- which means downloading it, which is why the picker
package/dist/imports.d.ts CHANGED
@@ -6,12 +6,13 @@ export interface ImportVersion {
6
6
  }
7
7
  export declare function writeImportVersion(importDir: string, value: ImportVersion): void;
8
8
  export declare function readImportVersion(deckDir: string, alias: string): ImportVersion | null;
9
- export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'no-such-dir' | 'self-import' | 'no-source' | 'bad-alias' | 'already-imported';
9
+ export type ImportErrorCode = 'no-deck-ref' | 'bad-deck-ref' | 'not-a-deck-link' | 'link-unreachable' | 'no-such-dir' | 'self-import' | 'classic-deck' | 'no-source' | 'bad-alias' | 'already-imported';
10
10
  export declare class ImportError extends Error {
11
11
  code: ImportErrorCode;
12
12
  constructor(code: ImportErrorCode, message: string);
13
13
  }
14
14
  export declare function parseDeckRef(raw: string): string | null;
15
+ export declare function resolveDeckRef(raw: string): Promise<string | null>;
15
16
  export declare function lockImportTree(dir: string): void;
16
17
  export declare function syncImportDependencies(deckDir: string): string[];
17
18
  export declare function restoreMissingImports(deckDir: string): Promise<string[]>;
package/dist/imports.js CHANGED
@@ -61,11 +61,8 @@ export class ImportError extends Error {
61
61
  this.code = code;
62
62
  }
63
63
  }
64
- // What someone has in hand is a deck id or the URL of the page they were just
65
- // looking at, so both are accepted here rather than in a separate resolve step.
66
- // Recognized: a bare id, a deck page (`castle.xyz/d/<id>`), and the cloud editor
67
- // (`castle.xyz/admin/cloud/<id>`) -- for anything else the last path segment is
68
- // tried, since every castle deck URL ends in the id.
64
+ // Share links (s.castle.xyz) go through resolveDeckRef instead: their last
65
+ // segment is a short-link id, not a deck id.
69
66
  export function parseDeckRef(raw) {
70
67
  const trimmed = raw.trim();
71
68
  if (!trimmed)
@@ -79,11 +76,69 @@ export function parseDeckRef(raw) {
79
76
  catch {
80
77
  return null;
81
78
  }
79
+ if (url.hostname.toLowerCase() === 's.castle.xyz')
80
+ return null;
82
81
  const segments = url.pathname.split('/').filter(Boolean);
83
82
  const afterD = segments.indexOf('d');
84
83
  const candidate = afterD >= 0 ? segments[afterD + 1] : segments[segments.length - 1];
85
84
  return candidate && api.isDeckIdShaped(candidate) ? candidate : null;
86
85
  }
86
+ function castleDeckPageId(raw, base) {
87
+ let url;
88
+ try {
89
+ url = base ? new URL(raw, base) : new URL(raw);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ const hostname = url.hostname.toLowerCase();
95
+ if (hostname !== 'castle.xyz' && hostname !== 'www.castle.xyz')
96
+ return null;
97
+ const segments = url.pathname.split('/').filter(Boolean);
98
+ const candidate = segments[0] === 'd' ? segments[1] : null;
99
+ return candidate && api.isDeckIdShaped(candidate) ? candidate : null;
100
+ }
101
+ function notADeckLink() {
102
+ return new ImportError('not-a-deck-link', "That share link doesn't lead to a Castle deck. Pass a deck id or a castle.xyz/d/<id> deck link.");
103
+ }
104
+ export async function resolveDeckRef(raw) {
105
+ const trimmed = raw.trim();
106
+ let url = null;
107
+ if (trimmed.includes('/')) {
108
+ try {
109
+ url = new URL(trimmed.includes('://') ? trimmed : `https://${trimmed}`);
110
+ }
111
+ catch {
112
+ url = null;
113
+ }
114
+ }
115
+ if (url?.hostname.toLowerCase() !== 's.castle.xyz')
116
+ return parseDeckRef(trimmed);
117
+ if (url.pathname === '/redirect') {
118
+ const app = url.searchParams.get('app');
119
+ const deckId = app ? castleDeckPageId(app, 'https://castle.xyz') : null;
120
+ if (!deckId)
121
+ throw notADeckLink();
122
+ return deckId;
123
+ }
124
+ let response;
125
+ try {
126
+ response = await fetch(url.href, {
127
+ redirect: 'manual',
128
+ signal: AbortSignal.timeout(15000),
129
+ });
130
+ }
131
+ catch {
132
+ throw new ImportError('link-unreachable', `Could not open the share link ${trimmed} to find its deck. Pass the deck's castle.xyz/d/<id> link instead.`);
133
+ }
134
+ if (response.status < 300 || response.status >= 400)
135
+ throw notADeckLink();
136
+ const location = response.headers.get('location');
137
+ const deckId = location ? castleDeckPageId(location, url.href) : null;
138
+ if (!deckId)
139
+ throw notADeckLink();
140
+ return deckId;
141
+ }
87
142
  // Only the `imports` key is ours; everything else in castle.json (deck identity,
88
143
  // editor config) is preserved as-is.
89
144
  function writeImportPin(dir, alias, pin) {
@@ -343,7 +398,7 @@ async function fetchDeckSourceInto(archiveUrl, destDir) {
343
398
  if (!res.ok)
344
399
  throw new Error(`Archive fetch failed: HTTP ${res.status}`);
345
400
  fs.writeFileSync(tmpFile, Buffer.from(await res.arrayBuffer()));
346
- await runTar(['-xzf', tmpFile, '-C', tmpDir]);
401
+ await runTar(['-xzf', tmpFile, '--no-same-owner', '-C', tmpDir]);
347
402
  // The new copy is whole; only now is it safe to drop the old one.
348
403
  if (fs.existsSync(destDir)) {
349
404
  unlockImportTree(destDir);
@@ -527,12 +582,25 @@ async function placeFetchedImport(targetDir, deckId, givenAlias) {
527
582
  if (readCastleJson(targetDir)?.deckId === deckId) {
528
583
  throw new ImportError('self-import', `Deck ${deckId} is this deck -- a deck can't import itself.`);
529
584
  }
530
- const [source, meta] = await Promise.all([
585
+ const [initialSource, meta] = await Promise.all([
531
586
  api.webDeckSource(deckId),
532
587
  api.deckMeta(deckId).catch(() => null),
533
588
  ]);
589
+ const canonicalDeckId = meta?.deckId ?? deckId;
590
+ if (readCastleJson(targetDir)?.deckId === canonicalDeckId) {
591
+ throw new ImportError('self-import', `Deck ${canonicalDeckId} is this deck -- a deck can't import itself.`);
592
+ }
593
+ const source = !initialSource && canonicalDeckId !== deckId
594
+ ? await api.webDeckSource(canonicalDeckId)
595
+ : initialSource;
534
596
  if (!source) {
535
- throw new ImportError('no-source', `No source archive on the server for deck ${deckId}. ` +
597
+ if (meta && meta.initialCard?.type !== 'experimentalWeb') {
598
+ const title = meta.title?.trim();
599
+ const subject = title ? `"${title}"` : `Deck ${canonicalDeckId}`;
600
+ throw new ImportError('classic-deck', `${subject} is a classic Castle deck, made in the Castle app's editor. ` +
601
+ `Only web decks built with castle-web can be imported; a classic deck's scenes can't be.`);
602
+ }
603
+ throw new ImportError('no-source', `No source archive on the server for deck ${canonicalDeckId}. ` +
536
604
  'Its owner needs to run `castle-web save-deck` before it can be imported.');
537
605
  }
538
606
  const given = givenAlias ? slugifyGivenAlias(givenAlias) : '';
@@ -541,10 +609,11 @@ async function placeFetchedImport(targetDir, deckId, givenAlias) {
541
609
  }
542
610
  // An explicit `--as` is the caller's call, collision and all. A derived one
543
611
  // gets a number instead, since nothing asked for that particular name.
544
- const alias = given || availableAlias(targetDir, qualifiedAlias(meta, deckId), deckId);
545
- const { replaced } = await placeImport(targetDir, alias, deckId, source);
612
+ const alias = given ||
613
+ availableAlias(targetDir, qualifiedAlias(meta, canonicalDeckId), canonicalDeckId);
614
+ const { replaced } = await placeImport(targetDir, alias, canonicalDeckId, source);
546
615
  const transitive = await addTransitiveImports(targetDir, alias, importedDeckIds(targetDir));
547
- return { deckId, alias, replaced, transitive };
616
+ return { deckId: canonicalDeckId, alias, replaced, transitive };
548
617
  }
549
618
  // The import itself. Throws ImportError rather than exiting, because this also
550
619
  // runs inside the serve (from the editor's Import panel), where taking the
@@ -558,10 +627,10 @@ export async function addImportTo(dir, options = {}) {
558
627
  if (!fs.existsSync(targetDir)) {
559
628
  throw new ImportError('no-such-dir', `No such directory: ${targetDir}`);
560
629
  }
561
- // Before parseDeckRef: a kit's name is id-shaped, so the other order would
630
+ // Before resolveDeckRef: a kit's name is id-shaped, so the other order would
562
631
  // send `physics-2d` to the server as a deck id.
563
632
  const kit = shippedFrameworkKit(ref);
564
- const deckId = kit ? null : parseDeckRef(ref);
633
+ const deckId = kit ? null : await resolveDeckRef(ref);
565
634
  let placed;
566
635
  if (kit) {
567
636
  placed = await placeShippedKit(targetDir, kit, options.alias);
package/dist/init.js CHANGED
@@ -19,10 +19,13 @@ const DEFAULT_KIT = 'physics-2d';
19
19
  // A framework kit imports it too, so a kit deck has it as well.
20
20
  export const BASE_KIT = 'base';
21
21
  export const BASE_ALIAS = shippedKitAlias(BASE_KIT);
22
+ // A bare deck lays itself out, so it starts as a fill deck (platformDoc.ts,
23
+ // "Fit the stage"); a kit deck's entry is the kit's, and follows its guide.
22
24
  const INDEX_HTML = `<!DOCTYPE html>
23
25
  <html>
24
26
  <head>
25
27
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
28
+ <meta name="castle-display" content="layout=fill">
26
29
  <title>My Castle Game</title>
27
30
  </head>
28
31
  <body>
@@ -40,7 +43,7 @@ function startGame(card) {
40
43
  el.style.cssText = \`
41
44
  width: 100%; height: 100%;
42
45
  display: flex; align-items: center; justify-content: center;
43
- font-family: system-ui; color: #fff; font-size: 24px;
46
+ font-family: system-ui; color: #fff; font-size: calc(6 * var(--castle-unit));
44
47
  \`;
45
48
  el.textContent = 'Hello Castle!';
46
49
  card.appendChild(el);
@@ -51,10 +54,19 @@ function startGame(card) {
51
54
  // takes the false branch on the first line and loads none of it.
52
55
  if (!(await mountEditorRoute())) startGame(initCard());
53
56
  `;
57
+ // Every bare scaffold `init` has written, so isPristineBareDeck still knows an
58
+ // untouched deck made before the scaffold became a fill deck.
59
+ const BARE_SCAFFOLDS = [
60
+ { html: INDEX_HTML, js: GAME_JS },
61
+ {
62
+ html: INDEX_HTML.replace(' <meta name="castle-display" content="layout=fill">\n', ''),
63
+ js: GAME_JS.replace('calc(6 * var(--castle-unit))', '24px'),
64
+ },
65
+ ];
54
66
  // Registry version of castle-web-sdk to inject when scaffolding from a
55
67
  // globally-installed castle-web (not from inside the workspace). Bumped
56
68
  // alongside cli/sdk version bumps.
57
- const PUBLISHED_SDK_VERSION = '0.4.43';
69
+ const PUBLISHED_SDK_VERSION = '0.4.44';
58
70
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
59
71
  // face can ship without a cli release, and a caret range means an existing
60
72
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -180,8 +192,9 @@ export function ensureAgentsSymlink(projectDir) {
180
192
  // has actually worked in is never quietly taken over.
181
193
  export function isPristineBareDeck(dir) {
182
194
  try {
183
- return (fs.readFileSync(path.join(dir, 'index.html'), 'utf8') === INDEX_HTML &&
184
- fs.readFileSync(path.join(dir, 'game.js'), 'utf8') === GAME_JS);
195
+ const html = fs.readFileSync(path.join(dir, 'index.html'), 'utf8');
196
+ const js = fs.readFileSync(path.join(dir, 'game.js'), 'utf8');
197
+ return BARE_SCAFFOLDS.some((stub) => stub.html === html && stub.js === js);
185
198
  }
186
199
  catch {
187
200
  return false;
@@ -3,6 +3,7 @@ export declare const PLATFORM_DOC_REL: string;
3
3
  export declare const MULTIPLAYER_DOC_REL: string;
4
4
  export declare function everyDeckBullets(deckDir: string): string[];
5
5
  export declare const HOST_LIMIT_BULLETS: string[];
6
+ export declare const CASTLE_UI_BULLETS: string[];
6
7
  export type AgentRole = 'router' | 'task';
7
8
  export declare function roleLoadsClaudeMd(role: AgentRole): boolean;
8
9
  export declare function claudeContextEnv(role: AgentRole): NodeJS.ProcessEnv;