castle-web-cli 0.4.256 → 0.4.258

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.
@@ -0,0 +1,35 @@
1
+ import type { EffortLevel } from './effortSupport.js';
2
+ import type { experimentArm, PaidClaudeModel } from './modelExperiment.js';
3
+ export type ClaudeModel = 'sonnet' | 'opus' | 'fable' | 'openrouter';
4
+ export interface AgentSettings {
5
+ routerClaudeModel: ClaudeModel;
6
+ tasksClaudeModel: ClaudeModel;
7
+ routerOpenrouterModel: string;
8
+ tasksOpenrouterModel: string;
9
+ routerEffort: EffortLevel;
10
+ tasksEffort: EffortLevel;
11
+ }
12
+ export declare function defaultEffortFor(role: 'router' | 'tasks', claudeModel: ClaudeModel, openrouterModel: string): EffortLevel;
13
+ export declare const EFFORT_ROLES: readonly [{
14
+ readonly role: "router";
15
+ readonly label: "operator";
16
+ readonly claude: "routerClaudeModel";
17
+ readonly slug: "routerOpenrouterModel";
18
+ readonly effort: "routerEffort";
19
+ }, {
20
+ readonly role: "tasks";
21
+ readonly label: "tasks";
22
+ readonly claude: "tasksClaudeModel";
23
+ readonly slug: "tasksOpenrouterModel";
24
+ readonly effort: "tasksEffort";
25
+ }];
26
+ export declare function defaultSettings(proxied: boolean, paidDefault: PaidClaudeModel | null): AgentSettings;
27
+ export declare function normalizeClaudeModel(value: unknown): ClaudeModel | null;
28
+ export declare function normalizeOpenrouterModel(value: unknown): string | null;
29
+ export declare function normalizeEffort(value: unknown): EffortLevel | null;
30
+ export type StoredAgentSettings = Partial<Record<keyof AgentSettings, unknown>> & {
31
+ settingsEpoch?: unknown;
32
+ chosenModels?: unknown;
33
+ };
34
+ export declare function resolveAgentSettings(stored: StoredAgentSettings | null, proxied: boolean, paidDefault: PaidClaudeModel | null): AgentSettings;
35
+ export declare function serializeAgentSettings(settings: AgentSettings, stored: StoredAgentSettings | null, incoming: Partial<Record<keyof AgentSettings, unknown>>, defaults: AgentSettings, arm: ReturnType<typeof experimentArm>): string;
@@ -0,0 +1,151 @@
1
+ import { isMuseModel } from './agent-prompts.js';
2
+ const DEFAULT_SETTINGS = {
3
+ // Both roles run the claude CLI routed through OpenRouter at the slug below.
4
+ // Note this takes the Anthropic credential out of play entirely: a role on
5
+ // "openrouter" resolves OpenRouter auth, so a user's `claude /login` or
6
+ // ANTHROPIC_API_KEY no longer applies (see buildAgentInvocation) -- which is
7
+ // exactly why a user who HAS one defaults to ANTHROPIC_DEFAULT_MODELS below.
8
+ routerClaudeModel: 'openrouter',
9
+ tasksClaudeModel: 'openrouter',
10
+ // Free-form -- change to any OpenRouter slug. Both roles default to the
11
+ // model Castle pays for (the proxy's freeModelPrefixes list), so an editor
12
+ // that has never touched settings costs the user nothing and never runs into
13
+ // a credit balance -- see freeTierForRoles / the free-model skip in
14
+ // castleSpendRefusal. Picking any other slug puts that role back on credits.
15
+ routerOpenrouterModel: 'meta/muse-spark-1.3-contributor',
16
+ tasksOpenrouterModel: 'meta/muse-spark-1.3-contributor',
17
+ routerEffort: 'medium',
18
+ tasksEffort: 'medium',
19
+ };
20
+ // What the two claude-model defaults become once the user has an Anthropic
21
+ // credential of their own -- a key or a claude.ai login, which
22
+ // resolveAnthropicAuth already treats as one question. Signing in has to move
23
+ // these or it buys the user nothing: the openrouter default never resolves
24
+ // Anthropic auth, so an account added in the Accounts modal would sit unused
25
+ // (and the runs stay metered) until the user also found the model picker.
26
+ const ANTHROPIC_DEFAULT_MODELS = {
27
+ routerClaudeModel: 'opus',
28
+ tasksClaudeModel: 'sonnet',
29
+ };
30
+ // The effort a role starts at for a given model. Tasks on a muse model start
31
+ // at low: castle-agent-evals/muse-tune measured medium as slower with more api
32
+ // guessing. The operator stays at medium on every model, and claude models
33
+ // stay at medium for both roles. A level the user picks is stored and stands.
34
+ export function defaultEffortFor(role, claudeModel, openrouterModel) {
35
+ return role === 'tasks' && claudeModel === 'openrouter' && isMuseModel(openrouterModel) ? 'low' : 'medium';
36
+ }
37
+ export const EFFORT_ROLES = [
38
+ { role: 'router', label: 'operator', claude: 'routerClaudeModel', slug: 'routerOpenrouterModel', effort: 'routerEffort' },
39
+ { role: 'tasks', label: 'tasks', claude: 'tasksClaudeModel', slug: 'tasksOpenrouterModel', effort: 'tasksEffort' },
40
+ ];
41
+ export function defaultSettings(proxied, paidDefault) {
42
+ const models = { ...DEFAULT_SETTINGS };
43
+ if (!proxied)
44
+ Object.assign(models, ANTHROPIC_DEFAULT_MODELS);
45
+ else if (paidDefault) {
46
+ models.routerClaudeModel = paidDefault;
47
+ models.tasksClaudeModel = paidDefault;
48
+ }
49
+ return {
50
+ ...models,
51
+ routerEffort: defaultEffortFor('router', models.routerClaudeModel, models.routerOpenrouterModel),
52
+ tasksEffort: defaultEffortFor('tasks', models.tasksClaudeModel, models.tasksOpenrouterModel),
53
+ };
54
+ }
55
+ // Bump to force every deck onto the current DEFAULT_SETTINGS once, discarding
56
+ // what users had chosen: a stored file below this epoch has ALL of its setting
57
+ // fields dropped on load (see resolveAgentSettings). Bump ONLY when a default
58
+ // change is meant to override existing choices -- an ordinary one needs no
59
+ // bump, since sparse storage already reaches anyone who never set that field.
60
+ // The wipe is also what retires older file shapes, so a migration for one is
61
+ // only worth writing if it must survive the epoch that introduces it.
62
+ //
63
+ // 2: the OpenRouter default moved to the model Castle pays for. Deliberately a
64
+ // bump rather than an ordinary default change -- decks that had already stored
65
+ // a slug (including the one that was the default when they stored it) would
66
+ // otherwise keep spending credits on a metered model while every user around
67
+ // them runs free.
68
+ const SETTINGS_EPOCH = 2;
69
+ export function normalizeClaudeModel(value) {
70
+ return value === 'sonnet' || value === 'opus' || value === 'fable' || value === 'openrouter'
71
+ ? value
72
+ : null;
73
+ }
74
+ // Free-form, so validation is just "non-empty, not absurdly long" (guards
75
+ // against a stray huge paste landing in settings.json / the CLI argv).
76
+ const OPENROUTER_MODEL_MAX_LEN = 200;
77
+ export function normalizeOpenrouterModel(value) {
78
+ if (typeof value !== 'string')
79
+ return null;
80
+ const trimmed = value.trim();
81
+ return trimmed && trimmed.length <= OPENROUTER_MODEL_MAX_LEN ? trimmed : null;
82
+ }
83
+ export function normalizeEffort(value) {
84
+ return value === 'low' ||
85
+ value === 'medium' ||
86
+ value === 'high' ||
87
+ value === 'xhigh' ||
88
+ value === 'max'
89
+ ? value
90
+ : null;
91
+ }
92
+ function currentSettings(stored) {
93
+ return typeof stored?.settingsEpoch === 'number' && stored.settingsEpoch >= SETTINGS_EPOCH
94
+ ? stored
95
+ : {};
96
+ }
97
+ // An existing sparse model override follows its old defaults for the missing
98
+ // half of the pair. A complete stored pair is honored in every arm.
99
+ export function resolveAgentSettings(stored, proxied, paidDefault) {
100
+ const values = currentSettings(stored);
101
+ const defaults = defaultSettings(proxied, paidDefault);
102
+ const ordinary = defaultSettings(proxied, null);
103
+ for (const { role, claude, slug, effort } of EFFORT_ROLES) {
104
+ const storedAlias = normalizeClaudeModel(values[claude]);
105
+ const storedSlug = normalizeOpenrouterModel(values[slug]);
106
+ if (storedAlias || storedSlug) {
107
+ defaults[claude] = storedAlias ?? ordinary[claude];
108
+ defaults[slug] = storedSlug ?? ordinary[slug];
109
+ }
110
+ defaults[effort] = normalizeEffort(values[effort]) ??
111
+ defaultEffortFor(role, defaults[claude], defaults[slug]);
112
+ }
113
+ return defaults;
114
+ }
115
+ export function serializeAgentSettings(settings, stored, incoming, defaults, arm) {
116
+ const values = currentSettings(stored);
117
+ const previousPins = Array.isArray(values.chosenModels) ? values.chosenModels : [];
118
+ const chosenModels = [];
119
+ const out = { settingsEpoch: SETTINGS_EPOCH };
120
+ for (const { role, claude, slug, effort } of EFFORT_ROLES) {
121
+ const chosen = normalizeClaudeModel(incoming[claude]) || normalizeOpenrouterModel(incoming[slug]);
122
+ const pinned = chosen ? arm === 'paid_default' : previousPins.includes(role);
123
+ if (pinned)
124
+ chosenModels.push(role);
125
+ if (pinned) {
126
+ out[claude] = settings[claude];
127
+ out[slug] = settings[slug];
128
+ }
129
+ else if (arm === 'paid_default') {
130
+ // Retain pre-experiment sparse overrides as the live defaults move.
131
+ const alias = normalizeClaudeModel(values[claude]);
132
+ const openrouterModel = normalizeOpenrouterModel(values[slug]);
133
+ if (alias)
134
+ out[claude] = alias;
135
+ if (openrouterModel)
136
+ out[slug] = openrouterModel;
137
+ }
138
+ else {
139
+ if (settings[claude] !== defaults[claude])
140
+ out[claude] = settings[claude];
141
+ if (settings[slug] !== defaults[slug])
142
+ out[slug] = settings[slug];
143
+ }
144
+ if (settings[effort] !== defaultEffortFor(role, settings[claude], settings[slug])) {
145
+ out[effort] = settings[effort];
146
+ }
147
+ }
148
+ if (chosenModels.length)
149
+ out.chosenModels = chosenModels;
150
+ return JSON.stringify(out, null, 2) + '\n';
151
+ }
@@ -121,7 +121,13 @@ async function handleMessage(data, isBinary) {
121
121
  }
122
122
  function createPlatformHandle(init, platformEvents) {
123
123
  const config = asRecord(init.config);
124
- return {
124
+ const assets = init.sessionAssets === undefined ? {} : asRecord(init.sessionAssets);
125
+ const handle = {
126
+ readAsset(name) {
127
+ const encoded = Object.hasOwn(assets, name) ? assets[name] : undefined;
128
+ const bytes = typeof encoded === 'string' ? new Uint8Array(Buffer.from(encoded, 'base64')) : null;
129
+ return Promise.resolve(bytes);
130
+ },
125
131
  send(connId, text) {
126
132
  send({ protocolVersion: PROTOCOL_VERSION, t: 'sendTo', playerId: connId, d: text });
127
133
  },
@@ -157,6 +163,7 @@ function createPlatformHandle(init, platformEvents) {
157
163
  maxPlayers: Number(config.maxPlayers),
158
164
  }),
159
165
  };
166
+ return Object.defineProperty(handle, 'sessionSecret', { value: init.sessionSecret });
160
167
  }
161
168
  async function dispatch(platformEvents, frame) {
162
169
  switch (frame.t) {
@@ -24,11 +24,17 @@ export interface DevSessionServer {
24
24
  shutdownNow(): void;
25
25
  }
26
26
  export declare function devSessionIdFor(key: string | null): string;
27
+ interface DevSessionFixtures {
28
+ readonly sessionSecret?: string;
29
+ readonly assets?: ReadonlyMap<string, Uint8Array>;
30
+ }
27
31
  export declare function startDevSessionServer(opts: {
28
32
  projectDir: string;
29
33
  log: (level: 'log' | 'error', text: string) => void;
30
34
  /** Tests shorten the empty named-session teardown. */
31
35
  namedSessionIdleMs?: number;
36
+ /** Boot inputs for the local deck's private platform connection. */
37
+ sessionFixtures?: DevSessionFixtures;
32
38
  }): Promise<DevSessionServer>;
33
39
  export declare function serverRestartNeeded(changes: ReadonlyArray<{
34
40
  path: string;
@@ -36,3 +42,4 @@ export declare function serverRestartNeeded(changes: ReadonlyArray<{
36
42
  serverEntry: string;
37
43
  serverDir: string;
38
44
  }): boolean;
45
+ export {};
@@ -32,7 +32,7 @@ export function devSessionIdFor(key) {
32
32
  return key === null ? DEFAULT_SESSION_ID : `${DEFAULT_SESSION_ID}:${key}`;
33
33
  }
34
34
  export async function startDevSessionServer(opts) {
35
- const server = new DevSessionRouter(opts.projectDir, opts.log, opts.namedSessionIdleMs ?? NAMED_SESSION_IDLE_MS);
35
+ const server = new DevSessionRouter(opts.projectDir, opts.log, opts.namedSessionIdleMs ?? NAMED_SESSION_IDLE_MS, opts.sessionFixtures);
36
36
  try {
37
37
  await server.start();
38
38
  return server;
@@ -52,17 +52,19 @@ class DevSessionRouter {
52
52
  projectDir;
53
53
  log;
54
54
  idleMs;
55
+ sessionFixtures;
55
56
  sessionId = DEFAULT_SESSION_ID;
56
57
  port = 0;
57
58
  server = http.createServer((_req, res) => res.writeHead(404).end());
58
59
  defaultSession;
59
60
  named = new Map();
60
61
  closed = false;
61
- constructor(projectDir, log, idleMs) {
62
+ constructor(projectDir, log, idleMs, sessionFixtures) {
62
63
  this.projectDir = projectDir;
63
64
  this.log = log;
64
65
  this.idleMs = idleMs;
65
- this.defaultSession = new DevSessionImpl(projectDir, log, null, () => this.port, () => { });
66
+ this.sessionFixtures = sessionFixtures;
67
+ this.defaultSession = new DevSessionImpl(projectDir, log, null, () => this.port, () => { }, idleMs, sessionFixtures);
66
68
  this.server.on('upgrade', (request, socket, head) => this.handleUpgrade(request, socket, head));
67
69
  }
68
70
  async start() {
@@ -119,7 +121,7 @@ class DevSessionRouter {
119
121
  // `deck:<name>/<key>` runs another local deck's server, one this deck lists
120
122
  // in `devDecks` (contentPack.ts): a door to a separately built deck.
121
123
  const other = devDeckSessionKey(this.projectDir, key);
122
- const session = new DevSessionImpl(other?.dir ?? this.projectDir, (level, text) => this.log(level, `(${key}) ${text}`), key, () => this.port, () => this.stopIdle(key, session), this.idleMs);
124
+ const session = new DevSessionImpl(other?.dir ?? this.projectDir, (level, text) => this.log(level, `(${key}) ${text}`), key, () => this.port, () => this.stopIdle(key, session), this.idleMs, other ? undefined : this.sessionFixtures);
123
125
  this.named.set(key, session);
124
126
  session.start().catch((error) => {
125
127
  this.log('error', `(${key}) start failed: ${error instanceof Error ? error.message : String(error)}`);
@@ -182,6 +184,7 @@ class DevSessionImpl {
182
184
  port;
183
185
  onIdle;
184
186
  idleMs;
187
+ sessionFixtures;
185
188
  sessionId;
186
189
  clientWss = new WebSocketServer({
187
190
  noServer: true,
@@ -221,13 +224,14 @@ class DevSessionImpl {
221
224
  * `key` null is the default session, which never idles out. A named one calls
222
225
  * `onIdle` once it has had nobody connected for `idleMs`.
223
226
  */
224
- constructor(projectDir, log, key, port, onIdle, idleMs = NAMED_SESSION_IDLE_MS) {
227
+ constructor(projectDir, log, key, port, onIdle, idleMs, sessionFixtures) {
225
228
  this.projectDir = projectDir;
226
229
  this.log = log;
227
230
  this.key = key;
228
231
  this.port = port;
229
232
  this.onIdle = onIdle;
230
233
  this.idleMs = idleMs;
234
+ this.sessionFixtures = sessionFixtures;
231
235
  this.sessionId = devSessionIdFor(key);
232
236
  this.serverEntry = resolveServerConfig(projectDir)?.entry ?? 'server/index.js';
233
237
  this.serverDir = serverDirOf(this.serverEntry);
@@ -516,6 +520,7 @@ class DevSessionImpl {
516
520
  socket.on('close', () => this.runtimeClosed(socket));
517
521
  socket.on('error', () => undefined);
518
522
  const config = this.currentConfig();
523
+ const assets = this.sessionFixtures?.assets;
519
524
  this.sendPlatform({
520
525
  protocolVersion: PROTOCOL_VERSION,
521
526
  t: 'init',
@@ -523,6 +528,8 @@ class DevSessionImpl {
523
528
  deckId: readCastleJson(this.projectDir)?.deckId ?? 'dev',
524
529
  mode: 'named',
525
530
  config: { tickRate: config.tickRate, maxPlayers: config.maxPlayers },
531
+ sessionSecret: this.sessionFixtures?.sessionSecret,
532
+ sessionAssets: assets && Object.fromEntries(Array.from(assets, ([name, bytes]) => [name, Buffer.from(bytes).toString('base64')])),
526
533
  });
527
534
  }
528
535
  handleRuntimeMessage(data, isBinary) {
@@ -0,0 +1,23 @@
1
+ import type { ResolvedServerConfig } from './castleJson.js';
2
+ export declare const WRITER_CHECKS_CAPABILITY = "writerChecksV1";
3
+ export interface FleetCapabilities {
4
+ readyHosts: number;
5
+ capabilities: {
6
+ name: string;
7
+ hosts: number;
8
+ }[];
9
+ }
10
+ /**
11
+ * Whether the published (minified) server bundle passes a writer check
12
+ * (`{ check: { target, writer } }`) on a storage write. The SDK and kits name `check`
13
+ * only in comments and reads (`options.check`), so an object key `check`, the
14
+ * `{ check }` shorthand or an assignment to a `check` property comes from the deck. A heuristic over the built
15
+ * code: an unrelated `check` key also matches, which costs only a warning.
16
+ */
17
+ export declare function bundleUsesWriterChecks(code: string): boolean;
18
+ export declare function usesPersistentWorlds(config: ResolvedServerConfig): boolean;
19
+ export declare function fetchFleetCapabilities(): Promise<FleetCapabilities | null>;
20
+ /** The warning to print, or null when there is nothing to say. */
21
+ export declare function writerCheckFleetWarning(fleet: FleetCapabilities | null): string | null;
22
+ /** Prints the warning for a deck that needs it. Never throws. */
23
+ export declare function warnOnMissingHostFeatures(config: ResolvedServerConfig, code: string, fetchFleet?: () => Promise<FleetCapabilities | null>): Promise<void>;
@@ -0,0 +1,70 @@
1
+ // Warns at save when a deck depends on a host-side Cauldron feature the production
2
+ // fleet does not run yet. Host-agent code ships only in an AMI roll, which can trail a
3
+ // CLI release: on Nov 18 writer-checked saves in persistent worlds were refused as
4
+ // storage unavailable until the hosts were rolled. Warn only, never block, and an
5
+ // unreadable fleet is "unknown", not a failure.
6
+ import * as api from './api.js';
7
+ export const WRITER_CHECKS_CAPABILITY = 'writerChecksV1';
8
+ /**
9
+ * Whether the published (minified) server bundle passes a writer check
10
+ * (`{ check: { target, writer } }`) on a storage write. The SDK and kits name `check`
11
+ * only in comments and reads (`options.check`), so an object key `check`, the
12
+ * `{ check }` shorthand or an assignment to a `check` property comes from the deck. A heuristic over the built
13
+ * code: an unrelated `check` key also matches, which costs only a warning.
14
+ */
15
+ export function bundleUsesWriterChecks(code) {
16
+ return (/[{,]\s*check\s*[:,}]/.test(code) ||
17
+ // options.check = …, options["check"] = …; never the SDK's own `.check === undefined`.
18
+ /(?:\.check|\[\s*["'`]check["'`]\s*\])\s*=(?!=)/.test(code));
19
+ }
20
+ export function usesPersistentWorlds(config) {
21
+ return config.destinations?.some((route) => route.persistence === 'world') === true;
22
+ }
23
+ export async function fetchFleetCapabilities() {
24
+ try {
25
+ const result = await api.graphql(`query CauldronFleetCapabilities {
26
+ cauldronFleetCapabilities(env: "prod") {
27
+ readyHosts
28
+ capabilities { name hosts }
29
+ }
30
+ }`, undefined, { timeoutMs: 5_000 });
31
+ const fleet = result.data?.cauldronFleetCapabilities;
32
+ if (!fleet ||
33
+ typeof fleet.readyHosts !== 'number' ||
34
+ !Array.isArray(fleet.capabilities)) {
35
+ return null;
36
+ }
37
+ return fleet;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ /** The warning to print, or null when there is nothing to say. */
44
+ export function writerCheckFleetWarning(fleet) {
45
+ if (!fleet) {
46
+ return ('This deck uses writer checks in a persistent world, and the Cauldron fleet could not be read, ' +
47
+ `so it is unknown whether production hosts support them (${WRITER_CHECKS_CAPABILITY}). ` +
48
+ 'Where they do not, those saves fail with CAULDRON_STORAGE_UNAVAILABLE.');
49
+ }
50
+ const capable = fleet.capabilities.find((c) => c.name === WRITER_CHECKS_CAPABILITY)?.hosts ?? 0;
51
+ if (fleet.readyHosts > 0 && capable >= fleet.readyHosts)
52
+ return null;
53
+ return (`This deck uses writer checks in a persistent world, but only ${capable} of ${fleet.readyHosts} ` +
54
+ `production Cauldron hosts support them (${WRITER_CHECKS_CAPABILITY}). ` +
55
+ 'Until the rest are updated, a checked save in a world on an older host fails with ' +
56
+ 'CAULDRON_STORAGE_UNAVAILABLE. The deck is saved; nothing was blocked.');
57
+ }
58
+ /** Prints the warning for a deck that needs it. Never throws. */
59
+ export async function warnOnMissingHostFeatures(config, code, fetchFleet = fetchFleetCapabilities) {
60
+ try {
61
+ if (!usesPersistentWorlds(config) || !bundleUsesWriterChecks(code))
62
+ return;
63
+ const warning = writerCheckFleetWarning(await fetchFleet());
64
+ if (warning)
65
+ console.warn(`Warning: ${warning}`);
66
+ }
67
+ catch {
68
+ // A warning must never fail a save.
69
+ }
70
+ }
package/dist/init.js CHANGED
@@ -65,7 +65,7 @@ const BARE_SCAFFOLDS = [
65
65
  // Registry version of castle-web-sdk to inject when scaffolding from a
66
66
  // globally-installed castle-web (not from inside the workspace). Bumped
67
67
  // alongside cli/sdk version bumps.
68
- const PUBLISHED_SDK_VERSION = '0.4.58';
68
+ const PUBLISHED_SDK_VERSION = '0.4.59';
69
69
  // Range, not a pin: `castle-web-fonts` is its own package precisely so a tenth
70
70
  // face can ship without a cli release, and a caret range means an existing
71
71
  // deck's next install picks it up. Nothing here has to move when it does.
@@ -1,3 +1,4 @@
1
+ import type { AiModelExperiment, ExperimentEvent, ExperimentProperties } from "./modelExperiment.js";
1
2
  export type MeteringRoute = "anthropic" | "openrouter";
2
3
  /**
3
4
  * A fresh id for one agent run -- one router turn (one user message) or one
@@ -99,6 +100,8 @@ export declare function createBudgetRefreshRetry(run: () => void): {
99
100
  export declare function castleCreditsExhausted(budget: CastleBudget, credits: AiCredits | null): boolean;
100
101
  /** Rich credit state, or null when ghost/proxy cannot provide the new field. */
101
102
  export declare function fetchAiCredits(): Promise<AiCredits | null>;
103
+ export declare function fetchAiModelExperiment(): Promise<AiModelExperiment | null>;
104
+ export declare function sendAiModelExperimentEvent(event: ExperimentEvent, properties: ExperimentProperties): Promise<AiModelExperiment | null | undefined>;
102
105
  /**
103
106
  * The daily Castle-paid AI budget for the user this sandbox belongs to, or null
104
107
  * when there is nothing to say: outside a sandbox, on a host whose proxy
package/dist/metering.js CHANGED
@@ -232,12 +232,31 @@ function isAiCredits(value) {
232
232
  typeof reload.amountCredits === "number") &&
233
233
  (reload.disabledReason === null || typeof reload.disabledReason === "string"));
234
234
  }
235
- /** Rich credit state, or null when ghost/proxy cannot provide the new field. */
236
- export async function fetchAiCredits() {
235
+ // Both editor reads use the sandbox identity and GraphQL scope of the proxy.
236
+ async function proxyGraphql(query, variables) {
237
237
  const base = process.env.CASTLE_LLM_PROXY_URL;
238
238
  const token = process.env.CASTLE_LLM_PROXY_TOKEN;
239
239
  if (!base || !token)
240
- return null;
240
+ return undefined;
241
+ const resp = await fetch(`${base}${CASTLE_API_PATH}`, {
242
+ method: "POST",
243
+ headers: {
244
+ "x-auth-token": token,
245
+ "content-type": "application/json",
246
+ accept: "application/json",
247
+ "x-os": "cli",
248
+ "x-cli-api-version": "2",
249
+ },
250
+ body: JSON.stringify({ query, variables }),
251
+ signal: AbortSignal.timeout(BUDGET_FETCH_TIMEOUT_MS),
252
+ });
253
+ if (!resp.ok)
254
+ return undefined;
255
+ const body = (await resp.json());
256
+ return body.errors?.length ? undefined : body.data;
257
+ }
258
+ /** Rich credit state, or null when ghost/proxy cannot provide the new field. */
259
+ export async function fetchAiCredits() {
241
260
  try {
242
261
  // Retry without rates for a ghost version whose schema predates the field.
243
262
  // GraphQL rejects the whole operation when even one selected field is unknown.
@@ -245,35 +264,19 @@ export async function fetchAiCredits() {
245
264
  "rates { usdPerCredit displayUnit }",
246
265
  "",
247
266
  ]) {
248
- const resp = await fetch(`${base}${CASTLE_API_PATH}`, {
249
- method: "POST",
250
- headers: {
251
- "x-auth-token": token,
252
- "content-type": "application/json",
253
- accept: "application/json",
254
- "x-os": "cli",
255
- "x-cli-api-version": "2",
256
- },
257
- body: JSON.stringify({
258
- query: `query {
259
- me {
260
- aiCredits {
261
- plan balanceCredits grantedCredits purchasedCredits pendingCredits
262
- dailyFreeRemainingCredits nextGrantAt lowBalance
263
- ${ratesField}
264
- autoReload { enabled thresholdCredits amountCredits disabledReason }
265
- }
266
- }
267
- }`,
268
- }),
269
- signal: AbortSignal.timeout(BUDGET_FETCH_TIMEOUT_MS),
270
- });
271
- if (!resp.ok)
272
- continue;
273
- const body = (await resp.json());
274
- if (body.errors?.length)
267
+ const data = await proxyGraphql(`query {
268
+ me {
269
+ aiCredits {
270
+ plan balanceCredits grantedCredits purchasedCredits pendingCredits
271
+ dailyFreeRemainingCredits nextGrantAt lowBalance
272
+ ${ratesField}
273
+ autoReload { enabled thresholdCredits amountCredits disabledReason }
274
+ }
275
+ }
276
+ }`);
277
+ if (!data)
275
278
  continue;
276
- const credits = body.data?.me?.aiCredits;
279
+ const credits = data.me?.aiCredits;
277
280
  return isAiCredits(credits) ? credits : null;
278
281
  }
279
282
  return null;
@@ -282,6 +285,32 @@ export async function fetchAiCredits() {
282
285
  return null;
283
286
  }
284
287
  }
288
+ const EXPERIMENT_FIELDS = `
289
+ name arm inExperiment running startsAt endsAt defaultPaidModel
290
+ typicalRequestCredits nudgeDue nudgeShown
291
+ `;
292
+ // Separate from aiCredits so older Ghost schemas preserve the credits UI.
293
+ export async function fetchAiModelExperiment() {
294
+ try {
295
+ const data = await proxyGraphql(`query { me { aiModelExperiment { ${EXPERIMENT_FIELDS} } } }`);
296
+ return data?.me?.aiModelExperiment ?? null;
297
+ }
298
+ catch {
299
+ return null;
300
+ }
301
+ }
302
+ export async function sendAiModelExperimentEvent(event, properties) {
303
+ try {
304
+ const data = await proxyGraphql(`mutation ($event: String!, $properties: Json) {
305
+ aiModelExperimentEvent(event: $event, properties: $properties) { ${EXPERIMENT_FIELDS} }
306
+ }`, { event, properties });
307
+ return data?.aiModelExperimentEvent;
308
+ }
309
+ catch {
310
+ // A telemetry failure leaves the last authoritative arm in place.
311
+ return undefined;
312
+ }
313
+ }
285
314
  /**
286
315
  * The daily Castle-paid AI budget for the user this sandbox belongs to, or null
287
316
  * when there is nothing to say: outside a sandbox, on a host whose proxy
@@ -0,0 +1,36 @@
1
+ export type PaidClaudeModel = 'sonnet' | 'opus' | 'fable';
2
+ export type ModelRole = 'router' | 'tasks';
3
+ export interface AiModelExperiment {
4
+ name: string;
5
+ arm: string;
6
+ inExperiment: boolean;
7
+ running: boolean;
8
+ startsAt: string | null;
9
+ endsAt: string | null;
10
+ defaultPaidModel: string;
11
+ typicalRequestCredits: Partial<Record<PaidClaudeModel, number>> | null;
12
+ nudgeDue: boolean;
13
+ nudgeShown: boolean;
14
+ }
15
+ export declare const EXPERIMENT_EVENTS: readonly ["exposure", "picker_opened", "paid_model_selected", "nudge_shown", "nudge_tapped", "nudge_dismissed", "fallback_to_free_shown", "get_credits_tapped", "free_model_reply"];
16
+ export type ExperimentEvent = typeof EXPERIMENT_EVENTS[number];
17
+ export type CreditsSource = 'composer' | 'failure' | 'fallback' | 'popover';
18
+ export interface ExperimentProperties {
19
+ model?: string;
20
+ role?: ModelRole;
21
+ surface?: 'web' | 'app';
22
+ deckId?: string;
23
+ source?: CreditsSource;
24
+ }
25
+ export declare function experimentArm(experiment: AiModelExperiment | null | undefined): "visible" | "nudge" | "paid_default" | "control";
26
+ export declare function isPaidClaudeModel(model: unknown): model is PaidClaudeModel;
27
+ export declare function paidExperimentDefault(experiment: AiModelExperiment | null | undefined, proxied: boolean, spendable: number | null): PaidClaudeModel | null;
28
+ export declare function fellBackToFree(previousDefault: PaidClaudeModel | null, previousRouter: string, nextRouter: string, experiment: AiModelExperiment | null, proxied: boolean, spendable: number | null): boolean;
29
+ export declare function nudgeModel(experiment: AiModelExperiment | null | undefined, spendable: number | null | undefined, blockedModels?: readonly string[]): PaidClaudeModel | null;
30
+ export declare function effectiveModelExperiment(experiment: AiModelExperiment | null, anthropicCastlePaid: boolean, openrouterCastlePaid: boolean): AiModelExperiment | null;
31
+ export declare function createFallbackNotice(): {
32
+ pending: () => number | undefined;
33
+ begin: () => void;
34
+ clear: () => void;
35
+ acknowledge: (id: unknown) => boolean;
36
+ };
@@ -0,0 +1,67 @@
1
+ export const EXPERIMENT_EVENTS = [
2
+ 'exposure',
3
+ 'picker_opened',
4
+ 'paid_model_selected',
5
+ 'nudge_shown',
6
+ 'nudge_tapped',
7
+ 'nudge_dismissed',
8
+ 'fallback_to_free_shown',
9
+ 'get_credits_tapped',
10
+ 'free_model_reply',
11
+ ];
12
+ export function experimentArm(experiment) {
13
+ switch (experiment?.arm) {
14
+ case 'visible':
15
+ case 'nudge':
16
+ case 'paid_default':
17
+ return experiment.arm;
18
+ default:
19
+ return 'control';
20
+ }
21
+ }
22
+ export function isPaidClaudeModel(model) {
23
+ return model === 'sonnet' || model === 'opus' || model === 'fable';
24
+ }
25
+ export function paidExperimentDefault(experiment, proxied, spendable) {
26
+ const model = experiment?.defaultPaidModel;
27
+ return experimentArm(experiment) === 'paid_default' &&
28
+ proxied && spendable !== null && spendable > 0 && isPaidClaudeModel(model)
29
+ ? model
30
+ : null;
31
+ }
32
+ // Compare resolved settings, so a pinned paid choice and a switch to control
33
+ // never produce the credit-exhaustion notice.
34
+ export function fellBackToFree(previousDefault, previousRouter, nextRouter, experiment, proxied, spendable) {
35
+ return previousDefault !== null && previousRouter === previousDefault &&
36
+ nextRouter === 'openrouter' && proxied && spendable === 0 &&
37
+ experimentArm(experiment) === 'paid_default';
38
+ }
39
+ export function nudgeModel(experiment, spendable, blockedModels = []) {
40
+ const model = experiment?.defaultPaidModel;
41
+ return experimentArm(experiment) === 'nudge' && experiment?.nudgeDue && !experiment.nudgeShown &&
42
+ (spendable ?? 0) > 0 && isPaidClaudeModel(model) && !blockedModels.includes(model)
43
+ ? model
44
+ : null;
45
+ }
46
+ // The experiment can change both roles and routes. An own credential on either
47
+ // route excludes the editor, including when its current model uses the other.
48
+ export function effectiveModelExperiment(experiment, anthropicCastlePaid, openrouterCastlePaid) {
49
+ return anthropicCastlePaid && openrouterCastlePaid ? experiment : null;
50
+ }
51
+ // The serve consumes a pending transition when any client reports it visible.
52
+ // The sequence prevents a late acknowledgement from consuming a newer notice.
53
+ export function createFallbackNotice() {
54
+ let sequence = 0;
55
+ let pending;
56
+ return {
57
+ pending: () => pending,
58
+ begin: () => { pending = ++sequence; },
59
+ clear: () => { pending = undefined; },
60
+ acknowledge: (id) => {
61
+ if (pending === undefined || id !== pending)
62
+ return false;
63
+ pending = undefined;
64
+ return true;
65
+ },
66
+ };
67
+ }
@@ -5,6 +5,7 @@ export declare const CHARACTER_DOC_REL: string;
5
5
  export declare function everyDeckBullets(deckDir: string): string[];
6
6
  export declare const HOST_LIMIT_BULLETS: string[];
7
7
  export declare const CASTLE_UI_BULLETS: string[];
8
+ export declare const CREATOR_DOCS_BULLETS: string[];
8
9
  export type AgentRole = 'router' | 'task';
9
10
  export declare function roleLoadsClaudeMd(role: AgentRole): boolean;
10
11
  export declare function claudeContextEnv(role: AgentRole): NodeJS.ProcessEnv;