castle-web-cli 0.4.213 → 0.4.215

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { listVersions, restoreVersion, saveVersion, showVersion } from './versio
17
17
  import { getKitsDir } from './localPaths.js';
18
18
  import * as api from './api.js';
19
19
  import * as config from './config.js';
20
+ import { CloudGitError } from './cloudGit.js';
20
21
  const args = process.argv.slice(2);
21
22
  const command = args[0];
22
23
  const FLAGS_WITH_VALUES = new Set([
@@ -33,6 +34,8 @@ const FLAGS_WITH_VALUES = new Set([
33
34
  '--dir',
34
35
  '--message',
35
36
  '-m',
37
+ '--reason',
38
+ '--remote',
36
39
  ]);
37
40
  // `--foo` is always a flag; a single dash only when it is one we know (`-m`).
38
41
  // Anything else starting with `-` is a positional -- a path can begin with one,
@@ -167,6 +170,9 @@ function usage() {
167
170
  castle-web restore-version <version> [--force] [--dir DIR]
168
171
  castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
169
172
  castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
173
+ castle-web git attach <dir> --remote <url> (cloud sandbox only: makes the deck a clone of its Castle repo)
174
+ castle-web git sync [--dir DIR] (cloud sandbox only: commit, merge the remote's main, push)
175
+ castle-web commit [-m MESSAGE] [--reason turn|task|leave|manual|sync] [--resolve] [paths...] [--dir DIR] (cloud sandbox only)
170
176
  castle-web login
171
177
  castle-web whoami
172
178
  castle-web --version
@@ -228,8 +234,15 @@ async function gitCommand() {
228
234
  process.stdout.write(answer.stdout);
229
235
  return;
230
236
  }
231
- if (sub !== 'init')
237
+ if (sub === 'attach' || sub === 'sync') {
238
+ await cloudGitCommand(sub);
239
+ return;
240
+ }
241
+ if (sub !== 'init') {
242
+ if (sub)
243
+ console.error(`Unknown command: git ${sub}`);
232
244
  usage();
245
+ }
233
246
  const initArgs = parseGitInitArgs();
234
247
  await gitRemote.gitInit(initArgs.dir, { environment: initArgs.staging ? 'staging' : 'production' }, {
235
248
  token: config.getToken(),
@@ -243,6 +256,131 @@ async function gitCommand() {
243
256
  warn: (message) => console.error(message),
244
257
  });
245
258
  }
259
+ // Strict parsing for the cloud git commands, which other programs call: an unknown flag or
260
+ // a flag missing its value is an error rather than a path.
261
+ function parseCloudArgs(from, valueFlags, booleanFlags = []) {
262
+ const flags = new Map();
263
+ const positionals = [];
264
+ let onlyPositionals = false;
265
+ for (let i = from; i < args.length; i++) {
266
+ const arg = args[i];
267
+ if (onlyPositionals) {
268
+ positionals.push(arg);
269
+ }
270
+ else if (arg === '--') {
271
+ onlyPositionals = true;
272
+ }
273
+ else if (valueFlags.includes(arg)) {
274
+ const value = args[++i];
275
+ if (value === undefined)
276
+ throw new Error(`${arg} needs a value.`);
277
+ flags.set(arg, value);
278
+ }
279
+ else if (booleanFlags.includes(arg)) {
280
+ flags.set(arg, 'true');
281
+ }
282
+ else if (arg.startsWith('-')) {
283
+ throw new Error(`Unknown option: ${arg}`);
284
+ }
285
+ else {
286
+ positionals.push(arg);
287
+ }
288
+ }
289
+ return { flags, positionals };
290
+ }
291
+ async function cloudGitDeps() {
292
+ const cloudGit = await import('./cloudGit.js');
293
+ return { cloudGit, deps: cloudGit.defaultCloudGitDeps(() => api.whoAmI()) };
294
+ }
295
+ function reportSync(sync, syncError) {
296
+ if (syncError)
297
+ console.error(`Not pushed yet (the next sync retries): ${syncError}`);
298
+ if (!sync)
299
+ return;
300
+ if (sync.merge === 'conflict') {
301
+ console.error('Merging the Castle remote left conflicts; the agent has been asked to resolve them.');
302
+ process.exitCode = 3;
303
+ return;
304
+ }
305
+ if (sync.merge === 'deferred') {
306
+ console.log(`${sync.pushed ? 'Pushed main. ' : ''}The remote has changes that are merged once the deck is idle.`);
307
+ return;
308
+ }
309
+ const merged = { none: '', 'fast-forward': 'Took changes from the remote. ', merged: 'Merged changes from the remote. ', seeded: '' }[sync.merge];
310
+ console.log(`${merged}${sync.pushed ? 'Pushed main.' : 'Up to date with the remote.'}`);
311
+ }
312
+ // `castle-web git attach <dir> --remote <url>` and `castle-web git sync [dir] [--dir DIR]`.
313
+ async function cloudGitCommand(sub) {
314
+ const { cloudGit, deps } = await cloudGitDeps();
315
+ const { flags, positionals } = parseCloudArgs(2, ['--remote', '--dir']);
316
+ if (sub === 'attach') {
317
+ const remote = flags.get('--remote');
318
+ const dir = positionals[0] ?? flags.get('--dir');
319
+ if (!remote || !dir || positionals.length > 1) {
320
+ throw new Error('Usage: castle-web git attach <dir> --remote <url>');
321
+ }
322
+ const outcome = await cloudGit.cloudAttach(dir, remote, deps);
323
+ console.log(`Attached ${path.resolve(dir)} to ${remote} (${outcome.repo} repo, ${outcome.outcome}).`);
324
+ if (outcome.backup)
325
+ console.log(`The cloud copy's differing files are saved in ${outcome.backup}.`);
326
+ reportSync(outcome.sync ?? null);
327
+ return;
328
+ }
329
+ if (positionals.length > 1)
330
+ throw new Error('Usage: castle-web git sync [dir] [--dir DIR]');
331
+ reportSync(await cloudGit.cloudSync(positionals[0] ?? flags.get('--dir') ?? '.', deps));
332
+ }
333
+ // `castle-web commit [-m MESSAGE] [--reason REASON] [--resolve] [paths...] [--dir DIR]`.
334
+ // --resolve concludes a conflicted merge (an agent's commit unless --reason says otherwise).
335
+ async function commitCommand() {
336
+ const { cloudGit, deps } = await cloudGitDeps();
337
+ const { flags, positionals } = parseCloudArgs(1, ['-m', '--message', '--reason', '--dir'], ['--resolve']);
338
+ const resolve = flags.has('--resolve');
339
+ const reason = flags.get('--reason') ?? (resolve ? 'task' : 'manual');
340
+ if (!cloudGit.COMMIT_REASONS.includes(reason)) {
341
+ throw new Error(`--reason must be one of ${cloudGit.COMMIT_REASONS.join(', ')}.`);
342
+ }
343
+ const outcome = await cloudGit.cloudCommit(flags.get('--dir') ?? '.', {
344
+ message: flags.get('-m') ?? flags.get('--message'),
345
+ reason: reason,
346
+ paths: positionals,
347
+ resolve,
348
+ }, deps);
349
+ console.log(outcome.sha ? `Committed ${outcome.sha}` : 'Nothing to commit.');
350
+ reportSync(outcome.sync, outcome.syncError);
351
+ }
352
+ // The version commands with git on (the serve's gate env plus an attached deck): a version
353
+ // is a commit, and the old store stops growing. A version id the old store has still goes
354
+ // there, so older versions stay readable. False when the command is the old store's.
355
+ const VERSION_COMMANDS = new Set(['save-version', 'list-versions', 'show-version', 'restore-version']);
356
+ async function gitVersionCommand(name) {
357
+ const dir = path.resolve(getFlagValue('--dir') ?? '.');
358
+ const target = readPositionals()[0];
359
+ const cloudGit = await import('./cloudGit.js');
360
+ if (!cloudGit.cloudGitMode(dir))
361
+ return false;
362
+ const store = await import('./versionStore.js');
363
+ if (target && name !== 'save-version' && store.versionExists(dir, target))
364
+ return false;
365
+ if (name === 'save-version') {
366
+ await commitCommand();
367
+ }
368
+ else if (name === 'list-versions') {
369
+ cloudGit.printGitLog(dir, target);
370
+ }
371
+ else if (name === 'show-version' && target) {
372
+ cloudGit.printGitShow(dir, target);
373
+ }
374
+ else if (name === 'restore-version' && target) {
375
+ const outcome = await cloudGit.cloudRestore(dir, target, cloudGit.defaultCloudGitDeps(() => api.whoAmI()));
376
+ console.log(outcome.sha ? `Restored ${target} as commit ${outcome.sha}` : `Already at ${target}.`);
377
+ reportSync(outcome.sync, outcome.syncError);
378
+ }
379
+ else {
380
+ return false;
381
+ }
382
+ return true;
383
+ }
246
384
  async function main() {
247
385
  // Before the switch: `--version` is a flag, not a command, and it has to work
248
386
  // when there is no command at all. Which version is installed is the first
@@ -251,6 +389,8 @@ async function main() {
251
389
  console.log(getCliVersion());
252
390
  return;
253
391
  }
392
+ if (VERSION_COMMANDS.has(command) && (await gitVersionCommand(command)))
393
+ return;
254
394
  switch (command) {
255
395
  case 'init': {
256
396
  const dir = findPositionalDir();
@@ -355,6 +495,9 @@ async function main() {
355
495
  // The version commands spend their positionals on their own arguments --
356
496
  // paths to save, a version to list from or restore to -- so the deck dir is
357
497
  // `--dir`, defaulting to the cwd.
498
+ case 'commit':
499
+ await commitCommand();
500
+ break;
358
501
  case 'save-version': {
359
502
  saveVersion(getFlagValue('--dir') ?? '.', {
360
503
  message: getFlagValue('-m') ?? getFlagValue('--message'),
@@ -437,10 +580,14 @@ async function main() {
437
580
  break;
438
581
  }
439
582
  default:
583
+ if (command)
584
+ console.error(`Unknown command: ${command}`);
440
585
  usage();
441
586
  }
442
587
  }
443
588
  main().catch((e) => {
444
589
  console.error(e instanceof Error ? e.message : String(e));
445
- process.exit(1);
590
+ // Only the cloud git commands' own errors carry an exit code (2: not enabled here, 3: a
591
+ // merge waiting on the agent); anything else is a plain failure.
592
+ process.exit(e instanceof CloudGitError ? e.exitCode : 1);
446
593
  });
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.36';
57
+ const PUBLISHED_SDK_VERSION = '0.4.39';
58
58
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
59
59
  // face can ship without a cli release, and a caret range means an existing
60
60
  // deck's next install picks it up. Nothing here has to move when it does.
package/dist/install.js CHANGED
@@ -4,9 +4,11 @@ import * as path from 'path';
4
4
  import { restoreMissingImports, syncImportDependencies } from './imports.js';
5
5
  import { normalizeDeckPackageJson } from './normalize.js';
6
6
  import { writePlatformDocs } from './platformDoc.js';
7
- function hasPnpm() {
7
+ // Probed in the deck, where the install itself runs: Corepack's pnpm shim refuses
8
+ // a directory whose package.json pins another package manager.
9
+ function hasPnpm(cwd) {
8
10
  try {
9
- execSync('pnpm --version', { stdio: 'ignore' });
11
+ execSync('pnpm --version', { cwd, stdio: 'ignore' });
10
12
  return true;
11
13
  }
12
14
  catch {
@@ -31,28 +33,31 @@ function run(command, cwd) {
31
33
  // scripts (pnpm 10+ gates them and exits non-zero otherwise, and the deck's deps are
32
34
  // all prebuilt pure JS that don't need them). `frozen` installs straight from the
33
35
  // shipped lockfile (skips resolution -> no network, fast + deterministic).
36
+ //
37
+ // pnpm is tried first and only probed once it has failed: an up-front
38
+ // `pnpm --version` is a whole pnpm start (~0.4 s), paid on every cold sandbox open
39
+ // for an answer that is almost always yes.
34
40
  export async function installDeps(projectDir, frozen) {
35
- if (hasPnpm()) {
36
- console.log('Installing deps (pnpm)...');
37
- const frozenFlag = frozen ? '--frozen-lockfile ' : '';
38
- try {
39
- await run(`pnpm install ${frozenFlag}--prefer-offline --ignore-scripts`, projectDir);
40
- }
41
- catch (err) {
42
- if (!frozen)
43
- throw err;
44
- // A frozen install hard-fails when the lockfile has drifted from
45
- // package.json (e.g. the sdk version bumped but the kit's pnpm-lock.yaml
46
- // wasn't regenerated). Rather than leave the deck with no node_modules,
47
- // retry with resolution allowed -- a little slower (re-resolves + may
48
- // fetch), but self-heals the drift instead of breaking.
49
- console.warn('Frozen install failed; retrying with resolution (lockfile drift?)...');
50
- await run('pnpm install --prefer-offline --ignore-scripts', projectDir);
51
- }
41
+ console.log('Installing deps (pnpm)...');
42
+ const frozenFlag = frozen ? '--frozen-lockfile ' : '';
43
+ try {
44
+ await run(`pnpm install ${frozenFlag}--prefer-offline --ignore-scripts`, projectDir);
52
45
  }
53
- else {
54
- console.log('Installing deps (npm)...');
55
- await run('npm install --no-audit --no-fund --loglevel=error', projectDir);
46
+ catch (err) {
47
+ if (!hasPnpm(projectDir)) {
48
+ console.log('pnpm is not available; installing deps (npm)...');
49
+ await run('npm install --no-audit --no-fund --loglevel=error', projectDir);
50
+ return;
51
+ }
52
+ if (!frozen)
53
+ throw err;
54
+ // A frozen install hard-fails when the lockfile has drifted from
55
+ // package.json (e.g. the sdk version bumped but the kit's pnpm-lock.yaml
56
+ // wasn't regenerated). Rather than leave the deck with no node_modules,
57
+ // retry with resolution allowed -- a little slower (re-resolves + may
58
+ // fetch), but self-heals the drift instead of breaking.
59
+ console.warn('Frozen install failed; retrying with resolution (lockfile drift?)...');
60
+ await run('pnpm install --prefer-offline --ignore-scripts', projectDir);
56
61
  }
57
62
  }
58
63
  // `castle-web install <dir>`: put node_modules in place for a deck that already has
@@ -9,6 +9,7 @@ export interface BoardTask {
9
9
  title: string;
10
10
  createdAt: string;
11
11
  }
12
+ export declare function stripTaskFencePlaceholder(prompt: string): string;
12
13
  export declare function parseTaskFenceBody(body: string): TaskDirective | null;
13
14
  export declare function taskFenceRegex(): RegExp;
14
15
  export declare function extractDirectives(full: string): {
@@ -16,7 +17,12 @@ export declare function extractDirectives(full: string): {
16
17
  directives: TaskDirective[];
17
18
  checkoffs: string[];
18
19
  stops: string[];
20
+ prefs: string[];
19
21
  plan?: string;
20
22
  };
23
+ export declare function closedPrefLines(raw: string): string[];
24
+ export declare function parsePrefLines(lines: string[]): {
25
+ playtest?: 'on' | 'off';
26
+ };
21
27
  export declare function meansAll(lines: string[]): boolean;
22
28
  export declare function resolveTargets<T extends BoardTask>(tasks: Map<string, T>, lines: string[]): string[];
@@ -1,3 +1,46 @@
1
+ import { TASK_FENCE_PROMPT_EXAMPLE } from './agent-prompts.js';
2
+ function escapeFlexible(text) {
3
+ return text
4
+ .split(/\s+/)
5
+ .map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
6
+ .join('\\s+');
7
+ }
8
+ function taskFencePlaceholderPatterns() {
9
+ const example = TASK_FENCE_PROMPT_EXAMPLE.replace(/\s+/g, ' ').trim();
10
+ const sentences = (example.match(/[^.]+\./g) ?? []).map((sentence) => sentence.trim());
11
+ if (sentences.length !== 2)
12
+ return { leading: /(?!)/, docs: /(?!)/ };
13
+ const firstSentence = sentences[0];
14
+ const colonAt = firstSentence.indexOf(': ');
15
+ const dashAt = firstSentence.indexOf(' -- ');
16
+ const asideAt = firstSentence.indexOf(' (', dashAt + 4);
17
+ if (colonAt < 0 || dashAt < 0 || asideAt < 0)
18
+ return { leading: /(?!)/, docs: /(?!)/ };
19
+ const lead = firstSentence.slice(0, dashAt).replace(/^Then\s+a\s+/, '');
20
+ const dash = firstSentence.slice(dashAt + 1, dashAt + 3);
21
+ const shape = firstSentence.slice(dashAt + 4, asideAt);
22
+ const aside = firstSentence.slice(asideAt + 1, colonAt);
23
+ const colon = firstSentence.slice(colonAt, colonAt + 1);
24
+ const content = firstSentence.slice(colonAt + 2);
25
+ const optional = (part) => `(?:\\s*${escapeFlexible(part)})?`;
26
+ const leading = new RegExp(`^(?:Then\\s+)?(?:[aA]\\s+)?${escapeFlexible(lead)}` +
27
+ `(?:\\s*${escapeFlexible(dash)}${optional(shape)}${optional(aside)}${optional(colon)}` +
28
+ `|\\s*${escapeFlexible(colon)})` +
29
+ optional(content));
30
+ return { leading, docs: new RegExp(escapeFlexible(sentences[1]), 'g') };
31
+ }
32
+ const TASK_FENCE_PLACEHOLDER_PATTERNS = taskFencePlaceholderPatterns();
33
+ export function stripTaskFencePlaceholder(prompt) {
34
+ const withoutLead = prompt.replace(TASK_FENCE_PLACEHOLDER_PATTERNS.leading, '');
35
+ const withoutDocs = withoutLead.replace(TASK_FENCE_PLACEHOLDER_PATTERNS.docs, '');
36
+ if (withoutDocs === prompt)
37
+ return prompt;
38
+ return withoutDocs
39
+ .replace(/[ \t]{2,}/g, ' ')
40
+ .replace(/[ \t]+\n/g, '\n')
41
+ .replace(/\n[ \t]+/g, '\n')
42
+ .trim();
43
+ }
1
44
  // Parse one ```castle-task fence's body (title line, optional "after:" and
2
45
  // "item:" lines in either order, then the prompt) into a directive. Shared by
3
46
  // the settle-time full-text extraction below and the mid-stream incremental
@@ -27,7 +70,7 @@ export function parseTaskFenceBody(body) {
27
70
  if (line)
28
71
  after.push(line);
29
72
  }
30
- return { title, after, item, prompt: lines.join('\n').trim() };
73
+ return { title, after, item, prompt: stripTaskFencePlaceholder(lines.join('\n').trim()) };
31
74
  }
32
75
  // A fresh RegExp per call -- this is matched with manual .exec() loops in
33
76
  // TWO independent call sites (settle-time extractDirectives via .replace, and
@@ -56,6 +99,7 @@ export function extractDirectives(full) {
56
99
  const directives = [];
57
100
  const checkoffs = [];
58
101
  const stops = [];
102
+ const prefs = [];
59
103
  const listFence = (source, name, into) => {
60
104
  const re = new RegExp('```' + name + '[ \\t]*\\r?\\n([\\s\\S]*?)```', 'g');
61
105
  return source.replace(re, (_match, body) => {
@@ -68,8 +112,8 @@ export function extractDirectives(full) {
68
112
  });
69
113
  };
70
114
  const { plan, rest } = takePlanFence(full);
71
- const withoutDone = listFence(listFence(rest, 'castle-done', checkoffs), 'castle-stop', stops);
72
- const cleaned = withoutDone.replace(taskFenceRegex(), (_match, body) => {
115
+ const withoutLists = listFence(listFence(listFence(rest, 'castle-done', checkoffs), 'castle-stop', stops), 'castle-pref', prefs);
116
+ const cleaned = withoutLists.replace(taskFenceRegex(), (_match, body) => {
73
117
  const directive = parseTaskFenceBody(String(body));
74
118
  if (directive)
75
119
  directives.push(directive);
@@ -80,9 +124,32 @@ export function extractDirectives(full) {
80
124
  directives,
81
125
  checkoffs,
82
126
  stops,
127
+ prefs,
83
128
  plan,
84
129
  };
85
130
  }
131
+ export function closedPrefLines(raw) {
132
+ if (!raw.includes('```castle-pref'))
133
+ return [];
134
+ const lines = [];
135
+ for (const match of raw.matchAll(/```castle-pref[ \t]*\r?\n([\s\S]*?)```/g)) {
136
+ for (const line of match[1].split('\n')) {
137
+ const trimmed = line.trim();
138
+ if (trimmed)
139
+ lines.push(trimmed);
140
+ }
141
+ }
142
+ return lines;
143
+ }
144
+ export function parsePrefLines(lines) {
145
+ let playtest;
146
+ for (const line of lines) {
147
+ const match = /^\s*playtest\s*:\s*(on|off)\s*$/i.exec(line);
148
+ if (match)
149
+ playtest = match[1].toLowerCase();
150
+ }
151
+ return playtest ? { playtest } : {};
152
+ }
86
153
  // True when a fence names the special token "all" / "*" (clear/stop
87
154
  // everything, no per-task enumeration).
88
155
  export function meansAll(lines) {
@@ -0,0 +1,22 @@
1
+ export declare const STOPPED_NOTE_REPLIES = 3;
2
+ export interface StopNote {
3
+ taskId: string;
4
+ title: string;
5
+ progress: number;
6
+ }
7
+ export interface StopTarget {
8
+ id: string;
9
+ title: string;
10
+ status: string;
11
+ progress?: number;
12
+ }
13
+ export declare function carriesStopNotes(message: {
14
+ stopped?: StopNote[];
15
+ }): boolean;
16
+ export declare function stopNotes(targets: StopTarget[]): StopNote[];
17
+ export declare function recentStops(messages: Array<{
18
+ role: string;
19
+ stopped?: StopNote[];
20
+ }>, limit?: number): Array<StopNote & {
21
+ repliesAgo: number;
22
+ }>;
@@ -0,0 +1,29 @@
1
+ export const STOPPED_NOTE_REPLIES = 3;
2
+ export function carriesStopNotes(message) {
3
+ return Array.isArray(message.stopped) && message.stopped.length > 0;
4
+ }
5
+ const HALTABLE = new Set(['running', 'waiting', 'blocked']);
6
+ export function stopNotes(targets) {
7
+ return targets
8
+ .filter((target) => HALTABLE.has(target.status))
9
+ .map((target) => ({
10
+ taskId: target.id,
11
+ title: target.title,
12
+ progress: target.progress ?? 0,
13
+ }));
14
+ }
15
+ export function recentStops(messages, limit = STOPPED_NOTE_REPLIES) {
16
+ const assistantCount = messages.filter((message) => message.role === 'assistant').length;
17
+ let assistantsSeen = 0;
18
+ const notes = [];
19
+ for (const message of messages) {
20
+ if (message.role !== 'assistant')
21
+ continue;
22
+ assistantsSeen += 1;
23
+ const repliesAgo = 1 + assistantCount - assistantsSeen;
24
+ if (repliesAgo > limit || !message.stopped)
25
+ continue;
26
+ notes.push(...message.stopped.map((note) => ({ ...note, repliesAgo })));
27
+ }
28
+ return notes;
29
+ }
package/dist/save-deck.js CHANGED
@@ -174,6 +174,7 @@ async function publishServerBundle(projectDir, deckId) {
174
174
  tickRate: serverConfig.tickRate,
175
175
  maxPlayers: serverConfig.maxPlayers,
176
176
  voice: { enabled: serverConfig.voiceEnabled },
177
+ ...(serverConfig.destinations ? { destinations: serverConfig.destinations } : {}),
177
178
  });
178
179
  // The server hashes what it actually stored. A mismatch means the bytes that
179
180
  // will run in sessions are not the bytes we bundled.