castle-web-cli 0.4.214 → 0.4.216

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.
@@ -2,7 +2,7 @@ import { spawn } from 'child_process';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import { fileURLToPath } from 'url';
5
- import { AGENT_MARKER_FILES, cloudGitModeAsync, CONFLICT_MARKER_FILE, DEADLINE_ENV, EXIT_CONFLICT, EXIT_NOT_ENABLED, mergeInProgress, readLeavePending, readMergeState, setDeckBusy, } from './cloudGit.js';
5
+ import { AGENT_MARKER_FILES, cloudGitModeAsync, CONFLICT_MARKER_FILE, DEADLINE_ENV, EXIT_CONFLICT, EXIT_NOT_ENABLED, mergeWaiting, readLeavePending, readMergeState, setDeckBusy, } from './cloudGit.js';
6
6
  // The serve's half of git in the cloud sandbox (castle-sandboxes docs/git-remotes-phase2.md):
7
7
  // - `commit --reason turn` when the router settles with the task board idle,
8
8
  // - `commit --reason task` when the task board goes idle,
@@ -125,17 +125,20 @@ export function createServeGitHooks(opts) {
125
125
  let resolverInFlight = false;
126
126
  let lastRaisedAt = Number.NEGATIVE_INFINITY;
127
127
  let lastBusy = null;
128
+ let lastTasksBusy = null;
128
129
  let lastMergeCheckAt = now();
129
130
  function busyNow() {
130
131
  return !opts.boardIdle() || (opts.routerBusy?.() ?? false);
131
132
  }
132
133
  function refreshBusy() {
133
134
  const busy = busyNow();
134
- if (busy === lastBusy)
135
+ const tasks = !opts.boardIdle();
136
+ if (busy === lastBusy && tasks === lastTasksBusy)
135
137
  return;
136
138
  try {
137
- setDeckBusy(opts.deckDir, busy);
139
+ setDeckBusy(opts.deckDir, busy, { tasks });
138
140
  lastBusy = busy;
141
+ lastTasksBusy = tasks;
139
142
  }
140
143
  catch (err) {
141
144
  console.error(`[git] could not update the busy note: ${String(err)}`);
@@ -215,7 +218,7 @@ export function createServeGitHooks(opts) {
215
218
  // A commit was refused because a merge still waits, and no resolver is working on it: ask
216
219
  // again, at most every REASK_MS, so a merge an earlier turn left unresolved is not stuck.
217
220
  function reraiseUnresolvedMerge() {
218
- if (resolverInFlight || now() - lastRaisedAt < REASK_MS || !mergeInProgress(opts.deckDir))
221
+ if (resolverInFlight || now() - lastRaisedAt < REASK_MS || !mergeWaiting(opts.deckDir))
219
222
  return;
220
223
  const state = readMergeState(opts.deckDir);
221
224
  const leave = readLeavePending(opts.deckDir);
@@ -36,6 +36,7 @@ export declare function isOnPath(name: string, env?: NodeJS.ProcessEnv, platform
36
36
  export declare function runGit(args: string[], cwd: string, opts?: {
37
37
  env?: NodeJS.ProcessEnv;
38
38
  timeoutMs?: number;
39
+ input?: string;
39
40
  }): GitResult;
40
41
  export declare function cloudKitFor(castleJson: Record<string, unknown> | null): CloudDeckKit;
41
42
  export declare const PENDING_INIT_FILE: string;
package/dist/gitRemote.js CHANGED
@@ -101,6 +101,7 @@ export function runGit(args, cwd, opts = {}) {
101
101
  env: { ...(opts.env ?? process.env), LC_ALL: 'C', LANGUAGE: 'C' },
102
102
  timeout: opts.timeoutMs,
103
103
  maxBuffer: 64 * 1024 * 1024,
104
+ ...(opts.input !== undefined ? { input: opts.input } : {}),
104
105
  });
105
106
  return {
106
107
  status: result.status,
package/dist/ide.js CHANGED
@@ -512,9 +512,9 @@ async function handleVersionsList(deckDir, res) {
512
512
  if (await cloudGitModeAsync(deckDir)) {
513
513
  // With git on, the history is the git log and "pending" is git status. The old
514
514
  // store's versions stay listed as older versions: readable, never imported.
515
- const { versions, pending } = await gitVersionHistory(deckDir);
515
+ const { versions, pending, loading } = await gitVersionHistory(deckDir);
516
516
  const older = versionSummaries(deckDir).map((v) => ({ ...v, later: false, older: true }));
517
- return sendJson(res, 200, { git: true, versions: [...versions, ...older], pending });
517
+ return sendJson(res, 200, { git: true, versions: [...versions, ...older], pending, ...(loading ? { loading: true } : {}) });
518
518
  }
519
519
  // The history and what is outstanding against it, together: the panel shows
520
520
  // them as one picture, and two calls could disagree about the moment.
package/dist/index.js CHANGED
@@ -172,6 +172,7 @@ function usage() {
172
172
  castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
173
173
  castle-web git attach <dir> --remote <url> (cloud sandbox only: makes the deck a clone of its Castle repo)
174
174
  castle-web git sync [--dir DIR] (cloud sandbox only: commit, merge the remote's main, push)
175
+ castle-web git rehydrate [--dir DIR] (cloud sandbox only: rebuild git history missing after a cold resume)
175
176
  castle-web commit [-m MESSAGE] [--reason turn|task|leave|manual|sync] [--resolve] [paths...] [--dir DIR] (cloud sandbox only)
176
177
  castle-web login
177
178
  castle-web whoami
@@ -234,7 +235,7 @@ async function gitCommand() {
234
235
  process.stdout.write(answer.stdout);
235
236
  return;
236
237
  }
237
- if (sub === 'attach' || sub === 'sync') {
238
+ if (sub === 'attach' || sub === 'sync' || sub === 'rehydrate') {
238
239
  await cloudGitCommand(sub);
239
240
  return;
240
241
  }
@@ -290,7 +291,12 @@ function parseCloudArgs(from, valueFlags, booleanFlags = []) {
290
291
  }
291
292
  async function cloudGitDeps() {
292
293
  const cloudGit = await import('./cloudGit.js');
293
- return { cloudGit, deps: cloudGit.defaultCloudGitDeps(() => api.whoAmI()) };
294
+ return {
295
+ cloudGit,
296
+ deps: cloudGit.defaultCloudGitDeps(() => api.whoAmI(), {
297
+ mirrorState: (deckId, opts) => api.gitMirrorState(deckId, opts.includeBundles, opts.timeoutMs),
298
+ }),
299
+ };
294
300
  }
295
301
  function reportSync(sync, syncError) {
296
302
  if (syncError)
@@ -313,6 +319,19 @@ function reportSync(sync, syncError) {
313
319
  async function cloudGitCommand(sub) {
314
320
  const { cloudGit, deps } = await cloudGitDeps();
315
321
  const { flags, positionals } = parseCloudArgs(2, ['--remote', '--dir']);
322
+ if (sub === 'rehydrate') {
323
+ const dir = positionals[0] ?? flags.get('--dir') ?? '.';
324
+ console.log(`[${new Date().toISOString()}] git rehydrate ${path.resolve(dir)}`);
325
+ try {
326
+ const outcome = await cloudGit.cloudRehydrate(dir, deps);
327
+ console.log(outcome === 'complete' ? 'rehydrate finished: history already complete' : 'rehydrate finished: rebuilt');
328
+ }
329
+ catch (e) {
330
+ console.error(`rehydrate finished: failed: ${e instanceof Error ? e.message : String(e)}`);
331
+ throw e;
332
+ }
333
+ return;
334
+ }
316
335
  if (sub === 'attach') {
317
336
  const remote = flags.get('--remote');
318
337
  const dir = positionals[0] ?? flags.get('--dir');
@@ -372,7 +391,8 @@ async function gitVersionCommand(name) {
372
391
  cloudGit.printGitShow(dir, target);
373
392
  }
374
393
  else if (name === 'restore-version' && target) {
375
- const outcome = await cloudGit.cloudRestore(dir, target, cloudGit.defaultCloudGitDeps(() => api.whoAmI()));
394
+ const { deps } = await cloudGitDeps();
395
+ const outcome = await cloudGit.cloudRestore(dir, target, deps);
376
396
  console.log(outcome.sha ? `Restored ${target} as commit ${outcome.sha}` : `Already at ${target}.`);
377
397
  reportSync(outcome.sync, outcome.syncError);
378
398
  }
@@ -588,6 +608,7 @@ async function main() {
588
608
  main().catch((e) => {
589
609
  console.error(e instanceof Error ? e.message : String(e));
590
610
  // 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.
611
+ // merge waiting on the agent, 4: git history not available yet); anything else is a plain
612
+ // failure.
592
613
  process.exit(e instanceof CloudGitError ? e.exitCode : 1);
593
614
  });
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.