castle-web-cli 0.4.214 → 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.
@@ -30,6 +30,7 @@ export const DEFAULT_SERVER_TICK_RATE = 20;
30
30
  export const DEFAULT_SERVER_MAX_PLAYERS = 8;
31
31
  export const SERVER_TICK_RATE_CAP = 30;
32
32
  export const SERVER_MAX_PLAYERS_CAP = 24;
33
+ export const SERVER_DESTINATIONS_CAP = 16;
33
34
  // A deck may keep its source under `code/`, so both roots are candidates.
34
35
  const DEFAULT_SERVER_ENTRIES = [
35
36
  'server/index.js',
@@ -52,8 +53,65 @@ export function resolveServerConfig(dir) {
52
53
  tickRate: clampNumber(server?.tickRate, DEFAULT_SERVER_TICK_RATE, 0, SERVER_TICK_RATE_CAP),
53
54
  maxPlayers: Math.floor(clampNumber(server?.maxPlayers, DEFAULT_SERVER_MAX_PLAYERS, 1, SERVER_MAX_PLAYERS_CAP)),
54
55
  voiceEnabled: castleJson?.voice?.enabled !== false,
56
+ ...(server?.destinations === undefined
57
+ ? {}
58
+ : { destinations: validateServerDestinations(server.destinations) }),
55
59
  };
56
60
  }
61
+ function validateServerDestinations(value) {
62
+ if (!Array.isArray(value) || value.length > SERVER_DESTINATIONS_CAP) {
63
+ throw new Error(`server.destinations must be an array of at most ${SERVER_DESTINATIONS_CAP} routes.`);
64
+ }
65
+ const routeIds = new Set();
66
+ return value.map((candidate, index) => {
67
+ if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate)) {
68
+ throw invalidDestination(index, 'must be an object');
69
+ }
70
+ const route = candidate;
71
+ const routeId = route.routeId;
72
+ if (typeof routeId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(routeId)) {
73
+ throw invalidDestination(index, 'routeId must match [A-Za-z0-9_-] and be 1 through 64 characters');
74
+ }
75
+ if (routeIds.has(routeId))
76
+ throw invalidDestination(index, `routeId "${routeId}" is duplicated`);
77
+ routeIds.add(routeId);
78
+ if (route.access !== 'player' && route.access !== 'party' && route.access !== 'public') {
79
+ throw invalidDestination(index, 'access must be player, party, or public');
80
+ }
81
+ if (route.selection !== 'exact' && route.selection !== 'find') {
82
+ throw invalidDestination(index, 'selection must be exact or find');
83
+ }
84
+ if (route.persistence !== 'transient' && route.persistence !== 'world') {
85
+ throw invalidDestination(index, 'persistence must be transient or world');
86
+ }
87
+ if (route.persistence === 'world' && route.selection === 'find') {
88
+ throw invalidDestination(index, 'persistent worlds require selection "exact"');
89
+ }
90
+ if (route.characters !== undefined && route.characters !== 'shared') {
91
+ throw invalidDestination(index, 'characters must be shared when present');
92
+ }
93
+ if (route.characters === 'shared' &&
94
+ (route.persistence !== 'world' || route.selection !== 'exact')) {
95
+ throw invalidDestination(index, 'shared characters require selection "exact" and persistence "world"');
96
+ }
97
+ if (!Number.isInteger(route.maxPlayers) ||
98
+ route.maxPlayers < 1 ||
99
+ route.maxPlayers > SERVER_MAX_PLAYERS_CAP) {
100
+ throw invalidDestination(index, `maxPlayers must be an integer from 1 through ${SERVER_MAX_PLAYERS_CAP}`);
101
+ }
102
+ return {
103
+ routeId,
104
+ access: route.access,
105
+ selection: route.selection,
106
+ persistence: route.persistence,
107
+ ...(route.characters === 'shared' ? { characters: 'shared' } : {}),
108
+ maxPlayers: route.maxPlayers,
109
+ };
110
+ });
111
+ }
112
+ function invalidDestination(index, message) {
113
+ return new Error(`server.destinations[${index}] ${message}.`);
114
+ }
57
115
  function isSafeServerEntry(dir, entry) {
58
116
  if (!/\.(?:js|ts|mjs)$/.test(entry))
59
117
  return false;
@@ -41,6 +41,7 @@ export declare const LEAVE_PENDING_FILE: string;
41
41
  export declare const ATTACH_BACKUP_MAX_AGE_MS: number;
42
42
  export declare const ATTACH_BACKUP_KEEP = 10;
43
43
  export declare const DEADLINE_ENV = "CASTLE_GIT_DEADLINE";
44
+ export declare const AGENT_ROLE_ENV = "CASTLE_AGENT_ROLE";
44
45
  export interface GitRunOptions {
45
46
  timeoutMs?: number;
46
47
  /** A scratch index instead of the repo's own. */
@@ -90,8 +91,14 @@ export declare function deckBusy(ctx: {
90
91
  dir: string;
91
92
  deps: Pick<CloudGitDeps, 'hostname' | 'isAlive'>;
92
93
  }): boolean;
94
+ export declare function deckTasksBusy(ctx: {
95
+ dir: string;
96
+ deps: Pick<CloudGitDeps, 'hostname' | 'isAlive'>;
97
+ }): boolean;
93
98
  /** The serve's side of deckBusy. */
94
- export declare function setDeckBusy(dir: string, busy: boolean): void;
99
+ export declare function setDeckBusy(dir: string, busy: boolean, opts?: {
100
+ tasks: boolean;
101
+ }): void;
95
102
  /**
96
103
  * An exclusive lock on `file`, returning its release. The lock is created exclusively (O_EXCL),
97
104
  * names its holder (pid, container hostname, process start time) and a random token, and is
package/dist/cloudGit.js CHANGED
@@ -94,6 +94,7 @@ export const ATTACH_BACKUP_KEEP = 10;
94
94
  // sets it to just short of its SIGKILL). Every git step's own timeout is capped by what is left,
95
95
  // so no step is still running when the kill lands, and none starts without time to finish.
96
96
  export const DEADLINE_ENV = 'CASTLE_GIT_DEADLINE';
97
+ export const AGENT_ROLE_ENV = 'CASTLE_AGENT_ROLE';
97
98
  const MIN_STEP_MS = 2_000;
98
99
  const MAIN = 'main';
99
100
  const REMOTE_MAIN = `refs/remotes/${GIT_REMOTE_NAME}/${MAIN}`;
@@ -315,11 +316,27 @@ export function deckBusy(ctx) {
315
316
  return false;
316
317
  }
317
318
  }
319
+ export function deckTasksBusy(ctx) {
320
+ if (!deckBusy(ctx))
321
+ return false;
322
+ try {
323
+ const held = JSON.parse(fs.readFileSync(path.join(ctx.dir, BUSY_FILE), 'utf-8'));
324
+ return held.tasks !== false;
325
+ }
326
+ catch {
327
+ return false;
328
+ }
329
+ }
318
330
  /** The serve's side of deckBusy. */
319
- export function setDeckBusy(dir, busy) {
331
+ export function setDeckBusy(dir, busy, opts) {
320
332
  const file = path.join(dir, BUSY_FILE);
321
333
  if (busy) {
322
- writeJsonAtomic(file, { pid: process.pid, host: os.hostname(), start: processStartTime(process.pid) });
334
+ writeJsonAtomic(file, {
335
+ pid: process.pid,
336
+ host: os.hostname(),
337
+ start: processStartTime(process.pid),
338
+ tasks: opts?.tasks ?? true,
339
+ });
323
340
  return;
324
341
  }
325
342
  try {
@@ -1305,7 +1322,8 @@ export async function cloudRestore(dir, target, deps) {
1305
1322
  // Rewriting the files under a task agent at work would mix its edits into the old version:
1306
1323
  // asked before anything is done, and again right before the files are rewritten.
1307
1324
  const refuseIfBusy = () => {
1308
- if (deckBusy(ctx)) {
1325
+ const busy = ctx.deps.env[AGENT_ROLE_ENV] === 'router' ? deckTasksBusy(ctx) : deckBusy(ctx);
1326
+ if (busy) {
1309
1327
  throw new CloudGitError('Task agents are working in this deck, so it was not restored. Restore it once they finish.');
1310
1328
  }
1311
1329
  };
@@ -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)}`);
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.