@slatesvideo/shared 0.7.21 → 0.7.23

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.
@@ -4,7 +4,7 @@ import { STYLE_LIBRARY, DEFAULT_STYLE_ID } from '../prompts/style-library.js';
4
4
  import { discoverGuides, guideCatalog } from '../prompts/guide-discovery.js';
5
5
  import { retrieveGuide, servedDepth } from '../prompts/guide-retrieval.js';
6
6
  import { BRAIN_ROUTER, MY_BRAIN_TOPIC, ROUTER_ALIASES } from '../prompts/brain.js';
7
- import { MINIMAX_MAX_REFERENCE, minimaxMaxReferenceTokens, MODEL_CAPABILITIES, RETIRED_MODELS, retiredModelOfKey, checkReferenceShape, GPT_QUALITY_TIERS, DEFAULT_GPT_QUALITY, GPT_BACKGROUNDS, seedream55CostKey } from '../prompts/model-capabilities.js';
7
+ import { MINIMAX_MAX_REFERENCE, minimaxMaxReferenceTokens, MODEL_CAPABILITIES, RETIRED_MODELS, retiredModelOfKey, checkReferenceShape, checkReferenceSeconds, checkFramesWithReferenceMedia, checkVideoParams, billedEditSeconds, EDIT_SECONDS_TOLERANCE, TOOL_BLOCK_SECONDS, toolBlockKey, toolBlocks, GPT_QUALITY_TIERS, DEFAULT_GPT_QUALITY, GPT_BACKGROUNDS, seedream55CostKey } from '../prompts/model-capabilities.js';
8
8
  // Operations layer — the ONE place every Slates agent tool is defined.
9
9
  // Both the MCP server and the CLI register these as their tool / command
10
10
  // surface. Every operation:
@@ -48,7 +48,7 @@ toolModelFor, CHATGPT_FRAMING_RATIOS, } from '../prompts/model-facts.js';
48
48
  // quoted for a model at 1080p that only took 8s there. A customer burned a
49
49
  // round trip on `4:5` + Seedance: accepted here, queued, credits reserved,
50
50
  // rejected by the provider asynchronously.
51
- import { AGENT_ROUTE_PROVIDER, defaultImageResolutionFor, aspectRatioUnion, videoResolutionUnion, durationBounds, aspectRatiosFor, getModelCapability, defaultVideoResolutionFor, checkAspectRatio, checkVideoResolution, checkDuration, describeAspectRatios, describeVideoResolutions, describeDurations, describeReferenceImageCaps, } from '../prompts/model-capabilities.js';
51
+ import { AGENT_ROUTE_PROVIDER, defaultImageResolutionFor, aspectRatioUnion, videoResolutionUnion, durationBounds, aspectRatioApplies, promptLengthError, promptLengthFor, videoPromptError, aspectRatiosFor, getModelCapability, defaultVideoResolutionFor, maxIngredientImagesFor, maxReferenceVideosFor, checkAspectRatio, checkVideoResolution, describeAspectRatios, describeVideoResolutions, describeDurations, describeReferenceImageCaps, } from '../prompts/model-capabilities.js';
52
52
  // Per-model warnings are extracted from skill @banned blocks. They ride the
53
53
  // selected model's estimate and submitted-prompt result, never another model's schema.
54
54
  import { describeBannedTokens, bannedTokenWarning, describeBannedTokensForSkill, } from '../prompts/banned-tokens.js';
@@ -143,6 +143,21 @@ function zEnum(values) {
143
143
  throw new Error('zEnum: empty value list');
144
144
  return z.enum(values);
145
145
  }
146
+ /**
147
+ * What a paid call is held to as it is sent: the credits approved for it, in the desktop's unit (list credits), and
148
+ * the quote they were approved for. From the host's decision (`ctx.spend`) where it has one, refused there once that
149
+ * approval was withdrawn; else from the input. Every billable op calls it immediately before its paid send, after
150
+ * its last await (`quote-ops-check.mjs` § 0), so a plan withdrawn while the op was pricing sends nothing.
151
+ */
152
+ function approvedSpend(ctx, input = {}) {
153
+ if (!ctx.spend)
154
+ return { approvedCredits: input.approvedCredits };
155
+ if (!ctx.spend.approved())
156
+ throw new Error('Nothing was sent: the approval for this call was withdrawn while it was being priced.');
157
+ return { approvedCredits: ctx.spend.approvedCredits, quoteFingerprint: ctx.spend.quoteFingerprint };
158
+ }
159
+ /** The fields a held send carries: the ceiling, and the quote it was approved for when there is one. */
160
+ const heldBody = (maxCredits, quoteFingerprint) => ({ maxCredits, ...(quoteFingerprint ? { quoteFingerprint } : {}) });
146
161
  function ok(data, text) {
147
162
  return {
148
163
  // Compact JSON — pretty-printing (indent 2) cost ~10-15% extra tokens
@@ -297,6 +312,14 @@ function creditCost(m) {
297
312
  return 0;
298
313
  return m.cost_credits ?? m.cost_cents ?? 0;
299
314
  }
315
+ /**
316
+ * A key's list price: what the desktop quotes, so the unit a desktop ceiling
317
+ * (`maxCredits`) is held in. `creditCost` is what the account is debited; the
318
+ * registry sends `list_credits` only where its tier pays something else.
319
+ */
320
+ function listCredits(m) {
321
+ return m?.list_credits ?? creditCost(m);
322
+ }
300
323
  function fmtCredits(credits) {
301
324
  return `${Math.round(credits).toLocaleString('en-US')} credits`;
302
325
  }
@@ -929,7 +952,7 @@ function describeComposer(r) {
929
952
  ? `a draft from ${r.draftFrom.code ?? r.draftFrom.assetId}`
930
953
  : 'an unsaved draft';
931
954
  lines.push(`Prompt box (${r.open ? 'showing' : 'hidden'}), ${r.lane} lane, ${r.model.label}${r.destination === 'chatgpt' ? ' (ChatGPT)' : ''}; ${where}.`);
932
- lines.push(`Words (${r.prompt.length}${r.promptMax ? `/${r.promptMax}` : ''}): ${r.prompt ? JSON.stringify(r.prompt) : 'none'}`);
955
+ lines.push(`Words (${promptLengthFor(r.model.id, r.prompt)}${r.promptMax ? `/${r.promptMax}` : ''}): ${r.prompt ? JSON.stringify(r.prompt) : 'none'}`);
933
956
  if (r.params.length)
934
957
  lines.push(`Settings: ${r.params.map((p) => `${p.label} ${p.value || '(none)'}`).join(' · ')}`);
935
958
  if (r.tiles.length) {
@@ -1066,7 +1089,7 @@ export const reorderPins = {
1066
1089
  async run(input, ctx) {
1067
1090
  await ctx.desktop().requireCapability('reorder', 'reordering folders and pins');
1068
1091
  const resolved = await resolveAssetRefs(ctx, input.projectId, input.assetIds);
1069
- return ok(await ctx.desktop().post('/agent/pins/reorder', { projectId: input.projectId, assetIds: input.assetIds.map((r) => resolved.get(r).id) }));
1092
+ return ok(await ctx.desktop().post('/agent/pins/reorder', { projectId: input.projectId, assetIds: input.assetIds.map((r) => resolved.id(r)) }));
1070
1093
  },
1071
1094
  };
1072
1095
  export const getUsage = {
@@ -1151,8 +1174,8 @@ export const getAsset = {
1151
1174
  input: z.object({ projectId: z.string().uuid(), assetId: z.string().min(1) }).strict(),
1152
1175
  async run(input, ctx) {
1153
1176
  await ctx.desktop().requireCapability('asset-detail', 'reading one asset in full');
1154
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
1155
- return ok(await ctx.desktop().get('/agent/assets/get', { id }));
1177
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
1178
+ return ok(await ctx.desktop().get('/agent/assets/get', { id, projectId: input.projectId }));
1156
1179
  },
1157
1180
  };
1158
1181
  export const linkAssetSource = {
@@ -1166,8 +1189,8 @@ export const linkAssetSource = {
1166
1189
  const refs = [input.assetId, ...(input.imageAssetId ? [input.imageAssetId] : [])];
1167
1190
  const resolved = await resolveAssetRefs(ctx, input.projectId, refs);
1168
1191
  return ok(await ctx.desktop().post('/agent/assets/link-source', {
1169
- assetId: resolved.get(input.assetId).id,
1170
- imageAssetId: input.imageAssetId ? resolved.get(input.imageAssetId).id : null,
1192
+ assetId: resolved.id(input.assetId),
1193
+ imageAssetId: input.imageAssetId ? resolved.id(input.imageAssetId) : null,
1171
1194
  }));
1172
1195
  },
1173
1196
  };
@@ -1184,7 +1207,7 @@ export const transcribeAsset = {
1184
1207
  .strict(),
1185
1208
  async run(input, ctx) {
1186
1209
  await ctx.desktop().requireCapability('transcripts', 'transcripts');
1187
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
1210
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
1188
1211
  const r = await ctx.desktop().post('/agent/assets/transcribe', { assetId: id, ...(input.force ? { force: true } : {}) });
1189
1212
  const what = r.noSpeech ? 'No speech in this asset.' : r.reused ? 'Reused the stored transcript.' : 'Transcribed.';
1190
1213
  const models = r.downloadedModelsMB ? ` Downloaded ${r.downloadedModelsMB} MB of speech models first.` : '';
@@ -1202,7 +1225,7 @@ export const getAssetTranscript = {
1202
1225
  .strict(),
1203
1226
  async run(input, ctx) {
1204
1227
  await ctx.desktop().requireCapability('transcripts', 'transcripts');
1205
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
1228
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
1206
1229
  return ok(await ctx.desktop().get('/agent/assets/transcript', { assetId: id }));
1207
1230
  },
1208
1231
  };
@@ -1220,7 +1243,7 @@ export const editAssetTranscript = {
1220
1243
  .strict(),
1221
1244
  async run(input, ctx) {
1222
1245
  await ctx.desktop().requireCapability('transcript-edit', 'transcript editing');
1223
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
1246
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
1224
1247
  const r = await ctx.desktop().post('/agent/assets/transcript/edit', {
1225
1248
  assetId: id, text: input.text, ...(input.recaption === false ? { recaption: false } : {}),
1226
1249
  });
@@ -1269,7 +1292,7 @@ async function beatTargetBody(ctx, input) {
1269
1292
  return { projectId: input.projectId, clipId: input.clipId };
1270
1293
  if (!input.assetId)
1271
1294
  throw new Error('Name assetId or clipId.');
1272
- return { projectId: input.projectId, assetId: (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id };
1295
+ return { projectId: input.projectId, assetId: (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId) };
1273
1296
  }
1274
1297
  function beatGridWords(r) {
1275
1298
  if (!r.beats || !r.summary)
@@ -1437,7 +1460,7 @@ async function maskTargetBody(ctx, input) {
1437
1460
  return { projectId: input.projectId };
1438
1461
  if (!input.assetId)
1439
1462
  throw new Error('Name assetId or clipId (or maskId, to read or change one mask).');
1440
- return { projectId: input.projectId, assetId: (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id };
1463
+ return { projectId: input.projectId, assetId: (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId) };
1441
1464
  }
1442
1465
  export const getSubjectMask = {
1443
1466
  id: 'slates_get_subject_mask',
@@ -1648,7 +1671,7 @@ export const extractVideoFrame = {
1648
1671
  .strict(),
1649
1672
  async run(input, ctx) {
1650
1673
  await ctx.desktop().requireCapability('frame-extract', 'extracting a frame');
1651
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
1674
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
1652
1675
  return ok(await ctx.desktop().post('/agent/assets/extract-frame', { assetId: id, at: input.at ?? 'first' }));
1653
1676
  },
1654
1677
  };
@@ -1728,6 +1751,10 @@ export const VIDEO_MODELS = [
1728
1751
  // start and end frames OR references (10 images, 5 videos, 5 audio clips).
1729
1752
  // Reference video seconds bill on top of output seconds, so it has a vref key.
1730
1753
  'wan-3.0',
1754
+ // MAGI-2 (added 2026-11-26): 4-30s at 1080p only, sound on or off, start and
1755
+ // end frames OR references (10 images, 5 videos, 5 audio clips). One price per
1756
+ // output second: references and sound do not move it.
1757
+ 'magi-2',
1731
1758
  // Kling 4.0 (added 2026-10-23 beside 3.0, which stays the default Kling):
1732
1759
  // one row with no Standard/Pro split, frames or text only, sound always on.
1733
1760
  // `kling-v4.0` never starts with `kling-v3.0`, so no 3.0 branch can take it.
@@ -1747,21 +1774,6 @@ export const VIDEO_MODELS = [
1747
1774
  'minimax-h3',
1748
1775
  'minimax-h3-max',
1749
1776
  'minimax-h3-max-turbo',
1750
- // LTX-2.5, two seats in one family (2026-08-29). Base is the VOLUME seat —
1751
- // cheapest native 1080p second with sound included, free native audio at every tier,
1752
- // the only row reaching 1440p, and clips up to 20s.
1753
- // Pro is the fidelity seat and is NOT a superset: shorter ladder (no
1754
- // 1440p/4K), shorter clips (6/8/10 only) and ~1/3 dearer.
1755
- //
1756
- // NEVER PREFIX-MATCH: 'ltx-2-5-pro' starts with 'ltx-2-5'. A prefix test
1757
- // bills Pro at base rates AND offers it 1440p/4K and 12-20s durations it
1758
- // cannot render — the same trap as the MiniMax pair, one row worse.
1759
- //
1760
- // Durations are DISCRETE AND EVEN (6,8,10,12,14,16,18,20); the union bounds
1761
- // below stay 3-30 because other rows are wider, so `assertVideoCapabilities`
1762
- // is what refuses an odd second. It reads `values`, not just min/max.
1763
- 'ltx-2-5',
1764
- 'ltx-2-5-pro',
1765
1777
  ];
1766
1778
  // ── Capability-derived param vocabulary + guard ─────────────────
1767
1779
  //
@@ -1812,20 +1824,6 @@ const MINIMAX_FREE_REF_IMAGES_BY_MODEL = {
1812
1824
  'minimax-h3': 5,
1813
1825
  'minimax-h3-max': 4,
1814
1826
  };
1815
- /**
1816
- * The LTX-2.5 pair. A SET, not a prefix test — `ltx-2-5-pro` starts with
1817
- * `ltx-2-5`, and the two rows differ on ladder, duration list AND price.
1818
- *
1819
- * Their cost key is the plainest shape in the file — `{model}-{res}-{N}s` with
1820
- * no suffix ever, because LTX has no paid option: native audio is included at
1821
- * every tier (so no `-audio` variant like Kling) and there is no reference
1822
- * endpoint at all (so no `-ref{K}` variant like H3). Mirrors `ltxCreditKey()`
1823
- * in slate/src/shared/pricing.ts.
1824
- */
1825
- const LTX_MODELS = new Set(['ltx-2-5', 'ltx-2-5-pro']);
1826
- /** Max billed seconds on a Wan 3.0 take: 30s of output plus 15s of reference
1827
- * video, which fal bills "in addition to output duration". */
1828
- const WAN_3_VREF_MAX_TOTAL = 45;
1829
1827
  /** K for the `-ref{K}` suffix: images past the free five, capped by the model's
1830
1828
  * own declared ceiling. 0 for h3-max (no reference transport) and for anything
1831
1829
  * that is not a MiniMax row. Mirrors refImageSurchargeCount() in
@@ -1856,13 +1854,12 @@ export const EDIT_VIDEO_MODELS = [
1856
1854
  'omni-flash-1-2-edit',
1857
1855
  'seedance-2.5-edit',
1858
1856
  ];
1859
- // The op's default, not MODEL_FACTS' edit tier default: the desktop route defaults to the same Kling
1860
- // engine (slate routes.ts, /agent/generation/edit-video), so moving it is a two-repo change.
1861
- const EDIT_VIDEO_DEFAULT = 'kling-v3.0-omni-edit';
1857
+ // The op's default, matching MODEL_FACTS' edit tier default and slate routes.ts (/agent/generation/edit-video).
1858
+ const EDIT_VIDEO_DEFAULT = 'seedance-2.5-edit';
1862
1859
  /** The edit engines that take character and style references (elements); the run refuses them on the rest. */
1863
1860
  const EDIT_VIDEO_ELEMENT_MODELS = EDIT_VIDEO_MODELS.filter((m) => (getModelCapability(m)?.maxIngredientImages ?? 0) > 0);
1864
1861
  const EDIT_VIDEO_ELEMENT_CAP = Math.max(...EDIT_VIDEO_ELEMENT_MODELS.map((m) => getModelCapability(m)?.maxIngredientImages ?? 0));
1865
- const EDIT_VIDEO_ELEMENTS_ONLY = `Only ${EDIT_VIDEO_ELEMENT_MODELS.join(' and ')} take them; the other engines refuse them.`;
1862
+ const EDIT_VIDEO_ELEMENTS_ONLY = `Only ${EDIT_VIDEO_ELEMENT_MODELS.join(', ')} take them; the other engines refuse them.`;
1866
1863
  /**
1867
1864
  * Source-clip length an edit engine accepts, read from the SSOT.
1868
1865
  *
@@ -1883,9 +1880,10 @@ function editClipBounds(model) {
1883
1880
  const EDIT_VIDEO_RESOLUTIONS = videoResolutionUnion(['seedance-2.5-edit', 'omni-flash-1-2-edit']);
1884
1881
  export const estimateGenerationCost = {
1885
1882
  id: 'slates_estimate_generation_cost',
1886
- description: 'Quote credits before any generate_* op. For saved Shots, a board or a scene, quote with slates_get_board_quote instead. Accepts the generation model ids and parameters (edit seats other than Kling, lip-sync and motion-transfer engines need an exact registry cost key), or an exact registry cost key. Show the user the total and wait for their OK before the generate call; the result flags requires_confirm above the threshold and carries the model\'s prompting card.',
1883
+ description: 'Quote credits before generating. For saved Shots, boards and scenes use slates_get_board_quote. Pass a model id and settings or an exact cost key (required for non-Kling edits, lip sync and motion transfer). Show the total and wait for approval. Returns the model card and requires_confirm above the threshold.',
1887
1884
  input: z.object({
1888
- model: z.string().describe('Base model id as passed to the generate op (e.g. "seedance-2", "kling-v3.0-std", "nano-banana-2-1") or an exact registry cost key ("nano-banana-2-1-2k", "seedance-2-1080p-8s")'),
1885
+ model: z.string().describe('Generation model id (e.g. "seedance-2") or exact cost key (e.g. "seedance-2-1080p-8s").'),
1886
+ prompt: z.string().optional().describe('Check prompt length before quoting.'),
1889
1887
  quantity: z.number().int().min(1).max(10).optional().describe('Number of generations (default 1)'),
1890
1888
  // Video windows and resolutions GENERATED from MODEL_CAPABILITIES. The
1891
1889
  // hand-typed "Video 3-15" here was wrong the day seedance-2.5 (4-30s)
@@ -1898,7 +1896,7 @@ export const estimateGenerationCost = {
1898
1896
  // one where someone edits a table and forgets there were two.
1899
1897
  duration: z.number().int().min(1).max(360).optional().describe(`Seconds; cost scales linearly. Required with a video or PER-SECOND audio base id. Per-model windows: see slates_generate_video's duration. Audio: seed-audio ${SEED_AUDIO_MIN_SECONDS}-${SEED_AUDIO_MAX_SECONDS} (⚠️ the requested duration IS the bill), eleven-sfx ${ELEVEN_SFX_MIN_SECONDS}-${ELEVEN_SFX_MAX_SECONDS}. ⛔ NOT for ${TTS_MODEL} — pass \`characters\`.`),
1900
1898
  characters: z.number().int().min(1).max(TTS_MAX_CHARACTERS).optional().describe(`${TTS_MODEL} only — the LENGTH OF THE TEXT to speak (${TTS_BUCKET_CHARS}-char buckets).`),
1901
- videoResolution: zEnum(VIDEO_RESOLUTIONS).optional().describe('Video only. Omitted, each model quotes at its own default. Per-model ladders: see slates_generate_video\'s videoResolution.'),
1899
+ videoResolution: zEnum(VIDEO_RESOLUTIONS).optional().describe('Video only. Omitted, each model quotes at its own default. Ladders: see slates_generate_video\'s videoResolution.'),
1902
1900
  resolution: z.enum(['1k', '2k', '3k', '4k']).optional().describe('Image only. Omit for the model default; pass the same value to generation.'),
1903
1901
  quality: z.enum(GPT_QUALITY_TIERS).optional().describe(`GPT Image tier; default ${DEFAULT_GPT_QUALITY}.`),
1904
1902
  aspectRatio: z.string().optional().describe('GPT Image: the frame shape changes the price; pass the generation\'s value.'),
@@ -1906,11 +1904,15 @@ export const estimateGenerationCost = {
1906
1904
  seedanceDraft: z.boolean().optional().describe('Create a finishable Seedance 2.5 preview at 480p.'),
1907
1905
  seedanceFace: z.boolean().optional().describe('Seedance Face row, for an AI character\'s face.'),
1908
1906
  seedanceRealFace: z.boolean().optional().describe('Seedance with a consented real person (premium key).'),
1909
- videoRefSeconds: z.number().nonnegative().optional().describe('Combined reference-video seconds, measured from the clips.'),
1910
- audioRefSeconds: z.number().nonnegative().optional().describe('Combined reference-audio seconds, including attached character voices.'),
1911
- referenceImages: z.number().int().min(0).optional().describe(`MiniMax H3 rows and seedream-5-5 — how many reference IMAGES the generation will carry. They are a paid dimension of the cost key, so a quote that omits this UNDER-REPORTS a reference-heavy job. seedream-5-5 pays for every input image, @mention pictures included, and an edit's source picture counts as one. The MiniMax allowances differ: minimax-h3 gives ${MINIMAX_FREE_REF_IMAGES_BY_MODEL['minimax-h3']} free, minimax-h3-max gives ${MINIMAX_FREE_REF_IMAGES_BY_MODEL['minimax-h3-max']}; start/end frames are free on both rows and are not reference images. Ignored by every other model.`),
1907
+ videoReferenceSecondsEach: z.array(z.number().nonnegative()).optional().describe('Seconds of each reference video, one per clip. Never the sum.'),
1908
+ videoRefSeconds: z.number().nonnegative().optional().describe('DEPRECATED: one clip.'),
1909
+ audioRefSeconds: z.number().nonnegative().optional().describe('Combined reference-audio seconds, attached voices too.'),
1910
+ referenceImages: z.number().int().min(0).optional().describe(`MiniMax H3 and seedream-5-5: how many reference IMAGES the generation carries. A paid dimension of the cost key: a quote without it UNDER-REPORTS a reference-heavy job. seedream-5-5 pays for every input image, @mention pictures included, and an edit's source picture counts as one. minimax-h3 gives ${MINIMAX_FREE_REF_IMAGES_BY_MODEL['minimax-h3']} free, minimax-h3-max ${MINIMAX_FREE_REF_IMAGES_BY_MODEL['minimax-h3-max']}; start/end frames are free and are not reference images. Ignored by every other model.`),
1912
1911
  }),
1913
1912
  async run(input, ctx) {
1913
+ const lengthError = promptLengthError(resolveVideoModel(input.model)?.model ?? input.model, input.prompt);
1914
+ if (lengthError)
1915
+ throw new Error(lengthError);
1914
1916
  // A retired seat is never quoted: its keys still bill older desktops, and `nano-banana-2-1k` (the
1915
1917
  // retired Nano Banana 2 at 1K) would otherwise answer an agent that meant Nano Banana 2.1.
1916
1918
  const retired = retiredModelOfKey(input.model);
@@ -1938,8 +1940,14 @@ export const estimateGenerationCost = {
1938
1940
  // billed `high`, so the op the doctrine tells agents to call before every
1939
1941
  // generation quoted 1 cr for a 2 cr job. Four separate copies of one
1940
1942
  // default is what made that possible; there are now none.
1941
- if (img)
1942
- key = imageCostKey(img, input.resolution ?? defaultImageResolutionFor(img), input.quality, input.aspectRatio, input.referenceImages ?? 0);
1943
+ if (img) {
1944
+ // The gate generation runs, so a quote never prices what generation refuses.
1945
+ const resolution = input.resolution ?? defaultImageResolutionFor(img);
1946
+ const capErr = assertImageCapabilities({ model: img, aspectRatio: input.aspectRatio, resolution });
1947
+ if (capErr)
1948
+ return ok(capErr);
1949
+ key = imageCostKey(img, resolution, input.quality, input.aspectRatio, input.referenceImages ?? 0);
1950
+ }
1943
1951
  }
1944
1952
  // 2a) audio base id → seconds. Both surfaces bill per second, so a
1945
1953
  // duration is always required. Runs BEFORE the video resolver: it is
@@ -2012,6 +2020,14 @@ export const estimateGenerationCost = {
2012
2020
  message: 'Kling O3 edit bills per second of output (≈ the source clip length, rounded up) — pass duration.',
2013
2021
  });
2014
2022
  }
2023
+ const clip = editClipBounds(input.model);
2024
+ if (input.duration < clip.min || input.duration > clip.max) {
2025
+ return ok({
2026
+ requires_clarification: true,
2027
+ missing: ['duration'],
2028
+ message: `${input.model} edits clips of ${clip.min}-${clip.max} seconds; ${input.duration}s is outside that, and slates_edit_video refuses it. Trim the source or pick another edit engine.`,
2029
+ });
2030
+ }
2015
2031
  key = klingEditCostKey(input.model, input.duration);
2016
2032
  }
2017
2033
  // 3) video base id (or cost-key spelling) → the same forgiving resolver
@@ -2032,11 +2048,15 @@ export const estimateGenerationCost = {
2032
2048
  // a quote can never promise something generation then refuses.
2033
2049
  const capErr = assertVideoCapabilities({
2034
2050
  model: resolved.model,
2051
+ aspectRatio: input.aspectRatio,
2035
2052
  videoResolution: input.videoResolution ?? resolved.videoResolution,
2036
2053
  duration,
2037
2054
  });
2038
2055
  if (capErr)
2039
2056
  return ok(capErr);
2057
+ const refErr = referenceSecondsRefusal(resolved.model, referenceVideoClips(input));
2058
+ if (refErr)
2059
+ return ok(refErr);
2040
2060
  key = videoCostKey({
2041
2061
  model: resolved.model,
2042
2062
  duration,
@@ -2052,12 +2072,16 @@ export const estimateGenerationCost = {
2052
2072
  seedanceFace: input.seedanceFace ?? resolved.seedanceFace,
2053
2073
  seedanceRealFace: input.seedanceRealFace ?? resolved.seedanceRealFace,
2054
2074
  referenceImages: input.referenceImages ?? resolved.referenceImages,
2055
- videoRefSeconds: input.videoRefSeconds, audioRefSeconds: input.audioRefSeconds,
2075
+ videoReferenceSecondsEach: referenceVideoClips(input), audioRefSeconds: input.audioRefSeconds,
2056
2076
  });
2057
2077
  }
2058
2078
  }
2059
2079
  await loadDynamicPrice(ctx, byKey, key);
2060
2080
  const perCredits = key != null ? byKey.get(key) : undefined;
2081
+ if (key != null && perCredits == null && key !== input.model) {
2082
+ // The model is known and these parameters built a key the price list lacks: name the key, not the model.
2083
+ throw new Error(`No price for ${key}: ${input.model} has no row with these parameters. Check duration, resolution, quality and the reference counts against slates_generate_* for this model, or pass an exact registry cost key from slates_list_available_models.`);
2084
+ }
2061
2085
  if (key == null || perCredits == null) {
2062
2086
  // Every id in the error comes from the SSOT arrays. The image half was
2063
2087
  // hand-typed and named three of six, so an agent that mis-spelled
@@ -2073,10 +2097,11 @@ export const estimateGenerationCost = {
2073
2097
  // It is here rather than in a param description because a description is
2074
2098
  // paid for on every turn of every session and read once — this is paid for
2075
2099
  // only by the call that is about to use the model.
2076
- const skill = promptingSkillFor(input.model);
2100
+ // A tool or engine key (upscale, the reasoning model) has no guide and gets no card.
2101
+ const skill = resolveGuideTopic(input.model);
2077
2102
  // From the user's brain: their My brain card for this model rides first when they wrote one (craft-cards.ts).
2078
- const card = describeCraftCard(skill, brainSkills().skills[skill]);
2079
- const banned = describeBannedTokensForSkill(skill);
2103
+ const card = skill ? describeCraftCard(skill, brainSkills().skills[skill]) : '';
2104
+ const banned = skill ? describeBannedTokensForSkill(skill) : '';
2080
2105
  // Before the card on purpose: the desktop strips a repeated card by cutting
2081
2106
  // the text at "--- HOW TO PROMPT", and this line must survive that.
2082
2107
  const ownImage = IMAGE_MODELS.includes(input.model) ? input.model : null;
@@ -2159,6 +2184,8 @@ function compactAsset(a) {
2159
2184
  prompt: typeof r.prompt === 'string' ? r.prompt : null,
2160
2185
  }),
2161
2186
  type: r.type,
2187
+ // A clip's measured length in seconds: what reference seconds are billed and capped on.
2188
+ ...(typeof r.duration === 'number' && r.duration > 0 ? { duration: Math.round(r.duration * 100) / 100 } : {}),
2162
2189
  // Only when it IS one. A compact row pays for every key on every asset,
2163
2190
  // and "not a favorite" is the default the app writes — absent says it.
2164
2191
  ...(r.isFavorite === true ? { isFavorite: true } : {}),
@@ -2166,6 +2193,25 @@ function compactAsset(a) {
2166
2193
  };
2167
2194
  }
2168
2195
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2196
+ const noAssetMatching = (ref) => `No asset matching "${ref}" in this project. Codes resolve at call time — ` +
2197
+ `call slates_list_assets (search: "${ref}") to see what actually exists, then pass the exact code or id. Never guess.`;
2198
+ /**
2199
+ * What `resolveAssetRefs` returns. `id(ref)` and `row(ref)` throw the teaching
2200
+ * error instead of handing back undefined, so a caller cannot reach a bare
2201
+ * TypeError the way `.id(ref)` did on a blank ref (2026-11-24).
2202
+ * `scripts/image-op-guards-check.mjs` refuses `.id(…)` in the ops.
2203
+ */
2204
+ class AssetRefs extends Map {
2205
+ row(ref) {
2206
+ const row = this.get(ref);
2207
+ if (!row)
2208
+ throw new Error(noAssetMatching(ref));
2209
+ return row;
2210
+ }
2211
+ id(ref) {
2212
+ return this.row(ref).id;
2213
+ }
2214
+ }
2169
2215
  /**
2170
2216
  * Resolve asset references that may be UUIDs OR badge codes ("IMG-A8",
2171
2217
  * "vid-v3", bare "A8"). Codes resolve against the project's asset list AT
@@ -2173,12 +2219,19 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
2173
2219
  * user creates assets in the Slates UI mid-chat; an agent that guesses or
2174
2220
  * reuses a nearby UUID for a code it never looked up burns real dollars on
2175
2221
  * the wrong start frame (observed live: "use A8" generated from A5).
2176
- * Unknown codes throw a teaching error; unknown UUIDs pass through for the
2177
- * desktop route to validate.
2222
+ * Unknown codes and blank refs throw a teaching error, and so does a UUID that
2223
+ * is not in the named project: an id copied from another project never reaches
2224
+ * a route as this project's asset. Two cases let a UUID through for the route
2225
+ * to validate: no project was named (the route falls back to the open one), or
2226
+ * the caller says the reference may cross projects (`anyProject`, a timeline
2227
+ * clip, the one cross-project reference Slates allows).
2178
2228
  */
2179
- async function resolveAssetRefs(ctx, projectId, refs) {
2180
- const out = new Map();
2181
- const pending = [...new Set(refs.filter((r) => typeof r === 'string' && r.trim().length > 0))];
2229
+ async function resolveAssetRefs(ctx, projectId, refs, scope = {}) {
2230
+ const out = new AssetRefs();
2231
+ if (refs.some((r) => typeof r === 'string' && r.trim().length === 0)) {
2232
+ throw new Error('An asset reference is blank. Pass an asset code (IMG-A8) or id: call slates_list_assets to see what exists.');
2233
+ }
2234
+ const pending = [...new Set(refs.filter((r) => typeof r === 'string'))];
2182
2235
  if (pending.length === 0)
2183
2236
  return out;
2184
2237
  const { assets } = await ctx.desktop().get('/agent/assets', { projectId });
@@ -2189,6 +2242,8 @@ async function resolveAssetRefs(ctx, projectId, refs) {
2189
2242
  const raw = ref.trim();
2190
2243
  if (UUID_RE.test(raw)) {
2191
2244
  const row = byId.get(raw.toLowerCase());
2245
+ if (!row && projectId && !scope.anyProject)
2246
+ throw new Error(noAssetMatching(ref));
2192
2247
  out.set(ref, {
2193
2248
  id: raw,
2194
2249
  code: row ? (row.code ?? null) : null,
@@ -2203,10 +2258,8 @@ async function resolveAssetRefs(ctx, projectId, refs) {
2203
2258
  const prefixed = norm.startsWith('A') ? `IMG-${norm}` : norm.startsWith('V') ? `VID-${norm}` : `AUD-${norm}`;
2204
2259
  row = byCode.get(prefixed);
2205
2260
  }
2206
- if (!row) {
2207
- throw new Error(`No asset matching "${ref}" in this project. Codes resolve at call time — ` +
2208
- `call slates_list_assets (search: "${ref}") to see what actually exists, then pass the exact code or id. Never guess.`);
2209
- }
2261
+ if (!row)
2262
+ throw new Error(noAssetMatching(ref));
2210
2263
  out.set(ref, {
2211
2264
  id: String(row.id),
2212
2265
  code: row.code ?? null,
@@ -2387,7 +2440,7 @@ export const generateChatGptImage = {
2387
2440
  await desktop.requireCapability('media-folder', 'choosing the folder a result lands in');
2388
2441
  const refs = await resolveAssetRefs(ctx, input.projectId, input.referenceAssetIds ?? []);
2389
2442
  const result = await desktop.post('/agent/generation/chatgpt-image', {
2390
- ...input, referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.get(id).id),
2443
+ ...input, referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.id(id)),
2391
2444
  });
2392
2445
  return ok(result, JSON.stringify(result) + '\n' + describeResolvedRefs((input.referenceAssetIds ?? []).map(ref => ({ ref, role: 'reference image' })), refs));
2393
2446
  },
@@ -2417,8 +2470,8 @@ export const saveExternalImage = {
2417
2470
  ]);
2418
2471
  const result = await desktop.post('/agent/assets/external-image', {
2419
2472
  ...input,
2420
- assetId: input.assetId ? refs.get(input.assetId).id : undefined,
2421
- referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.get(id).id),
2473
+ assetId: input.assetId ? refs.id(input.assetId) : undefined,
2474
+ referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.id(id)),
2422
2475
  });
2423
2476
  return ok(result, JSON.stringify(result) + '\n' + describeResolvedRefs((input.referenceAssetIds ?? []).map(ref => ({ ref, role: 'reference image' })), refs));
2424
2477
  },
@@ -2505,7 +2558,7 @@ export const updateAsset = {
2505
2558
  await desktop.requireCapability('asset-naming', 'naming an asset');
2506
2559
  if (proxying)
2507
2560
  await desktop.requireCapability('proxies', "a clip's proxy");
2508
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
2561
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
2509
2562
  const result = {};
2510
2563
  if (naming) {
2511
2564
  const { asset } = await desktop.post('/agent/assets/update', {
@@ -2603,7 +2656,7 @@ export const pinReferences = {
2603
2656
  async run(input, ctx) {
2604
2657
  await ctx.desktop().requireCapability('pins', 'pinned references');
2605
2658
  const resolved = await resolveAssetRefs(ctx, input.projectId, input.assetIds);
2606
- return ok(await ctx.desktop().post('/agent/pins', { projectId: input.projectId, assetIds: input.assetIds.map((r) => resolved.get(r).id) }));
2659
+ return ok(await ctx.desktop().post('/agent/pins', { projectId: input.projectId, assetIds: input.assetIds.map((r) => resolved.id(r)) }));
2607
2660
  },
2608
2661
  };
2609
2662
  export const unpinReference = {
@@ -2613,7 +2666,7 @@ export const unpinReference = {
2613
2666
  async run(input, ctx) {
2614
2667
  await ctx.desktop().requireCapability('pins', 'pinned references');
2615
2668
  const resolved = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
2616
- return ok(await ctx.desktop().post('/agent/pins/remove', { projectId: input.projectId, assetId: resolved.get(input.assetId).id }));
2669
+ return ok(await ctx.desktop().post('/agent/pins/remove', { projectId: input.projectId, assetId: resolved.id(input.assetId) }));
2617
2670
  },
2618
2671
  };
2619
2672
  export const moveAssetsToProject = {
@@ -2796,6 +2849,7 @@ export const generateCharacterIdentity = {
2796
2849
  const quote = await sheetConfirmGate(ctx, input, (input.model ?? toolModelFor('character-sheet')));
2797
2850
  if (quote)
2798
2851
  return quote;
2852
+ approvedSpend(ctx);
2799
2853
  const made = await ctx.desktop().post('/agent/characters/generate-identity', {
2800
2854
  characterId: input.characterId,
2801
2855
  projectId: input.projectId,
@@ -2830,6 +2884,7 @@ export const generateEnvironmentPlate = {
2830
2884
  const quote = await sheetConfirmGate(ctx, input, toolModelFor('environment-plate'));
2831
2885
  if (quote)
2832
2886
  return quote;
2887
+ approvedSpend(ctx);
2833
2888
  return ok(await ctx.desktop().post('/agent/environments/generate-plate', {
2834
2889
  environmentId: input.environmentId,
2835
2890
  projectId: input.projectId,
@@ -3184,15 +3239,99 @@ const HEADLESS_IMAGE_MODEL = 'nano-banana-2-1';
3184
3239
  * value no model accepts. It used to be a hand-typed eleven-value list whose
3185
3240
  * `9:21` exists in ZERO models; that phantom is gone by construction.
3186
3241
  *
3187
- * ⚠️ STILL A UNION, NOT A PER-MODEL CHECK. GPT Image takes five of these
3188
- * ten and the other five would be accepted here. The image param surface has
3189
- * not been audited (aspect ratios, resolution classes, per-model reference
3190
- * caps) — that audit is the named follow-up in
3191
- * `second-brain/plans/2026-08-16-slates-model-capability-ssot.md` §5. The machinery
3192
- * to close it already exists: call `checkAspectRatio(model, ratio)` the way
3193
- * `assertVideoCapabilities` does below.
3242
+ * It is the union, so the per-model narrowing is `assertImageCapabilities`
3243
+ * below, which every image entry point runs.
3194
3244
  */
3195
3245
  const IMAGE_ASPECT_RATIOS = aspectRatioUnion(IMAGE_MODELS);
3246
+ /**
3247
+ * The per-model image gate: the aspect ratio and the resolution rung the seat
3248
+ * declares in `MODEL_CAPABILITIES`. Generate, edit, the estimate and a saved
3249
+ * image Shot all run this one function, so a quote, a recipe and a generation
3250
+ * cannot disagree about what a seat takes.
3251
+ *
3252
+ * Why: GPT Image takes five of the union's ratios. A 4:5 or 21:9 ask passed,
3253
+ * was quoted at the 16:9 key, and the desktop's size table rendered a 16:9
3254
+ * frame for it and billed it (2026-11-24). An off-ladder rung built a cost key
3255
+ * the registry lacks and failed as "Unknown model", or, on Seedream, quoted the
3256
+ * default rung's price for a rung generation then refused.
3257
+ */
3258
+ export function assertImageCapabilities(input, field = { resolution: 'resolution' }) {
3259
+ const ratioErr = checkAspectRatio(input.model, input.aspectRatio, AGENT_ROUTE_PROVIDER);
3260
+ if (ratioErr)
3261
+ return { requires_clarification: true, missing: ['aspectRatio'], message: ratioErr };
3262
+ const rungs = MODEL_CAPABILITIES[input.model]?.imageResolutions ?? [];
3263
+ if (input.resolution && rungs.length > 0 && !rungs.includes(input.resolution)) {
3264
+ return {
3265
+ requires_clarification: true,
3266
+ missing: [field.resolution],
3267
+ message: `${input.model} accepts ${rungs.join(', ')}, not ${input.resolution}. Pick one of those, or switch to a model that renders ${input.resolution}.`,
3268
+ };
3269
+ }
3270
+ return null;
3271
+ }
3272
+ /** Reference images an image model reads in one request, from its capability row. */
3273
+ const imageReferenceCap = (model) => MODEL_CAPABILITIES[model]?.maxRefImages ?? 0;
3274
+ /**
3275
+ * The refusal for more references than the model reads. The desktop sends the
3276
+ * first `cap` and leaves the rest out, so a call over the cap would run, and
3277
+ * bill, without references the caller named. `cap` comes from the capability
3278
+ * row, never a typed number.
3279
+ */
3280
+ function referenceCapRefusal(model, count, cap, param, what = 'reference images') {
3281
+ if (count <= cap)
3282
+ return null;
3283
+ return {
3284
+ requires_clarification: true,
3285
+ missing: [param],
3286
+ message: cap > 0
3287
+ ? `Nothing ran. ${model} reads at most ${cap} ${what} and this call names ${count}. Remove ${count - cap}, or pick a model that reads more.`
3288
+ : `Nothing ran. ${model} reads no ${what}. Remove them, or pick a model that reads them.`,
3289
+ };
3290
+ }
3291
+ /**
3292
+ * The image params that only some calls consume, each with the condition under
3293
+ * which it reaches the request. A param set where its condition fails was
3294
+ * dropped while the generation ran and billed: reference URLs beside a
3295
+ * projectId, a transparent background on a seat without one (2026-11-24).
3296
+ * Generate and edit both run this table, and `scripts/image-op-guards-check.mjs`
3297
+ * proves every row refuses.
3298
+ */
3299
+ function droppedImageParams(model, input) {
3300
+ const rows = [
3301
+ {
3302
+ param: 'referenceImageUrls',
3303
+ set: (input.referenceImageUrls?.length ?? 0) > 0,
3304
+ consumed: !input.projectId,
3305
+ why: 'URLs reach the headless path only. With a projectId, upload each picture with slates_upload_reference_image and pass referenceAssetIds, or drop projectId for a headless run.',
3306
+ },
3307
+ {
3308
+ param: 'backgroundMode',
3309
+ set: input.backgroundMode !== undefined && input.backgroundMode !== 'auto',
3310
+ consumed: takesBackgroundMode(model),
3311
+ why: `${model} has no background control, so the picture would come back opaque. Seats that take it: ${IMAGE_MODELS.filter(takesBackgroundMode).join(', ')}.`,
3312
+ },
3313
+ {
3314
+ param: 'folderId',
3315
+ set: input.folderId !== undefined && input.folderId !== null,
3316
+ consumed: !!input.projectId,
3317
+ why: 'A folder belongs to a project. Pass the projectId it lives in, or drop folderId.',
3318
+ },
3319
+ {
3320
+ param: 'requestId',
3321
+ set: input.requestId !== undefined,
3322
+ consumed: !input.projectId,
3323
+ why: 'A requestId resumes a headless image only. With a projectId the desktop keeps the generation: read it with slates_get_generation_status.',
3324
+ },
3325
+ ];
3326
+ const dropped = rows.filter((r) => r.set && !r.consumed);
3327
+ if (dropped.length === 0)
3328
+ return null;
3329
+ return {
3330
+ requires_clarification: true,
3331
+ missing: dropped.map((r) => r.param),
3332
+ message: `Nothing ran. ${dropped.map((r) => `${r.param}: ${r.why}`).join(' ')}`,
3333
+ };
3334
+ }
3196
3335
  // Registry cost-key for an image model+resolution. Mirrors imageCreditKey()
3197
3336
  // in slate/src/shared/pricing.ts — MUST byte-match it (the same hard rule as
3198
3337
  // videoCostKey): Nano Banana 2.1 and FLUX 3 price per resolution, Seedream is
@@ -3309,7 +3448,7 @@ export const generateImage = {
3309
3448
  // demonstrably skipped the call that would have taught it.
3310
3449
  describeBannedTokens('image'),
3311
3450
  input: z.object({
3312
- prompt: z.string().min(1).max(4000),
3451
+ prompt: z.string().min(1),
3313
3452
  // Routing GENERATED from MODEL_FACTS.
3314
3453
  model: zEnum(IMAGE_MODELS).optional().describe(`Image model. Omitted: ${DEFAULT_IMAGE_MODEL} with projectId, ${HEADLESS_IMAGE_MODEL} (the only headless seat) without.\n` +
3315
3454
  `${describeRouting('image')}\n` +
@@ -3320,17 +3459,15 @@ export const generateImage = {
3320
3459
  backgroundMode: z.enum(GPT_BACKGROUNDS).optional().describe(`${IMAGE_MODELS.filter(takesBackgroundMode).join(', ')} only. transparent = alpha channel (PNG). Free.`),
3321
3460
  aspectRatio: zEnum(IMAGE_ASPECT_RATIOS).optional().describe(`Pick from the use case: cinematic 16:9 · TikTok/Reels 9:16 · IG square 1:1 · ultra-wide 21:9. 1:1 costs most on GPT Image. Per model: ${describeAspectRatios(IMAGE_MODELS)}`),
3322
3461
  count: z.number().int().min(1).max(MAX_IMAGE_VARIATIONS).optional().describe(`Variations of this one prompt: every image gets the same prompt, so different subjects are separate calls. Up to ${MAX_IMAGE_VARIATIONS} with projectId; headless caps at ${HEADLESS_BATCH_CAP}. A 2x2 or 3x3 grid in one picture is a Shot's or the prompt box's Grid (params.gridMode), not count.`),
3323
- referenceImageUrls: z.array(z.string().url()).max(14).optional().describe(`Headless (no projectId) ${HEADLESS_IMAGE_MODEL} only. With a projectId, upload via slates_upload_reference_image. Label every image role in the prompt.`),
3324
- referenceAssetIds: z.array(z.string()).max(16).optional().describe(`Project assets as references — UUIDs or badge codes ("IMG-A8"), resolved at call time. Requires projectId. Caps: ${describeReferenceImageCaps(IMAGE_MODELS)}. Label every reference role in the prompt.`),
3462
+ referenceImageUrls: z.array(z.string().url()).max(imageReferenceCap(HEADLESS_IMAGE_MODEL)).optional().describe(`Headless (no projectId) ${HEADLESS_IMAGE_MODEL} only. With a projectId, upload via slates_upload_reference_image. Label every image role in the prompt.`),
3463
+ referenceAssetIds: z.array(z.string()).max(Math.max(...IMAGE_MODELS.map(imageReferenceCap))).optional().describe(`Project assets as references — UUIDs or badge codes ("IMG-A8"), resolved at call time. Requires projectId. Caps: ${describeReferenceImageCaps(IMAGE_MODELS)}; over a model's cap is refused, never trimmed. Label every reference role in the prompt.`),
3325
3464
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
3326
3465
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
3327
- approvedCredits: z.number().int().positive().optional().describe('Only after a reply with `quote_exceeded`: the credits that reply named, once the user has approved them. The desktop counts @mention pictures as paid inputs on seedream-5-5 and runs nothing above the approved total.'),
3466
+ approvedCredits: z.number().int().positive().optional().describe('With confirm=true: the approvedCredits a reply named (its quote, or a quote_exceeded price), once the user has approved it. The desktop counts @mention pictures as paid inputs on seedream-5-5 and runs nothing above it.'),
3467
+ requestId: z.string().uuid().optional().describe('Headless only: the requestId a reply named. The same call sent with it again returns the image that request bought, never a second one.'),
3328
3468
  folderId: z.string().uuid().nullable().optional().describe(`${FOLDER_DESCRIBE} Needs projectId.`),
3329
3469
  }),
3330
3470
  async run(input, ctx) {
3331
- // A desktop before the folder rule ignores folderId and files at the root.
3332
- if (input.folderId !== undefined)
3333
- await ctx.desktop().requireCapability('media-folder', 'choosing the folder a result lands in');
3334
3471
  // Clarification gate: aspectRatio + resolution must be deliberate.
3335
3472
  // Mirrors the cost confirm gate — defaults silently wasted credits
3336
3473
  // (1:1 when user wanted 16:9, 4k when 1k would have done). The LLM
@@ -3346,6 +3483,15 @@ export const generateImage = {
3346
3483
  ? await defaultImageSeatFor(() => ctx.desktop(), input.model, `${input.model ?? DEFAULT_IMAGE_MODEL} generation`)
3347
3484
  : { model: input.model ?? HEADLESS_IMAGE_MODEL, note: '' };
3348
3485
  const imageModel = seat.model;
3486
+ const lengthError = promptLengthError(imageModel, input.prompt);
3487
+ if (lengthError)
3488
+ throw new Error(lengthError);
3489
+ const dropped = droppedImageParams(imageModel, input);
3490
+ if (dropped)
3491
+ return ok(dropped);
3492
+ // A desktop before the folder rule ignores folderId and files at the root.
3493
+ if (input.folderId !== undefined)
3494
+ await ctx.desktop().requireCapability('media-folder', 'choosing the folder a result lands in');
3349
3495
  requireGuideRead(ctx, imageModel);
3350
3496
  const promptWarning = bannedTokenWarning(input.prompt, 'image', promptingSkillFor(imageModel));
3351
3497
  input = { ...input, resolution: input.resolution ?? defaultImageResolutionFor(imageModel) };
@@ -3368,11 +3514,9 @@ export const generateImage = {
3368
3514
  });
3369
3515
  }
3370
3516
  const resolution = input.resolution;
3371
- const resolutions = MODEL_CAPABILITIES[imageModel]?.imageResolutions ?? [];
3372
- if (resolution && !resolutions.includes(resolution)) {
3373
- return ok({ requires_clarification: true, missing: ['resolution'],
3374
- message: `${imageModel} accepts ${resolutions.join(', ')}.` });
3375
- }
3517
+ const capErr = assertImageCapabilities({ model: imageModel, aspectRatio: input.aspectRatio, resolution });
3518
+ if (capErr)
3519
+ return ok(capErr);
3376
3520
  // Only HEADLESS_IMAGE_MODEL has a headless path — everything else routes
3377
3521
  // through the desktop generation pipeline, which needs a project.
3378
3522
  if (imageModel !== HEADLESS_IMAGE_MODEL && !input.projectId) {
@@ -3413,6 +3557,11 @@ export const generateImage = {
3413
3557
  message: `count above ${HEADLESS_BATCH_CAP} needs a projectId. The headless path is one request and ${HEADLESS_IMAGE_MODEL} caps it at ${HEADLESS_BATCH_CAP}; with a projectId the desktop fires them as separate generations and the limit is ${MAX_IMAGE_VARIATIONS}.`,
3414
3558
  });
3415
3559
  }
3560
+ // Past the model's cap the desktop sends the first ones and leaves the rest out, so the picture
3561
+ // would be made without references the caller named: refused here, before any spend.
3562
+ const overCap = referenceCapRefusal(imageModel, referenceAssetIds.length + (input.referenceImageUrls?.length ?? 0), imageReferenceCap(imageModel), input.referenceImageUrls?.length ? 'referenceImageUrls' : 'referenceAssetIds');
3563
+ if (overCap)
3564
+ return ok(overCap);
3416
3565
  let refEcho = '';
3417
3566
  if (referenceAssetIds.length > 0) {
3418
3567
  await ctx.desktop().requireCapability('image-references', 'reference images on image generation');
@@ -3450,20 +3599,32 @@ export const generateImage = {
3450
3599
  if (!entry)
3451
3600
  throw new Error(`Model not in registry: ${costKey}`);
3452
3601
  const totalCents = creditCost(entry) * (input.count ?? 1);
3602
+ // A seat that bills each input picture is held to a ceiling in the desktop's unit (list credits): the quote, or a
3603
+ // higher approved figure, which a confirm shows the user first (`toolCeiling`).
3604
+ const perInput = !!input.projectId && billsEachInputImage(sentModel);
3605
+ const listQuote = listCredits(entry) * (input.count ?? 1);
3606
+ const ceiling = toolCeiling(listQuote, perInput ? requestedCredits(ctx, input) : undefined);
3607
+ // A headless purchase is made under an id minted here and named in every reply, so a call whose answer is lost
3608
+ // is repeated with it and returns what it bought (`/proxy/generate` keeps one live job per id).
3609
+ const pressId = input.projectId ? undefined : (input.requestId ?? randomUUID());
3610
+ const press = pressId ? { requestId: pressId } : {};
3611
+ const pressText = pressId ? ` Pass requestId=${pressId} with it.` : '';
3453
3612
  // Confirm gate. Fires above CONFIRM_CREDITS, AND (look-first, mirroring
3454
3613
  // slates_generate_video) whenever reference assets are involved
3455
3614
  // regardless of cost — the LLM must see what it's referencing before
3456
3615
  // committing spend.
3457
- if ((totalCents > CONFIRM_CREDITS || referenceAssetIds.length > 0) && !input.confirm) {
3616
+ if ((totalCents > CONFIRM_CREDITS || referenceAssetIds.length > 0 || ceiling.raised) && !input.confirm) {
3458
3617
  if (referenceAssetIds.length === 0) {
3459
3618
  return ok({
3460
3619
  requires_confirm: true,
3461
3620
  model: costKey,
3462
3621
  estimated_cents: totalCents,
3463
3622
  estimated_credits: totalCents,
3623
+ approvedCredits: ceiling.credits,
3624
+ ...press,
3464
3625
  ...(promptWarning ? { prompt_warning: promptWarning } : {}),
3465
3626
  message: (promptWarning ? `${promptWarning}\n\n` : '') +
3466
- `Cost exceeds ${CONFIRM_CREDITS} credits. Re-call with confirm=true to proceed, or pick a smaller resolution / count.`,
3627
+ `Cost: ${fmtCredits(totalCents)}. ${ceiling.sentence}Re-call with confirm=true to proceed, or pick a smaller resolution / count.${pressText}`,
3467
3628
  });
3468
3629
  }
3469
3630
  const previews = await previewAssets(ctx, referenceAssetIds.map((id) => ({ id, type: 'image', role: 'reference' })));
@@ -3475,7 +3636,7 @@ export const generateImage = {
3475
3636
  `Review them against your prompt — every reference's role must be labeled in the prompt text. ` +
3476
3637
  `If the references suggest a different composition / style than the current prompt captures, REVISE the prompt before confirming. ` +
3477
3638
  `When you talk to the user about this gen, refer to each reference by its code (e.g. "${previews[0]?.ref ?? 'IMG-A?'}") — they'll see the matching badge in the Slates gallery.` +
3478
- `\n\nWhen ready, re-call slates_generate_image with confirm=true and the (possibly revised) prompt.` +
3639
+ `\n\n${ceiling.sentence}When ready, re-call slates_generate_image with confirm=true and the (possibly revised) prompt.${pressText}` +
3479
3640
  (promptWarning ? `\n\n${promptWarning}` : ''),
3480
3641
  images: previews.flatMap((p) => p.images),
3481
3642
  data: {
@@ -3484,6 +3645,8 @@ export const generateImage = {
3484
3645
  variant: costKey,
3485
3646
  estimated_cents: totalCents,
3486
3647
  estimated_credits: totalCents,
3648
+ approvedCredits: ceiling.credits,
3649
+ ...press,
3487
3650
  references: previews.map((p) => ({
3488
3651
  role: p.role,
3489
3652
  ref: p.ref,
@@ -3505,6 +3668,10 @@ export const generateImage = {
3505
3668
  // a desktop attached).
3506
3669
  if (input.projectId) {
3507
3670
  const desktop = ctx.desktop();
3671
+ const approved = approvedSpend(ctx, input);
3672
+ if (perInput && approved.approvedCredits != null && listQuote > approved.approvedCredits) {
3673
+ return toolPriceChanged(`${imageModel} image`, approved.approvedCredits, { credits: listQuote, costKey });
3674
+ }
3508
3675
  const result = await desktop.post('/agent/generation/image', {
3509
3676
  projectId: input.projectId,
3510
3677
  prompt: input.prompt,
@@ -3517,18 +3684,20 @@ export const generateImage = {
3517
3684
  ...(referenceAssetIds.length > 0 ? { referenceAssetIds } : {}),
3518
3685
  // The desktop adds @mention pictures this op cannot see; on a seat that bills
3519
3686
  // each input it runs nothing above what the user was quoted or approved.
3520
- ...(billsEachInputImage(sentModel) ? { maxCredits: Math.max(totalCents, input.approvedCredits ?? 0) } : {}),
3687
+ ...(perInput ? heldBody(approved.approvedCredits ?? listQuote, approved.quoteFingerprint) : {}),
3521
3688
  ...folderBody(input.folderId),
3522
3689
  background: input.background,
3523
3690
  });
3524
3691
  if (result.quoteExceeded) {
3525
- const { credits, costKey: billedKey } = result.quoteExceeded;
3692
+ const { credits, costKey: billedKey, fingerprint } = result.quoteExceeded;
3526
3693
  return ok({
3527
3694
  requires_confirm: true,
3528
3695
  quote_exceeded: true,
3529
3696
  model: billedKey,
3530
3697
  estimated_cents: credits,
3531
3698
  estimated_credits: credits,
3699
+ approvedCredits: credits,
3700
+ ...(fingerprint ? { quote_fingerprint: fingerprint } : {}),
3532
3701
  message: `Nothing ran. The @mention pictures in the prompt are paid inputs on ${imageModel}: this call bills ${fmtCredits(credits)} (${billedKey}), ` +
3533
3702
  `not the ${fmtCredits(totalCents)} quoted. Tell the user, and once they approve, re-call with confirm=true and approvedCredits=${credits}.`,
3534
3703
  });
@@ -3569,6 +3738,9 @@ export const generateImage = {
3569
3738
  }
3570
3739
  }
3571
3740
  const requestedCount = input.count ?? 1;
3741
+ // Each image is its own billed request and a failed one is refunded, so a partial batch cost the
3742
+ // saved images, not the quoted total.
3743
+ const chargedCents = partialFailure ? creditCost(entry) * assetList.length : totalCents;
3572
3744
  return {
3573
3745
  // The pixels are ALREADY here when the disk read worked, so the
3574
3746
  // review pointer says "look at what you have", not "call another op".
@@ -3578,6 +3750,7 @@ export const generateImage = {
3578
3750
  (promptWarning ? `${promptWarning} ` : '') +
3579
3751
  (partialFailure
3580
3752
  ? `Partial result: ${assetList.length} of ${requestedCount} image(s) saved into project ${input.projectId} ` +
3753
+ `for ${fmtCredits(chargedCents)}, not the ${fmtCredits(totalCents)} quoted ` +
3581
3754
  `(error on the rest: ${result.error ?? 'unknown error'}). ` +
3582
3755
  `The saved assets are in data.assets — re-generate only the missing count, don't redo the whole batch. ` +
3583
3756
  `Prompt: "${input.prompt.slice(0, 60)}${input.prompt.length > 60 ? '...' : ''}"`
@@ -3594,15 +3767,15 @@ export const generateImage = {
3594
3767
  projectId: input.projectId,
3595
3768
  aspectRatio: input.aspectRatio,
3596
3769
  resolution,
3597
- cost_cents: totalCents,
3598
- cost_credits: totalCents,
3770
+ cost_cents: chargedCents,
3771
+ cost_credits: chargedCents,
3599
3772
  // Compact refs only — the full rows (prompt/settings/paths) were a
3600
3773
  // multi-KB leak per generation and everything needed downstream is
3601
3774
  // the id/code/label.
3602
3775
  assets: assetList.map(compactAsset),
3603
3776
  generationIds: result.generationIds ?? (result.generationId ? [result.generationId] : []),
3604
3777
  ...(partialFailure
3605
- ? { partial: true, error: result.error ?? 'unknown error', requested_count: requestedCount }
3778
+ ? { partial: true, error: result.error ?? 'unknown error', requested_count: requestedCount, quoted_credits: totalCents }
3606
3779
  : {}),
3607
3780
  },
3608
3781
  };
@@ -3618,7 +3791,12 @@ export const generateImage = {
3618
3791
  const endpoint = hasReferenceImages
3619
3792
  ? 'google/nano-banana-2.1/edit'
3620
3793
  : 'google/nano-banana-2.1';
3621
- const proxyResult = await cloud.post('/proxy/generate', {
3794
+ // The server keeps the job a submit bought under this id, so an answer lost on the way back is asked for by it
3795
+ // (below), and a call that still cannot tell hands the id back to be repeated with, never a fresh one.
3796
+ const generationId = pressId;
3797
+ approvedSpend(ctx, input);
3798
+ const submitted = await cloud.post('/proxy/generate', {
3799
+ generationId,
3622
3800
  provider: 'fal',
3623
3801
  type: 'image',
3624
3802
  model: costKey,
@@ -3651,13 +3829,36 @@ export const generateImage = {
3651
3829
  ? { image_urls: input.referenceImageUrls }
3652
3830
  : {}),
3653
3831
  },
3832
+ }).catch((error) => {
3833
+ // The server answered with a refusal: nothing was bought, and the error says why.
3834
+ if (error instanceof SlatesCloudHttpError && error.status < 500)
3835
+ throw error;
3836
+ return { lost: error instanceof Error ? error.message : String(error) };
3654
3837
  });
3838
+ // An answer that never arrived, or arrived unreadable, may still have bought the image: ask for it by its id.
3839
+ let proxyResult;
3840
+ if (submitted && typeof submitted === 'object' && !('lost' in submitted)) {
3841
+ proxyResult = submitted;
3842
+ }
3843
+ else {
3844
+ const held = await cloud.get(`/proxy/generations/${generationId}`).catch(() => null);
3845
+ if (!held?.jobId) {
3846
+ const why = submitted && 'lost' in submitted ? submitted.lost : 'its answer could not be read';
3847
+ return ok({
3848
+ pending: true,
3849
+ requestId: generationId,
3850
+ message: `Slates cannot tell yet whether this image was bought (${why}). Call slates_generate_image again with the same arguments and requestId=${generationId}: ` +
3851
+ 'if this call bought it, that returns it and charges nothing again; if not, it buys it once. A call without that requestId buys another image.',
3852
+ });
3853
+ }
3854
+ proxyResult = { success: true, jobId: held.jobId };
3855
+ }
3655
3856
  if (!proxyResult.success) {
3656
3857
  throw new Error(proxyResult.error ?? 'Generation failed');
3657
3858
  }
3658
3859
  let imagesPayload = proxyResult.data?.images;
3659
3860
  if (!imagesPayload && proxyResult.jobId) {
3660
- const completed = await pollProxyJob(cloud, proxyResult.jobId);
3861
+ const completed = await pollProxyJob(cloud, proxyResult.jobId, { signal: ctx.signal });
3661
3862
  imagesPayload = completed.images;
3662
3863
  }
3663
3864
  const urls = (imagesPayload ?? [])
@@ -3666,17 +3867,24 @@ export const generateImage = {
3666
3867
  if (urls.length === 0) {
3667
3868
  throw new Error('Generation completed but returned no image URLs.');
3668
3869
  }
3870
+ // The credits are spent by now, so a URL that will not download is
3871
+ // reported with its link rather than thrown away or inlined as an error page.
3669
3872
  const images = [];
3873
+ const notInlined = [];
3670
3874
  for (const url of urls) {
3671
- const r = await fetch(url);
3672
- const buf = Buffer.from(await r.arrayBuffer());
3673
- const mt = r.headers.get('content-type') || 'image/png';
3674
- images.push({ data: buf.toString('base64'), mimeType: mt });
3875
+ const img = await inlineResultImage(url);
3876
+ if (img)
3877
+ images.push(img);
3878
+ else
3879
+ notInlined.push(url);
3675
3880
  }
3676
3881
  return {
3677
- text: `${IMAGE_INLINE_REVIEW} ` +
3882
+ text: (images.length > 0 ? `${IMAGE_INLINE_REVIEW} ` : '') +
3678
3883
  (promptWarning ? `${promptWarning} ` : '') +
3679
3884
  `Generated ${urls.length} image(s) for ${fmtCredits(totalCents)}. ` +
3885
+ (notInlined.length > 0
3886
+ ? `${notInlined.length} of them could not be attached here; they are paid for and at data.urls (${notInlined.join(' ')}). Open those links before describing them, and do not generate them again. `
3887
+ : '') +
3680
3888
  `Prompt: "${input.prompt.slice(0, 60)}${input.prompt.length > 60 ? '...' : ''}"`,
3681
3889
  images,
3682
3890
  data: {
@@ -3691,17 +3899,53 @@ export const generateImage = {
3691
3899
  };
3692
3900
  },
3693
3901
  };
3694
- async function pollProxyJob(cloud, jobId, options = {}) {
3902
+ /** One result URL as an inline image, or null when it does not answer with an image. */
3903
+ async function inlineResultImage(url) {
3904
+ try {
3905
+ const r = await fetch(url);
3906
+ const mimeType = r.headers.get('content-type') || 'image/png';
3907
+ if (!r.ok || !mimeType.startsWith('image/'))
3908
+ return null;
3909
+ return { data: Buffer.from(await r.arrayBuffer()).toString('base64'), mimeType };
3910
+ }
3911
+ catch {
3912
+ return null;
3913
+ }
3914
+ }
3915
+ /** Poll statuses that cannot change by asking again: a lost login, no credits, no access, no such job. */
3916
+ const PROXY_POLL_FINAL_STATUSES = new Set([401, 402, 403, 404]);
3917
+ /** Poll failures in a row (network or 5xx) before the poller stops and says so. */
3918
+ const PROXY_POLL_MAX_FAILURES = 10;
3919
+ /**
3920
+ * Wait for a headless proxy job. The job is submitted and its credits held
3921
+ * before this runs, so every way out but `completed` and `failed` names the
3922
+ * job and tells the caller not to start another: a retry is a second paid job.
3923
+ * It used to swallow every poll error for five minutes and then throw a bare
3924
+ * timeout with no job id (2026-11-24).
3925
+ */
3926
+ export async function pollProxyJob(cloud, jobId, options = {}) {
3695
3927
  const intervalMs = options.intervalMs ?? 3000;
3696
3928
  const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;
3929
+ const held = (why) => `${why} Job ${jobId} was submitted and its credits are held; it may still complete. ` +
3930
+ 'Do not call slates_generate_image again for this picture: that starts a second paid job.';
3697
3931
  const start = Date.now();
3932
+ let failures = 0;
3698
3933
  while (Date.now() - start < timeoutMs) {
3699
3934
  await new Promise((r) => setTimeout(r, intervalMs));
3935
+ if (options.signal?.aborted)
3936
+ throw new OperationCancelledError(held('Stopped waiting.'));
3700
3937
  let status;
3701
3938
  try {
3702
3939
  status = await cloud.get(`/proxy/jobs/${jobId}`);
3940
+ failures = 0;
3703
3941
  }
3704
- catch {
3942
+ catch (err) {
3943
+ const message = err instanceof Error ? err.message : String(err);
3944
+ const code = err.status;
3945
+ if (typeof code === 'number' && PROXY_POLL_FINAL_STATUSES.has(code))
3946
+ throw new Error(held(`Polling stopped: ${message}.`));
3947
+ if (++failures >= PROXY_POLL_MAX_FAILURES)
3948
+ throw new Error(held(`Polling failed ${failures} times in a row: ${message}.`));
3705
3949
  continue;
3706
3950
  }
3707
3951
  if (status.status === 'completed')
@@ -3710,28 +3954,28 @@ async function pollProxyJob(cloud, jobId, options = {}) {
3710
3954
  throw new Error(status.error ?? 'Generation failed');
3711
3955
  }
3712
3956
  }
3713
- throw new Error(`Generation timed out after ${Math.round(timeoutMs / 1000)}s.`);
3957
+ throw new Error(held(`Still running after ${Math.round(timeoutMs / 1000)}s.`));
3714
3958
  }
3715
3959
  // ── Edit image ──────────────────────────────────────────────────
3716
3960
  /** References an edit carries beside the source, which is image 1 of the same request. */
3717
- const editReferenceCap = (model) => Math.max(0, (MODEL_CAPABILITIES[model]?.maxRefImages ?? 1) - 1);
3961
+ const editReferenceCap = (model) => Math.max(0, imageReferenceCap(model) - 1);
3718
3962
  /** The models a 1.5.8 desktop sends edit references on, frozen with that build: on every other model it drops them and bills the edit in full. */
3719
3963
  const LEGACY_EDIT_REFERENCE_MODELS = ['nano-banana-2', 'nano-banana-2-lite', 'nano-banana-pro']; // 1.5.8's ids, retired since
3720
3964
  export const editImage = {
3721
3965
  id: 'slates_edit_image',
3722
3966
  billable: true,
3723
- description: 'Surgically edit an image asset with a text instruction (e.g. \'make the jacket red\') instead of regenerating from scratch — use when ~90% of the image is already right. The result is a NEW asset (prompt prefixed \'[Edit]\'); the source is untouched. Default model ' + toolModelFor('image-edit') + ' (the image-edit tool seat, the model the app\'s Edit box opens on). Every model also takes referenceAssetIds, up to its reference cap less one: the source is image 1 of the request. Use slates-edit-and-iterate for missing edit craft; reuse current guidance already in context. ' +
3967
+ description: 'Surgically edit an image asset with a text instruction (e.g. \'make the jacket red\') instead of regenerating from scratch — use when ~90% of the image is already right. The result is a NEW asset (prompt prefixed \'[Edit]\'); the source is untouched. Default model ' + toolModelFor('image-edit') + ' (the image-edit tool seat, the model the app\'s Edit box opens on). Every model also takes referenceAssetIds, up to its reference cap less one: the source is image 1 of the request, and more than that is refused. Use slates-edit-and-iterate for missing edit craft; reuse current guidance already in context. ' +
3724
3968
  CONFIRM_GATE_SENTENCE,
3725
3969
  input: z.object({
3726
3970
  projectId: z.string().uuid(),
3727
3971
  sourceAssetId: z.string().uuid().describe('Image asset to edit. Must exist in the project. ' + ASSET_UUID_ONLY),
3728
- prompt: z.string().min(1).max(4000).describe('The change, not the whole image. @name and #look words attach nothing here: pass those pictures in referenceAssetIds.'),
3972
+ prompt: z.string().min(1).describe('The change, not the whole image. @name and #look words attach nothing here: pass those pictures in referenceAssetIds.'),
3729
3973
  editModel: zEnum(IMAGE_MODELS).optional(),
3730
3974
  referenceAssetIds: z.array(z.string().uuid().describe(ASSET_UUID_ONLY)).max(Math.max(...IMAGE_MODELS.map(editReferenceCap))).optional().describe(`Images beside the source, which is image 1. Each model's own cap: ${IMAGE_MODELS.map((m) => `${m} ${editReferenceCap(m)}`).join(', ')}.`),
3731
3975
  resolution: z.enum(['1k', '2k', '3k', '4k']).optional().describe(`Omit for the model's default. Per model: ${IMAGE_MODELS.map((m) => `${m} ${(MODEL_CAPABILITIES[m]?.imageResolutions ?? []).join('/')}`).join(', ')}.`),
3732
3976
  quality: z.enum(GPT_QUALITY_TIERS).optional().describe(`GPT Image tier; default ${DEFAULT_GPT_QUALITY}.`),
3733
3977
  backgroundMode: z.enum(GPT_BACKGROUNDS).optional().describe(`${IMAGE_MODELS.filter(takesBackgroundMode).join(', ')} only. transparent = alpha channel (PNG). Free.`),
3734
- aspectRatio: z.string().optional(),
3978
+ aspectRatio: zEnum(IMAGE_ASPECT_RATIOS).optional().describe("Omit to keep the source picture's shape: the edit runs at the nearest ratio the model takes, and the reply names it. Each model's ratios: slates_generate_image's aspectRatio. A price dimension on GPT Image."),
3735
3979
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
3736
3980
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
3737
3981
  }),
@@ -3749,8 +3993,16 @@ export const editImage = {
3749
3993
  ? await defaultImageSeatFor(() => desktop, undefined, 'image editing')
3750
3994
  : { model: toolModelFor('image-edit'), note: '' };
3751
3995
  const editModel = seat.model;
3752
- requireGuideRead(ctx, editModel);
3996
+ const lengthError = promptLengthError(editModel, input.prompt);
3997
+ if (lengthError)
3998
+ throw new Error(lengthError);
3753
3999
  const resolution = input.resolution ?? defaultImageResolutionFor(editModel);
4000
+ // The same gates as slates_generate_image, from the same functions.
4001
+ const refusal = droppedImageParams(editModel, input) ??
4002
+ assertImageCapabilities({ model: editModel, aspectRatio: input.aspectRatio, resolution });
4003
+ if (refusal)
4004
+ return ok(refusal);
4005
+ requireGuideRead(ctx, editModel);
3754
4006
  let sentModel = editModel;
3755
4007
  if (isGptImageModel(editModel)) {
3756
4008
  // Like generateImage; this site was missed once already. A desktop that
@@ -3764,17 +4016,33 @@ export const editImage = {
3764
4016
  if (input.referenceAssetIds?.length && !LEGACY_EDIT_REFERENCE_MODELS.includes(editModel)) {
3765
4017
  await desktop.requireCapability('edit-references-all-models', `references on a ${editModel} edit`);
3766
4018
  }
3767
- // Past the model's cap the desktop sends the first ones and says so in its reply (`note`).
3768
- const referencesOver = (input.referenceAssetIds?.length ?? 0) - editReferenceCap(editModel);
3769
- // Nano Banana and GPT Image edits charge the same key as gen; FLUX routes to
3770
- // a dedicated edit endpoint priced under an '-edit' key; Seedream 5.5 bills
3771
- // every input image, the source included, so its key counts them.
3772
- // Mirrors `editCreditKey` in the desktop's src/shared/imageEdit.ts, which
3773
- // this package cannot import: change both together.
3774
- const editInputs = 1 + Math.min(input.referenceAssetIds?.length ?? 0, editReferenceCap(editModel));
3775
- const costKey = editModel === 'flux-3'
4019
+ // Past the model's cap the desktop sends the first ones and leaves the rest out: refused, never trimmed.
4020
+ const overCap = referenceCapRefusal(editModel, input.referenceAssetIds?.length ?? 0, editReferenceCap(editModel), 'referenceAssetIds', 'references beside the source');
4021
+ if (overCap)
4022
+ return ok(overCap);
4023
+ const request = {
4024
+ projectId: input.projectId,
4025
+ sourceAssetId: input.sourceAssetId,
4026
+ editModel: sentModel,
4027
+ referenceAssetIds: input.referenceAssetIds,
4028
+ resolution,
4029
+ ...(isGptImageModel(editModel) ? { gptQuality: input.quality ?? DEFAULT_GPT_QUALITY } : {}),
4030
+ aspectRatio: input.aspectRatio,
4031
+ };
4032
+ // The desktop prices the edit off the source picture: a ratio left out follows the picture's own
4033
+ // shape, and on GPT Image the ratio is part of the key, so only the desktop knows which key bills.
4034
+ // A desktop before 'edit-image-quote' prices a missing ratio at the 16:9 key, as this op did.
4035
+ const quote = await desktop.hasCapability('edit-image-quote')
4036
+ ? await desktop.post('/agent/generation/edit-image-quote', { request })
4037
+ : null;
4038
+ const aspectRatio = quote?.aspectRatio ?? input.aspectRatio;
4039
+ // The older desktop's key. Nano Banana and GPT Image edits charge the same key as gen; FLUX routes
4040
+ // to a dedicated edit endpoint priced under an '-edit' key; Seedream 5.5 bills every input image,
4041
+ // the source included. Mirrors `editCreditKey` in the desktop's src/shared/imageEdit.ts.
4042
+ const legacyKey = () => editModel === 'flux-3'
3776
4043
  ? `${imageCostKey(editModel, resolution)}-edit`
3777
- : imageCostKey(editModel, resolution, input.quality, input.aspectRatio, editInputs);
4044
+ : imageCostKey(editModel, resolution, input.quality, input.aspectRatio, 1 + (input.referenceAssetIds?.length ?? 0));
4045
+ const costKey = quote?.costKey ?? legacyKey();
3778
4046
  const cloud = ctx.cloud();
3779
4047
  const registry = await cloud.get('/api/agent/models');
3780
4048
  const entry = registry.models.find((m) => m.model === costKey) ??
@@ -3790,22 +4058,19 @@ export const editImage = {
3790
4058
  estimated_cents: totalCents,
3791
4059
  estimated_credits: totalCents,
3792
4060
  source_ref: sourceRef,
3793
- message: `Cost: ${fmtCredits(totalCents)} to edit ${sourceRef} with ${editModel} (${costKey}). ` +
3794
- (referencesOver > 0 ? `${editModel} takes ${editReferenceCap(editModel)} references beside the source; ${referencesOver} would not be sent. ` : '') +
4061
+ message: `Cost: ${fmtCredits(totalCents)} to edit ${sourceRef} with ${editModel} (${costKey})` +
4062
+ (aspectRatio && !input.aspectRatio ? `, at ${aspectRatio}, the ratio nearest the picture's shape. ` : '. ') +
3795
4063
  `Re-call with confirm=true after the user explicitly OKs the spend. ` +
3796
4064
  `When discussing with the user, refer to the source by its code (matches the gallery badge).`,
3797
4065
  });
3798
4066
  }
4067
+ approvedSpend(ctx);
3799
4068
  const result = await desktop.post('/agent/generation/edit-image', {
3800
- projectId: input.projectId,
3801
- sourceAssetId: input.sourceAssetId,
4069
+ ...request,
4070
+ // The ratio the quote named, so the run bills the key that was confirmed.
4071
+ aspectRatio,
3802
4072
  prompt: input.prompt,
3803
- editModel: sentModel,
3804
- referenceAssetIds: input.referenceAssetIds,
3805
- resolution,
3806
- ...(isGptImageModel(editModel) ? { gptQuality: input.quality ?? DEFAULT_GPT_QUALITY } : {}),
3807
4073
  ...(takesBackgroundMode(editModel) ? { gptBackground: input.backgroundMode } : {}),
3808
- aspectRatio: input.aspectRatio,
3809
4074
  background: input.background,
3810
4075
  });
3811
4076
  if (!result.success)
@@ -3851,6 +4116,7 @@ export const editImage = {
3851
4116
  projectId: input.projectId,
3852
4117
  sourceAssetId: input.sourceAssetId,
3853
4118
  resolution,
4119
+ ...(aspectRatio ? { aspectRatio } : {}),
3854
4120
  cost_cents: totalCents,
3855
4121
  cost_credits: totalCents,
3856
4122
  asset: result.asset,
@@ -3896,7 +4162,7 @@ export const extractGridCells = {
3896
4162
  if (input.background)
3897
4163
  await desktop.requireCapability('background-generation', 'background generation');
3898
4164
  const refs = await resolveAssetRefs(ctx, input.projectId, [input.assetId, ...(input.referenceAssetIds ?? [])]);
3899
- const grid = refs.get(input.assetId);
4165
+ const grid = refs.row(input.assetId);
3900
4166
  const request = {
3901
4167
  projectId: input.projectId,
3902
4168
  assetId: grid.id,
@@ -3905,11 +4171,11 @@ export const extractGridCells = {
3905
4171
  resolution: input.resolution,
3906
4172
  aspectRatio: input.aspectRatio,
3907
4173
  prompt: input.prompt,
3908
- referenceAssetIds: input.referenceAssetIds?.map((r) => refs.get(r).id),
4174
+ referenceAssetIds: input.referenceAssetIds?.map((r) => refs.id(r)),
3909
4175
  };
3910
4176
  // The desktop prices it: the viewer's own `imageCost`, for this seat, rung and cell count. The desktop also
3911
4177
  // refuses what the viewer would (not a grid, a cell the grid lacks, a seat it does not offer) before any spend.
3912
- const quote = await desktop.get('/agent/generation/extract-quote', { request: JSON.stringify(request) });
4178
+ const quote = await desktop.quote('/agent/generation/extract-quote', 'request', request);
3913
4179
  const gridName = grid.code ?? grid.id;
3914
4180
  if (quote.credits > CONFIRM_CREDITS && !input.confirm) {
3915
4181
  return ok({
@@ -3928,6 +4194,7 @@ export const extractGridCells = {
3928
4194
  `Re-call with confirm=true after the user explicitly OKs the spend. When discussing with the user, refer to the grid by its code (matches the gallery badge).`,
3929
4195
  });
3930
4196
  }
4197
+ approvedSpend(ctx);
3931
4198
  const result = await desktop.post('/agent/generation/extract-cells', { ...request, background: input.background });
3932
4199
  if (result.background) {
3933
4200
  return backgroundSubmitted(`extraction of ${quote.cells.join(', ')} from ${gridName}`, result.generationIds ?? [], {
@@ -3985,27 +4252,54 @@ export const extractGridCells = {
3985
4252
  * with no first/last frame IS ingredients mode.
3986
4253
  */
3987
4254
  function assertVideoCapabilities(input) {
3988
- const freeRefs = (input.ingredientAssetIds?.length ?? 0) +
3989
- (input.characterAssetIds?.length ?? 0) +
3990
- (input.environmentAssetIds?.length ?? 0) +
3991
- (input.styleAssetIds?.length ?? 0);
3992
- const promptMode = freeRefs > 0 && !input.firstFrameAssetId && !input.lastFrameAssetId ? 'ingredients' : undefined;
3993
- const ratioErr = checkAspectRatio(input.model, input.aspectRatio, AGENT_ROUTE_PROVIDER);
3994
- if (ratioErr)
3995
- return { requires_clarification: true, missing: ['aspectRatio'], message: ratioErr };
3996
- const resErr = checkVideoResolution(input.model, input.videoResolution);
3997
- if (resErr)
3998
- return { requires_clarification: true, missing: ['videoResolution'], message: resErr };
3999
- // Duration LAST: its legal window depends on the resolution, so a bad
4000
- // resolution must be reported first or the duration message names a window
4001
- // derived from a value the model never had.
4002
- const durErr = checkDuration(input.model, input.duration, {
4255
+ // `checkVideoParams` is the verdict the desktop's composition check reads too
4256
+ // (the prompt bar, the agent route and the handlers), so the op and the app
4257
+ // refuse the same ratio, resolution, references-at-resolution and length.
4258
+ const refusal = checkVideoParams(input.model, {
4259
+ aspectRatio: input.aspectRatio,
4003
4260
  videoResolution: input.videoResolution,
4004
- promptMode,
4261
+ duration: input.duration,
4262
+ provider: AGENT_ROUTE_PROVIDER,
4263
+ firstFrame: !!input.firstFrameAssetId,
4264
+ lastFrame: !!input.lastFrameAssetId,
4265
+ referenceImages: (input.ingredientAssetIds?.length ?? 0) +
4266
+ (input.characterAssetIds?.length ?? 0) +
4267
+ (input.environmentAssetIds?.length ?? 0) +
4268
+ (input.styleAssetIds?.length ?? 0),
4005
4269
  });
4006
- if (durErr)
4007
- return { requires_clarification: true, missing: ['duration'], message: durErr };
4008
- return null;
4270
+ return refusal
4271
+ ? { requires_clarification: true, missing: [refusal.field === 'references' ? 'videoResolution' : refusal.field], message: refusal.message }
4272
+ : null;
4273
+ }
4274
+ /** Each reference video's length, from whichever shape the caller used: the
4275
+ * per-clip list, plus the deprecated single value as one more clip. */
4276
+ function referenceVideoClips(input) {
4277
+ const single = input.videoReferenceSeconds ?? input.videoRefSeconds;
4278
+ return [...(input.videoReferenceSecondsEach ?? []), ...(single ? [single] : [])];
4279
+ }
4280
+ /** The reference-seconds gate, on every model: `checkReferenceSeconds` is the
4281
+ * verdict the desktop, its handlers and the server's key derivation reach for
4282
+ * the same clips, so a set quoted here is never refused after confirm. */
4283
+ function referenceSecondsRefusal(model, clips) {
4284
+ const error = checkReferenceSeconds(model, 'video', clips).error;
4285
+ return error
4286
+ ? { requires_clarification: true, missing: [], message: error.replace(/Trim (it|a clip) first\./, 'Trim $1 first with slates_trim_video.') }
4287
+ : null;
4288
+ }
4289
+ /** The reply when a video prices above what was approved: nothing ran, and the new price is the one to approve. */
4290
+ function videoPriceChanged(model, costKey, credits, approved) {
4291
+ return {
4292
+ requires_confirm: true,
4293
+ quote_exceeded: true,
4294
+ model,
4295
+ variant: costKey,
4296
+ estimated_cents: credits,
4297
+ estimated_credits: credits,
4298
+ approvedCredits: credits,
4299
+ message: `Nothing ran. This ${model} call now prices at ${fmtCredits(credits)} (${costKey}), above the ${fmtCredits(approved)} approved: ` +
4300
+ `a reference measured longer, or the prompt names a character or look that brings a billed input. ` +
4301
+ `Tell the user, and once they approve, re-call with confirm=true and approvedCredits=${credits}.`,
4302
+ };
4009
4303
  }
4010
4304
  // Model → registry cost-key. Each provider's keys ship with their own
4011
4305
  // shape (verified against /api/agent/models):
@@ -4026,28 +4320,19 @@ const KLING_TIER_MAP = {
4026
4320
  // Exported for scripts/pricing-consistency-check.mjs (slates-api repo), which
4027
4321
  // asserts this builder byte-matches the desktop's klingCreditKey/seedanceCreditKey.
4028
4322
  export function videoCostKey(input) {
4323
+ const refVideo = checkReferenceSeconds(input.model, 'video', referenceVideoClips(input));
4029
4324
  // EXACT-ID MAP, NEVER A PREFIX: 'minimax-h3-max' starts with 'minimax-h3'.
4030
4325
  // Mirrors minimaxCreditKey() in slate/src/shared/pricing.ts.
4031
4326
  if (MINIMAX_MODELS.has(input.model)) {
4032
4327
  const res = input.videoResolution ?? defaultVideoResolutionFor(input.model);
4033
4328
  if (input.model === 'minimax-h3-max') {
4034
4329
  const tokens = minimaxMaxReferenceTokens({ imagePixels: (input.referenceImages ?? 0) * MINIMAX_MAX_REFERENCE.normalizedImageEdge ** 2,
4035
- videoSeconds: input.videoRefSeconds ?? 0, audioSeconds: input.audioRefSeconds ?? 0, resolution: res ?? '' });
4330
+ videoSeconds: refVideo.actual, audioSeconds: input.audioRefSeconds ?? 0, resolution: res ?? '' });
4036
4331
  return `${input.model}-${res}-${input.duration}s${tokens ? `-rt${tokens}` : ''}`;
4037
4332
  }
4038
4333
  const k = minimaxRefSurchargeCount(input.model, input.referenceImages);
4039
4334
  return `${input.model}-${res}-${input.duration}s${k > 0 ? `-ref${k}` : ''}`;
4040
4335
  }
4041
- // LTX-2.5, both seats. EXACT-ID SET, NEVER A PREFIX — `ltx-2-5-pro` starts
4042
- // with `ltx-2-5`, and a prefix match would quote base rates for the dearer
4043
- // row. No suffix dimension exists: audio is free and there are no references.
4044
- // The resolution default is read PER ROW (both are 1080p today, but the two
4045
- // ladders differ, so a shared literal would be a latent bug the day one
4046
- // moves). Mirrors ltxCreditKey() in slate/src/shared/pricing.ts.
4047
- if (LTX_MODELS.has(input.model)) {
4048
- const res = input.videoResolution ?? defaultVideoResolutionFor(input.model);
4049
- return `${input.model}-${res}-${input.duration}s`;
4050
- }
4051
4336
  if (input.model.startsWith('seedance')) {
4052
4337
  // Mirrors seedanceCreditKey() in slate/src/shared/pricing.ts (version × face
4053
4338
  // × vref × res × duration). AI-face route bills the `-face-` key (~45% over
@@ -4063,16 +4348,13 @@ export function videoCostKey(input) {
4063
4348
  const v25 = input.model.startsWith('seedance-2.5');
4064
4349
  const res = input.videoResolution ?? (v25 ? '720p' : '1080p');
4065
4350
  const face = input.seedanceRealFace ? '-realface' : input.seedanceFace ? '-face' : '';
4066
- const vrefSecs = input.videoRefSeconds ?? 0;
4067
- if (vrefSecs > 0) {
4068
- // ceil(x - 0.05) matches the server's probe rounding — quote = bill.
4069
- const maxTotal = v25 ? SEEDANCE_25_VREF_MAX_TOTAL : SEEDANCE_20_VREF_MAX_TOTAL;
4351
+ if (refVideo.billed > 0) {
4070
4352
  // EvoLink (the AI-face rail) bills a reference on max(input, output) +
4071
4353
  // output on 2.0 and 2.5. Mirrors seedanceBilledRefSeconds in slate pricing.ts.
4072
- const inSecs = Math.ceil(vrefSecs - 0.05);
4073
- const billedIn = face === '-face' ? Math.max(inSecs, input.duration) : inSecs;
4074
- const total = Math.min(maxTotal, Math.max(6, billedIn + input.duration));
4075
- return `${input.model}${face}-vref-${res}-${total}s`;
4354
+ // Never clamped: a total past the last priced key is no price at all, and
4355
+ // `referenceSecondsRefusal` has already refused a set outside the row's bounds.
4356
+ const billedIn = face === '-face' ? Math.max(refVideo.billed, input.duration) : refVideo.billed;
4357
+ return `${input.model}${face}-vref-${res}-${billedIn + input.duration}s`;
4076
4358
  }
4077
4359
  return `${input.model}${face}-${res}-${input.duration}s`;
4078
4360
  }
@@ -4117,14 +4399,18 @@ export function videoCostKey(input) {
4117
4399
  // T = in + out. Sound on or off, reference images and reference audio do
4118
4400
  // not move the price.
4119
4401
  const res = input.videoResolution ?? defaultVideoResolutionFor(input.model);
4120
- const vrefSecs = input.videoRefSeconds ?? 0;
4121
- if (vrefSecs > 0) {
4122
- // ceil(x - 0.05) matches the server's probe rounding, so quote = bill.
4123
- const total = Math.min(WAN_3_VREF_MAX_TOTAL, Math.ceil(vrefSecs - 0.05) + input.duration);
4124
- return `wan-3.0-vref-${res}-${total}s`;
4402
+ if (refVideo.billed > 0) {
4403
+ // Never clamped: a clamp bills a longer clip at a shorter one's price.
4404
+ return `wan-3.0-vref-${res}-${refVideo.billed + input.duration}s`;
4125
4405
  }
4126
4406
  return `wan-3.0-${res}-${input.duration}s`;
4127
4407
  }
4408
+ if (input.model === 'magi-2') {
4409
+ // Mirrors magiCreditKey() in slate/src/shared/pricing.ts. One resolution
4410
+ // and one rate per output second on every endpoint: references, sound and
4411
+ // frames do not move the price, so the key is the length alone.
4412
+ return `magi-2-1080p-${input.duration}s`;
4413
+ }
4128
4414
  throw new Error(`Unknown video model: ${input.model}`);
4129
4415
  }
4130
4416
  // Kling O3 video-to-video edit cost key — mirrors klingEditCreditKey() in
@@ -4143,10 +4429,6 @@ export function omniFlashEditCostKey(duration, videoResolution) {
4143
4429
  const res = videoResolution ?? defaultVideoResolutionFor('omni-flash-1-2-edit');
4144
4430
  return `omni-flash-1-2-edit-${res}-${duration}s`;
4145
4431
  }
4146
- /** Max billed (input + output) seconds on a Seedance video-reference gen.
4147
- * 2.0: refs 2–15s + output 4–15s. 2.5: refs to 30s + output to 30s. */
4148
- const SEEDANCE_20_VREF_MAX_TOTAL = 30;
4149
- const SEEDANCE_25_VREF_MAX_TOTAL = 60;
4150
4432
  /** Seedance 2.5 source-clip bounds for the edit task type — READ from the
4151
4433
  * capability SSOT, not typed. Kept as named exports because published builds
4152
4434
  * import them. */
@@ -4349,6 +4631,9 @@ function resolveVideoModel(raw) {
4349
4631
  'hailuo-3': 'minimax-h3',
4350
4632
  'hailuo-3.0': 'minimax-h3',
4351
4633
  hailuo: 'minimax-h3',
4634
+ magi: 'magi-2',
4635
+ magi2: 'magi-2',
4636
+ 'magi-2.0': 'magi-2',
4352
4637
  };
4353
4638
  if (aliases[s]) {
4354
4639
  out.model = aliases[s];
@@ -4356,6 +4641,16 @@ function resolveVideoModel(raw) {
4356
4641
  }
4357
4642
  return null;
4358
4643
  }
4644
+ const GENERATE_VIDEO_SPOKEN_FIELDS = { spoken: 'audioReferenceSpokenText', clips: 'audioReferenceAssetIds' };
4645
+ const SHOT_SPOKEN_FIELDS = { spoken: 'audioRefSpokenText', clips: 'refs["audio-reference"]' };
4646
+ /** The pairing rule for a positional spoken-text array: present only beside its
4647
+ * clips, at the same length. Returns the refusal, or null when it pairs. */
4648
+ function spokenTextMisalignment(assetIds, spoken, fields) {
4649
+ if (spoken === undefined || spoken.length === (assetIds?.length ?? 0))
4650
+ return null;
4651
+ return (`${fields.spoken} pairs by position with ${fields.clips}, so send both together and at the same length ` +
4652
+ `(${spoken.length} line(s) vs ${assetIds?.length ?? 0} clip(s)). Use "" for a clip with no speech.`);
4653
+ }
4359
4654
  /**
4360
4655
  * Pair each reference-audio asset id with the words spoken in it.
4361
4656
  *
@@ -4371,8 +4666,15 @@ function resolveVideoModel(raw) {
4371
4666
  * address different clips depending on which shape the caller used. Blank
4372
4667
  * entries are dropped rather than sent as empty strings — a clip with no
4373
4668
  * speech has no line, which is not the same as a line that is empty.
4669
+ *
4670
+ * A misaligned array would attach one clip's line to another and send the
4671
+ * model the wrong words with nothing on screen to say so, so it is refused
4672
+ * here, for every model and every caller, rather than truncated.
4374
4673
  */
4375
- function spokenTextByAssetId(assetIds, spoken) {
4674
+ function spokenTextByAssetId(assetIds, spoken, fields = GENERATE_VIDEO_SPOKEN_FIELDS) {
4675
+ const misaligned = spokenTextMisalignment(assetIds, spoken, fields);
4676
+ if (misaligned)
4677
+ throw new Error(misaligned);
4376
4678
  if (!assetIds?.length || !spoken?.length)
4377
4679
  return undefined;
4378
4680
  const out = {};
@@ -4383,22 +4685,27 @@ function spokenTextByAssetId(assetIds, spoken) {
4383
4685
  });
4384
4686
  return Object.keys(out).length > 0 ? out : undefined;
4385
4687
  }
4386
- // Maps a model id to its bundled prompting skill (frontmatter `name:`), so
4387
- // guidance text points at a skill that actually exists.
4688
+ // Maps a model id to its prompting guide (frontmatter `name:`), so guidance
4689
+ // text points at a guide that actually exists.
4388
4690
  //
4389
4691
  // 🚨 ONE RESOLVER. This was a second hand-typed alias table beside
4390
4692
  // `resolveGuideTopic()`, and it had already fallen behind: it knew nothing
4391
- // about LTX-2.5, so every LTX generation was told to read the cost skill
4693
+ // about one seat, so every generation on it was told to read the cost skill
4392
4694
  // instead of its own guide. Delegate; the ordering traps (2.5 before seedance,
4393
- // seed-audio before seedance, minimax before both) are solved once, there.
4695
+ // seed-audio before seedance, minimax before both) are solved once, there. A
4696
+ // model with no guide throws: `VIDEO_MODEL_GUIDES` below runs it over the whole
4697
+ // video roster at load, and slates-api's model-lifecycle check over the registry.
4394
4698
  function promptingSkillFor(model) {
4395
- return resolveGuideTopic(model) ?? 'slates-cost-discipline';
4699
+ const guide = resolveGuideTopic(model);
4700
+ if (!guide)
4701
+ throw new Error(`No prompting guide resolves for model ${model}: add its prefix to resolveGuideTopic in packages/shared/src/operations/index.ts.`);
4702
+ return guide;
4396
4703
  }
4397
4704
  /**
4398
4705
  * The per-model prompting guides for the whole video roster, DERIVED.
4399
4706
  *
4400
4707
  * `slates_generate_video`'s description hand-typed five of them and omitted
4401
- * `slates-prompting-ltx-2-5` for as long as LTX shipped — an agent reading the
4708
+ * one seat's guide for as long as that seat shipped — an agent reading the
4402
4709
  * description could not learn the guide existed. A hand-typed index of a
4403
4710
  * generated corpus is a stale index; it is only a matter of when.
4404
4711
  */
@@ -4416,14 +4723,14 @@ export const generateVideo = {
4416
4723
  billable: true,
4417
4724
  description: 'Generate video via Slates credits. Choose the model with slates-model-selection. Video models prompt very differently: the estimate returns the chosen model\'s prompting card, and its full guide (' +
4418
4725
  VIDEO_MODEL_GUIDES +
4419
- ') covers modes the card leaves out, via slates_get_prompting_guide. Read slates-content-policy when the scene involves conflict, creatures, crowds, destruction, weapons, or young characters. projectId, aspectRatio, and duration are required (requires_clarification otherwise). ' +
4726
+ ') covers modes the card leaves out, via slates_get_prompting_guide. Read slates-content-policy when the scene involves conflict, creatures, crowds, destruction, weapons, or young characters. projectId and duration are required, plus aspectRatio when the endpoint takes it (requires_clarification otherwise). ' +
4420
4727
  confirmGateSentence('any image reference (frame, ingredient, character, environment or style)') +
4421
4728
  ' Image-to-video via firstFrameAssetId; a last frame via lastFrameAssetId and ingredients via ingredientAssetIds, each param stating which models take it. Asset params take UUIDs or badge codes ("IMG-A8"). ' +
4422
4729
  // GENERATED from the skill's own slop-token list. Always in context on both
4423
4730
  // surfaces, so it survives an agent that skips slates_get_prompting_guide.
4424
4731
  describeBannedTokens('video'),
4425
4732
  input: z.object({
4426
- prompt: z.string().min(1).max(4000),
4733
+ prompt: z.string().optional().describe("Optional when the selected model can animate a start frame on its own."),
4427
4734
  // ROUTING doctrine only. Every capability number was stripped on 2026-08-16
4428
4735
  // and now lives in the aspectRatio / duration / videoResolution descriptions
4429
4736
  // below, generated from MODEL_CAPABILITIES. "16:9 only" for a model and
@@ -4456,10 +4763,10 @@ export const generateVideo = {
4456
4763
  // WHY here, you are writing the skill in the wrong file.
4457
4764
  firstFrameAssetId: z.string().optional().describe('Starting frame for image-to-video (UUID or badge code, resolved at call time).'),
4458
4765
  lastFrameAssetId: z.string().optional().describe('Ending frame. Pairs with firstFrameAssetId.'),
4459
- ingredientAssetIds: z.array(z.string()).max(30).optional().describe(
4766
+ ingredientAssetIds: z.array(z.string()).max(Math.max(...VIDEO_MODELS.map((m) => maxIngredientImagesFor(m)))).optional().describe(
4460
4767
  // Caps DERIVED from MODEL_CAPABILITIES — the hand-typed list omitted
4461
4768
  // kling-v3.0-omni-pro entirely and read as if 7 were an Omni Flash-only rule.
4462
- `Visual reference / ingredient assets. Cap per model, combined across the ingredient/character/environment/style params: ${describeReferenceImageCaps(VIDEO_MODELS)}. 2-4 strong references beat both extremes.`),
4769
+ `Visual reference / ingredient assets. Cap per model, combined across the ingredient/character/environment/style params: ${describeReferenceImageCaps(VIDEO_MODELS)}. Over the cap is REFUSED, never trimmed. 2-4 strong references beat both extremes.`),
4463
4770
  characterAssetIds: z.array(z.string()).optional().describe('Character sheet assets — keeps a character consistent.'),
4464
4771
  environmentAssetIds: z.array(z.string()).optional().describe('Location references — keeps a location consistent.'),
4465
4772
  styleAssetIds: z.array(z.string()).optional().describe('Style references — locks the look.'),
@@ -4471,10 +4778,10 @@ export const generateVideo = {
4471
4778
  // multimodalRefSummary) rather than hand-typed, so a cap change in one
4472
4779
  // place cannot leave a stale number in a description an LLM reads.
4473
4780
  videoReferenceAssetIds: z.array(z.string()).optional().describe(`Reference VIDEOS, cited in the prompt as "video 1", "video 2"… in the order given. ${multimodalRefModels().join(' / ')} only; per-model caps are on audioReferenceAssetIds. On Seedance and Wan 3.0, billing switches to the vref key (input+output seconds); Omni Flash caps each clip at ${omniFlashRefClipMax}s. Pass videoReferenceSecondsEach. Over the cap is REFUSED, never trimmed.`),
4474
- videoReferenceSecondsEach: z.array(z.number()).optional().describe('REQUIRED with videoReferenceAssetIds, same order and length: each clip\'s duration in seconds. Feeds the vref cost key; the server re-probes and corrects an understated value upward.'),
4781
+ videoReferenceSecondsEach: z.array(z.number()).optional().describe("Each clip's duration in seconds (slates_list_assets shows it), same order and length as videoReferenceAssetIds. The desktop measures every clip for the quote; a desktop before that needs these."),
4475
4782
  audioReferenceAssetIds: z.array(z.string()).optional().describe(`Reference AUDIO, cited as "audio 1", "audio 2"… in the order given. ${multimodalRefModels().join(' / ')} only. No surcharge on Seedance; on H3 Max, audio counts toward the reference-token pool. ${multimodalRefModels().map(multimodalRefSummary).join(' ')}`),
4476
4783
  audioReferenceSpokenText: z.array(z.string()).optional().describe('The exact words in each reference clip — same order and length as audioReferenceAssetIds, "" for a clip with no speech. The model RE-TRANSCRIBES a take rather than using it verbatim, so audio decides voice/accent/timing and only this decides the WORDS. Omit it and the words are a guess.'),
4477
- sound: z.boolean().optional().describe('Kling 3.0 (every tier), LTX and Wan 3.0: sound on (default) or silent (false); Kling 3.0 bills audio as its own key. Seedance, Omni Flash, H3 and Kling 4.0 always generate audio.'),
4784
+ sound: z.boolean().optional().describe(`Sound on by default. Pass false for a silent take on ${VIDEO_MODELS.filter(id => getModelCapability(id)?.soundCanBeDisabled).join(', ')}. Kling 3.0 bills audio separately.`),
4478
4785
  audioLanguage: z.enum(['EN', 'ZH', 'JA', 'KO', 'ES']).optional().describe('Any Kling 3.0 model with sound on — language for dialogue.'),
4479
4786
  generateMusic: z.boolean().optional().describe('Any Kling 3.0 model with sound on — auto-generate background music.'),
4480
4787
  seedanceDraft: z.boolean().optional().describe('Create a finishable Seedance 2.5 preview at 480p.'),
@@ -4484,6 +4791,7 @@ export const generateVideo = {
4484
4791
  negativePrompt: z.string().optional(),
4485
4792
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
4486
4793
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
4794
+ approvedCredits: z.number().int().positive().optional().describe('With confirm=true: the credits the pre-flight named and the user approved. A call that now prices higher runs nothing and answers with the new price.'),
4487
4795
  folderId: folderIdField,
4488
4796
  }),
4489
4797
  async run(input, ctx) {
@@ -4523,6 +4831,15 @@ export const generateVideo = {
4523
4831
  // not reasonable for video given the cost.
4524
4832
  // Non-blocking prompt hygiene, computed once. Reported on the gates that
4525
4833
  // fire BEFORE any spend, where a rewrite is still free.
4834
+ const promptError = videoPromptError(input.model, input.prompt, !!input.firstFrameAssetId);
4835
+ if (promptError)
4836
+ return ok({ requires_clarification: true, missing: ['prompt'], message: promptError });
4837
+ input.prompt ??= '';
4838
+ const needsRatio = aspectRatioApplies(input.model, {
4839
+ firstFrame: !!input.firstFrameAssetId,
4840
+ referenceImages: [input.ingredientAssetIds, input.characterAssetIds, input.environmentAssetIds, input.styleAssetIds]
4841
+ .reduce((n, ids) => n + (ids?.length ?? 0), 0),
4842
+ });
4526
4843
  const promptWarning = bannedTokenWarning(input.prompt, 'video', promptingSkillFor(resolved.model));
4527
4844
  if (!input.projectId) {
4528
4845
  return ok({
@@ -4533,9 +4850,9 @@ export const generateVideo = {
4533
4850
  'projectId is required for video generation. Use slates_list_projects to find one or slates_create_project to make a new one. Video gens cost tens to a few hundred credits per call — they need to land in a project so the user sees the progress card and the result.',
4534
4851
  });
4535
4852
  }
4536
- if (!input.aspectRatio || !input.duration) {
4853
+ if ((needsRatio && !input.aspectRatio) || !input.duration) {
4537
4854
  const missing = [];
4538
- if (!input.aspectRatio)
4855
+ if (needsRatio && !input.aspectRatio)
4539
4856
  missing.push('aspectRatio');
4540
4857
  if (!input.duration)
4541
4858
  missing.push('duration');
@@ -4550,7 +4867,7 @@ export const generateVideo = {
4550
4867
  // a model locked to 16:9, "Kling/Seedance support 1:1 16:9 9:16 4:3 3:4
4551
4868
  // 21:9" and "Kling 5-15s" — three wrong claims in one sentence.
4552
4869
  `or ask the user. ` +
4553
- `Aspect ratio for ${input.model}: ${aspectRatiosFor(input.model, AGENT_ROUTE_PROVIDER).join(', ')}. ` +
4870
+ (needsRatio ? `Aspect ratio for ${input.model}: ${aspectRatiosFor(input.model, AGENT_ROUTE_PROVIDER).join(', ')}. ` : '') +
4554
4871
  `Duration: ${describeDurations([input.model])}. ` +
4555
4872
  `Cost scales linearly with duration.`,
4556
4873
  });
@@ -4563,6 +4880,10 @@ export const generateVideo = {
4563
4880
  const capErr = assertVideoCapabilities(input);
4564
4881
  if (capErr)
4565
4882
  return ok(capErr);
4883
+ // Every model reads the spoken text, so its pairing is checked before any model's shape block.
4884
+ const spokenErr = spokenTextMisalignment(input.audioReferenceAssetIds, input.audioReferenceSpokenText, GENERATE_VIDEO_SPOKEN_FIELDS);
4885
+ if (spokenErr)
4886
+ return ok({ requires_clarification: true, missing: [], message: spokenErr });
4566
4887
  // Omni Flash 1.2's SHAPE constraints. Frames ride image-to-video (a start
4567
4888
  // frame and an optional end frame, 10s or less with the end frame);
4568
4889
  // references ride reference-to-video (Google's limits: 6 images, reference
@@ -4581,7 +4902,7 @@ export const generateVideo = {
4581
4902
  (input.environmentAssetIds?.length ?? 0) +
4582
4903
  (input.styleAssetIds?.length ?? 0);
4583
4904
  const hasRefs = imageRefs + videoRefs > 0;
4584
- const refCount = imageRefs + (hasRefs && input.firstFrameAssetId ? 1 : 0);
4905
+ const refCount = imageRefs + (hasRefs && input.firstFrameAssetId && getModelCapability(input.model)?.firstFrameRidesAsReference ? 1 : 0);
4585
4906
  // Only the lengths given; a missing one is asked for below, before the quote.
4586
4907
  const refSeconds = [
4587
4908
  ...(input.videoReferenceAssetId && input.videoReferenceSeconds != null ? [input.videoReferenceSeconds] : []),
@@ -4606,14 +4927,16 @@ export const generateVideo = {
4606
4927
  return ok({ requires_clarification: true, missing: [], message: shapeError });
4607
4928
  }
4608
4929
  }
4609
- // Wan 3.0's SHAPE constraints. The same split as Omni Flash: image-to-video
4610
- // takes a start frame and an optional end frame, reference-to-video takes
4611
- // images, videos and audio, and Alibaba calls the two modes "mutually
4612
- // exclusive". The reference endpoint has no frame slot, so frames with
4930
+ // Wan 3.0's and MAGI-2's SHAPE constraints. The same split as Omni Flash:
4931
+ // image-to-video takes a start frame and an optional end frame,
4932
+ // reference-to-video takes images, videos and audio, and the two never mix
4933
+ // (Alibaba: "mutually exclusive"; MAGI-2: references "cannot be added to a
4934
+ // frame request"). The reference endpoint has no frame slot, so frames with
4613
4935
  // references are refused, never dropped (the MiniMax H3 rule, slate
4614
4936
  // .claude/rules/models.md invariant 7). Caps are read from the SSOT.
4615
- if (input.model === 'wan-3.0') {
4616
- const cap = getModelCapability('wan-3.0');
4937
+ if (input.model === 'wan-3.0' || input.model === 'magi-2') {
4938
+ const label = input.model === 'wan-3.0' ? 'Wan 3.0' : 'MAGI-2';
4939
+ const cap = getModelCapability(input.model);
4617
4940
  const imageRefs = (input.ingredientAssetIds?.length ?? 0) +
4618
4941
  (input.characterAssetIds?.length ?? 0) +
4619
4942
  (input.environmentAssetIds?.length ?? 0) +
@@ -4622,8 +4945,6 @@ export const generateVideo = {
4622
4945
  const audioRefs = (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0);
4623
4946
  const refImages = imageRefs;
4624
4947
  const refAll = refImages + videoRefs + audioRefs;
4625
- const videoSecs = [input.videoReferenceSeconds ?? 0, ...(input.videoReferenceSecondsEach ?? [])].reduce((n, d) => n + (d > 0 ? d : 0), 0);
4626
- const maxVideoSecs = cap?.maxReferenceVideoSeconds ?? 15;
4627
4948
  const overCap = [
4628
4949
  [refImages, cap?.maxIngredientImages, 'reference images'],
4629
4950
  [videoRefs, cap?.maxReferenceVideos, 'reference videos'],
@@ -4631,23 +4952,39 @@ export const generateVideo = {
4631
4952
  [refAll, cap?.maxReferenceFilesTotal, 'reference files across all types'],
4632
4953
  ].find(([n, max]) => max !== undefined && n > max);
4633
4954
  const shapeError = refAll > 0 && (input.firstFrameAssetId || input.lastFrameAssetId)
4634
- ? 'Wan 3.0 takes first/last frames OR references, not both: Alibaba calls the two modes mutually exclusive. Drop one side.'
4955
+ ? `${label} takes first/last frames OR references, not both: its reference endpoint has no frame slots. Drop one side.`
4635
4956
  : input.lastFrameAssetId && !input.firstFrameAssetId
4636
- ? 'Wan 3.0 needs a start frame (firstFrameAssetId) with a last frame.'
4957
+ ? `${label} needs a start frame (firstFrameAssetId) with a last frame.`
4637
4958
  : overCap
4638
- ? `Wan 3.0 takes at most ${overCap[1]} ${overCap[2]} (you passed ${overCap[0]}).`
4639
- : videoSecs > maxVideoSecs + 0.05
4640
- ? `Wan 3.0 takes at most ${maxVideoSecs}s of reference video in total (you passed ${videoSecs.toFixed(1)}s). Trim a clip first with slates_trim_video.`
4641
- : null;
4959
+ ? `${label} takes at most ${overCap[1]} ${overCap[2]} (you passed ${overCap[0]}).`
4960
+ : null;
4642
4961
  if (shapeError) {
4643
4962
  return ok({ requires_clarification: true, missing: [], message: shapeError });
4644
4963
  }
4645
4964
  }
4965
+ // Reference-video seconds, every model: each clip's window and the combined
4966
+ // total, before the quote. A missing length is asked for further down.
4967
+ const referenceClips = referenceVideoClips({
4968
+ videoReferenceSecondsEach: input.videoReferenceSecondsEach,
4969
+ videoReferenceSeconds: input.videoReferenceAssetId ? input.videoReferenceSeconds : undefined,
4970
+ });
4971
+ const refSecondsErr = referenceSecondsRefusal(input.model, referenceClips);
4972
+ if (refSecondsErr)
4973
+ return ok(refSecondsErr);
4974
+ // Frames beside reference video or audio, every model: the verdict the desktop's composer reaches.
4975
+ const framesErr = checkFramesWithReferenceMedia(input.model, {
4976
+ firstFrame: !!input.firstFrameAssetId,
4977
+ lastFrame: !!input.lastFrameAssetId,
4978
+ referenceVideos: (input.videoReferenceAssetIds?.length ?? 0) + (input.videoReferenceAssetId ? 1 : 0),
4979
+ referenceAudio: (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0),
4980
+ });
4981
+ if (framesErr)
4982
+ return ok({ requires_clarification: true, missing: [], message: framesErr });
4646
4983
  // Kling 4.0's SHAPE constraint: FRAMES, NEVER REFERENCES. Only fal's
4647
4984
  // `kling/v4/image-to-video` (start frame plus an optional end frame) and
4648
4985
  // `kling/v4/text-to-video` are sold; its reference-to-video is not, so a
4649
- // reference id has no transport and is refused rather than dropped (the
4650
- // LTX rule below). An end frame needs the start frame: text-to-video has
4986
+ // reference id has no transport and is refused rather than dropped. An end
4987
+ // frame needs the start frame: text-to-video has
4651
4988
  // no frame slot at all.
4652
4989
  if (input.model === 'kling-v4.0') {
4653
4990
  const refs = (input.ingredientAssetIds?.length ?? 0) +
@@ -4667,34 +5004,6 @@ export const generateVideo = {
4667
5004
  return ok({ requires_clarification: true, missing: [], message: shapeError });
4668
5005
  }
4669
5006
  }
4670
- // LTX-2.5's SHAPE constraint: FRAMES, NEVER REFERENCES. fal publishes
4671
- // text-to-video and image-to-video for `lightricks/ltx-2.5` and nothing
4672
- // else — there is no reference-to-video endpoint on either seat, so there
4673
- // is no transport for an ingredient, character, environment, style,
4674
- // reference-video or reference-audio input.
4675
- //
4676
- // This has to be an EXPLICIT refusal rather than a silent no-op: accepting
4677
- // reference ids we cannot send is the exact "no error, no warning, no
4678
- // images in the request" failure `seedance-2.5-edit` shipped with. Start
4679
- // and end FRAMES are unaffected — image-to-video carries `image_url` plus
4680
- // an optional `end_image_url`, which is what `features.lastFrame` records.
4681
- if (LTX_MODELS.has(input.model)) {
4682
- const refImages = (input.ingredientAssetIds?.length ?? 0) +
4683
- (input.characterAssetIds?.length ?? 0) +
4684
- (input.environmentAssetIds?.length ?? 0) +
4685
- (input.styleAssetIds?.length ?? 0);
4686
- const refMedia = (input.videoReferenceAssetIds?.length ?? 0) +
4687
- (input.audioReferenceAssetIds?.length ?? 0) +
4688
- (input.videoReferenceAssetId ? 1 : 0) +
4689
- (input.audioReferenceAssetId ? 1 : 0);
4690
- if (refImages > 0 || refMedia > 0) {
4691
- return ok({
4692
- requires_clarification: true,
4693
- missing: [],
4694
- message: `${input.model} takes a prompt and up to two frames (start and/or end) — it has no reference endpoint at all, so reference images, video and audio cannot be sent. Drop them, or switch to minimax-h3, which reads ${getModelCapability('minimax-h3')?.maxIngredientImages ?? 9} images plus reference video and audio.`,
4695
- });
4696
- }
4697
- }
4698
5007
  // MiniMax H3's SHAPE constraints. Counts and caps are read from the
4699
5008
  // capability SSOT; only the endpoint SHAPE is stated here, because it is
4700
5009
  // not a number the registry models: fal publishes text-to-video,
@@ -4758,20 +5067,6 @@ export const generateVideo = {
4758
5067
  message: `${input.model} takes at most ${maxTotal} reference files across all modalities (you passed ${refImages + refMedia}).`,
4759
5068
  });
4760
5069
  }
4761
- // A misaligned spoken-text array would attach one clip's line to another
4762
- // and send the model the wrong words with nothing on screen to say so.
4763
- // Refuse rather than truncate: the whole point of the field is that the
4764
- // WORDS are exact.
4765
- if (input.audioReferenceSpokenText &&
4766
- input.audioReferenceSpokenText.length !== (input.audioReferenceAssetIds?.length ?? 0)) {
4767
- return ok({
4768
- requires_clarification: true,
4769
- missing: [],
4770
- message: `audioReferenceSpokenText must be the same length as audioReferenceAssetIds ` +
4771
- `(${input.audioReferenceSpokenText.length} vs ${input.audioReferenceAssetIds?.length ?? 0}) ` +
4772
- `— it pairs by position. Use "" for a clip with no speech.`,
4773
- });
4774
- }
4775
5070
  // fal: "Audio cannot be the only reference input; provide at least one
4776
5071
  // reference image or video with it."
4777
5072
  const audioRefs = (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0);
@@ -4784,6 +5079,26 @@ export const generateVideo = {
4784
5079
  });
4785
5080
  }
4786
5081
  }
5082
+ // Reference counts, every model, from its capability row. The desktop sends the first `cap`
5083
+ // pictures and leaves the rest out, so a call over a cap would run, and bill, without references
5084
+ // the caller named: refused here, before the quote. The blocks above word their own model's caps.
5085
+ {
5086
+ const cap = getModelCapability(input.model);
5087
+ const images = (input.ingredientAssetIds?.length ?? 0) + (input.characterAssetIds?.length ?? 0) +
5088
+ (input.environmentAssetIds?.length ?? 0) + (input.styleAssetIds?.length ?? 0);
5089
+ const videos = (input.videoReferenceAssetIds?.length ?? 0) + (input.videoReferenceAssetId ? 1 : 0);
5090
+ const audio = (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0);
5091
+ // Beside references a start frame rides as reference image 1 on some rows and uses a slot.
5092
+ const frameSlot = input.firstFrameAssetId && images + videos > 0 && cap?.firstFrameRidesAsReference ? 1 : 0;
5093
+ const overCap = referenceCapRefusal(input.model, images, Math.max(0, maxIngredientImagesFor(input.model, input.videoResolution) - frameSlot), 'ingredientAssetIds', frameSlot ? 'reference images beside a start frame, which uses one slot' : 'reference images') ??
5094
+ referenceCapRefusal(input.model, videos, maxReferenceVideosFor(input.model, input.duration), 'videoReferenceAssetIds', 'reference videos on a clip this long') ??
5095
+ referenceCapRefusal(input.model, audio, cap?.maxReferenceAudio ?? 0, 'audioReferenceAssetIds', 'reference audio clips') ??
5096
+ (cap?.maxReferenceFilesTotal
5097
+ ? referenceCapRefusal(input.model, images + frameSlot + videos + audio, cap.maxReferenceFilesTotal, 'ingredientAssetIds', 'reference files across images, video and audio')
5098
+ : null);
5099
+ if (overCap)
5100
+ return ok(overCap);
5101
+ }
4787
5102
  // Resolve every asset reference (UUID or badge code) against the
4788
5103
  // project AT CALL TIME. Codes the user just spoke ("a8 is the one")
4789
5104
  // resolve to whatever exists NOW — including assets created in the UI
@@ -4853,13 +5168,16 @@ export const generateVideo = {
4853
5168
  // a local literal had already lost 'continue the story'.
4854
5169
  intentHits = hasRefs ? seedanceTaskIntentWords(input.prompt) : [];
4855
5170
  }
4856
- // The quote needs a length for EVERY reference clip, in both shapes. A
4857
- // missing one doesn't fail the generation (the server probes and corrects
4858
- // upward) — it silently under-quotes, which is worse than asking.
4859
- // Wan 3.0 bills reference video seconds on top of output seconds too, and
4860
- // Omni Flash's per-clip cap needs every length to check.
5171
+ // A desktop with 'video-quote' prices the composition it will send: it resolves every reference,
5172
+ // prompt @mentions included, and measures each clip itself, so the caller's seconds are not needed.
5173
+ const desktop = ctx.desktop();
5174
+ const desktopQuotes = await desktop.hasCapability('video-quote');
5175
+ // An older desktop quotes H3 Max only, so this op builds the key and needs a length for EVERY
5176
+ // reference clip, in both shapes. A missing one does not fail the generation (the server probes
5177
+ // and corrects upward): it under-quotes, which is worse than asking. Wan 3.0 bills reference video
5178
+ // seconds on top of output seconds too, and Omni Flash's per-clip cap needs every length to check.
4861
5179
  const isSeedance = input.model.startsWith('seedance');
4862
- const needsRefSeconds = isSeedance || input.model === 'wan-3.0' || input.model === 'omni-flash-1-2';
5180
+ const needsRefSeconds = !desktopQuotes && (isSeedance || input.model === 'wan-3.0' || input.model === 'omni-flash-1-2');
4863
5181
  if (input.videoReferenceAssetId && needsRefSeconds && !input.videoReferenceSeconds) {
4864
5182
  return ok({
4865
5183
  requires_clarification: true,
@@ -4878,11 +5196,55 @@ export const generateVideo = {
4878
5196
  }
4879
5197
  // A desktop without Omni Flash 1.2 gets the 1.1 seat at the same price (`desktopModelId`), resolved before the
4880
5198
  // quote so a job it cannot run is refused before the agent is asked to confirm it.
4881
- const seat = await desktopModelId(ctx.desktop(), input.model, `${input.model} generation`, input.duration);
5199
+ const seat = await desktopModelId(desktop, input.model, `${input.model} generation`, input.duration);
5200
+ // One body for the quote and the submission, so the desktop prices exactly what it will be sent.
5201
+ const request = {
5202
+ projectId: input.projectId,
5203
+ model: seat.model,
5204
+ prompt: input.prompt,
5205
+ aspectRatio: input.aspectRatio,
5206
+ duration: input.duration,
5207
+ videoResolution: input.videoResolution,
5208
+ firstFrameAssetId: input.firstFrameAssetId,
5209
+ lastFrameAssetId: input.lastFrameAssetId,
5210
+ ingredientAssetIds: input.ingredientAssetIds ?? [],
5211
+ characterAssetIds: input.characterAssetIds ?? [],
5212
+ environmentAssetIds: input.environmentAssetIds ?? [],
5213
+ styleAssetIds: input.styleAssetIds ?? [],
5214
+ // Both shapes on the wire. The route merges and dedupes them, so an old
5215
+ // client sending only the singular and a new one sending only the plural
5216
+ // reach the identical handler params.
5217
+ videoReferenceAssetId: input.videoReferenceAssetId,
5218
+ audioReferenceAssetId: input.audioReferenceAssetId,
5219
+ videoReferenceAssetIds: input.videoReferenceAssetIds,
5220
+ audioReferenceAssetIds: input.audioReferenceAssetIds,
5221
+ // The route keys this by ASSET ID, not by position, because its own
5222
+ // singular/plural merge appends to the END of the list — an index would
5223
+ // mean different clips depending on which shape the caller used. The op
5224
+ // takes the friendlier positional array and re-keys it here, AFTER
5225
+ // `rids()` has resolved badge codes, so the keys are the ids the route
5226
+ // will resolve. A blank entry is dropped rather than sent as "".
5227
+ audioReferenceSpokenText: spokenTextByAssetId(input.audioReferenceAssetIds, input.audioReferenceSpokenText),
5228
+ sound: input.sound,
5229
+ audioLanguage: input.audioLanguage,
5230
+ generateMusic: input.generateMusic,
5231
+ seedanceFace: input.seedanceFace,
5232
+ seedanceRealFace: input.seedanceRealFace,
5233
+ seedanceDraft: input.seedanceDraft,
5234
+ realFaceConsent: input.realFaceConsent,
5235
+ negativePrompt: input.negativePrompt,
5236
+ ...folderBody(input.folderId),
5237
+ };
4882
5238
  const cloud = ctx.cloud();
4883
5239
  const registry = await cloud.get('/api/agent/models');
4884
- const costKey = input.model === 'minimax-h3-max'
4885
- ? (await ctx.desktop().get('/agent/generation/video-quote', { request: JSON.stringify(input) })).costKey
5240
+ // The desktop's quote: the key its handler bills and its credits, which the submission below is
5241
+ // held to (`maxCredits`). Null on a desktop before 'video-quote'.
5242
+ const quote = desktopQuotes
5243
+ ? await desktop.quote('/agent/generation/video-quote', 'request', request)
5244
+ : null;
5245
+ const costKey = quote?.costKey ?? (input.model === 'minimax-h3-max'
5246
+ // The older desktop's one quote: H3 Max, whose reference tokens only it can count.
5247
+ ? (await desktop.quote('/agent/generation/video-quote', 'request', request)).costKey
4886
5248
  : videoCostKey({
4887
5249
  model: input.model,
4888
5250
  duration: input.duration,
@@ -4894,14 +5256,10 @@ export const generateVideo = {
4894
5256
  // dimension. Counted from the same four arrays the request sends, so the
4895
5257
  // quote and the server's own re-derivation see the same number.
4896
5258
  referenceImages: minimaxRefImageCount(input),
4897
- // Σ ceil(d - 0.05) over every reference clip, both shapes — the same
4898
- // expression the desktop's estimateCost and the handler's key builder
4899
- // use. Quoting only the singular would understate a multi-clip call.
4900
- videoRefSeconds: (input.videoReferenceAssetId && input.videoReferenceSeconds
4901
- ? Math.ceil(input.videoReferenceSeconds - 0.05)
4902
- : 0) +
4903
- (input.videoReferenceSecondsEach ?? []).reduce((n, d) => n + (d > 0 ? Math.ceil(d - 0.05) : 0), 0),
4904
- });
5259
+ // Every reference clip, both shapes: quoting only the singular would
5260
+ // understate a multi-clip call.
5261
+ videoReferenceSecondsEach: referenceClips,
5262
+ }));
4905
5263
  // Hard consent gate, checked before any spend: the real-face route is
4906
5264
  // consent-attested by design (the desktop enforces it too).
4907
5265
  if (input.seedanceRealFace && !input.realFaceConsent) {
@@ -4920,6 +5278,14 @@ export const generateVideo = {
4920
5278
  `Available video models: ${registry.models.filter((m) => VIDEO_MODELS.some((v) => m.model.startsWith(v.split('.')[0]))).map((m) => m.model).slice(0, 20).join(', ')}`);
4921
5279
  }
4922
5280
  const totalCents = creditCost(entry);
5281
+ // What the send is held to, in the desktop's unit (list credits): its own quote, else the registry's list price.
5282
+ const quotedCredits = quote?.credits ?? listCredits(entry);
5283
+ // The price the user approved binds the call that spends: a reference re-measured longer or a
5284
+ // character that gained a billed picture since the pre-flight is asked about again, never run.
5285
+ const approvedCredits = requestedCredits(ctx, input);
5286
+ if (approvedCredits != null && quotedCredits > approvedCredits) {
5287
+ return ok(videoPriceChanged(input.model, costKey, quotedCredits, approvedCredits));
5288
+ }
4923
5289
  if (intentHits.length > 0 && !input.confirm) {
4924
5290
  return ok({
4925
5291
  requires_clarification: true,
@@ -4927,6 +5293,7 @@ export const generateVideo = {
4927
5293
  missing: ['prompt'],
4928
5294
  variant: costKey,
4929
5295
  estimated_credits: totalCents,
5296
+ approvedCredits: quotedCredits,
4930
5297
  message: `Seedance 2.5 reads ${intentHits.map((w) => `"${w}"`).join(', ')} in this prompt as an EDIT or EXTEND instruction and may run it as a video edit, ` +
4931
5298
  `which fails after the job has queued. If you mean to edit an existing clip, call slates_edit_video with model "seedance-2.5-edit". ` +
4932
5299
  `If you mean a fresh shot, describe the finished frame instead of an instruction to change one ("the workshop bench, clear and uncluttered" rather than "remove the tripod"). ` +
@@ -4974,7 +5341,7 @@ export const generateVideo = {
4974
5341
  `${fmtCredits(totalCents)}.` +
4975
5342
  refSummary +
4976
5343
  (promptWarning ? `\n\n${promptWarning}` : '') +
4977
- `\n\nWhen ready, re-call slates_generate_video with confirm=true and the (possibly revised) prompt.`,
5344
+ `\n\nWhen ready, re-call slates_generate_video with confirm=true, approvedCredits=${quotedCredits} and the (possibly revised) prompt.`,
4978
5345
  images: refImages,
4979
5346
  data: {
4980
5347
  requires_confirm: true,
@@ -4982,6 +5349,7 @@ export const generateVideo = {
4982
5349
  variant: costKey,
4983
5350
  estimated_cents: totalCents,
4984
5351
  estimated_credits: totalCents,
5352
+ approvedCredits: quotedCredits,
4985
5353
  references: previews.map((p) => ({
4986
5354
  role: p.role,
4987
5355
  ref: p.ref,
@@ -4994,48 +5362,20 @@ export const generateVideo = {
4994
5362
  },
4995
5363
  };
4996
5364
  }
4997
- const desktop = ctx.desktop();
4998
5365
  if (input.background) {
4999
5366
  await desktop.requireCapability('background-generation', 'background generation');
5000
5367
  }
5368
+ const approved = approvedSpend(ctx, input);
5001
5369
  const result = await desktop.post('/agent/generation/video', {
5002
- projectId: input.projectId,
5003
- model: seat.model,
5004
- prompt: input.prompt,
5005
- aspectRatio: input.aspectRatio,
5006
- duration: input.duration,
5007
- videoResolution: input.videoResolution,
5008
- firstFrameAssetId: input.firstFrameAssetId,
5009
- lastFrameAssetId: input.lastFrameAssetId,
5010
- ingredientAssetIds: input.ingredientAssetIds ?? [],
5011
- characterAssetIds: input.characterAssetIds ?? [],
5012
- environmentAssetIds: input.environmentAssetIds ?? [],
5013
- styleAssetIds: input.styleAssetIds ?? [],
5014
- // Both shapes on the wire. The route merges and dedupes them, so an old
5015
- // client sending only the singular and a new one sending only the plural
5016
- // reach the identical handler params.
5017
- videoReferenceAssetId: input.videoReferenceAssetId,
5018
- audioReferenceAssetId: input.audioReferenceAssetId,
5019
- videoReferenceAssetIds: input.videoReferenceAssetIds,
5020
- audioReferenceAssetIds: input.audioReferenceAssetIds,
5021
- // The route keys this by ASSET ID, not by position, because its own
5022
- // singular/plural merge appends to the END of the list — an index would
5023
- // mean different clips depending on which shape the caller used. The op
5024
- // takes the friendlier positional array and re-keys it here, AFTER
5025
- // `rids()` has resolved badge codes, so the keys are the ids the route
5026
- // will resolve. A blank entry is dropped rather than sent as "".
5027
- audioReferenceSpokenText: spokenTextByAssetId(input.audioReferenceAssetIds, input.audioReferenceSpokenText),
5028
- sound: input.sound,
5029
- audioLanguage: input.audioLanguage,
5030
- generateMusic: input.generateMusic,
5031
- seedanceFace: input.seedanceFace,
5032
- seedanceRealFace: input.seedanceRealFace,
5033
- seedanceDraft: input.seedanceDraft,
5034
- realFaceConsent: input.realFaceConsent,
5035
- negativePrompt: input.negativePrompt,
5036
- ...folderBody(input.folderId),
5370
+ ...request,
5371
+ // The desktop composes the request again and sends nothing that prices above its own quote, which the
5372
+ // check above holds at or below the approved credits, for the quote they were approved for.
5373
+ ...(quote ? heldBody(quote.credits, approved.quoteFingerprint) : {}),
5037
5374
  background: input.background,
5038
5375
  });
5376
+ if (result.quoteExceeded) {
5377
+ return ok(videoPriceChanged(input.model, result.quoteExceeded.costKey, result.quoteExceeded.credits, quotedCredits));
5378
+ }
5039
5379
  if (!result.success) {
5040
5380
  throw new Error(result.error ?? 'Generation failed');
5041
5381
  }
@@ -5199,6 +5539,9 @@ export const generateAudio = {
5199
5539
  }),
5200
5540
  run: async (input, ctx) => {
5201
5541
  requireGuideRead(ctx, input.model);
5542
+ const lengthError = promptLengthError(input.model, input.prompt);
5543
+ if (lengthError)
5544
+ throw new Error(lengthError);
5202
5545
  // A desktop before the folder rule ignores folderId and files at the root.
5203
5546
  if (input.folderId !== undefined)
5204
5547
  await ctx.desktop().requireCapability('media-folder', 'choosing the folder a result lands in');
@@ -5220,8 +5563,9 @@ export const generateAudio = {
5220
5563
  // because "the words that get spoken" and "what you asked for" are the
5221
5564
  // same thing here. That also means the character count is knowable
5222
5565
  // client-side, which is what makes the quote below exact.
5223
- if (input.prompt.length > TTS_MAX_CHARACTERS) {
5224
- throw new Error(`${TTS_MODEL} accepts up to ${TTS_MAX_CHARACTERS} characters in one take — this text is ${input.prompt.length}. Split it into separate lines and generate each one.`);
5566
+ const characters = promptLengthFor(input.model, input.prompt);
5567
+ if (characters > TTS_MAX_CHARACTERS) {
5568
+ throw new Error(`${TTS_MODEL} accepts up to ${TTS_MAX_CHARACTERS} characters in one take — this text is ${characters}. Split it into separate lines and generate each one.`);
5225
5569
  }
5226
5570
  if (input.durationSeconds != null) {
5227
5571
  throw new Error(`${TTS_MODEL} has no duration parameter — speech length falls out of the text, and it bills per character. Drop durationSeconds.`);
@@ -5260,11 +5604,12 @@ export const generateAudio = {
5260
5604
  return ok({
5261
5605
  requires_clarification: true,
5262
5606
  missing: ['durationSeconds'],
5263
- message: `Sound Effects needs a durationSeconds of ${ELEVEN_SFX_MIN_SECONDS}-${ELEVEN_SFX_MAX_SECONDS}. It is billed per second and is never left for the model to pick (that would make the charge non-deterministic). Roughly: 0.5-1s for an impact, 2-4s for a whoosh, 8-22s for a loopable bed.`,
5607
+ message: `Sound Effects needs a durationSeconds of ${ELEVEN_SFX_MIN_SECONDS}-${ELEVEN_SFX_MAX_SECONDS}. It is billed per second and is never left for the model to pick (that would make the charge non-deterministic). Roughly: ${ELEVEN_SFX_MIN_SECONDS}s for an impact, 2-4s for a whoosh, 8-${ELEVEN_SFX_MAX_SECONDS}s for a loopable bed.`,
5264
5608
  });
5265
5609
  }
5266
- if (input.prompt.length > 450) {
5267
- throw new Error(`Sound Effects accepts up to 450 characters — this prompt is ${input.prompt.length}.`);
5610
+ const characters = promptLengthFor(input.model, input.prompt);
5611
+ if (characters > 450) {
5612
+ throw new Error(`Sound Effects accepts up to 450 characters — this prompt is ${characters}.`);
5268
5613
  }
5269
5614
  }
5270
5615
  await ctx.desktop().requireCapability('audio-generation', 'audio generation');
@@ -5290,7 +5635,7 @@ export const generateAudio = {
5290
5635
  const costKey = audioCostKey({
5291
5636
  model: input.model,
5292
5637
  durationSeconds: seconds,
5293
- characters: input.model === TTS_MODEL ? input.prompt.length : undefined,
5638
+ characters: input.model === TTS_MODEL ? promptLengthFor(input.model, input.prompt) : undefined,
5294
5639
  });
5295
5640
  const entry = registry.models.find((m) => m.model === costKey) ??
5296
5641
  (await cloud.get(`/api/agent/models?costKey=${encodeURIComponent(costKey)}`)).models[0];
@@ -5318,6 +5663,7 @@ export const generateAudio = {
5318
5663
  if (input.background) {
5319
5664
  await desktop.requireCapability('background-generation', 'background generation');
5320
5665
  }
5666
+ approvedSpend(ctx);
5321
5667
  const result = await desktop.post('/agent/generation/audio', {
5322
5668
  projectId: input.projectId,
5323
5669
  model: input.model,
@@ -5361,8 +5707,6 @@ export const generateAudio = {
5361
5707
  },
5362
5708
  };
5363
5709
  // ── The Kling tools' quote (lip-sync, motion transfer) ─────────
5364
- /** The server bills the tools in blocks of this many seconds (slates-api `TOOL_BLOCK_SECONDS`). */
5365
- const TOOL_BLOCK_SECONDS = 5;
5366
5710
  /** A project asset's recorded length in seconds, or null when its row has none. */
5367
5711
  async function recordedSeconds(desktop, projectId, assetId) {
5368
5712
  const { assets } = await desktop.get('/agent/assets', { projectId });
@@ -5378,18 +5722,69 @@ async function recordedSeconds(desktop, projectId, assetId) {
5378
5722
  * Control Pro at 42 credits that billed 252.
5379
5723
  */
5380
5724
  async function quoteToolBlocks(ctx, stem, seconds, voiceStep) {
5381
- const blocks = Math.max(1, Math.ceil((seconds ?? 0) / TOOL_BLOCK_SECONDS));
5382
- const costKey = `${stem}-${blocks * TOOL_BLOCK_SECONDS}s`;
5383
- const byKey = new Map();
5384
- const price = async (key) => {
5385
- await loadDynamicPrice(ctx, byKey, key);
5386
- const credits = byKey.get(key);
5387
- if (credits == null)
5725
+ const blocks = Math.max(1, toolBlocks(seconds ?? 0));
5726
+ const costKey = toolBlockKey(stem, blocks);
5727
+ const row = async (key) => {
5728
+ const found = (await ctx.cloud().get(`/api/agent/models?costKey=${encodeURIComponent(key)}`)).models.find((m) => m.model === key);
5729
+ if (!found)
5388
5730
  throw new Error(`Model variant not in registry: ${key}`);
5389
- return credits;
5731
+ return found;
5390
5732
  };
5391
- const totalCents = (await price(costKey)) + (voiceStep ? await price(`${stem}-${TOOL_BLOCK_SECONDS}s`) : 0);
5392
- return { costKey, totalCents, blocks };
5733
+ const rows = [await row(costKey), ...(voiceStep ? [await row(toolBlockKey(stem, 1))] : [])];
5734
+ // `totalCents` is what the account is debited; `listTotal` is the same quote in the desktop's unit, which the
5735
+ // run's ceiling (`maxCredits`) is held in. They differ only on a tier the registry prices below list.
5736
+ const sum = (price) => rows.reduce((total, m) => total + price(m), 0);
5737
+ return { costKey, totalCents: sum(creditCost), listTotal: sum(listCredits), blocks };
5738
+ }
5739
+ /** `approvedCredits` on the two tools: the figure a reply named as `approvedCredits`, once the user approved it. */
5740
+ const TOOL_APPROVED_CREDITS = z.number().int().positive().optional().describe('With confirm=true: the approvedCredits a reply named (its quote, or a quote_exceeded price), once the user has approved it. The desktop measures the media before it runs and runs nothing above it; a call that now quotes higher runs nothing and asks again.');
5741
+ /**
5742
+ * The credits approved for a call, as it is priced: the host's decision where it has one, else the input's.
5743
+ * `approvedSpend` reads the same figure again at the send.
5744
+ */
5745
+ const requestedCredits = (ctx, input) => ctx.spend ? ctx.spend.approvedCredits : input.approvedCredits;
5746
+ /**
5747
+ * A tool run whose length the op could not read is quoted at one block and measured by the desktop as it runs, and
5748
+ * only a desktop with 'lip-sync-quote' does that: its lip-sync and motion-transfer routes hold a run to the
5749
+ * `maxCredits` it is sent (`holdTool`, released with that token). Desktop 1.6.12 and older ignore the ceiling and
5750
+ * bill every 5s block of the media against a one-block approval, so there the run is refused before any spend.
5751
+ */
5752
+ async function requireToolHold(ctx, seconds, feature) {
5753
+ if (seconds == null)
5754
+ await ctx.desktop().requireCapability('lip-sync-quote', feature);
5755
+ }
5756
+ /**
5757
+ * What a confirm asks the user to approve, in the desktop's unit: the quote, or a higher figure the call already
5758
+ * carries (a `quote_exceeded` price, or the model's own claim), which the user is then shown. The reply names it
5759
+ * as `approvedCredits`, and the MCP confirm gate sends exactly that figure with the confirmed run.
5760
+ */
5761
+ function toolCeiling(quoted, requested) {
5762
+ const raised = requested != null && requested > quoted;
5763
+ return {
5764
+ credits: raised ? requested : quoted,
5765
+ raised,
5766
+ sentence: raised ? `Approving lets it spend up to ${fmtCredits(requested)}. ` : '',
5767
+ };
5768
+ }
5769
+ /** The reply when the desktop measured a tool's media above the credits it was sent: nothing ran, and that price is the one to approve. */
5770
+ function toolPriceChanged(tool, held, exceeded) {
5771
+ return ok({
5772
+ requires_confirm: true,
5773
+ quote_exceeded: true,
5774
+ variant: exceeded.costKey,
5775
+ estimated_cents: exceeded.credits,
5776
+ estimated_credits: exceeded.credits,
5777
+ approvedCredits: exceeded.credits,
5778
+ ...(exceeded.fingerprint ? { quote_fingerprint: exceeded.fingerprint } : {}),
5779
+ message: `Nothing ran. Slates measured this ${tool} at ${fmtCredits(exceeded.credits)} (${exceeded.costKey}), above the ${fmtCredits(held)} it was held to. ` +
5780
+ `Tell the user, and once they approve, re-call with confirm=true and approvedCredits=${exceeded.credits}.`,
5781
+ });
5782
+ }
5783
+ /** What a tool run reports it charged. With no measured length the quote was one block, a floor: the charge is unknown, never the floor. */
5784
+ function toolCharge(seconds, totalCents) {
5785
+ return seconds == null
5786
+ ? { cost_cents: null, cost_credits: null, minimum_credits: totalCents, quote_is_floor: true }
5787
+ : { cost_cents: totalCents, cost_credits: totalCents };
5393
5788
  }
5394
5789
  // ── Generate lip-sync ───────────────────────────────────────────
5395
5790
  export const generateLipSync = {
@@ -5410,6 +5805,7 @@ export const generateLipSync = {
5410
5805
  avatarModel: z.enum(['avatar-standard', 'avatar-pro']).optional().describe('Image-source only. avatar-standard for general use; avatar-pro for sharper face fidelity. Price each with slates_estimate_generation_cost.'),
5411
5806
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
5412
5807
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
5808
+ approvedCredits: TOOL_APPROVED_CREDITS,
5413
5809
  }),
5414
5810
  async run(input, ctx) {
5415
5811
  if (input.audioMethod === 'tts' && !input.ttsText) {
@@ -5433,22 +5829,43 @@ export const generateLipSync = {
5433
5829
  // Billed per 5s block of the output: the clip's length on a video source;
5434
5830
  // on a still, the voice track's — typed words at the desktop's reading pace
5435
5831
  // (`lipSyncEstimate`, 13 characters a second, so this quote is the Generate
5436
- // button's), an uploaded file unknown until the desktop measures it. Typed
5832
+ // button's), an uploaded file measured by the desktop off disk. Typed
5437
5833
  // words on a still are two billed calls: the voice step adds one flat block.
5834
+ const uploadOnStill = input.sourceType === 'image' && input.audioMethod === 'upload';
5835
+ // An uploaded track is measured by the desktop, and one that cannot measure it cannot hold the run either.
5836
+ if (uploadOnStill)
5837
+ await ctx.desktop().requireCapability('lip-sync-quote', 'pricing a lip-sync on uploaded audio before it runs');
5438
5838
  const seconds = input.sourceType === 'video'
5439
5839
  ? await recordedSeconds(ctx.desktop(), input.projectId, input.sourceAssetId)
5440
5840
  : input.audioMethod === 'tts'
5441
5841
  ? (input.ttsText ?? '').trim().length / (13 * (input.ttsSpeed ?? 1))
5442
- : null;
5842
+ : (await ctx.desktop().post('/agent/generation/lip-sync-quote', {
5843
+ request: {
5844
+ projectId: input.projectId, sourceAssetId: input.sourceAssetId, audioMethod: input.audioMethod,
5845
+ audioFilePath: input.audioFilePath, avatarModel: input.avatarModel,
5846
+ },
5847
+ })).seconds;
5848
+ // The desktop could not read the file's length, so there is no price to confirm: one block would
5849
+ // be a guess, and the run bills every 5s of the audio.
5850
+ if (uploadOnStill && seconds == null) {
5851
+ return ok({
5852
+ requires_clarification: true,
5853
+ missing: ['audioFilePath'],
5854
+ message: `Nothing ran. Slates could not read the length of ${input.audioFilePath}, and a lip-sync on a still is billed per 5s of its audio, so it cannot be priced. ` +
5855
+ 'Check the path and that the file plays (mp3, wav or m4a), then call again.',
5856
+ });
5857
+ }
5858
+ await requireToolHold(ctx, seconds, 'holding a lip-sync on a clip with no recorded length to the price approved');
5443
5859
  const voiceStep = input.sourceType === 'image' && input.audioMethod === 'tts';
5444
- const { costKey, totalCents, blocks } = await quoteToolBlocks(ctx, stem, seconds, voiceStep);
5860
+ const { costKey, totalCents, listTotal, blocks } = await quoteToolBlocks(ctx, stem, seconds, voiceStep);
5445
5861
  const length = `${blocks * TOOL_BLOCK_SECONDS}s${voiceStep ? ' + voice' : ''}`;
5862
+ const ceiling = toolCeiling(listTotal, requestedCredits(ctx, input));
5446
5863
  // Cost confirm gate. Lip-sync is mechanical — the model re-syncs the
5447
5864
  // user-chosen source to the user-chosen audio. The agent doesn't
5448
5865
  // write a prompt that depends on what the source looks like, so we
5449
5866
  // skip the inline preview and just announce the source code in text.
5450
- // An unknown length quotes one block, a floor, so it always asks.
5451
- if ((totalCents > CONFIRM_CREDITS || seconds == null) && !input.confirm) {
5867
+ // An unknown length quotes one block, a floor, so it always asks, and so does a ceiling above the quote.
5868
+ if ((totalCents > CONFIRM_CREDITS || seconds == null || ceiling.raised) && !input.confirm) {
5452
5869
  const sourceRef = await lookupAssetRef(ctx.desktop(), input.sourceAssetId);
5453
5870
  const audioPreview = input.audioMethod === 'tts'
5454
5871
  ? `Audio: TTS — "${(input.ttsText ?? '').slice(0, 120)}"`
@@ -5458,8 +5875,13 @@ export const generateLipSync = {
5458
5875
  variant: costKey,
5459
5876
  estimated_cents: totalCents,
5460
5877
  estimated_credits: totalCents,
5878
+ approvedCredits: ceiling.credits,
5879
+ ...(seconds == null ? { quote_is_floor: true } : {}),
5461
5880
  source_ref: sourceRef,
5462
- message: `Cost: ${fmtCredits(totalCents)}${seconds == null ? ' or more' : ''} for ${length} lip-sync (${costKey}). ` +
5881
+ message: (seconds == null
5882
+ ? `Cost: at least ${fmtCredits(totalCents)}, one 5s block (${costKey}). The source clip has no recorded length: Slates measures it before it runs and runs nothing above the credits approved, answering with the measured price instead. `
5883
+ : `Cost: ${fmtCredits(totalCents)} for ${length} lip-sync (${costKey}). `) +
5884
+ ceiling.sentence +
5463
5885
  `Source: ${sourceRef}. ${audioPreview}. ` +
5464
5886
  `Re-call with confirm=true after the user explicitly OKs the spend. ` +
5465
5887
  `When discussing with the user, refer to the source by its code (matches the gallery badge).`,
@@ -5469,6 +5891,12 @@ export const generateLipSync = {
5469
5891
  if (input.background) {
5470
5892
  await desktop.requireCapability('background-generation', 'background generation');
5471
5893
  }
5894
+ // Held to the credits approved, else the quote: the desktop measures the media first and runs nothing above
5895
+ // it, so a one-block floor cannot bill eighteen. A quote now above the approval runs nothing and asks again.
5896
+ const approved = approvedSpend(ctx, input);
5897
+ if (approved.approvedCredits != null && listTotal > approved.approvedCredits)
5898
+ return toolPriceChanged('lip-sync', approved.approvedCredits, { credits: listTotal, costKey });
5899
+ const held = approved.approvedCredits ?? listTotal;
5472
5900
  const result = await desktop.post('/agent/generation/lip-sync', {
5473
5901
  projectId: input.projectId,
5474
5902
  sourceAssetId: input.sourceAssetId,
@@ -5481,23 +5909,29 @@ export const generateLipSync = {
5481
5909
  avatarModel: input.avatarModel,
5482
5910
  // No estimatedCost: the desktop prices the media itself, in dollars.
5483
5911
  // This op's figure is CREDITS, which a 1.5.8 desktop recorded as dollars.
5912
+ ...heldBody(held, approved.quoteFingerprint),
5484
5913
  background: input.background,
5485
5914
  });
5915
+ if (result.quoteExceeded)
5916
+ return toolPriceChanged('lip-sync', held, result.quoteExceeded);
5486
5917
  if (!result.success)
5487
5918
  throw new Error(result.error ?? 'Lip-sync generation failed');
5919
+ const charged = toolCharge(seconds, totalCents);
5920
+ const chargedText = seconds == null
5921
+ ? `at ${fmtCredits(totalCents)} per 5s of the audio (its length was not measured, so read the charge from the credit balance)`
5922
+ : `for ${fmtCredits(totalCents)}`;
5488
5923
  if (result.background) {
5489
5924
  const ids = result.generationIds ?? (result.generationId ? [result.generationId] : []);
5490
5925
  return backgroundSubmitted(`${length} lip-sync (${costKey})`, ids, {
5491
5926
  variant: costKey,
5492
5927
  projectId: input.projectId,
5493
5928
  sourceAssetId: input.sourceAssetId,
5494
- cost_cents: totalCents,
5495
- cost_credits: totalCents,
5929
+ ...charged,
5496
5930
  });
5497
5931
  }
5498
5932
  return {
5499
- text: `Generated ${length} lip-sync (${costKey}) into project ${input.projectId} ` +
5500
- `for ${fmtCredits(totalCents)}. ` +
5933
+ text: `Generated ${seconds == null ? 'a' : length} lip-sync (${costKey}) into project ${input.projectId} ` +
5934
+ `${chargedText}. ` +
5501
5935
  (input.audioMethod === 'tts'
5502
5936
  ? `Spoken: "${(input.ttsText ?? '').slice(0, 60)}${(input.ttsText ?? '').length > 60 ? '...' : ''}"`
5503
5937
  : `Audio: ${input.audioFilePath}`),
@@ -5506,8 +5940,7 @@ export const generateLipSync = {
5506
5940
  projectId: input.projectId,
5507
5941
  sourceType: input.sourceType,
5508
5942
  sourceAssetId: input.sourceAssetId,
5509
- cost_cents: totalCents,
5510
- cost_credits: totalCents,
5943
+ ...charged,
5511
5944
  asset: result.asset,
5512
5945
  generationId: result.generationId,
5513
5946
  },
@@ -5529,6 +5962,7 @@ export const generateMotionTransfer = {
5529
5962
  prompt: z.string().optional().describe('Optional refinement. Read slates-prompting-motion-transfer.'),
5530
5963
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
5531
5964
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
5965
+ approvedCredits: TOOL_APPROVED_CREDITS,
5532
5966
  }),
5533
5967
  async run(input, ctx) {
5534
5968
  const motionModel = input.motionModel ?? 'kling-mc-pro';
@@ -5537,13 +5971,15 @@ export const generateMotionTransfer = {
5537
5971
  // the orientation's maximum (the desktop's `motionTransferEstimate`).
5538
5972
  const clipSeconds = await recordedSeconds(ctx.desktop(), input.projectId, input.sourceVideoAssetId);
5539
5973
  const seconds = clipSeconds == null ? null : Math.min(clipSeconds, MOTION_TRANSFER_MAX_SECONDS[input.characterOrientation ?? 'video']);
5540
- const { costKey, totalCents, blocks } = await quoteToolBlocks(ctx, motionModel, seconds, false);
5974
+ await requireToolHold(ctx, seconds, 'holding a motion transfer on a clip with no recorded length to the price approved');
5975
+ const { costKey, totalCents, listTotal, blocks } = await quoteToolBlocks(ctx, motionModel, seconds, false);
5976
+ const ceiling = toolCeiling(listTotal, requestedCredits(ctx, input));
5541
5977
  // Cost confirm gate. Motion transfer is mechanical — the model
5542
5978
  // applies source motion to target image deterministically. We don't
5543
5979
  // burn tokens previewing assets the user already chose; codes in the
5544
5980
  // text are enough to keep the chat unambiguous. A clip with no recorded
5545
- // length quotes one block, a floor, so it always asks.
5546
- if ((totalCents > CONFIRM_CREDITS || seconds == null) && !input.confirm) {
5981
+ // length quotes one block, a floor, so it always asks, and so does a ceiling above the quote.
5982
+ if ((totalCents > CONFIRM_CREDITS || seconds == null || ceiling.raised) && !input.confirm) {
5547
5983
  const desktop = ctx.desktop();
5548
5984
  const [source, target] = await Promise.all([
5549
5985
  lookupAssetRef(desktop, input.sourceVideoAssetId),
@@ -5554,9 +5990,12 @@ export const generateMotionTransfer = {
5554
5990
  variant: costKey,
5555
5991
  estimated_cents: totalCents,
5556
5992
  estimated_credits: totalCents,
5993
+ approvedCredits: ceiling.credits,
5994
+ ...(seconds == null ? { quote_is_floor: true } : {}),
5557
5995
  source_ref: source,
5558
5996
  target_ref: target,
5559
5997
  message: `Cost: ${fmtCredits(totalCents)}${seconds == null ? ' or more' : ''} for ${blocks * TOOL_BLOCK_SECONDS}s ${motionModel} (${costKey}). ` +
5998
+ ceiling.sentence +
5560
5999
  `Transferring motion from ${source} onto ${target}. ` +
5561
6000
  // The saving is READ from the registry, never guessed: "~10 credits"
5562
6001
  // was hand-typed and is a rate change away from being a lie.
@@ -5574,6 +6013,11 @@ export const generateMotionTransfer = {
5574
6013
  if (input.background) {
5575
6014
  await desktop.requireCapability('background-generation', 'background generation');
5576
6015
  }
6016
+ // Held to the credits approved, else the quote, as the lip-sync run is.
6017
+ const approved = approvedSpend(ctx, input);
6018
+ if (approved.approvedCredits != null && listTotal > approved.approvedCredits)
6019
+ return toolPriceChanged('motion transfer', approved.approvedCredits, { credits: listTotal, costKey });
6020
+ const held = approved.approvedCredits ?? listTotal;
5577
6021
  const result = await desktop.post('/agent/generation/motion-transfer', {
5578
6022
  projectId: input.projectId,
5579
6023
  sourceVideoAssetId: input.sourceVideoAssetId,
@@ -5583,10 +6027,14 @@ export const generateMotionTransfer = {
5583
6027
  prompt: input.prompt,
5584
6028
  // No estimatedCost: the desktop prices the media itself, in dollars.
5585
6029
  // This op's figure is CREDITS, which a 1.5.8 desktop recorded as dollars.
6030
+ ...heldBody(held, approved.quoteFingerprint),
5586
6031
  background: input.background,
5587
6032
  });
6033
+ if (result.quoteExceeded)
6034
+ return toolPriceChanged('motion transfer', held, result.quoteExceeded);
5588
6035
  if (!result.success)
5589
6036
  throw new Error(result.error ?? 'Motion transfer generation failed');
6037
+ const charged = toolCharge(seconds, totalCents);
5590
6038
  if (result.background) {
5591
6039
  const ids = result.generationIds ?? (result.generationId ? [result.generationId] : []);
5592
6040
  return backgroundSubmitted(`motion transfer (${motionModel})`, ids, {
@@ -5595,13 +6043,12 @@ export const generateMotionTransfer = {
5595
6043
  projectId: input.projectId,
5596
6044
  sourceVideoAssetId: input.sourceVideoAssetId,
5597
6045
  targetImageAssetId: input.targetImageAssetId,
5598
- cost_cents: totalCents,
5599
- cost_credits: totalCents,
6046
+ ...charged,
5600
6047
  });
5601
6048
  }
5602
6049
  return {
5603
6050
  text: `Generated motion transfer (${motionModel}) into project ${input.projectId} ` +
5604
- `for ${fmtCredits(totalCents)}.` +
6051
+ (seconds == null ? `at ${fmtCredits(totalCents)} per 5s of the clip (its length was not measured, so read the charge from the credit balance).` : `for ${fmtCredits(totalCents)}.`) +
5605
6052
  (input.prompt ? ` Prompt: "${input.prompt.slice(0, 60)}${input.prompt.length > 60 ? '...' : ''}"` : ''),
5606
6053
  data: {
5607
6054
  variant: costKey,
@@ -5609,8 +6056,7 @@ export const generateMotionTransfer = {
5609
6056
  projectId: input.projectId,
5610
6057
  sourceVideoAssetId: input.sourceVideoAssetId,
5611
6058
  targetImageAssetId: input.targetImageAssetId,
5612
- cost_cents: totalCents,
5613
- cost_credits: totalCents,
6059
+ ...charged,
5614
6060
  asset: result.asset,
5615
6061
  generationId: result.generationId,
5616
6062
  },
@@ -5628,12 +6074,12 @@ export const editVideo = {
5628
6074
  // point to in a tool result) and go stale on the next rate change; the
5629
6075
  // windows are owned by MODEL_CAPABILITIES and are generated below into the
5630
6076
  // params that enforce them.
5631
- 'Edit an EXISTING video clip with one instruction — character swap, environment change, style transfer — in one pass, no masking. Original motion, camera, and audio are preserved; only what the prompt names changes. Use when a clip is ~90% right (fix it, don\'t re-roll it) or to AI-edit the user\'s own footage. Engine routing, clip-length and resolution windows are on the `model` param (subject and style refs: ' + EDIT_VIDEO_ELEMENT_MODELS.join(' and ') + ' only); seedanceFace:true for AI-character faces on seedance-2.5-edit. Cost is per second: output seconds on Kling and Omni Flash, input + output on Seedance; quote it with slates_estimate_generation_cost. Subjects to swap IN go as characterAssetIds (frontal + angle images become Kling elements — Kling models only); style refs as styleAssetIds; max 4 combined. The edited clip saves as a NEW asset linked to its parent (chain edits freely). Routing: the `model` param and slates-model-selection. Prompting: slates-prompting-kling-v3 §Edit / slates-prompting-omni-flash. ' +
6077
+ 'Edit an EXISTING video clip with one instruction — character swap, environment change, style transfer — in one pass, no masking. Original motion, camera, and audio are preserved; only what the prompt names changes. Use when a clip is ~90% right (fix it, don\'t re-roll it) or to AI-edit the user\'s own footage. Engine routing, clip-length and resolution windows are on the `model` param (subject and style refs: ' + EDIT_VIDEO_ELEMENT_MODELS.join(', ') + ' only); seedanceFace:true for AI-character faces on seedance-2.5-edit. Cost is per second: output seconds on Kling and Omni Flash, input + output on Seedance; quote it with slates_estimate_generation_cost. Subjects to swap IN go as characterAssetIds; style refs as styleAssetIds (up to the model\'s reference cap combined). The edited clip saves as a NEW asset linked to its parent (chain edits freely). Routing: the `model` param and slates-model-selection. Prompting: slates-prompting-seedance-2-5 / slates-prompting-kling-v3 §Edit / slates-prompting-omni-flash. ' +
5632
6078
  confirmGateSentence('any character or style reference'),
5633
6079
  input: z.object({
5634
6080
  projectId: z.string().uuid().describe('Project the source clip lives in.'),
5635
6081
  sourceVideoAssetId: z.string().describe('The VIDEO asset to edit — UUID or badge code ("VID-V3", bare "V3"); codes resolve against the project at call time. Clip-length windows per engine are on `model`.'),
5636
- prompt: z.string().min(1).max(2500).describe('The change, not the whole scene — e.g. "replace the man with @marcus", "make it a rainy night", "turn the street into a neon Tokyo alley". Mention subjects with @name; the transport compiles them to Kling\'s @ElementN notation (Kling models). For omni-flash-1-2-edit keep it simple and add "Keep everything else the same."'),
6082
+ prompt: z.string().min(1).describe('The change, not the whole scene — e.g. "replace the man with @marcus", "make it a rainy night", "turn the street into a neon Tokyo alley". Mention subjects with @name; the transport compiles them to Kling\'s @ElementN notation (Kling models). For omni-flash-1-2-edit keep it simple and add "Keep everything else the same."'),
5637
6083
  // Clip windows and resolutions GENERATED from MODEL_CAPABILITIES.
5638
6084
  model: zEnum(EDIT_VIDEO_MODELS).optional().describe(
5639
6085
  // Routing GENERATED from MODEL_FACTS; the paragraph that stood here was
@@ -5661,12 +6107,19 @@ export const editVideo = {
5661
6107
  await desktop.requireCapability('background-generation', 'background generation');
5662
6108
  }
5663
6109
  const model = input.model ?? EDIT_VIDEO_DEFAULT;
6110
+ const lengthError = promptLengthError(model, input.prompt);
6111
+ if (lengthError)
6112
+ throw new Error(lengthError);
5664
6113
  requireGuideRead(ctx, model);
5665
6114
  const isOmniFlashEdit = model === 'omni-flash-1-2-edit';
5666
6115
  const isSeedanceEdit = model === 'seedance-2.5-edit';
5667
6116
  // Source-clip window, read from the capability SSOT per engine — never a
5668
6117
  // model-id ternary. (Kling 3–15s, Omni Flash 1.2 3–15s, Seedance 2.5 4–30s.)
5669
6118
  const { min: minClipSeconds, max: maxClipSeconds } = editClipBounds(model);
6119
+ // The enum is the union of the engines' rows, so each engine's own row decides; Kling's output follows the source clip.
6120
+ const resErr = isSeedanceEdit || isOmniFlashEdit ? checkVideoResolution(model, input.videoResolution) : null;
6121
+ if (resErr)
6122
+ return ok({ requires_clarification: true, missing: ['videoResolution'], message: resErr });
5670
6123
  if (!EDIT_VIDEO_ELEMENT_MODELS.includes(model) && ((input.characterAssetIds?.length ?? 0) > 0 || (input.styleAssetIds?.length ?? 0) > 0)) {
5671
6124
  throw new Error(`${model} takes the prompt and the source clip only on this op — no character/style reference images. Drop the refs, or switch to ${EDIT_VIDEO_ELEMENT_MODELS.join(' or ')}, which take them.`);
5672
6125
  }
@@ -5682,8 +6135,9 @@ export const editVideo = {
5682
6135
  const characterAssetIds = (input.characterAssetIds ?? []).map(rid);
5683
6136
  const styleAssetIds = (input.styleAssetIds ?? []).map(rid);
5684
6137
  const refEcho = describeResolvedRefs(refInputs, resolved);
5685
- if (characterAssetIds.length + styleAssetIds.length > EDIT_VIDEO_ELEMENT_CAP) {
5686
- throw new Error(`${model} takes at most ${EDIT_VIDEO_ELEMENT_CAP} subject and style references combined.`);
6138
+ const modelElementCap = getModelCapability(model)?.maxIngredientImages ?? 0;
6139
+ if (characterAssetIds.length + styleAssetIds.length > modelElementCap) {
6140
+ throw new Error(`${model} takes at most ${modelElementCap} subject and style references combined.`);
5687
6141
  }
5688
6142
  // The billed key needs the clip's duration (ceiled). Read it from the
5689
6143
  // project's asset records — the desktop route independently re-validates.
@@ -5697,7 +6151,7 @@ export const editVideo = {
5697
6151
  if (!Number.isFinite(clipSeconds) || clipSeconds <= 0) {
5698
6152
  throw new Error('Source clip has no recorded duration — cannot quote the edit. Re-import the clip or pick another.');
5699
6153
  }
5700
- if (clipSeconds > maxClipSeconds + 0.05 || clipSeconds < minClipSeconds - 0.05) {
6154
+ if (clipSeconds > maxClipSeconds + EDIT_SECONDS_TOLERANCE || clipSeconds < minClipSeconds - EDIT_SECONDS_TOLERANCE) {
5701
6155
  throw new Error(`Source clip is ${clipSeconds.toFixed(1)}s — ${model} accepts ${minClipSeconds}–${maxClipSeconds}s. ` +
5702
6156
  `Trim it first with slates_trim_video (e.g. inSec 0, outSec ${maxClipSeconds}), then edit the trimmed clip` +
5703
6157
  (maxClipSeconds < SEEDANCE_25_EDIT_MAX_SECONDS ? ', or switch to seedance-2.5-edit which accepts up to 30s' : '') +
@@ -5706,7 +6160,7 @@ export const editVideo = {
5706
6160
  // A desktop without Omni Flash 1.2 gets the 1.1 edit seat at the same price, on a clip 1.1 takes
5707
6161
  // (`desktopModelId`), resolved before the quote so a job it cannot run is refused before the agent confirms it.
5708
6162
  const seat = await desktopModelId(desktop, model, `${model} editing`, clipSeconds);
5709
- const billedSeconds = Math.min(maxClipSeconds, Math.max(minClipSeconds, Math.ceil(clipSeconds - 0.05)));
6163
+ const billedSeconds = billedEditSeconds(model, clipSeconds);
5710
6164
  // Three engines, three key shapes — only Seedance's carries a resolution and
5711
6165
  // a face route, because only its price moves with them.
5712
6166
  const costKey = isSeedanceEdit
@@ -5752,6 +6206,7 @@ export const editVideo = {
5752
6206
  },
5753
6207
  };
5754
6208
  }
6209
+ approvedSpend(ctx);
5755
6210
  const result = await desktop.post('/agent/generation/edit-video', {
5756
6211
  projectId: input.projectId,
5757
6212
  model: seat.model,
@@ -6113,7 +6568,9 @@ const reframeClipInput = reframeReportInput.extend({ clipId: z.string().uuid(),
6113
6568
  mode: z.enum(['fill', 'fit']).optional(), focusX: z.number().min(0).max(1).optional(),
6114
6569
  focusY: z.number().min(0).max(1).optional(), zoom: z.number().min(1).optional(),
6115
6570
  }).strict().nullable().optional().describe('Normalized focus and zoom for this clip/aspect. Null resets the override; the desktop binds it to the current take. Required unless follow is set.'),
6116
- follow: z.union([z.enum(['face', 'off']), z.object({ maskId: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/) }).strict()]).optional().describe('"face" finds the face in the clip and keys its focusX/focusY to it (smooth, held where the face is lost; every format draws those keys, each keyframe editable by hand or with slates_set_clip_keyframes); { maskId } follows one of the clip\'s subject masks instead (slates_get_subject_mask lists them); "off" removes those keys. Runs on the computer and spends nothing.') });
6571
+ follow: z.union([z.enum(['face', 'off']), z.object({ maskId: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/) }).strict()]).optional().describe('"face" finds the face in the clip and keys its focusX/focusY to it (smooth, held where the face is lost; every format draws those keys, each keyframe editable by hand or with slates_set_clip_keyframes); { maskId } follows one of the clip\'s subject masks instead (slates_get_subject_mask lists them); "off" removes those keys. Runs on the computer and spends nothing.') })
6572
+ // Every follow form stands alone; the rule lives in the schema so each host applies it before run().
6573
+ .refine((d) => d.framing !== undefined || d.follow !== undefined, { message: 'Send framing (null resets it) or follow', path: ['framing'] });
6117
6574
  export const reframeClip = {
6118
6575
  id: 'slates_reframe_clip', description: 'Set or reset a clip framing override for one delivery aspect and return the desktop computed framing report. Changes focus, fill/fit and zoom without duplicating the timeline or generating media. follow: "face" makes a vertical cut follow a talking head, or { maskId } a subject mask (framing, when sent too, lands first) and answers follow: the clip keyframes, samples, found, still and the lost spans in seconds. Requires ad-variant-export, and reframe-follow for follow; update Slates on capability refusal.',
6119
6576
  billable: false,
@@ -6124,8 +6581,6 @@ export const reframeClip = {
6124
6581
  await ctx.desktop().requireCapability('reframe-follow', 'following a face');
6125
6582
  if (typeof input.follow === 'object')
6126
6583
  await ctx.desktop().requireCapability('subject-follow', 'following a subject mask');
6127
- else if (input.framing === undefined)
6128
- throw new Error('Send framing (null resets it) or follow');
6129
6584
  return ok(await ctx.desktop().post('/agent/timeline/reframe', input));
6130
6585
  },
6131
6586
  };
@@ -6296,21 +6751,29 @@ export const upscaleImage = {
6296
6751
  async run(input, ctx) {
6297
6752
  const desktop = ctx.desktop();
6298
6753
  await desktop.requireCapability('image-upscale', 'picture upscale');
6299
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
6754
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
6300
6755
  const quote = await desktop.get('/agent/generation/upscale-quote', { projectId: input.projectId, assetId: id, factor: String(input.factor) });
6301
6756
  if (quote.credits === null)
6302
6757
  throw new Error(quote.refused ?? 'This picture cannot be upscaled at that size.');
6303
6758
  const name = quote.code ?? id;
6304
6759
  const size = `${quote.width}x${quote.height} to ${quote.outWidth}x${quote.outHeight}`;
6760
+ // Minted here, before the confirm gate, and handed back with the quote: the
6761
+ // confirmed call and any retry of it then carry one id, so a retry after a
6762
+ // dropped connection waits on the same run instead of paying again.
6763
+ const requestId = input.requestId ?? randomUUID();
6305
6764
  if (quote.credits > CONFIRM_CREDITS && !input.confirm) {
6306
6765
  return ok({
6307
6766
  requires_confirm: true, estimated_credits: quote.credits, estimated_cents: quote.credits, factor: quote.factor,
6308
- width: quote.width, height: quote.height, outWidth: quote.outWidth, outHeight: quote.outHeight,
6309
- message: `Cost: ${fmtCredits(quote.credits)} to upscale ${name} ${quote.factor}x (${size}). Re-call with confirm=true after the user explicitly OKs the spend.`,
6767
+ width: quote.width, height: quote.height, outWidth: quote.outWidth, outHeight: quote.outHeight, requestId,
6768
+ message: `Cost: ${fmtCredits(quote.credits)} to upscale ${name} ${quote.factor}x (${size}). Re-call with confirm=true and requestId=${requestId} after the user explicitly OKs the spend, and keep that requestId on any retry.`,
6310
6769
  });
6311
6770
  }
6312
- const requestId = input.requestId ?? randomUUID();
6313
- const r = await desktop.post('/agent/generation/upscale-image', { projectId: input.projectId, assetId: id, factor: input.factor, expectedCredits: quote.credits, requestId });
6771
+ approvedSpend(ctx);
6772
+ const r = await desktop.post('/agent/generation/upscale-image', { projectId: input.projectId, assetId: id, factor: input.factor, expectedCredits: quote.credits, requestId }).catch((error) => {
6773
+ // The request may have reached the desktop before the connection failed: the retry reuses this id.
6774
+ const said = error instanceof Error ? error.message : String(error);
6775
+ throw new Error(`${said.replace(/[.\s]+$/, '')}. The upscale may still be running. Retry with requestId=${requestId}: the same id never pays twice.`, { cause: error });
6776
+ });
6314
6777
  if (!r.asset)
6315
6778
  return ok({ ...r, requestId }, `The upscale of ${name} under this requestId is still running; check slates_get_generation_status with ${r.generationId ?? requestId}. Do not start it again with a new requestId.`);
6316
6779
  const spent = r.cost_credits ?? r.credits ?? quote.credits;
@@ -6351,13 +6814,31 @@ export const resolveReviewNote = {
6351
6814
  async run(input, ctx) {
6352
6815
  await ctx.desktop().requireCapability('review-mode', 'Review mode');
6353
6816
  const refs = [...new Set(input.replies.flatMap((r) => r.assetIds ?? []))];
6354
- const resolved = refs.length ? await resolveAssetRefs(ctx, input.projectId, refs) : new Map();
6355
- const replies = input.replies.map((r) => (r.assetIds ? { ...r, assetIds: r.assetIds.map((a) => resolved.get(a).id) } : r));
6817
+ const resolved = refs.length ? await resolveAssetRefs(ctx, input.projectId, refs) : new AssetRefs();
6818
+ const replies = input.replies.map((r) => (r.assetIds ? { ...r, assetIds: r.assetIds.map((a) => resolved.id(a)) } : r));
6356
6819
  return ok(await ctx.desktop().post('/agent/review/resolve', { projectId: input.projectId, replies }));
6357
6820
  },
6358
6821
  };
6359
6822
  // ── Wave 6: the Winners Loop, Visual QA, stacked video edits, diagnostics, winning ads ──
6360
6823
  const META_WINNERS = 'the Winners Loop (ad results per recipe)';
6824
+ export const getClientAdReport = {
6825
+ id: 'slates_get_client_ad_report',
6826
+ // No Google Ads: Google's Ads API policy bars re-exposing it through an MCP server on our Cloud project.
6827
+ description: 'List connected TikTok Ads advertisers, or read date-range ad performance with linked Slates exports. Uses the signed-in desktop connection. Publishing and account changes happen in the window. Google Ads results are shown only in the Slates window: agents cannot read or change Google Ads, so send the person to Ads, then Google Ads.',
6828
+ input: z.object({
6829
+ platform: z.enum(['tiktok']),
6830
+ accountId: z.string().regex(/^\d{1,24}$/).optional(),
6831
+ managerId: z.string().regex(/^\d{10}$/).optional(),
6832
+ since: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
6833
+ until: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
6834
+ projectId: z.string().uuid().optional().describe('Resolve linked export names within this project.'),
6835
+ }).strict(),
6836
+ async run(input, ctx) {
6837
+ const desktop = ctx.desktop();
6838
+ await desktop.requireCapability('client-ads', 'connected ad account reporting');
6839
+ return ok(await desktop.get('/agent/client-ads', { ...input }));
6840
+ },
6841
+ };
6361
6842
  export const getAdWinners = {
6362
6843
  id: 'slates_get_ad_winners',
6363
6844
  description: "What each exported ad recipe earned in the person's ad account over the last pulled range, as the account reports it: spend, purchases, ROAS, the person's winner or loser mark, the losers, and the project's split tests (splitTests: each local id for slates_evaluate_split_test_winner, campaign, status and stored winner). Never remake a recipe listed in losers. Read this before planning more variants of an ad. Free. Requires meta-winners; update Slates on capability refusal.",
@@ -6518,7 +6999,7 @@ async function resolvePassAssets(ctx, projectId, input) {
6518
6999
  if (!refs.length)
6519
7000
  return input;
6520
7001
  const resolved = await resolveAssetRefs(ctx, projectId, refs);
6521
- const id = (ref) => resolved.get(ref).id;
7002
+ const id = (ref) => resolved.id(ref);
6522
7003
  return {
6523
7004
  ...input,
6524
7005
  ...(input.params ? { params: { ...params, ...Object.fromEntries(named.map((k) => [k, id(params[k])])) } } : {}),
@@ -6590,6 +7071,7 @@ export const runV2vPasses = {
6590
7071
  throw new Error(`These passes are not on timeline ${input.timelineId}: ${missing.join(', ')}. Run passes of one timeline at a time.`);
6591
7072
  for (const model of new Set(input.passIds.map((id) => byId.get(id).model)))
6592
7073
  requireGuideRead(ctx, model);
7074
+ approvedSpend(ctx);
6593
7075
  return ok(await desktop.post('/agent/timeline/v2v/run', input));
6594
7076
  },
6595
7077
  };
@@ -8016,7 +8498,7 @@ export const createLibraryItem = {
8016
8498
  return ok(created);
8017
8499
  return ok(await ctx.desktop().post('/agent/library/items/update', {
8018
8500
  id: created.item.id,
8019
- data: { imageAssetId: resolved.get(imageAssetId).id },
8501
+ data: { imageAssetId: resolved.id(imageAssetId) },
8020
8502
  }));
8021
8503
  },
8022
8504
  };
@@ -8043,7 +8525,7 @@ export const updateLibraryItem = {
8043
8525
  }
8044
8526
  const refs = [input.imageAssetId, input.voiceAssetId, ...(input.extraAssetIds ?? [])].filter((r) => typeof r === 'string');
8045
8527
  const resolved = await resolveAssetRefs(ctx, input.projectId, refs);
8046
- const asset = (ref) => typeof ref === 'string' ? resolved.get(ref).id : ref;
8528
+ const asset = (ref) => typeof ref === 'string' ? resolved.id(ref) : ref;
8047
8529
  return ok(await ctx.desktop().post('/agent/library/items/update', {
8048
8530
  id: input.itemId,
8049
8531
  retagShots: input.retagShots,
@@ -8056,7 +8538,7 @@ export const updateLibraryItem = {
8056
8538
  // explicit null is the clear.
8057
8539
  ...(input.imageAssetId !== undefined ? { imageAssetId: asset(input.imageAssetId) } : {}),
8058
8540
  ...(input.voiceAssetId !== undefined ? { voiceAssetId: asset(input.voiceAssetId) } : {}),
8059
- ...(input.extraAssetIds !== undefined ? { extraAssetIds: input.extraAssetIds.map((ref) => resolved.get(ref).id) } : {}),
8541
+ ...(input.extraAssetIds !== undefined ? { extraAssetIds: input.extraAssetIds.map((ref) => resolved.id(ref)) } : {}),
8060
8542
  ...(input.palette !== undefined ? { palette: input.palette } : {}),
8061
8543
  },
8062
8544
  }));
@@ -8188,7 +8670,7 @@ export const getReferenceBreakdown = {
8188
8670
  .strict(),
8189
8671
  async run(input, ctx) {
8190
8672
  await ctx.desktop().requireCapability('reference-breakdown', 'breaking a reference ad into shots');
8191
- const assetId = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
8673
+ const assetId = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
8192
8674
  return ok(await ctx.desktop().get('/agent/reference/breakdown', { projectId: input.projectId, assetId }));
8193
8675
  },
8194
8676
  };
@@ -8252,7 +8734,7 @@ export const breakDownReference = {
8252
8734
  if ([input.assetId, input.filePath, input.url].filter(Boolean).length !== 1) {
8253
8735
  throw new Error('Give exactly one of assetId (a video or picture in the project), filePath or url.');
8254
8736
  }
8255
- const assetId = input.assetId ? (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id : input.assetId;
8737
+ const assetId = input.assetId ? (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId) : input.assetId;
8256
8738
  // Every Shot is stored under this id, as the desktop knows it (`desktopModelId`).
8257
8739
  const seat = await desktopModelId(ctx.desktop(), input.model, `a breakdown's Shots on ${input.model}`);
8258
8740
  const r = await ctx.desktop().post('/agent/reference/breakdown', { ...input, assetId, model: seat.model, cancel: undefined });
@@ -8511,9 +8993,8 @@ const shotRefsSchemaTerse = z
8511
8993
  .optional()
8512
8994
  .describe(SEE_CREATE_SHOT + SHOT_REFS_LEAD);
8513
8995
  // The full ratio vocabulary a Shot can hold — image OR video, because a Shot is
8514
- // any generation. Per-model narrowing happens at create time for video (the same
8515
- // `assertVideoCapabilities` gate `slates_generate_video` uses) and at generate
8516
- // time for everything.
8996
+ // any generation. Per-model narrowing happens at save time through
8997
+ // `assertShotCapabilities`, the same gates the generate ops run.
8517
8998
  const SHOT_ASPECT_RATIOS = [...new Set([...VIDEO_ASPECT_RATIOS, ...IMAGE_ASPECT_RATIOS])];
8518
8999
  // 🚨 THE PER-MODEL CAPABILITY TABLES ARE DELIBERATELY NOT REPEATED HERE.
8519
9000
  // `slates_generate_video`'s param descriptions already carry them and are always
@@ -8650,33 +9131,13 @@ function shotParamsPatch(p) {
8650
9131
  for (const [k, v] of Object.entries(p))
8651
9132
  if (v !== undefined)
8652
9133
  out[k] = v;
8653
- if (p.seedanceDraft && p.videoResolution === undefined)
8654
- out.videoResolution = '480p';
8655
9134
  return out;
8656
9135
  }
8657
- /**
8658
- * `audioRefSpokenText` pairs POSITIONALLY with the audio references, so it can
8659
- * only be sent alongside them.
8660
- *
8661
- * Refused rather than truncated or silently re-keyed: the whole point of the
8662
- * field is that the WORDS are exact, and a misaligned array attaches one clip's
8663
- * line to another clip with nothing on screen to say so. Same rule
8664
- * `slates_generate_video` already applies.
8665
- */
9136
+ /** `audioRefSpokenText` pairs by position with the audio references: the
9137
+ * `slates_generate_video` rule, as a clarification before anything is written. */
8666
9138
  function checkSpokenTextAlignment(input) {
8667
- if (input.audioRefSpokenText === undefined)
8668
- return null;
8669
- const clips = input.refs?.['audio-reference'];
8670
- if (!clips || clips.length !== input.audioRefSpokenText.length) {
8671
- return ok({
8672
- requires_clarification: true,
8673
- missing: ['refs["audio-reference"]'],
8674
- message: `audioRefSpokenText pairs by position with refs["audio-reference"], so send both together ` +
8675
- `and at the same length (${input.audioRefSpokenText.length} line(s) vs ${clips?.length ?? 0} clip(s)). ` +
8676
- `Use "" for a clip with no speech.`,
8677
- });
8678
- }
8679
- return null;
9139
+ const message = spokenTextMisalignment(input.refs?.['audio-reference'], input.audioRefSpokenText, SHOT_SPOKEN_FIELDS);
9140
+ return message ? ok({ requires_clarification: true, missing: [SHOT_SPOKEN_FIELDS.clips], message }) : null;
8680
9141
  }
8681
9142
  /** Every asset reference a Shot input carries, flat, for one `resolveAssetRefs`
8682
9143
  * pass. Derived from the role list so a new role resolves badge codes too. */
@@ -8692,6 +9153,8 @@ function shotRefInputs(input) {
8692
9153
  out.push({ ref: input.lastFrameAssetId, role: 'last frame' });
8693
9154
  if (input.params?.voiceReferenceAssetId)
8694
9155
  out.push({ ref: input.params.voiceReferenceAssetId, role: 'voice reference' });
9156
+ if (input.posterAssetId)
9157
+ out.push({ ref: input.posterAssetId, role: 'poster' });
8695
9158
  return out;
8696
9159
  }
8697
9160
  /**
@@ -8715,13 +9178,7 @@ async function buildShotSpecInput(ctx, projectId, input) {
8715
9178
  // Positional in, KEYED out — the same re-keying `slates_generate_video` does,
8716
9179
  // and for the same reason: an index means different clips depending on how the
8717
9180
  // list was assembled, while an asset id cannot drift.
8718
- const audioIds = refs['audio-reference'] ?? [];
8719
- const spoken = {};
8720
- (input.audioRefSpokenText ?? []).forEach((text, i) => {
8721
- const id = audioIds[i];
8722
- if (id && text?.trim())
8723
- spoken[id] = text.trim();
8724
- });
9181
+ const spoken = spokenTextByAssetId(refs['audio-reference'], input.audioRefSpokenText, SHOT_SPOKEN_FIELDS) ?? {};
8725
9182
  return {
8726
9183
  spec: {
8727
9184
  prompt: input.prompt,
@@ -8746,6 +9203,8 @@ async function buildShotSpecInput(ctx, projectId, input) {
8746
9203
  },
8747
9204
  refEcho: describeResolvedRefs(refInputs, resolvedRefs),
8748
9205
  seatNote: seat.note,
9206
+ // null resets the poster to its default; undefined leaves it alone.
9207
+ posterAssetId: input.posterAssetId === undefined ? undefined : rid(input.posterAssetId ?? undefined),
8749
9208
  };
8750
9209
  }
8751
9210
  /**
@@ -8806,16 +9265,19 @@ function namedSpecPatch(input, spec) {
8806
9265
  /**
8807
9266
  * The capability gate, applied to a SAVED recipe.
8808
9267
  *
8809
- * It enforces exactly what the matching generate op enforces and no more: video
8810
- * goes through `assertVideoCapabilities` (the MODEL_CAPABILITIES SSOT), image
8811
- * does not, because `slates_generate_image`'s own per-model ratio check is the
8812
- * named open follow-up in the capability plan. A Shot that refused what
8813
- * `slates_generate_image` accepts would be a THIRD opinion about the same
8814
- * model, which is worse than the gap.
9268
+ * It enforces exactly what the matching generate op enforces and no more, from
9269
+ * the same functions: `assertVideoCapabilities` for a video seat,
9270
+ * `assertImageCapabilities` for an image seat. A Shot that refused what the
9271
+ * generate op accepts, or saved what it refuses, would be a third opinion
9272
+ * about the same model.
8815
9273
  */
8816
9274
  function assertShotCapabilities(model, params) {
8817
9275
  if (params?.seedanceDraft && model)
8818
9276
  draftResolution(model, params.videoResolution);
9277
+ if (model && IMAGE_MODELS.includes(model)) {
9278
+ const err = assertImageCapabilities({ model, aspectRatio: params?.aspectRatio, resolution: params?.imageResolution }, { resolution: 'imageResolution' });
9279
+ return err ? ok(err) : null;
9280
+ }
8819
9281
  if (!model || !VIDEO_MODELS.includes(model))
8820
9282
  return null;
8821
9283
  const err = assertVideoCapabilities({
@@ -8826,12 +9288,47 @@ function assertShotCapabilities(model, params) {
8826
9288
  });
8827
9289
  return err ? ok(err) : null;
8828
9290
  }
8829
- async function requireDraftShotDesktop(desktop, model, params, shotId) {
9291
+ const SHOT_PROJECT_DESCRIBE = "The Shot's project. A SHOT-A code is unique only within its project, so pass this with a code.";
9292
+ /**
9293
+ * The Shot a ref names, read at most once per call. A SHOT-A code is unique only
9294
+ * within its project, so it resolves against `projectId` whenever the caller has
9295
+ * one, and a Shot that lives in another project is refused rather than edited,
9296
+ * priced or billed.
9297
+ */
9298
+ function shotReader(desktop, ref, projectId) {
9299
+ let read;
9300
+ return () => (read ??= desktop
9301
+ .get('/agent/shots/get', projectId ? { id: ref, projectId } : { id: ref })
9302
+ .then(({ shot }) => {
9303
+ if (projectId && shot.projectId && shot.projectId !== projectId) {
9304
+ throw new Error(`${ref} is a Shot of another project (${shot.projectId}), not ${projectId}. Pass that project as projectId to work on it, or a Shot of this project.`);
9305
+ }
9306
+ return shot;
9307
+ }));
9308
+ }
9309
+ /** The row id to send for a Shot ref: an id as given, a code resolved through its reader. */
9310
+ async function shotRowId(ref, read) {
9311
+ return UUID_RE.test(ref.trim()) ? ref : (await read()).id;
9312
+ }
9313
+ /** Params whose legality depends on the Shot's model. */
9314
+ const MODEL_BOUND_SHOT_PARAMS = ['aspectRatio', 'videoResolution', 'imageResolution', 'duration', 'seedanceDraft'];
9315
+ /** An edit that names no model is checked against the stored Shot's, the gate create runs. */
9316
+ async function assertStoredShotCapabilities(model, params, read, prompt) {
9317
+ if (prompt !== undefined || model !== undefined) {
9318
+ const error = promptLengthError(model ?? (await read()).model, prompt ?? (await read()).rawPrompt);
9319
+ if (error)
9320
+ throw new Error(error);
9321
+ }
9322
+ if (model !== undefined || !MODEL_BOUND_SHOT_PARAMS.some((k) => params?.[k] !== undefined))
9323
+ return null;
9324
+ return assertShotCapabilities((await read()).model ?? undefined, params);
9325
+ }
9326
+ async function requireDraftShotDesktop(desktop, model, params, read) {
8830
9327
  if (params?.seedanceDraft) {
8831
9328
  await desktop.requireCapability('seedance-drafts', 'saving a Seedance 2.5 draft');
8832
9329
  }
8833
9330
  else if (params?.videoResolution === '4k') {
8834
- const target = model ?? (shotId ? (await desktop.get('/agent/shots/get', { id: shotId })).shot.model : undefined);
9331
+ const target = model ?? (read ? (await read()).model : undefined);
8835
9332
  if (target === 'seedance-2.5')
8836
9333
  await desktop.requireCapability('seedance-drafts', 'saving a native 4K Seedance Shot');
8837
9334
  }
@@ -8851,7 +9348,7 @@ export const createShot = {
8851
9348
  input: z.object({
8852
9349
  projectId: z.string().uuid(),
8853
9350
  name: z.string().max(120).optional().describe('What to call it. Shown on the card; the prompt supplies one if you omit it.'),
8854
- prompt: z.string().min(1).max(4000).optional().describe('The RAW prompt, @mentions intact. Never write "image 1" yourself — the composer numbers references, and a hand-written number is wrong the moment one moves. Required unless fromAssetId supplies the recipe.'),
9351
+ prompt: z.string().min(1).optional().describe('The RAW prompt, @mentions intact. Never write "image 1" yourself — the composer numbers references, and a hand-written number is wrong the moment one moves. Required unless fromAssetId supplies the recipe.'),
8855
9352
  fromAssetId: z.string().optional().describe("Save as shot: start from this asset's RECORDED recipe (UUID or badge code) — its prompt, model, settings and references — as Media's Save as shot does. That result becomes the Shot's first take unless another Shot already holds it. Anything else you pass overrides the recipe."),
8856
9353
  model: z.string().optional().describe('Model id — the same ids slates_generate_image / slates_generate_video / slates_generate_audio take, and their descriptions carry the routing. Optional: a Shot can be planned before the model is decided.'),
8857
9354
  params: shotParamsSchema,
@@ -8871,6 +9368,9 @@ export const createShot = {
8871
9368
  async run(input, ctx) {
8872
9369
  if (!input.prompt && !input.fromAssetId)
8873
9370
  throw new Error('Pass a prompt, or fromAssetId to save a result\'s recorded recipe as the Shot.');
9371
+ const lengthError = promptLengthError(input.model, input.prompt);
9372
+ if (lengthError)
9373
+ throw new Error(lengthError);
8874
9374
  const capErr = assertShotCapabilities(input.model, input.params);
8875
9375
  if (capErr)
8876
9376
  return capErr;
@@ -8958,7 +9458,7 @@ export const updateShot = {
8958
9458
  shotId: z.string().describe('The Shot id, or its SHOT-A code as shown on the row.'),
8959
9459
  projectId: z.string().uuid().describe('The Shot\'s project — badge codes and entity ids resolve against it.'),
8960
9460
  name: z.string().max(120).optional(),
8961
- prompt: z.string().max(4000).optional(),
9461
+ prompt: z.string().optional(),
8962
9462
  model: z.string().optional(),
8963
9463
  params: shotParamsSchemaTerse,
8964
9464
  refs: shotRefsSchemaTerse,
@@ -8982,19 +9482,23 @@ export const updateShot = {
8982
9482
  return alignErr;
8983
9483
  const desktop = ctx.desktop();
8984
9484
  await desktop.requireCapability('shots', 'saved Shots');
8985
- await requireDraftShotDesktop(desktop, input.model, input.params, input.shotId);
8986
- const { spec, seatNote } = await buildShotSpecInput(ctx, input.projectId, input);
9485
+ const read = shotReader(desktop, input.shotId, input.projectId);
9486
+ const storedErr = await assertStoredShotCapabilities(input.model, input.params, read, input.prompt);
9487
+ if (storedErr)
9488
+ return storedErr;
9489
+ await requireDraftShotDesktop(desktop, input.model, input.params, read);
9490
+ const { spec, seatNote, posterAssetId } = await buildShotSpecInput(ctx, input.projectId, input);
8987
9491
  // Only send the halves the caller actually named; the route merges a PARTIAL
8988
9492
  // spec over the stored one, so an omitted field is never silently cleared.
8989
9493
  const patch = namedSpecPatch(input, spec);
8990
9494
  const r = await desktop.post('/agent/shots/update', {
8991
- id: input.shotId,
9495
+ id: await shotRowId(input.shotId, read),
8992
9496
  data: {
8993
9497
  name: input.name,
8994
9498
  ...(Object.keys(patch).length > 0 ? { spec: patch } : {}),
8995
9499
  attachFrameId: input.attachFrameId,
8996
9500
  detachFrameId: input.detachFrameId,
8997
- posterAssetId: input.posterAssetId,
9501
+ posterAssetId,
8998
9502
  },
8999
9503
  });
9000
9504
  // An edit to framing changes the counts, and the agent read them BEFORE it
@@ -9008,8 +9512,9 @@ export const duplicateShot = {
9008
9512
  description: 'Fork a saved Shot, changing the prompt, the model or any param on the COPY in the same call — make one, fork it five times, change one thing on each. The original is never touched.',
9009
9513
  input: z.object({
9010
9514
  shotId: z.string().describe('The Shot id, or its SHOT-A code.'),
9515
+ projectId: z.string().uuid().optional().describe(SHOT_PROJECT_DESCRIBE),
9011
9516
  name: z.string().max(120).optional().describe('Name for the copy (default: the original plus "copy").'),
9012
- prompt: z.string().max(4000).optional().describe('Replace the prompt on the copy. Omit to keep the original\'s.'),
9517
+ prompt: z.string().optional().describe('Replace the prompt on the copy. Omit to keep the original\'s.'),
9013
9518
  model: z.string().optional().describe('Point the copy at a different model — the A/B lever. The prompt is NOT rewritten, and the copy records which model it was written for.'),
9014
9519
  params: shotParamsSchemaTerse,
9015
9520
  frameId: z.string().uuid().nullable().optional().describe('Attach the copy to this frame. Omit to keep the original\'s frame; pass null to leave it unattached.'),
@@ -9020,7 +9525,11 @@ export const duplicateShot = {
9020
9525
  return capErr;
9021
9526
  const desktop = ctx.desktop();
9022
9527
  await desktop.requireCapability('shots', 'saved Shots');
9023
- await requireDraftShotDesktop(desktop, input.model, input.params, input.shotId);
9528
+ const read = shotReader(desktop, input.shotId, input.projectId);
9529
+ const storedErr = await assertStoredShotCapabilities(input.model, input.params, read, input.prompt);
9530
+ if (storedErr)
9531
+ return storedErr;
9532
+ await requireDraftShotDesktop(desktop, input.model, input.params, read);
9024
9533
  // Only the halves actually named. The route merges two levels deep, so an
9025
9534
  // omitted param on the copy keeps the original's value rather than clearing it.
9026
9535
  const spec = {};
@@ -9032,8 +9541,7 @@ export const duplicateShot = {
9032
9541
  if (input.params !== undefined) {
9033
9542
  const voiceRef = input.params.voiceReferenceAssetId;
9034
9543
  if (voiceRef && !UUID_RE.test(voiceRef)) {
9035
- const { shot } = await desktop.get('/agent/shots/get', { id: input.shotId });
9036
- const built = await buildShotSpecInput(ctx, shot.projectId, { params: input.params });
9544
+ const built = await buildShotSpecInput(ctx, (await read()).projectId, { params: input.params });
9037
9545
  spec.params = built.spec.params;
9038
9546
  }
9039
9547
  else {
@@ -9041,7 +9549,7 @@ export const duplicateShot = {
9041
9549
  }
9042
9550
  }
9043
9551
  const r = await desktop.post('/agent/shots/duplicate', {
9044
- id: input.shotId,
9552
+ id: await shotRowId(input.shotId, read),
9045
9553
  name: input.name,
9046
9554
  ...(Object.keys(spec).length > 0 ? { spec } : {}),
9047
9555
  frameId: input.frameId,
@@ -9114,15 +9622,8 @@ export const listShots = {
9114
9622
  });
9115
9623
  const rows = r.shots ?? [];
9116
9624
  const projectId = input.projectId;
9117
- // The quote is a GET with every id in its query string, and Node refuses a
9118
- // request head over 16 KiB (about 345 ids), so a long board is quoted in
9119
- // chunks. Each Shot's price is its own; only this listing reads them.
9120
- const QUOTE_CHUNK = 150;
9121
- const chunks = [];
9122
- for (let i = 0; i < rows.length; i += QUOTE_CHUNK)
9123
- chunks.push(rows.slice(i, i + QUOTE_CHUNK).map(r => r.id));
9124
9625
  const quote = projectId && rows.length
9125
- ? { items: (await Promise.all(chunks.map((shotIds) => desktop.get('/agent/shots/quote', { input: JSON.stringify({ projectId, shotIds }) })))).flatMap((q) => q.items) }
9626
+ ? await desktop.quote('/agent/shots/quote', 'input', { projectId, shotIds: rows.map((r) => r.id) })
9126
9627
  : null;
9127
9628
  let total = 0;
9128
9629
  let unpriced = 0;
@@ -9196,14 +9697,18 @@ export const getShot = {
9196
9697
  description: 'Read one Shot in full — the COMPOSED prompt the request will actually carry, its numbered references, anything it points at that no longer exists, its exact credit quote, and its place on the board (2C, as the window shows it). Audit your own work here before firing.',
9197
9698
  input: z.object({
9198
9699
  shotId: z.string().describe('The Shot id, or its SHOT-A code as shown on the row.'),
9700
+ projectId: z.string().uuid().optional().describe(SHOT_PROJECT_DESCRIBE),
9199
9701
  }),
9200
9702
  async run(input, ctx) {
9201
9703
  const desktop = ctx.desktop();
9202
9704
  await desktop.requireCapability('shots', 'saved Shots');
9203
9705
  // Prices come only from the desktop's quote; a 1.5.8 desktop has none.
9204
9706
  await desktop.requireCapability('board-quote', 'Shot prices');
9205
- const r = await desktop.get('/agent/shots/get', { id: input.shotId });
9206
- const quote = await desktop.get('/agent/shots/quote', { input: JSON.stringify({ projectId: r.shot.projectId, shotIds: [r.shot.id] }) });
9707
+ // A read by the Shot's own id needs no project: the project only says where a code is looked up, and a
9708
+ // default one (the CLI's `slates use`) must not refuse a Shot that lives elsewhere.
9709
+ const scope = UUID_RE.test(input.shotId.trim()) ? undefined : input.projectId;
9710
+ const r = { shot: await shotReader(desktop, input.shotId, scope)() };
9711
+ const quote = await desktop.quote('/agent/shots/quote', 'input', { projectId: r.shot.projectId, shotIds: [r.shot.id] });
9207
9712
  const q = quote.items[0];
9208
9713
  return ok({ ...r.shot, credits: q.credits, quoteFingerprint: quote.fingerprint }, `${r.shot.place ? `${r.shot.place} ` : ''}"${r.shot.name || 'Untitled'}" — ${r.shot.model ?? 'no model set'}, ` +
9209
9714
  (q.credits != null && !r.shot.blocked
@@ -9258,6 +9763,7 @@ export const splitShot = {
9258
9763
  description: 'Split one Shot into two at a caret in its line. The text after the caret moves to the new Shot, which INHERITS the model, params and references and lands directly after it in the scene. A mid-sentence split marks the second row as continuing the first — one sentence, two cuts, which is the signature voiceover move. Takes stay with the first row. Omit the caret to add a sibling cut with the same visuals and no words moved.',
9259
9764
  input: z.object({
9260
9765
  shotId: z.string().describe('The Shot id, or its SHOT-A code.'),
9766
+ projectId: z.string().uuid().optional().describe(SHOT_PROJECT_DESCRIBE),
9261
9767
  caret: z
9262
9768
  .number()
9263
9769
  .int()
@@ -9268,7 +9774,7 @@ export const splitShot = {
9268
9774
  async run(input, ctx) {
9269
9775
  const desktop = ctx.desktop();
9270
9776
  await desktop.requireCapability('shots', 'saved Shots');
9271
- const r = await desktop.post('/agent/shots/split', { id: input.shotId, caret: input.caret });
9777
+ const r = await desktop.post('/agent/shots/split', { id: await shotRowId(input.shotId, shotReader(desktop, input.shotId, input.projectId)), caret: input.caret });
9272
9778
  return ok(r, `Split into ${r.first?.code || 'the first Shot'} and ` +
9273
9779
  `${r.second?.code || 'a new Shot'}. Duration was INHERITED, not divided — ` +
9274
9780
  `set it on each if the chop changed how long they run.`);
@@ -9317,13 +9823,14 @@ export const mergeShots = {
9317
9823
  input: z.object({
9318
9824
  firstId: z.string().describe('The Shot that survives — its model and params win. Id or SHOT-A code.'),
9319
9825
  secondId: z.string().describe('The Shot folded into it. Id or SHOT-A code.'),
9826
+ projectId: z.string().uuid().optional().describe("The Shots' project. A SHOT-A code is unique only within its project, so pass this with codes."),
9320
9827
  }),
9321
9828
  async run(input, ctx) {
9322
9829
  const desktop = ctx.desktop();
9323
9830
  await desktop.requireCapability('shots', 'saved Shots');
9324
9831
  const r = await desktop.post('/agent/shots/merge', {
9325
- firstId: input.firstId,
9326
- secondId: input.secondId,
9832
+ firstId: await shotRowId(input.firstId, shotReader(desktop, input.firstId, input.projectId)),
9833
+ secondId: await shotRowId(input.secondId, shotReader(desktop, input.secondId, input.projectId)),
9327
9834
  });
9328
9835
  return ok(r.shot, `Merged into ${r.shot?.code || 'one Shot'} — ` +
9329
9836
  `${r.shot?.cuts ?? 1} cut(s), ${r.shot?.runtimeSeconds ?? 'no'} second(s).`);
@@ -9381,7 +9888,7 @@ async function resolveVariationRefs(input, ctx) {
9381
9888
  return input;
9382
9889
  const { storyboard } = await ctx.desktop().get('/agent/storyboards/get', { id: input.storyboardId });
9383
9890
  const assets = await resolveAssetRefs(ctx, storyboard.projectId, input.assetOverrides.flatMap(o => [o.from, o.to]));
9384
- return { ...input, assetOverrides: input.assetOverrides.map(o => ({ from: assets.get(o.from).id, to: assets.get(o.to).id })) };
9891
+ return { ...input, assetOverrides: input.assetOverrides.map(o => ({ from: assets.id(o.from), to: assets.id(o.to) })) };
9385
9892
  }
9386
9893
  export const getScriptUses = {
9387
9894
  id: 'slates_get_script_uses',
@@ -9408,7 +9915,7 @@ export const reuseShotTake = {
9408
9915
  async run(input, ctx) {
9409
9916
  await ctx.desktop().requireCapability('script-documents', 'script documents');
9410
9917
  const assets = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
9411
- return ok(await ctx.desktop().post('/agent/shots/reuse-take', { ...input, assetId: assets.get(input.assetId).id }));
9918
+ return ok(await ctx.desktop().post('/agent/shots/reuse-take', { ...input, assetId: assets.id(input.assetId) }));
9412
9919
  },
9413
9920
  };
9414
9921
  export const getScriptSections = {
@@ -9606,6 +10113,7 @@ export const generateFromShots = {
9606
10113
  description: 'Generate results for saved Shots, spending credits. Call without confirm for the itemized prices the Generate panel shows and a fingerprint; show the user the total and wait for their OK, then pass confirm with that fingerprint. Changed recipes require a fresh price. Runs sequentially; after a timeout inspect generations (slates_list_generations, status processing) instead of re-firing. Pass draft to generate previews instead: one picture for each Shot that has none, kept as a take of that Shot; the Shot\'s recipe does not change.',
9607
10114
  input: z.object({
9608
10115
  shotIds: z.array(z.string()).min(1).max(20),
10116
+ projectId: z.string().uuid().optional().describe("The Shots' project. A SHOT-A code is unique only within its project, so pass this with codes."),
9609
10117
  confirm: z.boolean().optional().describe(CONFIRM_PARAM + " Pass it with the quote's fingerprint."),
9610
10118
  fingerprint: z.string().optional(),
9611
10119
  draft: DRAFT_INPUT.describe('Generate previews: pass {} to price ONE picture for each Shot in scope that has no picture, instead of each Shot recipe, at the chosen image model’s default settings. Works on a Shot with no model. No Shot row changes; the picture becomes a take of that Shot. Pass the same value when confirming.'),
@@ -9616,16 +10124,22 @@ export const generateFromShots = {
9616
10124
  // Prices come only from the desktop's quote; a 1.5.8 desktop has none.
9617
10125
  await desktop.requireCapability('board-quote', 'Shot prices');
9618
10126
  // Resolved first so a SHOT-A code fails here, not halfway through a billed run.
9619
- const details = await Promise.all(input.shotIds.map((id) => desktop.get('/agent/shots/get', { id })));
10127
+ const details = await Promise.all(input.shotIds.map((id) => shotReader(desktop, id, input.projectId)()));
10128
+ // One quote, one board: Shots from two projects are never priced or billed together.
10129
+ const projects = new Set(details.map((shot) => shot.projectId));
10130
+ if (projects.size > 1) {
10131
+ throw new Error(`These Shots belong to ${projects.size} projects (${details.map((s) => `${s.code ?? s.id}: ${s.projectId}`).join(', ')}). ` +
10132
+ 'Pass projectId so each SHOT-A code resolves in that project, or generate each project\'s Shots separately.');
10133
+ }
9620
10134
  // Older desktops drop the draft flag when reading a saved recipe. Its persisted 480p
9621
10135
  // resolution survives, so require a capable desktop before firing an ambiguous video Shot.
9622
- if (!input.draft && details.some(({ shot }) => shot.model === 'seedance-2.5' &&
10136
+ if (!input.draft && details.some((shot) => shot.model === 'seedance-2.5' &&
9623
10137
  (shot.params?.seedanceDraft || ['480p', '4k'].includes(String(shot.params?.videoResolution))))) {
9624
10138
  await desktop.requireCapability('seedance-drafts', 'generating saved Seedance 2.5 preview or 4K Shots');
9625
10139
  }
9626
10140
  const { draft, note: seatNote } = await desktopDraft(desktop, input.draft);
9627
- const quote = await desktop.get('/agent/shots/quote', {
9628
- input: JSON.stringify({ projectId: details[0].shot.projectId, shotIds: details.map((d) => d.shot.id), draft }),
10141
+ const quote = await desktop.quote('/agent/shots/quote', 'input', {
10142
+ projectId: details[0].projectId, shotIds: details.map((d) => d.id), draft,
9629
10143
  });
9630
10144
  for (const model of new Set(quote.items.map((i) => i.model)))
9631
10145
  requireGuideRead(ctx, model);
@@ -9644,6 +10158,7 @@ export const generateFromShots = {
9644
10158
  '\nGet approval for these prices, then pass this fingerprint with confirm: true.' +
9645
10159
  (seatNote ? `\n${seatNote}` : ''));
9646
10160
  }
10161
+ approvedSpend(ctx);
9647
10162
  const ran = await desktop.post('/agent/shots/batch-generate', {
9648
10163
  shotIds: quote.items.map((i) => i.shotId),
9649
10164
  fingerprint: quote.fingerprint,
@@ -9667,7 +10182,7 @@ export const quoteBoard = {
9667
10182
  const desktop = ctx.desktop();
9668
10183
  await desktop.requireCapability('board-quote', 'the board prices');
9669
10184
  const { draft, note } = await desktopDraft(desktop, input.draft);
9670
- const quote = await desktop.get('/agent/shots/quote', { input: JSON.stringify({ ...input, draft }) });
10185
+ const quote = await desktop.quote('/agent/shots/quote', 'input', { ...input, draft });
9671
10186
  return note ? ok(quote, `${JSON.stringify(quote)}\n${note}`) : ok(quote);
9672
10187
  },
9673
10188
  };
@@ -9698,7 +10213,7 @@ export const quoteDraftFinish = {
9698
10213
  const desktop = ctx.desktop();
9699
10214
  await desktop.requireCapability('seedance-drafts', 'finishing draft takes');
9700
10215
  const refs = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
9701
- return ok(await desktop.get('/agent/assets/quote-draft-finish', { ...input, assetId: refs.get(input.assetId).id }));
10216
+ return ok(await desktop.get('/agent/assets/quote-draft-finish', { ...input, assetId: refs.id(input.assetId) }));
9702
10217
  },
9703
10218
  };
9704
10219
  export const finishDraft = {
@@ -9711,7 +10226,8 @@ export const finishDraft = {
9711
10226
  const desktop = ctx.desktop();
9712
10227
  await desktop.requireCapability('seedance-drafts', 'finishing draft takes');
9713
10228
  const refs = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
9714
- const receipt = await desktop.post('/agent/assets/finish-draft', { ...input, assetId: refs.get(input.assetId).id, background: true });
10229
+ approvedSpend(ctx);
10230
+ const receipt = await desktop.post('/agent/assets/finish-draft', { ...input, assetId: refs.id(input.assetId), background: true });
9715
10231
  if (!ctx.waitForCutFinish || receipt.status === 'completed')
9716
10232
  return ok(receipt);
9717
10233
  if (!receipt.generationId)
@@ -9759,6 +10275,7 @@ export const finishCutDrafts = {
9759
10275
  const desktop = ctx.desktop();
9760
10276
  await desktop.requireCapability('seedance-drafts', 'finishing drafts in a cut');
9761
10277
  const query = { projectId: input.projectId, timelineId: input.timelineId, quoteId: input.quoteId };
10278
+ approvedSpend(ctx);
9762
10279
  let receipt = await desktop.post('/agent/timeline/cut', {
9763
10280
  ...input, action: 'finishDrafts', background: true,
9764
10281
  });
@@ -9814,8 +10331,9 @@ export const editCut = {
9814
10331
  }),
9815
10332
  async run(input, ctx) {
9816
10333
  await ctx.desktop().requireCapability('cut-edit', 'editing a cut');
9817
- const refs = input.assetId ? await resolveAssetRefs(ctx, input.projectId, [input.assetId]) : new Map();
9818
- return ok(await ctx.desktop().post('/agent/timeline/cut', { ...input, assetId: input.assetId ? refs.get(input.assetId)?.id : undefined }));
10334
+ // A timeline clip is the one reference that may point into another project, so an id from one passes.
10335
+ const refs = input.assetId ? await resolveAssetRefs(ctx, input.projectId, [input.assetId], { anyProject: true }) : new AssetRefs();
10336
+ return ok(await ctx.desktop().post('/agent/timeline/cut', { ...input, assetId: input.assetId ? refs.id(input.assetId) : undefined }));
9819
10337
  },
9820
10338
  };
9821
10339
  export function resolveGuideTopic(topic) {
@@ -9916,6 +10434,8 @@ export function resolveGuideTopic(topic) {
9916
10434
  return 'slates-prompting-omni-flash';
9917
10435
  if (t.startsWith('wan') || t === 'alibaba-wan-3.0')
9918
10436
  return 'slates-prompting-wan-3';
10437
+ if (t.startsWith('magi'))
10438
+ return 'slates-prompting-magi-2';
9919
10439
  // MiniMax H3 — both seats share one skill. Placed BEFORE the seed/seedance
9920
10440
  // block for the same reason seed-audio is: no prefix collision exists today,
9921
10441
  // but a `minimax-*` id must never fall through to a Seedance guide.
@@ -9925,12 +10445,6 @@ export function resolveGuideTopic(topic) {
9925
10445
  t.startsWith('h3-')) {
9926
10446
  return 'slates-prompting-minimax-h3';
9927
10447
  }
9928
- // LTX-2.5 — both seats share one skill. A PREFIX is right HERE (unlike every
9929
- // rate, key and endpoint lookup, which must be exact) precisely because both
9930
- // rows resolve to the same guide: `ltx-2-5-pro` matching the `ltx` prefix is
9931
- // the intended outcome, not a collision.
9932
- if (t.startsWith('ltx') || t === 'lightricks')
9933
- return 'slates-prompting-ltx-2-5';
9934
10448
  if (t.startsWith('kling-mc'))
9935
10449
  return 'slates-prompting-motion-transfer';
9936
10450
  if (t === 'edit-video' || t === 'video-edit' || t === 'edit video' || t === 'video edit')
@@ -10599,6 +11113,7 @@ export const ALL_OPERATIONS = [
10599
11113
  getReviewPacket,
10600
11114
  resolveReviewNote,
10601
11115
  getAdWinners,
11116
+ getClientAdReport,
10602
11117
  setRecipeVerdict,
10603
11118
  moreLikeThis,
10604
11119
  planSplitTest,