@slatesvideo/shared 0.7.20 → 0.7.22

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, 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
  }
@@ -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
  };
@@ -1747,21 +1770,6 @@ export const VIDEO_MODELS = [
1747
1770
  'minimax-h3',
1748
1771
  'minimax-h3-max',
1749
1772
  '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
1773
  ];
1766
1774
  // ── Capability-derived param vocabulary + guard ─────────────────
1767
1775
  //
@@ -1812,20 +1820,6 @@ const MINIMAX_FREE_REF_IMAGES_BY_MODEL = {
1812
1820
  'minimax-h3': 5,
1813
1821
  'minimax-h3-max': 4,
1814
1822
  };
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
1823
  /** K for the `-ref{K}` suffix: images past the free five, capped by the model's
1830
1824
  * own declared ceiling. 0 for h3-max (no reference transport) and for anything
1831
1825
  * that is not a MiniMax row. Mirrors refImageSurchargeCount() in
@@ -1856,13 +1850,12 @@ export const EDIT_VIDEO_MODELS = [
1856
1850
  'omni-flash-1-2-edit',
1857
1851
  'seedance-2.5-edit',
1858
1852
  ];
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';
1853
+ // The op's default, matching MODEL_FACTS' edit tier default and slate routes.ts (/agent/generation/edit-video).
1854
+ const EDIT_VIDEO_DEFAULT = 'seedance-2.5-edit';
1862
1855
  /** The edit engines that take character and style references (elements); the run refuses them on the rest. */
1863
1856
  const EDIT_VIDEO_ELEMENT_MODELS = EDIT_VIDEO_MODELS.filter((m) => (getModelCapability(m)?.maxIngredientImages ?? 0) > 0);
1864
1857
  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.`;
1858
+ const EDIT_VIDEO_ELEMENTS_ONLY = `Only ${EDIT_VIDEO_ELEMENT_MODELS.join(', ')} take them; the other engines refuse them.`;
1866
1859
  /**
1867
1860
  * Source-clip length an edit engine accepts, read from the SSOT.
1868
1861
  *
@@ -1898,7 +1891,7 @@ export const estimateGenerationCost = {
1898
1891
  // one where someone edits a table and forgets there were two.
1899
1892
  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
1893
  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.'),
1894
+ videoResolution: zEnum(VIDEO_RESOLUTIONS).optional().describe('Video only. Omitted, each model quotes at its own default. Ladders: see slates_generate_video\'s videoResolution.'),
1902
1895
  resolution: z.enum(['1k', '2k', '3k', '4k']).optional().describe('Image only. Omit for the model default; pass the same value to generation.'),
1903
1896
  quality: z.enum(GPT_QUALITY_TIERS).optional().describe(`GPT Image tier; default ${DEFAULT_GPT_QUALITY}.`),
1904
1897
  aspectRatio: z.string().optional().describe('GPT Image: the frame shape changes the price; pass the generation\'s value.'),
@@ -1906,9 +1899,10 @@ export const estimateGenerationCost = {
1906
1899
  seedanceDraft: z.boolean().optional().describe('Create a finishable Seedance 2.5 preview at 480p.'),
1907
1900
  seedanceFace: z.boolean().optional().describe('Seedance Face row, for an AI character\'s face.'),
1908
1901
  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.`),
1902
+ videoReferenceSecondsEach: z.array(z.number().nonnegative()).optional().describe('Seconds of each reference video, one per clip. Never the sum.'),
1903
+ videoRefSeconds: z.number().nonnegative().optional().describe('DEPRECATED: one clip.'),
1904
+ audioRefSeconds: z.number().nonnegative().optional().describe('Combined reference-audio seconds, attached voices too.'),
1905
+ 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
1906
  }),
1913
1907
  async run(input, ctx) {
1914
1908
  // A retired seat is never quoted: its keys still bill older desktops, and `nano-banana-2-1k` (the
@@ -1938,8 +1932,14 @@ export const estimateGenerationCost = {
1938
1932
  // billed `high`, so the op the doctrine tells agents to call before every
1939
1933
  // generation quoted 1 cr for a 2 cr job. Four separate copies of one
1940
1934
  // 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);
1935
+ if (img) {
1936
+ // The gate generation runs, so a quote never prices what generation refuses.
1937
+ const resolution = input.resolution ?? defaultImageResolutionFor(img);
1938
+ const capErr = assertImageCapabilities({ model: img, aspectRatio: input.aspectRatio, resolution });
1939
+ if (capErr)
1940
+ return ok(capErr);
1941
+ key = imageCostKey(img, resolution, input.quality, input.aspectRatio, input.referenceImages ?? 0);
1942
+ }
1943
1943
  }
1944
1944
  // 2a) audio base id → seconds. Both surfaces bill per second, so a
1945
1945
  // duration is always required. Runs BEFORE the video resolver: it is
@@ -2012,6 +2012,14 @@ export const estimateGenerationCost = {
2012
2012
  message: 'Kling O3 edit bills per second of output (≈ the source clip length, rounded up) — pass duration.',
2013
2013
  });
2014
2014
  }
2015
+ const clip = editClipBounds(input.model);
2016
+ if (input.duration < clip.min || input.duration > clip.max) {
2017
+ return ok({
2018
+ requires_clarification: true,
2019
+ missing: ['duration'],
2020
+ 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.`,
2021
+ });
2022
+ }
2015
2023
  key = klingEditCostKey(input.model, input.duration);
2016
2024
  }
2017
2025
  // 3) video base id (or cost-key spelling) → the same forgiving resolver
@@ -2032,11 +2040,15 @@ export const estimateGenerationCost = {
2032
2040
  // a quote can never promise something generation then refuses.
2033
2041
  const capErr = assertVideoCapabilities({
2034
2042
  model: resolved.model,
2043
+ aspectRatio: input.aspectRatio,
2035
2044
  videoResolution: input.videoResolution ?? resolved.videoResolution,
2036
2045
  duration,
2037
2046
  });
2038
2047
  if (capErr)
2039
2048
  return ok(capErr);
2049
+ const refErr = referenceSecondsRefusal(resolved.model, referenceVideoClips(input));
2050
+ if (refErr)
2051
+ return ok(refErr);
2040
2052
  key = videoCostKey({
2041
2053
  model: resolved.model,
2042
2054
  duration,
@@ -2052,12 +2064,16 @@ export const estimateGenerationCost = {
2052
2064
  seedanceFace: input.seedanceFace ?? resolved.seedanceFace,
2053
2065
  seedanceRealFace: input.seedanceRealFace ?? resolved.seedanceRealFace,
2054
2066
  referenceImages: input.referenceImages ?? resolved.referenceImages,
2055
- videoRefSeconds: input.videoRefSeconds, audioRefSeconds: input.audioRefSeconds,
2067
+ videoReferenceSecondsEach: referenceVideoClips(input), audioRefSeconds: input.audioRefSeconds,
2056
2068
  });
2057
2069
  }
2058
2070
  }
2059
2071
  await loadDynamicPrice(ctx, byKey, key);
2060
2072
  const perCredits = key != null ? byKey.get(key) : undefined;
2073
+ if (key != null && perCredits == null && key !== input.model) {
2074
+ // The model is known and these parameters built a key the price list lacks: name the key, not the model.
2075
+ 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.`);
2076
+ }
2061
2077
  if (key == null || perCredits == null) {
2062
2078
  // Every id in the error comes from the SSOT arrays. The image half was
2063
2079
  // hand-typed and named three of six, so an agent that mis-spelled
@@ -2073,10 +2089,11 @@ export const estimateGenerationCost = {
2073
2089
  // It is here rather than in a param description because a description is
2074
2090
  // paid for on every turn of every session and read once — this is paid for
2075
2091
  // only by the call that is about to use the model.
2076
- const skill = promptingSkillFor(input.model);
2092
+ // A tool or engine key (upscale, the reasoning model) has no guide and gets no card.
2093
+ const skill = resolveGuideTopic(input.model);
2077
2094
  // 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);
2095
+ const card = skill ? describeCraftCard(skill, brainSkills().skills[skill]) : '';
2096
+ const banned = skill ? describeBannedTokensForSkill(skill) : '';
2080
2097
  // Before the card on purpose: the desktop strips a repeated card by cutting
2081
2098
  // the text at "--- HOW TO PROMPT", and this line must survive that.
2082
2099
  const ownImage = IMAGE_MODELS.includes(input.model) ? input.model : null;
@@ -2159,6 +2176,8 @@ function compactAsset(a) {
2159
2176
  prompt: typeof r.prompt === 'string' ? r.prompt : null,
2160
2177
  }),
2161
2178
  type: r.type,
2179
+ // A clip's measured length in seconds: what reference seconds are billed and capped on.
2180
+ ...(typeof r.duration === 'number' && r.duration > 0 ? { duration: Math.round(r.duration * 100) / 100 } : {}),
2162
2181
  // Only when it IS one. A compact row pays for every key on every asset,
2163
2182
  // and "not a favorite" is the default the app writes — absent says it.
2164
2183
  ...(r.isFavorite === true ? { isFavorite: true } : {}),
@@ -2166,6 +2185,25 @@ function compactAsset(a) {
2166
2185
  };
2167
2186
  }
2168
2187
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
2188
+ const noAssetMatching = (ref) => `No asset matching "${ref}" in this project. Codes resolve at call time — ` +
2189
+ `call slates_list_assets (search: "${ref}") to see what actually exists, then pass the exact code or id. Never guess.`;
2190
+ /**
2191
+ * What `resolveAssetRefs` returns. `id(ref)` and `row(ref)` throw the teaching
2192
+ * error instead of handing back undefined, so a caller cannot reach a bare
2193
+ * TypeError the way `.id(ref)` did on a blank ref (2026-11-24).
2194
+ * `scripts/image-op-guards-check.mjs` refuses `.id(…)` in the ops.
2195
+ */
2196
+ class AssetRefs extends Map {
2197
+ row(ref) {
2198
+ const row = this.get(ref);
2199
+ if (!row)
2200
+ throw new Error(noAssetMatching(ref));
2201
+ return row;
2202
+ }
2203
+ id(ref) {
2204
+ return this.row(ref).id;
2205
+ }
2206
+ }
2169
2207
  /**
2170
2208
  * Resolve asset references that may be UUIDs OR badge codes ("IMG-A8",
2171
2209
  * "vid-v3", bare "A8"). Codes resolve against the project's asset list AT
@@ -2173,12 +2211,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
2211
  * user creates assets in the Slates UI mid-chat; an agent that guesses or
2174
2212
  * reuses a nearby UUID for a code it never looked up burns real dollars on
2175
2213
  * 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.
2214
+ * Unknown codes and blank refs throw a teaching error, and so does a UUID that
2215
+ * is not in the named project: an id copied from another project never reaches
2216
+ * a route as this project's asset. Two cases let a UUID through for the route
2217
+ * to validate: no project was named (the route falls back to the open one), or
2218
+ * the caller says the reference may cross projects (`anyProject`, a timeline
2219
+ * clip, the one cross-project reference Slates allows).
2178
2220
  */
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))];
2221
+ async function resolveAssetRefs(ctx, projectId, refs, scope = {}) {
2222
+ const out = new AssetRefs();
2223
+ if (refs.some((r) => typeof r === 'string' && r.trim().length === 0)) {
2224
+ throw new Error('An asset reference is blank. Pass an asset code (IMG-A8) or id: call slates_list_assets to see what exists.');
2225
+ }
2226
+ const pending = [...new Set(refs.filter((r) => typeof r === 'string'))];
2182
2227
  if (pending.length === 0)
2183
2228
  return out;
2184
2229
  const { assets } = await ctx.desktop().get('/agent/assets', { projectId });
@@ -2189,6 +2234,8 @@ async function resolveAssetRefs(ctx, projectId, refs) {
2189
2234
  const raw = ref.trim();
2190
2235
  if (UUID_RE.test(raw)) {
2191
2236
  const row = byId.get(raw.toLowerCase());
2237
+ if (!row && projectId && !scope.anyProject)
2238
+ throw new Error(noAssetMatching(ref));
2192
2239
  out.set(ref, {
2193
2240
  id: raw,
2194
2241
  code: row ? (row.code ?? null) : null,
@@ -2203,10 +2250,8 @@ async function resolveAssetRefs(ctx, projectId, refs) {
2203
2250
  const prefixed = norm.startsWith('A') ? `IMG-${norm}` : norm.startsWith('V') ? `VID-${norm}` : `AUD-${norm}`;
2204
2251
  row = byCode.get(prefixed);
2205
2252
  }
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
- }
2253
+ if (!row)
2254
+ throw new Error(noAssetMatching(ref));
2210
2255
  out.set(ref, {
2211
2256
  id: String(row.id),
2212
2257
  code: row.code ?? null,
@@ -2387,7 +2432,7 @@ export const generateChatGptImage = {
2387
2432
  await desktop.requireCapability('media-folder', 'choosing the folder a result lands in');
2388
2433
  const refs = await resolveAssetRefs(ctx, input.projectId, input.referenceAssetIds ?? []);
2389
2434
  const result = await desktop.post('/agent/generation/chatgpt-image', {
2390
- ...input, referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.get(id).id),
2435
+ ...input, referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.id(id)),
2391
2436
  });
2392
2437
  return ok(result, JSON.stringify(result) + '\n' + describeResolvedRefs((input.referenceAssetIds ?? []).map(ref => ({ ref, role: 'reference image' })), refs));
2393
2438
  },
@@ -2417,8 +2462,8 @@ export const saveExternalImage = {
2417
2462
  ]);
2418
2463
  const result = await desktop.post('/agent/assets/external-image', {
2419
2464
  ...input,
2420
- assetId: input.assetId ? refs.get(input.assetId).id : undefined,
2421
- referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.get(id).id),
2465
+ assetId: input.assetId ? refs.id(input.assetId) : undefined,
2466
+ referenceAssetIds: (input.referenceAssetIds ?? []).map(id => refs.id(id)),
2422
2467
  });
2423
2468
  return ok(result, JSON.stringify(result) + '\n' + describeResolvedRefs((input.referenceAssetIds ?? []).map(ref => ({ ref, role: 'reference image' })), refs));
2424
2469
  },
@@ -2505,7 +2550,7 @@ export const updateAsset = {
2505
2550
  await desktop.requireCapability('asset-naming', 'naming an asset');
2506
2551
  if (proxying)
2507
2552
  await desktop.requireCapability('proxies', "a clip's proxy");
2508
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
2553
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
2509
2554
  const result = {};
2510
2555
  if (naming) {
2511
2556
  const { asset } = await desktop.post('/agent/assets/update', {
@@ -2603,7 +2648,7 @@ export const pinReferences = {
2603
2648
  async run(input, ctx) {
2604
2649
  await ctx.desktop().requireCapability('pins', 'pinned references');
2605
2650
  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) }));
2651
+ return ok(await ctx.desktop().post('/agent/pins', { projectId: input.projectId, assetIds: input.assetIds.map((r) => resolved.id(r)) }));
2607
2652
  },
2608
2653
  };
2609
2654
  export const unpinReference = {
@@ -2613,7 +2658,7 @@ export const unpinReference = {
2613
2658
  async run(input, ctx) {
2614
2659
  await ctx.desktop().requireCapability('pins', 'pinned references');
2615
2660
  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 }));
2661
+ return ok(await ctx.desktop().post('/agent/pins/remove', { projectId: input.projectId, assetId: resolved.id(input.assetId) }));
2617
2662
  },
2618
2663
  };
2619
2664
  export const moveAssetsToProject = {
@@ -2796,6 +2841,7 @@ export const generateCharacterIdentity = {
2796
2841
  const quote = await sheetConfirmGate(ctx, input, (input.model ?? toolModelFor('character-sheet')));
2797
2842
  if (quote)
2798
2843
  return quote;
2844
+ approvedSpend(ctx);
2799
2845
  const made = await ctx.desktop().post('/agent/characters/generate-identity', {
2800
2846
  characterId: input.characterId,
2801
2847
  projectId: input.projectId,
@@ -2830,6 +2876,7 @@ export const generateEnvironmentPlate = {
2830
2876
  const quote = await sheetConfirmGate(ctx, input, toolModelFor('environment-plate'));
2831
2877
  if (quote)
2832
2878
  return quote;
2879
+ approvedSpend(ctx);
2833
2880
  return ok(await ctx.desktop().post('/agent/environments/generate-plate', {
2834
2881
  environmentId: input.environmentId,
2835
2882
  projectId: input.projectId,
@@ -3184,15 +3231,99 @@ const HEADLESS_IMAGE_MODEL = 'nano-banana-2-1';
3184
3231
  * value no model accepts. It used to be a hand-typed eleven-value list whose
3185
3232
  * `9:21` exists in ZERO models; that phantom is gone by construction.
3186
3233
  *
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.
3234
+ * It is the union, so the per-model narrowing is `assertImageCapabilities`
3235
+ * below, which every image entry point runs.
3194
3236
  */
3195
3237
  const IMAGE_ASPECT_RATIOS = aspectRatioUnion(IMAGE_MODELS);
3238
+ /**
3239
+ * The per-model image gate: the aspect ratio and the resolution rung the seat
3240
+ * declares in `MODEL_CAPABILITIES`. Generate, edit, the estimate and a saved
3241
+ * image Shot all run this one function, so a quote, a recipe and a generation
3242
+ * cannot disagree about what a seat takes.
3243
+ *
3244
+ * Why: GPT Image takes five of the union's ratios. A 4:5 or 21:9 ask passed,
3245
+ * was quoted at the 16:9 key, and the desktop's size table rendered a 16:9
3246
+ * frame for it and billed it (2026-11-24). An off-ladder rung built a cost key
3247
+ * the registry lacks and failed as "Unknown model", or, on Seedream, quoted the
3248
+ * default rung's price for a rung generation then refused.
3249
+ */
3250
+ export function assertImageCapabilities(input, field = { resolution: 'resolution' }) {
3251
+ const ratioErr = checkAspectRatio(input.model, input.aspectRatio, AGENT_ROUTE_PROVIDER);
3252
+ if (ratioErr)
3253
+ return { requires_clarification: true, missing: ['aspectRatio'], message: ratioErr };
3254
+ const rungs = MODEL_CAPABILITIES[input.model]?.imageResolutions ?? [];
3255
+ if (input.resolution && rungs.length > 0 && !rungs.includes(input.resolution)) {
3256
+ return {
3257
+ requires_clarification: true,
3258
+ missing: [field.resolution],
3259
+ message: `${input.model} accepts ${rungs.join(', ')}, not ${input.resolution}. Pick one of those, or switch to a model that renders ${input.resolution}.`,
3260
+ };
3261
+ }
3262
+ return null;
3263
+ }
3264
+ /** Reference images an image model reads in one request, from its capability row. */
3265
+ const imageReferenceCap = (model) => MODEL_CAPABILITIES[model]?.maxRefImages ?? 0;
3266
+ /**
3267
+ * The refusal for more references than the model reads. The desktop sends the
3268
+ * first `cap` and leaves the rest out, so a call over the cap would run, and
3269
+ * bill, without references the caller named. `cap` comes from the capability
3270
+ * row, never a typed number.
3271
+ */
3272
+ function referenceCapRefusal(model, count, cap, param, what = 'reference images') {
3273
+ if (count <= cap)
3274
+ return null;
3275
+ return {
3276
+ requires_clarification: true,
3277
+ missing: [param],
3278
+ message: cap > 0
3279
+ ? `Nothing ran. ${model} reads at most ${cap} ${what} and this call names ${count}. Remove ${count - cap}, or pick a model that reads more.`
3280
+ : `Nothing ran. ${model} reads no ${what}. Remove them, or pick a model that reads them.`,
3281
+ };
3282
+ }
3283
+ /**
3284
+ * The image params that only some calls consume, each with the condition under
3285
+ * which it reaches the request. A param set where its condition fails was
3286
+ * dropped while the generation ran and billed: reference URLs beside a
3287
+ * projectId, a transparent background on a seat without one (2026-11-24).
3288
+ * Generate and edit both run this table, and `scripts/image-op-guards-check.mjs`
3289
+ * proves every row refuses.
3290
+ */
3291
+ function droppedImageParams(model, input) {
3292
+ const rows = [
3293
+ {
3294
+ param: 'referenceImageUrls',
3295
+ set: (input.referenceImageUrls?.length ?? 0) > 0,
3296
+ consumed: !input.projectId,
3297
+ 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.',
3298
+ },
3299
+ {
3300
+ param: 'backgroundMode',
3301
+ set: input.backgroundMode !== undefined && input.backgroundMode !== 'auto',
3302
+ consumed: takesBackgroundMode(model),
3303
+ why: `${model} has no background control, so the picture would come back opaque. Seats that take it: ${IMAGE_MODELS.filter(takesBackgroundMode).join(', ')}.`,
3304
+ },
3305
+ {
3306
+ param: 'folderId',
3307
+ set: input.folderId !== undefined && input.folderId !== null,
3308
+ consumed: !!input.projectId,
3309
+ why: 'A folder belongs to a project. Pass the projectId it lives in, or drop folderId.',
3310
+ },
3311
+ {
3312
+ param: 'requestId',
3313
+ set: input.requestId !== undefined,
3314
+ consumed: !input.projectId,
3315
+ why: 'A requestId resumes a headless image only. With a projectId the desktop keeps the generation: read it with slates_get_generation_status.',
3316
+ },
3317
+ ];
3318
+ const dropped = rows.filter((r) => r.set && !r.consumed);
3319
+ if (dropped.length === 0)
3320
+ return null;
3321
+ return {
3322
+ requires_clarification: true,
3323
+ missing: dropped.map((r) => r.param),
3324
+ message: `Nothing ran. ${dropped.map((r) => `${r.param}: ${r.why}`).join(' ')}`,
3325
+ };
3326
+ }
3196
3327
  // Registry cost-key for an image model+resolution. Mirrors imageCreditKey()
3197
3328
  // in slate/src/shared/pricing.ts — MUST byte-match it (the same hard rule as
3198
3329
  // videoCostKey): Nano Banana 2.1 and FLUX 3 price per resolution, Seedream is
@@ -3320,17 +3451,15 @@ export const generateImage = {
3320
3451
  backgroundMode: z.enum(GPT_BACKGROUNDS).optional().describe(`${IMAGE_MODELS.filter(takesBackgroundMode).join(', ')} only. transparent = alpha channel (PNG). Free.`),
3321
3452
  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
3453
  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.`),
3454
+ 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.`),
3455
+ 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
3456
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
3326
3457
  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.'),
3458
+ 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.'),
3459
+ 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
3460
  folderId: z.string().uuid().nullable().optional().describe(`${FOLDER_DESCRIBE} Needs projectId.`),
3329
3461
  }),
3330
3462
  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
3463
  // Clarification gate: aspectRatio + resolution must be deliberate.
3335
3464
  // Mirrors the cost confirm gate — defaults silently wasted credits
3336
3465
  // (1:1 when user wanted 16:9, 4k when 1k would have done). The LLM
@@ -3346,6 +3475,12 @@ export const generateImage = {
3346
3475
  ? await defaultImageSeatFor(() => ctx.desktop(), input.model, `${input.model ?? DEFAULT_IMAGE_MODEL} generation`)
3347
3476
  : { model: input.model ?? HEADLESS_IMAGE_MODEL, note: '' };
3348
3477
  const imageModel = seat.model;
3478
+ const dropped = droppedImageParams(imageModel, input);
3479
+ if (dropped)
3480
+ return ok(dropped);
3481
+ // A desktop before the folder rule ignores folderId and files at the root.
3482
+ if (input.folderId !== undefined)
3483
+ await ctx.desktop().requireCapability('media-folder', 'choosing the folder a result lands in');
3349
3484
  requireGuideRead(ctx, imageModel);
3350
3485
  const promptWarning = bannedTokenWarning(input.prompt, 'image', promptingSkillFor(imageModel));
3351
3486
  input = { ...input, resolution: input.resolution ?? defaultImageResolutionFor(imageModel) };
@@ -3368,11 +3503,9 @@ export const generateImage = {
3368
3503
  });
3369
3504
  }
3370
3505
  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
- }
3506
+ const capErr = assertImageCapabilities({ model: imageModel, aspectRatio: input.aspectRatio, resolution });
3507
+ if (capErr)
3508
+ return ok(capErr);
3376
3509
  // Only HEADLESS_IMAGE_MODEL has a headless path — everything else routes
3377
3510
  // through the desktop generation pipeline, which needs a project.
3378
3511
  if (imageModel !== HEADLESS_IMAGE_MODEL && !input.projectId) {
@@ -3413,6 +3546,11 @@ export const generateImage = {
3413
3546
  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
3547
  });
3415
3548
  }
3549
+ // Past the model's cap the desktop sends the first ones and leaves the rest out, so the picture
3550
+ // would be made without references the caller named: refused here, before any spend.
3551
+ const overCap = referenceCapRefusal(imageModel, referenceAssetIds.length + (input.referenceImageUrls?.length ?? 0), imageReferenceCap(imageModel), input.referenceImageUrls?.length ? 'referenceImageUrls' : 'referenceAssetIds');
3552
+ if (overCap)
3553
+ return ok(overCap);
3416
3554
  let refEcho = '';
3417
3555
  if (referenceAssetIds.length > 0) {
3418
3556
  await ctx.desktop().requireCapability('image-references', 'reference images on image generation');
@@ -3450,20 +3588,32 @@ export const generateImage = {
3450
3588
  if (!entry)
3451
3589
  throw new Error(`Model not in registry: ${costKey}`);
3452
3590
  const totalCents = creditCost(entry) * (input.count ?? 1);
3591
+ // A seat that bills each input picture is held to a ceiling in the desktop's unit (list credits): the quote, or a
3592
+ // higher approved figure, which a confirm shows the user first (`toolCeiling`).
3593
+ const perInput = !!input.projectId && billsEachInputImage(sentModel);
3594
+ const listQuote = listCredits(entry) * (input.count ?? 1);
3595
+ const ceiling = toolCeiling(listQuote, perInput ? requestedCredits(ctx, input) : undefined);
3596
+ // A headless purchase is made under an id minted here and named in every reply, so a call whose answer is lost
3597
+ // is repeated with it and returns what it bought (`/proxy/generate` keeps one live job per id).
3598
+ const pressId = input.projectId ? undefined : (input.requestId ?? randomUUID());
3599
+ const press = pressId ? { requestId: pressId } : {};
3600
+ const pressText = pressId ? ` Pass requestId=${pressId} with it.` : '';
3453
3601
  // Confirm gate. Fires above CONFIRM_CREDITS, AND (look-first, mirroring
3454
3602
  // slates_generate_video) whenever reference assets are involved
3455
3603
  // regardless of cost — the LLM must see what it's referencing before
3456
3604
  // committing spend.
3457
- if ((totalCents > CONFIRM_CREDITS || referenceAssetIds.length > 0) && !input.confirm) {
3605
+ if ((totalCents > CONFIRM_CREDITS || referenceAssetIds.length > 0 || ceiling.raised) && !input.confirm) {
3458
3606
  if (referenceAssetIds.length === 0) {
3459
3607
  return ok({
3460
3608
  requires_confirm: true,
3461
3609
  model: costKey,
3462
3610
  estimated_cents: totalCents,
3463
3611
  estimated_credits: totalCents,
3612
+ approvedCredits: ceiling.credits,
3613
+ ...press,
3464
3614
  ...(promptWarning ? { prompt_warning: promptWarning } : {}),
3465
3615
  message: (promptWarning ? `${promptWarning}\n\n` : '') +
3466
- `Cost exceeds ${CONFIRM_CREDITS} credits. Re-call with confirm=true to proceed, or pick a smaller resolution / count.`,
3616
+ `Cost: ${fmtCredits(totalCents)}. ${ceiling.sentence}Re-call with confirm=true to proceed, or pick a smaller resolution / count.${pressText}`,
3467
3617
  });
3468
3618
  }
3469
3619
  const previews = await previewAssets(ctx, referenceAssetIds.map((id) => ({ id, type: 'image', role: 'reference' })));
@@ -3475,7 +3625,7 @@ export const generateImage = {
3475
3625
  `Review them against your prompt — every reference's role must be labeled in the prompt text. ` +
3476
3626
  `If the references suggest a different composition / style than the current prompt captures, REVISE the prompt before confirming. ` +
3477
3627
  `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.` +
3628
+ `\n\n${ceiling.sentence}When ready, re-call slates_generate_image with confirm=true and the (possibly revised) prompt.${pressText}` +
3479
3629
  (promptWarning ? `\n\n${promptWarning}` : ''),
3480
3630
  images: previews.flatMap((p) => p.images),
3481
3631
  data: {
@@ -3484,6 +3634,8 @@ export const generateImage = {
3484
3634
  variant: costKey,
3485
3635
  estimated_cents: totalCents,
3486
3636
  estimated_credits: totalCents,
3637
+ approvedCredits: ceiling.credits,
3638
+ ...press,
3487
3639
  references: previews.map((p) => ({
3488
3640
  role: p.role,
3489
3641
  ref: p.ref,
@@ -3505,6 +3657,10 @@ export const generateImage = {
3505
3657
  // a desktop attached).
3506
3658
  if (input.projectId) {
3507
3659
  const desktop = ctx.desktop();
3660
+ const approved = approvedSpend(ctx, input);
3661
+ if (perInput && approved.approvedCredits != null && listQuote > approved.approvedCredits) {
3662
+ return toolPriceChanged(`${imageModel} image`, approved.approvedCredits, { credits: listQuote, costKey });
3663
+ }
3508
3664
  const result = await desktop.post('/agent/generation/image', {
3509
3665
  projectId: input.projectId,
3510
3666
  prompt: input.prompt,
@@ -3517,18 +3673,20 @@ export const generateImage = {
3517
3673
  ...(referenceAssetIds.length > 0 ? { referenceAssetIds } : {}),
3518
3674
  // The desktop adds @mention pictures this op cannot see; on a seat that bills
3519
3675
  // each input it runs nothing above what the user was quoted or approved.
3520
- ...(billsEachInputImage(sentModel) ? { maxCredits: Math.max(totalCents, input.approvedCredits ?? 0) } : {}),
3676
+ ...(perInput ? heldBody(approved.approvedCredits ?? listQuote, approved.quoteFingerprint) : {}),
3521
3677
  ...folderBody(input.folderId),
3522
3678
  background: input.background,
3523
3679
  });
3524
3680
  if (result.quoteExceeded) {
3525
- const { credits, costKey: billedKey } = result.quoteExceeded;
3681
+ const { credits, costKey: billedKey, fingerprint } = result.quoteExceeded;
3526
3682
  return ok({
3527
3683
  requires_confirm: true,
3528
3684
  quote_exceeded: true,
3529
3685
  model: billedKey,
3530
3686
  estimated_cents: credits,
3531
3687
  estimated_credits: credits,
3688
+ approvedCredits: credits,
3689
+ ...(fingerprint ? { quote_fingerprint: fingerprint } : {}),
3532
3690
  message: `Nothing ran. The @mention pictures in the prompt are paid inputs on ${imageModel}: this call bills ${fmtCredits(credits)} (${billedKey}), ` +
3533
3691
  `not the ${fmtCredits(totalCents)} quoted. Tell the user, and once they approve, re-call with confirm=true and approvedCredits=${credits}.`,
3534
3692
  });
@@ -3569,6 +3727,9 @@ export const generateImage = {
3569
3727
  }
3570
3728
  }
3571
3729
  const requestedCount = input.count ?? 1;
3730
+ // Each image is its own billed request and a failed one is refunded, so a partial batch cost the
3731
+ // saved images, not the quoted total.
3732
+ const chargedCents = partialFailure ? creditCost(entry) * assetList.length : totalCents;
3572
3733
  return {
3573
3734
  // The pixels are ALREADY here when the disk read worked, so the
3574
3735
  // review pointer says "look at what you have", not "call another op".
@@ -3578,6 +3739,7 @@ export const generateImage = {
3578
3739
  (promptWarning ? `${promptWarning} ` : '') +
3579
3740
  (partialFailure
3580
3741
  ? `Partial result: ${assetList.length} of ${requestedCount} image(s) saved into project ${input.projectId} ` +
3742
+ `for ${fmtCredits(chargedCents)}, not the ${fmtCredits(totalCents)} quoted ` +
3581
3743
  `(error on the rest: ${result.error ?? 'unknown error'}). ` +
3582
3744
  `The saved assets are in data.assets — re-generate only the missing count, don't redo the whole batch. ` +
3583
3745
  `Prompt: "${input.prompt.slice(0, 60)}${input.prompt.length > 60 ? '...' : ''}"`
@@ -3594,15 +3756,15 @@ export const generateImage = {
3594
3756
  projectId: input.projectId,
3595
3757
  aspectRatio: input.aspectRatio,
3596
3758
  resolution,
3597
- cost_cents: totalCents,
3598
- cost_credits: totalCents,
3759
+ cost_cents: chargedCents,
3760
+ cost_credits: chargedCents,
3599
3761
  // Compact refs only — the full rows (prompt/settings/paths) were a
3600
3762
  // multi-KB leak per generation and everything needed downstream is
3601
3763
  // the id/code/label.
3602
3764
  assets: assetList.map(compactAsset),
3603
3765
  generationIds: result.generationIds ?? (result.generationId ? [result.generationId] : []),
3604
3766
  ...(partialFailure
3605
- ? { partial: true, error: result.error ?? 'unknown error', requested_count: requestedCount }
3767
+ ? { partial: true, error: result.error ?? 'unknown error', requested_count: requestedCount, quoted_credits: totalCents }
3606
3768
  : {}),
3607
3769
  },
3608
3770
  };
@@ -3618,7 +3780,12 @@ export const generateImage = {
3618
3780
  const endpoint = hasReferenceImages
3619
3781
  ? 'google/nano-banana-2.1/edit'
3620
3782
  : 'google/nano-banana-2.1';
3621
- const proxyResult = await cloud.post('/proxy/generate', {
3783
+ // The server keeps the job a submit bought under this id, so an answer lost on the way back is asked for by it
3784
+ // (below), and a call that still cannot tell hands the id back to be repeated with, never a fresh one.
3785
+ const generationId = pressId;
3786
+ approvedSpend(ctx, input);
3787
+ const submitted = await cloud.post('/proxy/generate', {
3788
+ generationId,
3622
3789
  provider: 'fal',
3623
3790
  type: 'image',
3624
3791
  model: costKey,
@@ -3651,13 +3818,36 @@ export const generateImage = {
3651
3818
  ? { image_urls: input.referenceImageUrls }
3652
3819
  : {}),
3653
3820
  },
3821
+ }).catch((error) => {
3822
+ // The server answered with a refusal: nothing was bought, and the error says why.
3823
+ if (error instanceof SlatesCloudHttpError && error.status < 500)
3824
+ throw error;
3825
+ return { lost: error instanceof Error ? error.message : String(error) };
3654
3826
  });
3827
+ // An answer that never arrived, or arrived unreadable, may still have bought the image: ask for it by its id.
3828
+ let proxyResult;
3829
+ if (submitted && typeof submitted === 'object' && !('lost' in submitted)) {
3830
+ proxyResult = submitted;
3831
+ }
3832
+ else {
3833
+ const held = await cloud.get(`/proxy/generations/${generationId}`).catch(() => null);
3834
+ if (!held?.jobId) {
3835
+ const why = submitted && 'lost' in submitted ? submitted.lost : 'its answer could not be read';
3836
+ return ok({
3837
+ pending: true,
3838
+ requestId: generationId,
3839
+ message: `Slates cannot tell yet whether this image was bought (${why}). Call slates_generate_image again with the same arguments and requestId=${generationId}: ` +
3840
+ '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.',
3841
+ });
3842
+ }
3843
+ proxyResult = { success: true, jobId: held.jobId };
3844
+ }
3655
3845
  if (!proxyResult.success) {
3656
3846
  throw new Error(proxyResult.error ?? 'Generation failed');
3657
3847
  }
3658
3848
  let imagesPayload = proxyResult.data?.images;
3659
3849
  if (!imagesPayload && proxyResult.jobId) {
3660
- const completed = await pollProxyJob(cloud, proxyResult.jobId);
3850
+ const completed = await pollProxyJob(cloud, proxyResult.jobId, { signal: ctx.signal });
3661
3851
  imagesPayload = completed.images;
3662
3852
  }
3663
3853
  const urls = (imagesPayload ?? [])
@@ -3666,17 +3856,24 @@ export const generateImage = {
3666
3856
  if (urls.length === 0) {
3667
3857
  throw new Error('Generation completed but returned no image URLs.');
3668
3858
  }
3859
+ // The credits are spent by now, so a URL that will not download is
3860
+ // reported with its link rather than thrown away or inlined as an error page.
3669
3861
  const images = [];
3862
+ const notInlined = [];
3670
3863
  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 });
3864
+ const img = await inlineResultImage(url);
3865
+ if (img)
3866
+ images.push(img);
3867
+ else
3868
+ notInlined.push(url);
3675
3869
  }
3676
3870
  return {
3677
- text: `${IMAGE_INLINE_REVIEW} ` +
3871
+ text: (images.length > 0 ? `${IMAGE_INLINE_REVIEW} ` : '') +
3678
3872
  (promptWarning ? `${promptWarning} ` : '') +
3679
3873
  `Generated ${urls.length} image(s) for ${fmtCredits(totalCents)}. ` +
3874
+ (notInlined.length > 0
3875
+ ? `${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. `
3876
+ : '') +
3680
3877
  `Prompt: "${input.prompt.slice(0, 60)}${input.prompt.length > 60 ? '...' : ''}"`,
3681
3878
  images,
3682
3879
  data: {
@@ -3691,17 +3888,53 @@ export const generateImage = {
3691
3888
  };
3692
3889
  },
3693
3890
  };
3694
- async function pollProxyJob(cloud, jobId, options = {}) {
3891
+ /** One result URL as an inline image, or null when it does not answer with an image. */
3892
+ async function inlineResultImage(url) {
3893
+ try {
3894
+ const r = await fetch(url);
3895
+ const mimeType = r.headers.get('content-type') || 'image/png';
3896
+ if (!r.ok || !mimeType.startsWith('image/'))
3897
+ return null;
3898
+ return { data: Buffer.from(await r.arrayBuffer()).toString('base64'), mimeType };
3899
+ }
3900
+ catch {
3901
+ return null;
3902
+ }
3903
+ }
3904
+ /** Poll statuses that cannot change by asking again: a lost login, no credits, no access, no such job. */
3905
+ const PROXY_POLL_FINAL_STATUSES = new Set([401, 402, 403, 404]);
3906
+ /** Poll failures in a row (network or 5xx) before the poller stops and says so. */
3907
+ const PROXY_POLL_MAX_FAILURES = 10;
3908
+ /**
3909
+ * Wait for a headless proxy job. The job is submitted and its credits held
3910
+ * before this runs, so every way out but `completed` and `failed` names the
3911
+ * job and tells the caller not to start another: a retry is a second paid job.
3912
+ * It used to swallow every poll error for five minutes and then throw a bare
3913
+ * timeout with no job id (2026-11-24).
3914
+ */
3915
+ export async function pollProxyJob(cloud, jobId, options = {}) {
3695
3916
  const intervalMs = options.intervalMs ?? 3000;
3696
3917
  const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;
3918
+ const held = (why) => `${why} Job ${jobId} was submitted and its credits are held; it may still complete. ` +
3919
+ 'Do not call slates_generate_image again for this picture: that starts a second paid job.';
3697
3920
  const start = Date.now();
3921
+ let failures = 0;
3698
3922
  while (Date.now() - start < timeoutMs) {
3699
3923
  await new Promise((r) => setTimeout(r, intervalMs));
3924
+ if (options.signal?.aborted)
3925
+ throw new OperationCancelledError(held('Stopped waiting.'));
3700
3926
  let status;
3701
3927
  try {
3702
3928
  status = await cloud.get(`/proxy/jobs/${jobId}`);
3929
+ failures = 0;
3703
3930
  }
3704
- catch {
3931
+ catch (err) {
3932
+ const message = err instanceof Error ? err.message : String(err);
3933
+ const code = err.status;
3934
+ if (typeof code === 'number' && PROXY_POLL_FINAL_STATUSES.has(code))
3935
+ throw new Error(held(`Polling stopped: ${message}.`));
3936
+ if (++failures >= PROXY_POLL_MAX_FAILURES)
3937
+ throw new Error(held(`Polling failed ${failures} times in a row: ${message}.`));
3705
3938
  continue;
3706
3939
  }
3707
3940
  if (status.status === 'completed')
@@ -3710,17 +3943,17 @@ async function pollProxyJob(cloud, jobId, options = {}) {
3710
3943
  throw new Error(status.error ?? 'Generation failed');
3711
3944
  }
3712
3945
  }
3713
- throw new Error(`Generation timed out after ${Math.round(timeoutMs / 1000)}s.`);
3946
+ throw new Error(held(`Still running after ${Math.round(timeoutMs / 1000)}s.`));
3714
3947
  }
3715
3948
  // ── Edit image ──────────────────────────────────────────────────
3716
3949
  /** 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);
3950
+ const editReferenceCap = (model) => Math.max(0, imageReferenceCap(model) - 1);
3718
3951
  /** 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
3952
  const LEGACY_EDIT_REFERENCE_MODELS = ['nano-banana-2', 'nano-banana-2-lite', 'nano-banana-pro']; // 1.5.8's ids, retired since
3720
3953
  export const editImage = {
3721
3954
  id: 'slates_edit_image',
3722
3955
  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. ' +
3956
+ 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
3957
  CONFIRM_GATE_SENTENCE,
3725
3958
  input: z.object({
3726
3959
  projectId: z.string().uuid(),
@@ -3731,7 +3964,7 @@ export const editImage = {
3731
3964
  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
3965
  quality: z.enum(GPT_QUALITY_TIERS).optional().describe(`GPT Image tier; default ${DEFAULT_GPT_QUALITY}.`),
3733
3966
  backgroundMode: z.enum(GPT_BACKGROUNDS).optional().describe(`${IMAGE_MODELS.filter(takesBackgroundMode).join(', ')} only. transparent = alpha channel (PNG). Free.`),
3734
- aspectRatio: z.string().optional(),
3967
+ 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
3968
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
3736
3969
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
3737
3970
  }),
@@ -3749,8 +3982,13 @@ export const editImage = {
3749
3982
  ? await defaultImageSeatFor(() => desktop, undefined, 'image editing')
3750
3983
  : { model: toolModelFor('image-edit'), note: '' };
3751
3984
  const editModel = seat.model;
3752
- requireGuideRead(ctx, editModel);
3753
3985
  const resolution = input.resolution ?? defaultImageResolutionFor(editModel);
3986
+ // The same gates as slates_generate_image, from the same functions.
3987
+ const refusal = droppedImageParams(editModel, input) ??
3988
+ assertImageCapabilities({ model: editModel, aspectRatio: input.aspectRatio, resolution });
3989
+ if (refusal)
3990
+ return ok(refusal);
3991
+ requireGuideRead(ctx, editModel);
3754
3992
  let sentModel = editModel;
3755
3993
  if (isGptImageModel(editModel)) {
3756
3994
  // Like generateImage; this site was missed once already. A desktop that
@@ -3764,17 +4002,33 @@ export const editImage = {
3764
4002
  if (input.referenceAssetIds?.length && !LEGACY_EDIT_REFERENCE_MODELS.includes(editModel)) {
3765
4003
  await desktop.requireCapability('edit-references-all-models', `references on a ${editModel} edit`);
3766
4004
  }
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'
4005
+ // Past the model's cap the desktop sends the first ones and leaves the rest out: refused, never trimmed.
4006
+ const overCap = referenceCapRefusal(editModel, input.referenceAssetIds?.length ?? 0, editReferenceCap(editModel), 'referenceAssetIds', 'references beside the source');
4007
+ if (overCap)
4008
+ return ok(overCap);
4009
+ const request = {
4010
+ projectId: input.projectId,
4011
+ sourceAssetId: input.sourceAssetId,
4012
+ editModel: sentModel,
4013
+ referenceAssetIds: input.referenceAssetIds,
4014
+ resolution,
4015
+ ...(isGptImageModel(editModel) ? { gptQuality: input.quality ?? DEFAULT_GPT_QUALITY } : {}),
4016
+ aspectRatio: input.aspectRatio,
4017
+ };
4018
+ // The desktop prices the edit off the source picture: a ratio left out follows the picture's own
4019
+ // shape, and on GPT Image the ratio is part of the key, so only the desktop knows which key bills.
4020
+ // A desktop before 'edit-image-quote' prices a missing ratio at the 16:9 key, as this op did.
4021
+ const quote = await desktop.hasCapability('edit-image-quote')
4022
+ ? await desktop.post('/agent/generation/edit-image-quote', { request })
4023
+ : null;
4024
+ const aspectRatio = quote?.aspectRatio ?? input.aspectRatio;
4025
+ // The older desktop's key. Nano Banana and GPT Image edits charge the same key as gen; FLUX routes
4026
+ // to a dedicated edit endpoint priced under an '-edit' key; Seedream 5.5 bills every input image,
4027
+ // the source included. Mirrors `editCreditKey` in the desktop's src/shared/imageEdit.ts.
4028
+ const legacyKey = () => editModel === 'flux-3'
3776
4029
  ? `${imageCostKey(editModel, resolution)}-edit`
3777
- : imageCostKey(editModel, resolution, input.quality, input.aspectRatio, editInputs);
4030
+ : imageCostKey(editModel, resolution, input.quality, input.aspectRatio, 1 + (input.referenceAssetIds?.length ?? 0));
4031
+ const costKey = quote?.costKey ?? legacyKey();
3778
4032
  const cloud = ctx.cloud();
3779
4033
  const registry = await cloud.get('/api/agent/models');
3780
4034
  const entry = registry.models.find((m) => m.model === costKey) ??
@@ -3790,22 +4044,19 @@ export const editImage = {
3790
4044
  estimated_cents: totalCents,
3791
4045
  estimated_credits: totalCents,
3792
4046
  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. ` : '') +
4047
+ message: `Cost: ${fmtCredits(totalCents)} to edit ${sourceRef} with ${editModel} (${costKey})` +
4048
+ (aspectRatio && !input.aspectRatio ? `, at ${aspectRatio}, the ratio nearest the picture's shape. ` : '. ') +
3795
4049
  `Re-call with confirm=true after the user explicitly OKs the spend. ` +
3796
4050
  `When discussing with the user, refer to the source by its code (matches the gallery badge).`,
3797
4051
  });
3798
4052
  }
4053
+ approvedSpend(ctx);
3799
4054
  const result = await desktop.post('/agent/generation/edit-image', {
3800
- projectId: input.projectId,
3801
- sourceAssetId: input.sourceAssetId,
4055
+ ...request,
4056
+ // The ratio the quote named, so the run bills the key that was confirmed.
4057
+ aspectRatio,
3802
4058
  prompt: input.prompt,
3803
- editModel: sentModel,
3804
- referenceAssetIds: input.referenceAssetIds,
3805
- resolution,
3806
- ...(isGptImageModel(editModel) ? { gptQuality: input.quality ?? DEFAULT_GPT_QUALITY } : {}),
3807
4059
  ...(takesBackgroundMode(editModel) ? { gptBackground: input.backgroundMode } : {}),
3808
- aspectRatio: input.aspectRatio,
3809
4060
  background: input.background,
3810
4061
  });
3811
4062
  if (!result.success)
@@ -3851,6 +4102,7 @@ export const editImage = {
3851
4102
  projectId: input.projectId,
3852
4103
  sourceAssetId: input.sourceAssetId,
3853
4104
  resolution,
4105
+ ...(aspectRatio ? { aspectRatio } : {}),
3854
4106
  cost_cents: totalCents,
3855
4107
  cost_credits: totalCents,
3856
4108
  asset: result.asset,
@@ -3896,7 +4148,7 @@ export const extractGridCells = {
3896
4148
  if (input.background)
3897
4149
  await desktop.requireCapability('background-generation', 'background generation');
3898
4150
  const refs = await resolveAssetRefs(ctx, input.projectId, [input.assetId, ...(input.referenceAssetIds ?? [])]);
3899
- const grid = refs.get(input.assetId);
4151
+ const grid = refs.row(input.assetId);
3900
4152
  const request = {
3901
4153
  projectId: input.projectId,
3902
4154
  assetId: grid.id,
@@ -3905,11 +4157,11 @@ export const extractGridCells = {
3905
4157
  resolution: input.resolution,
3906
4158
  aspectRatio: input.aspectRatio,
3907
4159
  prompt: input.prompt,
3908
- referenceAssetIds: input.referenceAssetIds?.map((r) => refs.get(r).id),
4160
+ referenceAssetIds: input.referenceAssetIds?.map((r) => refs.id(r)),
3909
4161
  };
3910
4162
  // The desktop prices it: the viewer's own `imageCost`, for this seat, rung and cell count. The desktop also
3911
4163
  // 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) });
4164
+ const quote = await desktop.quote('/agent/generation/extract-quote', 'request', request);
3913
4165
  const gridName = grid.code ?? grid.id;
3914
4166
  if (quote.credits > CONFIRM_CREDITS && !input.confirm) {
3915
4167
  return ok({
@@ -3928,6 +4180,7 @@ export const extractGridCells = {
3928
4180
  `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
4181
  });
3930
4182
  }
4183
+ approvedSpend(ctx);
3931
4184
  const result = await desktop.post('/agent/generation/extract-cells', { ...request, background: input.background });
3932
4185
  if (result.background) {
3933
4186
  return backgroundSubmitted(`extraction of ${quote.cells.join(', ')} from ${gridName}`, result.generationIds ?? [], {
@@ -3985,27 +4238,54 @@ export const extractGridCells = {
3985
4238
  * with no first/last frame IS ingredients mode.
3986
4239
  */
3987
4240
  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, {
4241
+ // `checkVideoParams` is the verdict the desktop's composition check reads too
4242
+ // (the prompt bar, the agent route and the handlers), so the op and the app
4243
+ // refuse the same ratio, resolution, references-at-resolution and length.
4244
+ const refusal = checkVideoParams(input.model, {
4245
+ aspectRatio: input.aspectRatio,
4003
4246
  videoResolution: input.videoResolution,
4004
- promptMode,
4247
+ duration: input.duration,
4248
+ provider: AGENT_ROUTE_PROVIDER,
4249
+ firstFrame: !!input.firstFrameAssetId,
4250
+ lastFrame: !!input.lastFrameAssetId,
4251
+ referenceImages: (input.ingredientAssetIds?.length ?? 0) +
4252
+ (input.characterAssetIds?.length ?? 0) +
4253
+ (input.environmentAssetIds?.length ?? 0) +
4254
+ (input.styleAssetIds?.length ?? 0),
4005
4255
  });
4006
- if (durErr)
4007
- return { requires_clarification: true, missing: ['duration'], message: durErr };
4008
- return null;
4256
+ return refusal
4257
+ ? { requires_clarification: true, missing: [refusal.field === 'references' ? 'videoResolution' : refusal.field], message: refusal.message }
4258
+ : null;
4259
+ }
4260
+ /** Each reference video's length, from whichever shape the caller used: the
4261
+ * per-clip list, plus the deprecated single value as one more clip. */
4262
+ function referenceVideoClips(input) {
4263
+ const single = input.videoReferenceSeconds ?? input.videoRefSeconds;
4264
+ return [...(input.videoReferenceSecondsEach ?? []), ...(single ? [single] : [])];
4265
+ }
4266
+ /** The reference-seconds gate, on every model: `checkReferenceSeconds` is the
4267
+ * verdict the desktop, its handlers and the server's key derivation reach for
4268
+ * the same clips, so a set quoted here is never refused after confirm. */
4269
+ function referenceSecondsRefusal(model, clips) {
4270
+ const error = checkReferenceSeconds(model, 'video', clips).error;
4271
+ return error
4272
+ ? { requires_clarification: true, missing: [], message: error.replace(/Trim (it|a clip) first\./, 'Trim $1 first with slates_trim_video.') }
4273
+ : null;
4274
+ }
4275
+ /** The reply when a video prices above what was approved: nothing ran, and the new price is the one to approve. */
4276
+ function videoPriceChanged(model, costKey, credits, approved) {
4277
+ return {
4278
+ requires_confirm: true,
4279
+ quote_exceeded: true,
4280
+ model,
4281
+ variant: costKey,
4282
+ estimated_cents: credits,
4283
+ estimated_credits: credits,
4284
+ approvedCredits: credits,
4285
+ message: `Nothing ran. This ${model} call now prices at ${fmtCredits(credits)} (${costKey}), above the ${fmtCredits(approved)} approved: ` +
4286
+ `a reference measured longer, or the prompt names a character or look that brings a billed input. ` +
4287
+ `Tell the user, and once they approve, re-call with confirm=true and approvedCredits=${credits}.`,
4288
+ };
4009
4289
  }
4010
4290
  // Model → registry cost-key. Each provider's keys ship with their own
4011
4291
  // shape (verified against /api/agent/models):
@@ -4026,28 +4306,19 @@ const KLING_TIER_MAP = {
4026
4306
  // Exported for scripts/pricing-consistency-check.mjs (slates-api repo), which
4027
4307
  // asserts this builder byte-matches the desktop's klingCreditKey/seedanceCreditKey.
4028
4308
  export function videoCostKey(input) {
4309
+ const refVideo = checkReferenceSeconds(input.model, 'video', referenceVideoClips(input));
4029
4310
  // EXACT-ID MAP, NEVER A PREFIX: 'minimax-h3-max' starts with 'minimax-h3'.
4030
4311
  // Mirrors minimaxCreditKey() in slate/src/shared/pricing.ts.
4031
4312
  if (MINIMAX_MODELS.has(input.model)) {
4032
4313
  const res = input.videoResolution ?? defaultVideoResolutionFor(input.model);
4033
4314
  if (input.model === 'minimax-h3-max') {
4034
4315
  const tokens = minimaxMaxReferenceTokens({ imagePixels: (input.referenceImages ?? 0) * MINIMAX_MAX_REFERENCE.normalizedImageEdge ** 2,
4035
- videoSeconds: input.videoRefSeconds ?? 0, audioSeconds: input.audioRefSeconds ?? 0, resolution: res ?? '' });
4316
+ videoSeconds: refVideo.actual, audioSeconds: input.audioRefSeconds ?? 0, resolution: res ?? '' });
4036
4317
  return `${input.model}-${res}-${input.duration}s${tokens ? `-rt${tokens}` : ''}`;
4037
4318
  }
4038
4319
  const k = minimaxRefSurchargeCount(input.model, input.referenceImages);
4039
4320
  return `${input.model}-${res}-${input.duration}s${k > 0 ? `-ref${k}` : ''}`;
4040
4321
  }
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
4322
  if (input.model.startsWith('seedance')) {
4052
4323
  // Mirrors seedanceCreditKey() in slate/src/shared/pricing.ts (version × face
4053
4324
  // × vref × res × duration). AI-face route bills the `-face-` key (~45% over
@@ -4063,16 +4334,13 @@ export function videoCostKey(input) {
4063
4334
  const v25 = input.model.startsWith('seedance-2.5');
4064
4335
  const res = input.videoResolution ?? (v25 ? '720p' : '1080p');
4065
4336
  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;
4337
+ if (refVideo.billed > 0) {
4070
4338
  // EvoLink (the AI-face rail) bills a reference on max(input, output) +
4071
4339
  // 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`;
4340
+ // Never clamped: a total past the last priced key is no price at all, and
4341
+ // `referenceSecondsRefusal` has already refused a set outside the row's bounds.
4342
+ const billedIn = face === '-face' ? Math.max(refVideo.billed, input.duration) : refVideo.billed;
4343
+ return `${input.model}${face}-vref-${res}-${billedIn + input.duration}s`;
4076
4344
  }
4077
4345
  return `${input.model}${face}-${res}-${input.duration}s`;
4078
4346
  }
@@ -4117,11 +4385,9 @@ export function videoCostKey(input) {
4117
4385
  // T = in + out. Sound on or off, reference images and reference audio do
4118
4386
  // not move the price.
4119
4387
  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`;
4388
+ if (refVideo.billed > 0) {
4389
+ // Never clamped: a clamp bills a longer clip at a shorter one's price.
4390
+ return `wan-3.0-vref-${res}-${refVideo.billed + input.duration}s`;
4125
4391
  }
4126
4392
  return `wan-3.0-${res}-${input.duration}s`;
4127
4393
  }
@@ -4143,10 +4409,6 @@ export function omniFlashEditCostKey(duration, videoResolution) {
4143
4409
  const res = videoResolution ?? defaultVideoResolutionFor('omni-flash-1-2-edit');
4144
4410
  return `omni-flash-1-2-edit-${res}-${duration}s`;
4145
4411
  }
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
4412
  /** Seedance 2.5 source-clip bounds for the edit task type — READ from the
4151
4413
  * capability SSOT, not typed. Kept as named exports because published builds
4152
4414
  * import them. */
@@ -4356,6 +4618,16 @@ function resolveVideoModel(raw) {
4356
4618
  }
4357
4619
  return null;
4358
4620
  }
4621
+ const GENERATE_VIDEO_SPOKEN_FIELDS = { spoken: 'audioReferenceSpokenText', clips: 'audioReferenceAssetIds' };
4622
+ const SHOT_SPOKEN_FIELDS = { spoken: 'audioRefSpokenText', clips: 'refs["audio-reference"]' };
4623
+ /** The pairing rule for a positional spoken-text array: present only beside its
4624
+ * clips, at the same length. Returns the refusal, or null when it pairs. */
4625
+ function spokenTextMisalignment(assetIds, spoken, fields) {
4626
+ if (spoken === undefined || spoken.length === (assetIds?.length ?? 0))
4627
+ return null;
4628
+ return (`${fields.spoken} pairs by position with ${fields.clips}, so send both together and at the same length ` +
4629
+ `(${spoken.length} line(s) vs ${assetIds?.length ?? 0} clip(s)). Use "" for a clip with no speech.`);
4630
+ }
4359
4631
  /**
4360
4632
  * Pair each reference-audio asset id with the words spoken in it.
4361
4633
  *
@@ -4371,8 +4643,15 @@ function resolveVideoModel(raw) {
4371
4643
  * address different clips depending on which shape the caller used. Blank
4372
4644
  * entries are dropped rather than sent as empty strings — a clip with no
4373
4645
  * speech has no line, which is not the same as a line that is empty.
4646
+ *
4647
+ * A misaligned array would attach one clip's line to another and send the
4648
+ * model the wrong words with nothing on screen to say so, so it is refused
4649
+ * here, for every model and every caller, rather than truncated.
4374
4650
  */
4375
- function spokenTextByAssetId(assetIds, spoken) {
4651
+ function spokenTextByAssetId(assetIds, spoken, fields = GENERATE_VIDEO_SPOKEN_FIELDS) {
4652
+ const misaligned = spokenTextMisalignment(assetIds, spoken, fields);
4653
+ if (misaligned)
4654
+ throw new Error(misaligned);
4376
4655
  if (!assetIds?.length || !spoken?.length)
4377
4656
  return undefined;
4378
4657
  const out = {};
@@ -4383,22 +4662,27 @@ function spokenTextByAssetId(assetIds, spoken) {
4383
4662
  });
4384
4663
  return Object.keys(out).length > 0 ? out : undefined;
4385
4664
  }
4386
- // Maps a model id to its bundled prompting skill (frontmatter `name:`), so
4387
- // guidance text points at a skill that actually exists.
4665
+ // Maps a model id to its prompting guide (frontmatter `name:`), so guidance
4666
+ // text points at a guide that actually exists.
4388
4667
  //
4389
4668
  // 🚨 ONE RESOLVER. This was a second hand-typed alias table beside
4390
4669
  // `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
4670
+ // about one seat, so every generation on it was told to read the cost skill
4392
4671
  // 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.
4672
+ // seed-audio before seedance, minimax before both) are solved once, there. A
4673
+ // model with no guide throws: `VIDEO_MODEL_GUIDES` below runs it over the whole
4674
+ // video roster at load, and slates-api's model-lifecycle check over the registry.
4394
4675
  function promptingSkillFor(model) {
4395
- return resolveGuideTopic(model) ?? 'slates-cost-discipline';
4676
+ const guide = resolveGuideTopic(model);
4677
+ if (!guide)
4678
+ throw new Error(`No prompting guide resolves for model ${model}: add its prefix to resolveGuideTopic in packages/shared/src/operations/index.ts.`);
4679
+ return guide;
4396
4680
  }
4397
4681
  /**
4398
4682
  * The per-model prompting guides for the whole video roster, DERIVED.
4399
4683
  *
4400
4684
  * `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
4685
+ * one seat's guide for as long as that seat shipped — an agent reading the
4402
4686
  * description could not learn the guide existed. A hand-typed index of a
4403
4687
  * generated corpus is a stale index; it is only a matter of when.
4404
4688
  */
@@ -4456,10 +4740,10 @@ export const generateVideo = {
4456
4740
  // WHY here, you are writing the skill in the wrong file.
4457
4741
  firstFrameAssetId: z.string().optional().describe('Starting frame for image-to-video (UUID or badge code, resolved at call time).'),
4458
4742
  lastFrameAssetId: z.string().optional().describe('Ending frame. Pairs with firstFrameAssetId.'),
4459
- ingredientAssetIds: z.array(z.string()).max(30).optional().describe(
4743
+ ingredientAssetIds: z.array(z.string()).max(Math.max(...VIDEO_MODELS.map((m) => maxIngredientImagesFor(m)))).optional().describe(
4460
4744
  // Caps DERIVED from MODEL_CAPABILITIES — the hand-typed list omitted
4461
4745
  // 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.`),
4746
+ `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
4747
  characterAssetIds: z.array(z.string()).optional().describe('Character sheet assets — keeps a character consistent.'),
4464
4748
  environmentAssetIds: z.array(z.string()).optional().describe('Location references — keeps a location consistent.'),
4465
4749
  styleAssetIds: z.array(z.string()).optional().describe('Style references — locks the look.'),
@@ -4471,10 +4755,10 @@ export const generateVideo = {
4471
4755
  // multimodalRefSummary) rather than hand-typed, so a cap change in one
4472
4756
  // place cannot leave a stale number in a description an LLM reads.
4473
4757
  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.'),
4758
+ 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
4759
  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
4760
  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.'),
4761
+ sound: z.boolean().optional().describe('Kling 3.0 (every tier) 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.'),
4478
4762
  audioLanguage: z.enum(['EN', 'ZH', 'JA', 'KO', 'ES']).optional().describe('Any Kling 3.0 model with sound on — language for dialogue.'),
4479
4763
  generateMusic: z.boolean().optional().describe('Any Kling 3.0 model with sound on — auto-generate background music.'),
4480
4764
  seedanceDraft: z.boolean().optional().describe('Create a finishable Seedance 2.5 preview at 480p.'),
@@ -4484,6 +4768,7 @@ export const generateVideo = {
4484
4768
  negativePrompt: z.string().optional(),
4485
4769
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
4486
4770
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
4771
+ 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
4772
  folderId: folderIdField,
4488
4773
  }),
4489
4774
  async run(input, ctx) {
@@ -4563,6 +4848,10 @@ export const generateVideo = {
4563
4848
  const capErr = assertVideoCapabilities(input);
4564
4849
  if (capErr)
4565
4850
  return ok(capErr);
4851
+ // Every model reads the spoken text, so its pairing is checked before any model's shape block.
4852
+ const spokenErr = spokenTextMisalignment(input.audioReferenceAssetIds, input.audioReferenceSpokenText, GENERATE_VIDEO_SPOKEN_FIELDS);
4853
+ if (spokenErr)
4854
+ return ok({ requires_clarification: true, missing: [], message: spokenErr });
4566
4855
  // Omni Flash 1.2's SHAPE constraints. Frames ride image-to-video (a start
4567
4856
  // frame and an optional end frame, 10s or less with the end frame);
4568
4857
  // references ride reference-to-video (Google's limits: 6 images, reference
@@ -4581,7 +4870,7 @@ export const generateVideo = {
4581
4870
  (input.environmentAssetIds?.length ?? 0) +
4582
4871
  (input.styleAssetIds?.length ?? 0);
4583
4872
  const hasRefs = imageRefs + videoRefs > 0;
4584
- const refCount = imageRefs + (hasRefs && input.firstFrameAssetId ? 1 : 0);
4873
+ const refCount = imageRefs + (hasRefs && input.firstFrameAssetId && getModelCapability(input.model)?.firstFrameRidesAsReference ? 1 : 0);
4585
4874
  // Only the lengths given; a missing one is asked for below, before the quote.
4586
4875
  const refSeconds = [
4587
4876
  ...(input.videoReferenceAssetId && input.videoReferenceSeconds != null ? [input.videoReferenceSeconds] : []),
@@ -4622,8 +4911,6 @@ export const generateVideo = {
4622
4911
  const audioRefs = (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0);
4623
4912
  const refImages = imageRefs;
4624
4913
  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
4914
  const overCap = [
4628
4915
  [refImages, cap?.maxIngredientImages, 'reference images'],
4629
4916
  [videoRefs, cap?.maxReferenceVideos, 'reference videos'],
@@ -4636,18 +4923,34 @@ export const generateVideo = {
4636
4923
  ? 'Wan 3.0 needs a start frame (firstFrameAssetId) with a last frame.'
4637
4924
  : overCap
4638
4925
  ? `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;
4926
+ : null;
4642
4927
  if (shapeError) {
4643
4928
  return ok({ requires_clarification: true, missing: [], message: shapeError });
4644
4929
  }
4645
4930
  }
4931
+ // Reference-video seconds, every model: each clip's window and the combined
4932
+ // total, before the quote. A missing length is asked for further down.
4933
+ const referenceClips = referenceVideoClips({
4934
+ videoReferenceSecondsEach: input.videoReferenceSecondsEach,
4935
+ videoReferenceSeconds: input.videoReferenceAssetId ? input.videoReferenceSeconds : undefined,
4936
+ });
4937
+ const refSecondsErr = referenceSecondsRefusal(input.model, referenceClips);
4938
+ if (refSecondsErr)
4939
+ return ok(refSecondsErr);
4940
+ // Frames beside reference video or audio, every model: the verdict the desktop's composer reaches.
4941
+ const framesErr = checkFramesWithReferenceMedia(input.model, {
4942
+ firstFrame: !!input.firstFrameAssetId,
4943
+ lastFrame: !!input.lastFrameAssetId,
4944
+ referenceVideos: (input.videoReferenceAssetIds?.length ?? 0) + (input.videoReferenceAssetId ? 1 : 0),
4945
+ referenceAudio: (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0),
4946
+ });
4947
+ if (framesErr)
4948
+ return ok({ requires_clarification: true, missing: [], message: framesErr });
4646
4949
  // Kling 4.0's SHAPE constraint: FRAMES, NEVER REFERENCES. Only fal's
4647
4950
  // `kling/v4/image-to-video` (start frame plus an optional end frame) and
4648
4951
  // `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
4952
+ // reference id has no transport and is refused rather than dropped. An end
4953
+ // frame needs the start frame: text-to-video has
4651
4954
  // no frame slot at all.
4652
4955
  if (input.model === 'kling-v4.0') {
4653
4956
  const refs = (input.ingredientAssetIds?.length ?? 0) +
@@ -4667,34 +4970,6 @@ export const generateVideo = {
4667
4970
  return ok({ requires_clarification: true, missing: [], message: shapeError });
4668
4971
  }
4669
4972
  }
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
4973
  // MiniMax H3's SHAPE constraints. Counts and caps are read from the
4699
4974
  // capability SSOT; only the endpoint SHAPE is stated here, because it is
4700
4975
  // not a number the registry models: fal publishes text-to-video,
@@ -4758,20 +5033,6 @@ export const generateVideo = {
4758
5033
  message: `${input.model} takes at most ${maxTotal} reference files across all modalities (you passed ${refImages + refMedia}).`,
4759
5034
  });
4760
5035
  }
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
5036
  // fal: "Audio cannot be the only reference input; provide at least one
4776
5037
  // reference image or video with it."
4777
5038
  const audioRefs = (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0);
@@ -4784,6 +5045,26 @@ export const generateVideo = {
4784
5045
  });
4785
5046
  }
4786
5047
  }
5048
+ // Reference counts, every model, from its capability row. The desktop sends the first `cap`
5049
+ // pictures and leaves the rest out, so a call over a cap would run, and bill, without references
5050
+ // the caller named: refused here, before the quote. The blocks above word their own model's caps.
5051
+ {
5052
+ const cap = getModelCapability(input.model);
5053
+ const images = (input.ingredientAssetIds?.length ?? 0) + (input.characterAssetIds?.length ?? 0) +
5054
+ (input.environmentAssetIds?.length ?? 0) + (input.styleAssetIds?.length ?? 0);
5055
+ const videos = (input.videoReferenceAssetIds?.length ?? 0) + (input.videoReferenceAssetId ? 1 : 0);
5056
+ const audio = (input.audioReferenceAssetIds?.length ?? 0) + (input.audioReferenceAssetId ? 1 : 0);
5057
+ // Beside references a start frame rides as reference image 1 on some rows and uses a slot.
5058
+ const frameSlot = input.firstFrameAssetId && images + videos > 0 && cap?.firstFrameRidesAsReference ? 1 : 0;
5059
+ 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') ??
5060
+ referenceCapRefusal(input.model, videos, maxReferenceVideosFor(input.model, input.duration), 'videoReferenceAssetIds', 'reference videos on a clip this long') ??
5061
+ referenceCapRefusal(input.model, audio, cap?.maxReferenceAudio ?? 0, 'audioReferenceAssetIds', 'reference audio clips') ??
5062
+ (cap?.maxReferenceFilesTotal
5063
+ ? referenceCapRefusal(input.model, images + frameSlot + videos + audio, cap.maxReferenceFilesTotal, 'ingredientAssetIds', 'reference files across images, video and audio')
5064
+ : null);
5065
+ if (overCap)
5066
+ return ok(overCap);
5067
+ }
4787
5068
  // Resolve every asset reference (UUID or badge code) against the
4788
5069
  // project AT CALL TIME. Codes the user just spoke ("a8 is the one")
4789
5070
  // resolve to whatever exists NOW — including assets created in the UI
@@ -4853,13 +5134,16 @@ export const generateVideo = {
4853
5134
  // a local literal had already lost 'continue the story'.
4854
5135
  intentHits = hasRefs ? seedanceTaskIntentWords(input.prompt) : [];
4855
5136
  }
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.
5137
+ // A desktop with 'video-quote' prices the composition it will send: it resolves every reference,
5138
+ // prompt @mentions included, and measures each clip itself, so the caller's seconds are not needed.
5139
+ const desktop = ctx.desktop();
5140
+ const desktopQuotes = await desktop.hasCapability('video-quote');
5141
+ // An older desktop quotes H3 Max only, so this op builds the key and needs a length for EVERY
5142
+ // reference clip, in both shapes. A missing one does not fail the generation (the server probes
5143
+ // and corrects upward): it under-quotes, which is worse than asking. Wan 3.0 bills reference video
5144
+ // seconds on top of output seconds too, and Omni Flash's per-clip cap needs every length to check.
4861
5145
  const isSeedance = input.model.startsWith('seedance');
4862
- const needsRefSeconds = isSeedance || input.model === 'wan-3.0' || input.model === 'omni-flash-1-2';
5146
+ const needsRefSeconds = !desktopQuotes && (isSeedance || input.model === 'wan-3.0' || input.model === 'omni-flash-1-2');
4863
5147
  if (input.videoReferenceAssetId && needsRefSeconds && !input.videoReferenceSeconds) {
4864
5148
  return ok({
4865
5149
  requires_clarification: true,
@@ -4878,11 +5162,55 @@ export const generateVideo = {
4878
5162
  }
4879
5163
  // A desktop without Omni Flash 1.2 gets the 1.1 seat at the same price (`desktopModelId`), resolved before the
4880
5164
  // 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);
5165
+ const seat = await desktopModelId(desktop, input.model, `${input.model} generation`, input.duration);
5166
+ // One body for the quote and the submission, so the desktop prices exactly what it will be sent.
5167
+ const request = {
5168
+ projectId: input.projectId,
5169
+ model: seat.model,
5170
+ prompt: input.prompt,
5171
+ aspectRatio: input.aspectRatio,
5172
+ duration: input.duration,
5173
+ videoResolution: input.videoResolution,
5174
+ firstFrameAssetId: input.firstFrameAssetId,
5175
+ lastFrameAssetId: input.lastFrameAssetId,
5176
+ ingredientAssetIds: input.ingredientAssetIds ?? [],
5177
+ characterAssetIds: input.characterAssetIds ?? [],
5178
+ environmentAssetIds: input.environmentAssetIds ?? [],
5179
+ styleAssetIds: input.styleAssetIds ?? [],
5180
+ // Both shapes on the wire. The route merges and dedupes them, so an old
5181
+ // client sending only the singular and a new one sending only the plural
5182
+ // reach the identical handler params.
5183
+ videoReferenceAssetId: input.videoReferenceAssetId,
5184
+ audioReferenceAssetId: input.audioReferenceAssetId,
5185
+ videoReferenceAssetIds: input.videoReferenceAssetIds,
5186
+ audioReferenceAssetIds: input.audioReferenceAssetIds,
5187
+ // The route keys this by ASSET ID, not by position, because its own
5188
+ // singular/plural merge appends to the END of the list — an index would
5189
+ // mean different clips depending on which shape the caller used. The op
5190
+ // takes the friendlier positional array and re-keys it here, AFTER
5191
+ // `rids()` has resolved badge codes, so the keys are the ids the route
5192
+ // will resolve. A blank entry is dropped rather than sent as "".
5193
+ audioReferenceSpokenText: spokenTextByAssetId(input.audioReferenceAssetIds, input.audioReferenceSpokenText),
5194
+ sound: input.sound,
5195
+ audioLanguage: input.audioLanguage,
5196
+ generateMusic: input.generateMusic,
5197
+ seedanceFace: input.seedanceFace,
5198
+ seedanceRealFace: input.seedanceRealFace,
5199
+ seedanceDraft: input.seedanceDraft,
5200
+ realFaceConsent: input.realFaceConsent,
5201
+ negativePrompt: input.negativePrompt,
5202
+ ...folderBody(input.folderId),
5203
+ };
4882
5204
  const cloud = ctx.cloud();
4883
5205
  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
5206
+ // The desktop's quote: the key its handler bills and its credits, which the submission below is
5207
+ // held to (`maxCredits`). Null on a desktop before 'video-quote'.
5208
+ const quote = desktopQuotes
5209
+ ? await desktop.quote('/agent/generation/video-quote', 'request', request)
5210
+ : null;
5211
+ const costKey = quote?.costKey ?? (input.model === 'minimax-h3-max'
5212
+ // The older desktop's one quote: H3 Max, whose reference tokens only it can count.
5213
+ ? (await desktop.quote('/agent/generation/video-quote', 'request', request)).costKey
4886
5214
  : videoCostKey({
4887
5215
  model: input.model,
4888
5216
  duration: input.duration,
@@ -4894,14 +5222,10 @@ export const generateVideo = {
4894
5222
  // dimension. Counted from the same four arrays the request sends, so the
4895
5223
  // quote and the server's own re-derivation see the same number.
4896
5224
  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
- });
5225
+ // Every reference clip, both shapes: quoting only the singular would
5226
+ // understate a multi-clip call.
5227
+ videoReferenceSecondsEach: referenceClips,
5228
+ }));
4905
5229
  // Hard consent gate, checked before any spend: the real-face route is
4906
5230
  // consent-attested by design (the desktop enforces it too).
4907
5231
  if (input.seedanceRealFace && !input.realFaceConsent) {
@@ -4920,6 +5244,14 @@ export const generateVideo = {
4920
5244
  `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
5245
  }
4922
5246
  const totalCents = creditCost(entry);
5247
+ // What the send is held to, in the desktop's unit (list credits): its own quote, else the registry's list price.
5248
+ const quotedCredits = quote?.credits ?? listCredits(entry);
5249
+ // The price the user approved binds the call that spends: a reference re-measured longer or a
5250
+ // character that gained a billed picture since the pre-flight is asked about again, never run.
5251
+ const approvedCredits = requestedCredits(ctx, input);
5252
+ if (approvedCredits != null && quotedCredits > approvedCredits) {
5253
+ return ok(videoPriceChanged(input.model, costKey, quotedCredits, approvedCredits));
5254
+ }
4923
5255
  if (intentHits.length > 0 && !input.confirm) {
4924
5256
  return ok({
4925
5257
  requires_clarification: true,
@@ -4927,6 +5259,7 @@ export const generateVideo = {
4927
5259
  missing: ['prompt'],
4928
5260
  variant: costKey,
4929
5261
  estimated_credits: totalCents,
5262
+ approvedCredits: quotedCredits,
4930
5263
  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
5264
  `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
5265
  `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 +5307,7 @@ export const generateVideo = {
4974
5307
  `${fmtCredits(totalCents)}.` +
4975
5308
  refSummary +
4976
5309
  (promptWarning ? `\n\n${promptWarning}` : '') +
4977
- `\n\nWhen ready, re-call slates_generate_video with confirm=true and the (possibly revised) prompt.`,
5310
+ `\n\nWhen ready, re-call slates_generate_video with confirm=true, approvedCredits=${quotedCredits} and the (possibly revised) prompt.`,
4978
5311
  images: refImages,
4979
5312
  data: {
4980
5313
  requires_confirm: true,
@@ -4982,6 +5315,7 @@ export const generateVideo = {
4982
5315
  variant: costKey,
4983
5316
  estimated_cents: totalCents,
4984
5317
  estimated_credits: totalCents,
5318
+ approvedCredits: quotedCredits,
4985
5319
  references: previews.map((p) => ({
4986
5320
  role: p.role,
4987
5321
  ref: p.ref,
@@ -4994,48 +5328,20 @@ export const generateVideo = {
4994
5328
  },
4995
5329
  };
4996
5330
  }
4997
- const desktop = ctx.desktop();
4998
5331
  if (input.background) {
4999
5332
  await desktop.requireCapability('background-generation', 'background generation');
5000
5333
  }
5334
+ const approved = approvedSpend(ctx, input);
5001
5335
  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),
5336
+ ...request,
5337
+ // The desktop composes the request again and sends nothing that prices above its own quote, which the
5338
+ // check above holds at or below the approved credits, for the quote they were approved for.
5339
+ ...(quote ? heldBody(quote.credits, approved.quoteFingerprint) : {}),
5037
5340
  background: input.background,
5038
5341
  });
5342
+ if (result.quoteExceeded) {
5343
+ return ok(videoPriceChanged(input.model, result.quoteExceeded.costKey, result.quoteExceeded.credits, quotedCredits));
5344
+ }
5039
5345
  if (!result.success) {
5040
5346
  throw new Error(result.error ?? 'Generation failed');
5041
5347
  }
@@ -5260,7 +5566,7 @@ export const generateAudio = {
5260
5566
  return ok({
5261
5567
  requires_clarification: true,
5262
5568
  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.`,
5569
+ 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
5570
  });
5265
5571
  }
5266
5572
  if (input.prompt.length > 450) {
@@ -5318,6 +5624,7 @@ export const generateAudio = {
5318
5624
  if (input.background) {
5319
5625
  await desktop.requireCapability('background-generation', 'background generation');
5320
5626
  }
5627
+ approvedSpend(ctx);
5321
5628
  const result = await desktop.post('/agent/generation/audio', {
5322
5629
  projectId: input.projectId,
5323
5630
  model: input.model,
@@ -5361,8 +5668,6 @@ export const generateAudio = {
5361
5668
  },
5362
5669
  };
5363
5670
  // ── 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
5671
  /** A project asset's recorded length in seconds, or null when its row has none. */
5367
5672
  async function recordedSeconds(desktop, projectId, assetId) {
5368
5673
  const { assets } = await desktop.get('/agent/assets', { projectId });
@@ -5378,18 +5683,69 @@ async function recordedSeconds(desktop, projectId, assetId) {
5378
5683
  * Control Pro at 42 credits that billed 252.
5379
5684
  */
5380
5685
  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)
5686
+ const blocks = Math.max(1, toolBlocks(seconds ?? 0));
5687
+ const costKey = toolBlockKey(stem, blocks);
5688
+ const row = async (key) => {
5689
+ const found = (await ctx.cloud().get(`/api/agent/models?costKey=${encodeURIComponent(key)}`)).models.find((m) => m.model === key);
5690
+ if (!found)
5388
5691
  throw new Error(`Model variant not in registry: ${key}`);
5389
- return credits;
5692
+ return found;
5693
+ };
5694
+ const rows = [await row(costKey), ...(voiceStep ? [await row(toolBlockKey(stem, 1))] : [])];
5695
+ // `totalCents` is what the account is debited; `listTotal` is the same quote in the desktop's unit, which the
5696
+ // run's ceiling (`maxCredits`) is held in. They differ only on a tier the registry prices below list.
5697
+ const sum = (price) => rows.reduce((total, m) => total + price(m), 0);
5698
+ return { costKey, totalCents: sum(creditCost), listTotal: sum(listCredits), blocks };
5699
+ }
5700
+ /** `approvedCredits` on the two tools: the figure a reply named as `approvedCredits`, once the user approved it. */
5701
+ 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.');
5702
+ /**
5703
+ * The credits approved for a call, as it is priced: the host's decision where it has one, else the input's.
5704
+ * `approvedSpend` reads the same figure again at the send.
5705
+ */
5706
+ const requestedCredits = (ctx, input) => ctx.spend ? ctx.spend.approvedCredits : input.approvedCredits;
5707
+ /**
5708
+ * A tool run whose length the op could not read is quoted at one block and measured by the desktop as it runs, and
5709
+ * only a desktop with 'lip-sync-quote' does that: its lip-sync and motion-transfer routes hold a run to the
5710
+ * `maxCredits` it is sent (`holdTool`, released with that token). Desktop 1.6.12 and older ignore the ceiling and
5711
+ * bill every 5s block of the media against a one-block approval, so there the run is refused before any spend.
5712
+ */
5713
+ async function requireToolHold(ctx, seconds, feature) {
5714
+ if (seconds == null)
5715
+ await ctx.desktop().requireCapability('lip-sync-quote', feature);
5716
+ }
5717
+ /**
5718
+ * What a confirm asks the user to approve, in the desktop's unit: the quote, or a higher figure the call already
5719
+ * carries (a `quote_exceeded` price, or the model's own claim), which the user is then shown. The reply names it
5720
+ * as `approvedCredits`, and the MCP confirm gate sends exactly that figure with the confirmed run.
5721
+ */
5722
+ function toolCeiling(quoted, requested) {
5723
+ const raised = requested != null && requested > quoted;
5724
+ return {
5725
+ credits: raised ? requested : quoted,
5726
+ raised,
5727
+ sentence: raised ? `Approving lets it spend up to ${fmtCredits(requested)}. ` : '',
5390
5728
  };
5391
- const totalCents = (await price(costKey)) + (voiceStep ? await price(`${stem}-${TOOL_BLOCK_SECONDS}s`) : 0);
5392
- return { costKey, totalCents, blocks };
5729
+ }
5730
+ /** 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. */
5731
+ function toolPriceChanged(tool, held, exceeded) {
5732
+ return ok({
5733
+ requires_confirm: true,
5734
+ quote_exceeded: true,
5735
+ variant: exceeded.costKey,
5736
+ estimated_cents: exceeded.credits,
5737
+ estimated_credits: exceeded.credits,
5738
+ approvedCredits: exceeded.credits,
5739
+ ...(exceeded.fingerprint ? { quote_fingerprint: exceeded.fingerprint } : {}),
5740
+ message: `Nothing ran. Slates measured this ${tool} at ${fmtCredits(exceeded.credits)} (${exceeded.costKey}), above the ${fmtCredits(held)} it was held to. ` +
5741
+ `Tell the user, and once they approve, re-call with confirm=true and approvedCredits=${exceeded.credits}.`,
5742
+ });
5743
+ }
5744
+ /** 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. */
5745
+ function toolCharge(seconds, totalCents) {
5746
+ return seconds == null
5747
+ ? { cost_cents: null, cost_credits: null, minimum_credits: totalCents, quote_is_floor: true }
5748
+ : { cost_cents: totalCents, cost_credits: totalCents };
5393
5749
  }
5394
5750
  // ── Generate lip-sync ───────────────────────────────────────────
5395
5751
  export const generateLipSync = {
@@ -5410,6 +5766,7 @@ export const generateLipSync = {
5410
5766
  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
5767
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
5412
5768
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
5769
+ approvedCredits: TOOL_APPROVED_CREDITS,
5413
5770
  }),
5414
5771
  async run(input, ctx) {
5415
5772
  if (input.audioMethod === 'tts' && !input.ttsText) {
@@ -5433,22 +5790,43 @@ export const generateLipSync = {
5433
5790
  // Billed per 5s block of the output: the clip's length on a video source;
5434
5791
  // on a still, the voice track's — typed words at the desktop's reading pace
5435
5792
  // (`lipSyncEstimate`, 13 characters a second, so this quote is the Generate
5436
- // button's), an uploaded file unknown until the desktop measures it. Typed
5793
+ // button's), an uploaded file measured by the desktop off disk. Typed
5437
5794
  // words on a still are two billed calls: the voice step adds one flat block.
5795
+ const uploadOnStill = input.sourceType === 'image' && input.audioMethod === 'upload';
5796
+ // An uploaded track is measured by the desktop, and one that cannot measure it cannot hold the run either.
5797
+ if (uploadOnStill)
5798
+ await ctx.desktop().requireCapability('lip-sync-quote', 'pricing a lip-sync on uploaded audio before it runs');
5438
5799
  const seconds = input.sourceType === 'video'
5439
5800
  ? await recordedSeconds(ctx.desktop(), input.projectId, input.sourceAssetId)
5440
5801
  : input.audioMethod === 'tts'
5441
5802
  ? (input.ttsText ?? '').trim().length / (13 * (input.ttsSpeed ?? 1))
5442
- : null;
5803
+ : (await ctx.desktop().post('/agent/generation/lip-sync-quote', {
5804
+ request: {
5805
+ projectId: input.projectId, sourceAssetId: input.sourceAssetId, audioMethod: input.audioMethod,
5806
+ audioFilePath: input.audioFilePath, avatarModel: input.avatarModel,
5807
+ },
5808
+ })).seconds;
5809
+ // The desktop could not read the file's length, so there is no price to confirm: one block would
5810
+ // be a guess, and the run bills every 5s of the audio.
5811
+ if (uploadOnStill && seconds == null) {
5812
+ return ok({
5813
+ requires_clarification: true,
5814
+ missing: ['audioFilePath'],
5815
+ 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. ` +
5816
+ 'Check the path and that the file plays (mp3, wav or m4a), then call again.',
5817
+ });
5818
+ }
5819
+ await requireToolHold(ctx, seconds, 'holding a lip-sync on a clip with no recorded length to the price approved');
5443
5820
  const voiceStep = input.sourceType === 'image' && input.audioMethod === 'tts';
5444
- const { costKey, totalCents, blocks } = await quoteToolBlocks(ctx, stem, seconds, voiceStep);
5821
+ const { costKey, totalCents, listTotal, blocks } = await quoteToolBlocks(ctx, stem, seconds, voiceStep);
5445
5822
  const length = `${blocks * TOOL_BLOCK_SECONDS}s${voiceStep ? ' + voice' : ''}`;
5823
+ const ceiling = toolCeiling(listTotal, requestedCredits(ctx, input));
5446
5824
  // Cost confirm gate. Lip-sync is mechanical — the model re-syncs the
5447
5825
  // user-chosen source to the user-chosen audio. The agent doesn't
5448
5826
  // write a prompt that depends on what the source looks like, so we
5449
5827
  // 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) {
5828
+ // An unknown length quotes one block, a floor, so it always asks, and so does a ceiling above the quote.
5829
+ if ((totalCents > CONFIRM_CREDITS || seconds == null || ceiling.raised) && !input.confirm) {
5452
5830
  const sourceRef = await lookupAssetRef(ctx.desktop(), input.sourceAssetId);
5453
5831
  const audioPreview = input.audioMethod === 'tts'
5454
5832
  ? `Audio: TTS — "${(input.ttsText ?? '').slice(0, 120)}"`
@@ -5458,8 +5836,13 @@ export const generateLipSync = {
5458
5836
  variant: costKey,
5459
5837
  estimated_cents: totalCents,
5460
5838
  estimated_credits: totalCents,
5839
+ approvedCredits: ceiling.credits,
5840
+ ...(seconds == null ? { quote_is_floor: true } : {}),
5461
5841
  source_ref: sourceRef,
5462
- message: `Cost: ${fmtCredits(totalCents)}${seconds == null ? ' or more' : ''} for ${length} lip-sync (${costKey}). ` +
5842
+ message: (seconds == null
5843
+ ? `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. `
5844
+ : `Cost: ${fmtCredits(totalCents)} for ${length} lip-sync (${costKey}). `) +
5845
+ ceiling.sentence +
5463
5846
  `Source: ${sourceRef}. ${audioPreview}. ` +
5464
5847
  `Re-call with confirm=true after the user explicitly OKs the spend. ` +
5465
5848
  `When discussing with the user, refer to the source by its code (matches the gallery badge).`,
@@ -5469,6 +5852,12 @@ export const generateLipSync = {
5469
5852
  if (input.background) {
5470
5853
  await desktop.requireCapability('background-generation', 'background generation');
5471
5854
  }
5855
+ // Held to the credits approved, else the quote: the desktop measures the media first and runs nothing above
5856
+ // it, so a one-block floor cannot bill eighteen. A quote now above the approval runs nothing and asks again.
5857
+ const approved = approvedSpend(ctx, input);
5858
+ if (approved.approvedCredits != null && listTotal > approved.approvedCredits)
5859
+ return toolPriceChanged('lip-sync', approved.approvedCredits, { credits: listTotal, costKey });
5860
+ const held = approved.approvedCredits ?? listTotal;
5472
5861
  const result = await desktop.post('/agent/generation/lip-sync', {
5473
5862
  projectId: input.projectId,
5474
5863
  sourceAssetId: input.sourceAssetId,
@@ -5481,23 +5870,29 @@ export const generateLipSync = {
5481
5870
  avatarModel: input.avatarModel,
5482
5871
  // No estimatedCost: the desktop prices the media itself, in dollars.
5483
5872
  // This op's figure is CREDITS, which a 1.5.8 desktop recorded as dollars.
5873
+ ...heldBody(held, approved.quoteFingerprint),
5484
5874
  background: input.background,
5485
5875
  });
5876
+ if (result.quoteExceeded)
5877
+ return toolPriceChanged('lip-sync', held, result.quoteExceeded);
5486
5878
  if (!result.success)
5487
5879
  throw new Error(result.error ?? 'Lip-sync generation failed');
5880
+ const charged = toolCharge(seconds, totalCents);
5881
+ const chargedText = seconds == null
5882
+ ? `at ${fmtCredits(totalCents)} per 5s of the audio (its length was not measured, so read the charge from the credit balance)`
5883
+ : `for ${fmtCredits(totalCents)}`;
5488
5884
  if (result.background) {
5489
5885
  const ids = result.generationIds ?? (result.generationId ? [result.generationId] : []);
5490
5886
  return backgroundSubmitted(`${length} lip-sync (${costKey})`, ids, {
5491
5887
  variant: costKey,
5492
5888
  projectId: input.projectId,
5493
5889
  sourceAssetId: input.sourceAssetId,
5494
- cost_cents: totalCents,
5495
- cost_credits: totalCents,
5890
+ ...charged,
5496
5891
  });
5497
5892
  }
5498
5893
  return {
5499
- text: `Generated ${length} lip-sync (${costKey}) into project ${input.projectId} ` +
5500
- `for ${fmtCredits(totalCents)}. ` +
5894
+ text: `Generated ${seconds == null ? 'a' : length} lip-sync (${costKey}) into project ${input.projectId} ` +
5895
+ `${chargedText}. ` +
5501
5896
  (input.audioMethod === 'tts'
5502
5897
  ? `Spoken: "${(input.ttsText ?? '').slice(0, 60)}${(input.ttsText ?? '').length > 60 ? '...' : ''}"`
5503
5898
  : `Audio: ${input.audioFilePath}`),
@@ -5506,8 +5901,7 @@ export const generateLipSync = {
5506
5901
  projectId: input.projectId,
5507
5902
  sourceType: input.sourceType,
5508
5903
  sourceAssetId: input.sourceAssetId,
5509
- cost_cents: totalCents,
5510
- cost_credits: totalCents,
5904
+ ...charged,
5511
5905
  asset: result.asset,
5512
5906
  generationId: result.generationId,
5513
5907
  },
@@ -5529,6 +5923,7 @@ export const generateMotionTransfer = {
5529
5923
  prompt: z.string().optional().describe('Optional refinement. Read slates-prompting-motion-transfer.'),
5530
5924
  background: z.boolean().optional().describe(BACKGROUND_DESCRIBE),
5531
5925
  confirm: z.boolean().optional().describe(CONFIRM_PARAM),
5926
+ approvedCredits: TOOL_APPROVED_CREDITS,
5532
5927
  }),
5533
5928
  async run(input, ctx) {
5534
5929
  const motionModel = input.motionModel ?? 'kling-mc-pro';
@@ -5537,13 +5932,15 @@ export const generateMotionTransfer = {
5537
5932
  // the orientation's maximum (the desktop's `motionTransferEstimate`).
5538
5933
  const clipSeconds = await recordedSeconds(ctx.desktop(), input.projectId, input.sourceVideoAssetId);
5539
5934
  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);
5935
+ await requireToolHold(ctx, seconds, 'holding a motion transfer on a clip with no recorded length to the price approved');
5936
+ const { costKey, totalCents, listTotal, blocks } = await quoteToolBlocks(ctx, motionModel, seconds, false);
5937
+ const ceiling = toolCeiling(listTotal, requestedCredits(ctx, input));
5541
5938
  // Cost confirm gate. Motion transfer is mechanical — the model
5542
5939
  // applies source motion to target image deterministically. We don't
5543
5940
  // burn tokens previewing assets the user already chose; codes in the
5544
5941
  // 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) {
5942
+ // length quotes one block, a floor, so it always asks, and so does a ceiling above the quote.
5943
+ if ((totalCents > CONFIRM_CREDITS || seconds == null || ceiling.raised) && !input.confirm) {
5547
5944
  const desktop = ctx.desktop();
5548
5945
  const [source, target] = await Promise.all([
5549
5946
  lookupAssetRef(desktop, input.sourceVideoAssetId),
@@ -5554,9 +5951,12 @@ export const generateMotionTransfer = {
5554
5951
  variant: costKey,
5555
5952
  estimated_cents: totalCents,
5556
5953
  estimated_credits: totalCents,
5954
+ approvedCredits: ceiling.credits,
5955
+ ...(seconds == null ? { quote_is_floor: true } : {}),
5557
5956
  source_ref: source,
5558
5957
  target_ref: target,
5559
5958
  message: `Cost: ${fmtCredits(totalCents)}${seconds == null ? ' or more' : ''} for ${blocks * TOOL_BLOCK_SECONDS}s ${motionModel} (${costKey}). ` +
5959
+ ceiling.sentence +
5560
5960
  `Transferring motion from ${source} onto ${target}. ` +
5561
5961
  // The saving is READ from the registry, never guessed: "~10 credits"
5562
5962
  // was hand-typed and is a rate change away from being a lie.
@@ -5574,6 +5974,11 @@ export const generateMotionTransfer = {
5574
5974
  if (input.background) {
5575
5975
  await desktop.requireCapability('background-generation', 'background generation');
5576
5976
  }
5977
+ // Held to the credits approved, else the quote, as the lip-sync run is.
5978
+ const approved = approvedSpend(ctx, input);
5979
+ if (approved.approvedCredits != null && listTotal > approved.approvedCredits)
5980
+ return toolPriceChanged('motion transfer', approved.approvedCredits, { credits: listTotal, costKey });
5981
+ const held = approved.approvedCredits ?? listTotal;
5577
5982
  const result = await desktop.post('/agent/generation/motion-transfer', {
5578
5983
  projectId: input.projectId,
5579
5984
  sourceVideoAssetId: input.sourceVideoAssetId,
@@ -5583,10 +5988,14 @@ export const generateMotionTransfer = {
5583
5988
  prompt: input.prompt,
5584
5989
  // No estimatedCost: the desktop prices the media itself, in dollars.
5585
5990
  // This op's figure is CREDITS, which a 1.5.8 desktop recorded as dollars.
5991
+ ...heldBody(held, approved.quoteFingerprint),
5586
5992
  background: input.background,
5587
5993
  });
5994
+ if (result.quoteExceeded)
5995
+ return toolPriceChanged('motion transfer', held, result.quoteExceeded);
5588
5996
  if (!result.success)
5589
5997
  throw new Error(result.error ?? 'Motion transfer generation failed');
5998
+ const charged = toolCharge(seconds, totalCents);
5590
5999
  if (result.background) {
5591
6000
  const ids = result.generationIds ?? (result.generationId ? [result.generationId] : []);
5592
6001
  return backgroundSubmitted(`motion transfer (${motionModel})`, ids, {
@@ -5595,13 +6004,12 @@ export const generateMotionTransfer = {
5595
6004
  projectId: input.projectId,
5596
6005
  sourceVideoAssetId: input.sourceVideoAssetId,
5597
6006
  targetImageAssetId: input.targetImageAssetId,
5598
- cost_cents: totalCents,
5599
- cost_credits: totalCents,
6007
+ ...charged,
5600
6008
  });
5601
6009
  }
5602
6010
  return {
5603
6011
  text: `Generated motion transfer (${motionModel}) into project ${input.projectId} ` +
5604
- `for ${fmtCredits(totalCents)}.` +
6012
+ (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
6013
  (input.prompt ? ` Prompt: "${input.prompt.slice(0, 60)}${input.prompt.length > 60 ? '...' : ''}"` : ''),
5606
6014
  data: {
5607
6015
  variant: costKey,
@@ -5609,8 +6017,7 @@ export const generateMotionTransfer = {
5609
6017
  projectId: input.projectId,
5610
6018
  sourceVideoAssetId: input.sourceVideoAssetId,
5611
6019
  targetImageAssetId: input.targetImageAssetId,
5612
- cost_cents: totalCents,
5613
- cost_credits: totalCents,
6020
+ ...charged,
5614
6021
  asset: result.asset,
5615
6022
  generationId: result.generationId,
5616
6023
  },
@@ -5628,7 +6035,7 @@ export const editVideo = {
5628
6035
  // point to in a tool result) and go stale on the next rate change; the
5629
6036
  // windows are owned by MODEL_CAPABILITIES and are generated below into the
5630
6037
  // 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. ' +
6038
+ '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
6039
  confirmGateSentence('any character or style reference'),
5633
6040
  input: z.object({
5634
6041
  projectId: z.string().uuid().describe('Project the source clip lives in.'),
@@ -5667,6 +6074,10 @@ export const editVideo = {
5667
6074
  // Source-clip window, read from the capability SSOT per engine — never a
5668
6075
  // model-id ternary. (Kling 3–15s, Omni Flash 1.2 3–15s, Seedance 2.5 4–30s.)
5669
6076
  const { min: minClipSeconds, max: maxClipSeconds } = editClipBounds(model);
6077
+ // The enum is the union of the engines' rows, so each engine's own row decides; Kling's output follows the source clip.
6078
+ const resErr = isSeedanceEdit || isOmniFlashEdit ? checkVideoResolution(model, input.videoResolution) : null;
6079
+ if (resErr)
6080
+ return ok({ requires_clarification: true, missing: ['videoResolution'], message: resErr });
5670
6081
  if (!EDIT_VIDEO_ELEMENT_MODELS.includes(model) && ((input.characterAssetIds?.length ?? 0) > 0 || (input.styleAssetIds?.length ?? 0) > 0)) {
5671
6082
  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
6083
  }
@@ -5682,8 +6093,9 @@ export const editVideo = {
5682
6093
  const characterAssetIds = (input.characterAssetIds ?? []).map(rid);
5683
6094
  const styleAssetIds = (input.styleAssetIds ?? []).map(rid);
5684
6095
  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.`);
6096
+ const modelElementCap = getModelCapability(model)?.maxIngredientImages ?? 0;
6097
+ if (characterAssetIds.length + styleAssetIds.length > modelElementCap) {
6098
+ throw new Error(`${model} takes at most ${modelElementCap} subject and style references combined.`);
5687
6099
  }
5688
6100
  // The billed key needs the clip's duration (ceiled). Read it from the
5689
6101
  // project's asset records — the desktop route independently re-validates.
@@ -5697,7 +6109,7 @@ export const editVideo = {
5697
6109
  if (!Number.isFinite(clipSeconds) || clipSeconds <= 0) {
5698
6110
  throw new Error('Source clip has no recorded duration — cannot quote the edit. Re-import the clip or pick another.');
5699
6111
  }
5700
- if (clipSeconds > maxClipSeconds + 0.05 || clipSeconds < minClipSeconds - 0.05) {
6112
+ if (clipSeconds > maxClipSeconds + EDIT_SECONDS_TOLERANCE || clipSeconds < minClipSeconds - EDIT_SECONDS_TOLERANCE) {
5701
6113
  throw new Error(`Source clip is ${clipSeconds.toFixed(1)}s — ${model} accepts ${minClipSeconds}–${maxClipSeconds}s. ` +
5702
6114
  `Trim it first with slates_trim_video (e.g. inSec 0, outSec ${maxClipSeconds}), then edit the trimmed clip` +
5703
6115
  (maxClipSeconds < SEEDANCE_25_EDIT_MAX_SECONDS ? ', or switch to seedance-2.5-edit which accepts up to 30s' : '') +
@@ -5706,7 +6118,7 @@ export const editVideo = {
5706
6118
  // A desktop without Omni Flash 1.2 gets the 1.1 edit seat at the same price, on a clip 1.1 takes
5707
6119
  // (`desktopModelId`), resolved before the quote so a job it cannot run is refused before the agent confirms it.
5708
6120
  const seat = await desktopModelId(desktop, model, `${model} editing`, clipSeconds);
5709
- const billedSeconds = Math.min(maxClipSeconds, Math.max(minClipSeconds, Math.ceil(clipSeconds - 0.05)));
6121
+ const billedSeconds = billedEditSeconds(model, clipSeconds);
5710
6122
  // Three engines, three key shapes — only Seedance's carries a resolution and
5711
6123
  // a face route, because only its price moves with them.
5712
6124
  const costKey = isSeedanceEdit
@@ -5752,6 +6164,7 @@ export const editVideo = {
5752
6164
  },
5753
6165
  };
5754
6166
  }
6167
+ approvedSpend(ctx);
5755
6168
  const result = await desktop.post('/agent/generation/edit-video', {
5756
6169
  projectId: input.projectId,
5757
6170
  model: seat.model,
@@ -6113,7 +6526,9 @@ const reframeClipInput = reframeReportInput.extend({ clipId: z.string().uuid(),
6113
6526
  mode: z.enum(['fill', 'fit']).optional(), focusX: z.number().min(0).max(1).optional(),
6114
6527
  focusY: z.number().min(0).max(1).optional(), zoom: z.number().min(1).optional(),
6115
6528
  }).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.') });
6529
+ 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.') })
6530
+ // Every follow form stands alone; the rule lives in the schema so each host applies it before run().
6531
+ .refine((d) => d.framing !== undefined || d.follow !== undefined, { message: 'Send framing (null resets it) or follow', path: ['framing'] });
6117
6532
  export const reframeClip = {
6118
6533
  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
6534
  billable: false,
@@ -6124,8 +6539,6 @@ export const reframeClip = {
6124
6539
  await ctx.desktop().requireCapability('reframe-follow', 'following a face');
6125
6540
  if (typeof input.follow === 'object')
6126
6541
  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
6542
  return ok(await ctx.desktop().post('/agent/timeline/reframe', input));
6130
6543
  },
6131
6544
  };
@@ -6296,21 +6709,29 @@ export const upscaleImage = {
6296
6709
  async run(input, ctx) {
6297
6710
  const desktop = ctx.desktop();
6298
6711
  await desktop.requireCapability('image-upscale', 'picture upscale');
6299
- const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
6712
+ const id = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
6300
6713
  const quote = await desktop.get('/agent/generation/upscale-quote', { projectId: input.projectId, assetId: id, factor: String(input.factor) });
6301
6714
  if (quote.credits === null)
6302
6715
  throw new Error(quote.refused ?? 'This picture cannot be upscaled at that size.');
6303
6716
  const name = quote.code ?? id;
6304
6717
  const size = `${quote.width}x${quote.height} to ${quote.outWidth}x${quote.outHeight}`;
6718
+ // Minted here, before the confirm gate, and handed back with the quote: the
6719
+ // confirmed call and any retry of it then carry one id, so a retry after a
6720
+ // dropped connection waits on the same run instead of paying again.
6721
+ const requestId = input.requestId ?? randomUUID();
6305
6722
  if (quote.credits > CONFIRM_CREDITS && !input.confirm) {
6306
6723
  return ok({
6307
6724
  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.`,
6725
+ width: quote.width, height: quote.height, outWidth: quote.outWidth, outHeight: quote.outHeight, requestId,
6726
+ 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
6727
  });
6311
6728
  }
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 });
6729
+ approvedSpend(ctx);
6730
+ const r = await desktop.post('/agent/generation/upscale-image', { projectId: input.projectId, assetId: id, factor: input.factor, expectedCredits: quote.credits, requestId }).catch((error) => {
6731
+ // The request may have reached the desktop before the connection failed: the retry reuses this id.
6732
+ const said = error instanceof Error ? error.message : String(error);
6733
+ throw new Error(`${said.replace(/[.\s]+$/, '')}. The upscale may still be running. Retry with requestId=${requestId}: the same id never pays twice.`, { cause: error });
6734
+ });
6314
6735
  if (!r.asset)
6315
6736
  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
6737
  const spent = r.cost_credits ?? r.credits ?? quote.credits;
@@ -6351,11 +6772,331 @@ export const resolveReviewNote = {
6351
6772
  async run(input, ctx) {
6352
6773
  await ctx.desktop().requireCapability('review-mode', 'Review mode');
6353
6774
  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));
6775
+ const resolved = refs.length ? await resolveAssetRefs(ctx, input.projectId, refs) : new AssetRefs();
6776
+ const replies = input.replies.map((r) => (r.assetIds ? { ...r, assetIds: r.assetIds.map((a) => resolved.id(a)) } : r));
6356
6777
  return ok(await ctx.desktop().post('/agent/review/resolve', { projectId: input.projectId, replies }));
6357
6778
  },
6358
6779
  };
6780
+ // ── Wave 6: the Winners Loop, Visual QA, stacked video edits, diagnostics, winning ads ──
6781
+ const META_WINNERS = 'the Winners Loop (ad results per recipe)';
6782
+ export const getClientAdReport = {
6783
+ id: 'slates_get_client_ad_report',
6784
+ description: 'List connected Google Ads or 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.',
6785
+ input: z.object({
6786
+ platform: z.enum(['google', 'tiktok']),
6787
+ accountId: z.string().regex(/^\d{1,24}$/).optional(),
6788
+ managerId: z.string().regex(/^\d{10}$/).optional(),
6789
+ since: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
6790
+ until: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
6791
+ projectId: z.string().uuid().optional().describe('Resolve linked export names within this project.'),
6792
+ }).strict(),
6793
+ async run(input, ctx) {
6794
+ const desktop = ctx.desktop();
6795
+ await desktop.requireCapability('client-ads', 'connected ad account reporting');
6796
+ return ok(await desktop.get('/agent/client-ads', { ...input }));
6797
+ },
6798
+ };
6799
+ export const getAdWinners = {
6800
+ id: 'slates_get_ad_winners',
6801
+ 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.",
6802
+ input: z.object({ projectId: z.string().uuid().optional().describe('One project; absent: every project.') }).strict(),
6803
+ async run(input, ctx) {
6804
+ await ctx.desktop().requireCapability('meta-winners', META_WINNERS);
6805
+ return ok(await ctx.desktop().get('/agent/meta/winners', { projectId: input.projectId }));
6806
+ },
6807
+ };
6808
+ export const setRecipeVerdict = {
6809
+ id: 'slates_set_recipe_verdict',
6810
+ description: "Mark an ad recipe a winner or a loser (null clears the mark), as the person decided from its results. A loser is never remade; More like this starts from a winner. Free. Requires meta-winners; update Slates on capability refusal.",
6811
+ input: z.object({
6812
+ recipeId: z.string().min(1).describe('The recipe ID from slates_get_ad_winners or an export.'),
6813
+ projectId: z.string().uuid().nullable().optional(),
6814
+ verdict: z.enum(['winner', 'loser']).nullable(),
6815
+ note: z.string().max(2000).optional(),
6816
+ }).strict(),
6817
+ async run(input, ctx) {
6818
+ await ctx.desktop().requireCapability('meta-winners', META_WINNERS);
6819
+ return ok(await ctx.desktop().post('/agent/meta/verdict', input));
6820
+ },
6821
+ };
6822
+ export const moreLikeThis = {
6823
+ id: 'slates_more_like_this',
6824
+ description: "Start a new cut from a winning export: its hook becomes a slot holding the winning hook plus open ones, and the answer quotes what finishing the variants would cost. Nothing is generated; show the person the quote before filling an open hook. Free. Requires meta-winners; update Slates on capability refusal.",
6825
+ input: z.object({
6826
+ exportRef: z.string().min(1).describe('The export reference from slates_get_ad_winners (exportRef).'),
6827
+ openHookSlot: z.boolean().optional().describe('Default true: the hook becomes a slot.'),
6828
+ extraHookCount: z.number().int().min(1).optional().describe('Open hook alternatives to add; the app caps it.'),
6829
+ }).strict(),
6830
+ async run(input, ctx) {
6831
+ await ctx.desktop().requireCapability('meta-winners', META_WINNERS);
6832
+ return ok(await ctx.desktop().post('/agent/meta/more-like-this', input));
6833
+ },
6834
+ };
6835
+ const SPLIT_TEST_INPUT = z.object({
6836
+ projectId: z.string().uuid(),
6837
+ accountId: z.string().min(1).describe('The ad account id.'),
6838
+ campaignName: z.string().min(1),
6839
+ dailyBudgetMinor: z.number().int().positive().describe("The ad set's daily budget in the currency's minor units (cents)."),
6840
+ currency: z.string().min(3).max(3),
6841
+ exportRefs: z.array(z.string().min(1)).min(2).describe('The exported variants, one paused ad each.'),
6842
+ country: z.string().length(2).describe('Two-letter audience country.'),
6843
+ specialAdCategories: z.array(z.string()).nullable().describe('[] when none apply; the plan refuses null.'),
6844
+ pageId: z.string().min(1),
6845
+ destinationUrl: z.string().url(),
6846
+ headline: z.string().optional(),
6847
+ primaryText: z.string().optional(),
6848
+ cta: z.string().optional(),
6849
+ thresholdSpend: z.number().nonnegative().nullable().optional(),
6850
+ thresholdImpressions: z.number().int().nonnegative().nullable().optional(),
6851
+ }).strict();
6852
+ export const planSplitTest = {
6853
+ id: 'slates_plan_split_test',
6854
+ description: "Plan a split test of exported variants: one campaign, one ad set and one paused ad per variant, checked against the spend caps, with every problem named. Creates nothing; the person creates the paused test from New split test… in Meta Ads. Free. Requires meta-winners; update Slates on capability refusal.",
6855
+ input: SPLIT_TEST_INPUT,
6856
+ async run(input, ctx) {
6857
+ await ctx.desktop().requireCapability('meta-winners', META_WINNERS);
6858
+ return ok(await ctx.desktop().post('/agent/meta/split-test/plan', input));
6859
+ },
6860
+ };
6861
+ export const evaluateSplitTestWinner = {
6862
+ id: 'slates_evaluate_split_test_winner',
6863
+ description: "Call a split test's winner from the ad account's report for that test's own ads only (read now, from the day the test was made): no call until every variant has results and passes the spend and impression thresholds; it compares ROAS (else cost per purchase, else click rate) and labels every figure as the ad account reports it. A tie or no call clears an older stored winner. Free. Requires meta-winners; update Slates on capability refusal.",
6864
+ input: z.object({
6865
+ testId: z.string().min(1).describe('The local split test id, from splitTests in slates_get_ad_winners.'),
6866
+ thresholds: z.object({
6867
+ minSpend: z.number().nonnegative().nullable().optional(),
6868
+ minImpressions: z.number().int().nonnegative().nullable().optional(),
6869
+ }).strict().optional().describe("Absent: the test's own thresholds."),
6870
+ }).strict(),
6871
+ async run(input, ctx) {
6872
+ await ctx.desktop().requireCapability('meta-winners', META_WINNERS);
6873
+ return ok(await ctx.desktop().post('/agent/meta/split-test/winner', input));
6874
+ },
6875
+ };
6876
+ const VISUAL_QA = 'Visual QA';
6877
+ export const visualQaSample = {
6878
+ id: 'slates_visual_qa_sample',
6879
+ description: "Visual QA, step one of a round: stills of the cut's overlay beats, transition middles and cuts, returned inline so you see every frame, with what this machine measured in them (clipped or crowded text, contrast, hold times, gaps), the rubric and the critique prompt. Score every still against the rubric, then answer with slates_visual_qa_record_round. Pass runId to take the next round's stills after your fixes. Free: the looking is yours. Requires visual-qa; update Slates on capability refusal.",
6880
+ input: z.object({
6881
+ projectId: z.string().uuid().optional().describe('Defaults to the open project.'),
6882
+ timelineId: z.string().min(1).optional().describe("Defaults to the project's timeline."),
6883
+ runId: z.string().min(1).optional().describe('Continue this run with its next round; absent starts a run.'),
6884
+ maxRounds: z.number().int().positive().optional().describe("Rounds a new run takes; the app's default and limits apply."),
6885
+ // 24 is the desktop's MAX_VISUAL_QA_SAMPLES (slate src/shared/visualQa.ts), which the route enforces too.
6886
+ budget: z.number().int().positive().max(24).optional().describe("The most stills a round takes, up to 24; the app's default applies."),
6887
+ }).strict(),
6888
+ async run(input, ctx) {
6889
+ await ctx.desktop().requireCapability('visual-qa', VISUAL_QA);
6890
+ const r = await ctx.desktop().post('/agent/timeline/visual-qa/sample', input);
6891
+ const stills = r.stills ?? [];
6892
+ const { stills: _inline, ...data } = r;
6893
+ const when = new Map((r.samples ?? []).map((s) => [s.id, s.sec]));
6894
+ return {
6895
+ text: `${JSON.stringify(data)}\n\nStills, in order: ${stills.map((s) => `${s.sampleId} (${when.get(s.sampleId) ?? '?'}s)`).join(', ') || 'none could be read'}.`,
6896
+ images: stills.map((s) => ({ data: s.data, mimeType: s.mimeType })),
6897
+ data,
6898
+ };
6899
+ },
6900
+ };
6901
+ const VQA_DIMENSION = z.enum(['alignment', 'legibility', 'hierarchy', 'pacing', 'transitions', 'motion', 'restraint']);
6902
+ export const visualQaRecordRound = {
6903
+ id: 'slates_visual_qa_record_round',
6904
+ description: "Visual QA, step two: record your scores (0-10 per rubric dimension) and findings for the round slates_visual_qa_sample handed you, each finding on its still with what is wrong and the exact fix. A measured finding stays unless your finding restates it (findingId) at the same or a higher severity. Answers pass or iterate, the score change and what stays open; after fixing, sample the next round with the same runId. A round is recorded once: on the final round pass promoteToReview: true, which turns what stays open into Review notes for the person only if the round does not pass. Free. Requires visual-qa; update Slates on capability refusal.",
6905
+ input: z.object({
6906
+ runId: z.string().min(1).describe('From slates_visual_qa_sample.'),
6907
+ scores: z.record(VQA_DIMENSION, z.number().min(0).max(10)).describe('Every rubric dimension, 0-10.'),
6908
+ findings: z.array(z.object({
6909
+ sampleId: z.string().min(1).describe('The still it was seen in.'),
6910
+ dimension: VQA_DIMENSION,
6911
+ severity: z.enum(['blocker', 'should-fix', 'polish']),
6912
+ diagnosis: z.string().min(1).describe('What is wrong, in that frame.'),
6913
+ exactFix: z.string().min(1).describe('The change that fixes it: what to set, to what.'),
6914
+ region: z.object({ x: z.number(), y: z.number(), w: z.number(), h: z.number() }).strict().nullable().optional().describe('Where in the frame, as fractions 0-1.'),
6915
+ span: z.object({ startSec: z.number(), endSec: z.number() }).strict().nullable().optional(),
6916
+ targetClipId: z.string().optional(),
6917
+ targetTransitionId: z.string().optional(),
6918
+ findingId: z.string().optional().describe("The measured finding's id this one restates; it replaces it only at the same or a higher severity."),
6919
+ }).strict()),
6920
+ summary: z.string().optional(),
6921
+ promoteToReview: z.boolean().optional(),
6922
+ }).strict(),
6923
+ async run(input, ctx) {
6924
+ await ctx.desktop().requireCapability('visual-qa', VISUAL_QA);
6925
+ return ok(await ctx.desktop().post('/agent/timeline/visual-qa/round', input));
6926
+ },
6927
+ };
6928
+ export const listVisualQaRuns = {
6929
+ id: 'slates_list_visual_qa_runs',
6930
+ description: "A timeline's Visual QA runs, newest first: status, rounds, round one's score against the last and the gain; runId reads one run in full. Free. Requires visual-qa; update Slates on capability refusal.",
6931
+ input: z.object({
6932
+ projectId: z.string().uuid().optional().describe('Defaults to the open project.'),
6933
+ timelineId: z.string().min(1).optional(),
6934
+ runId: z.string().min(1).optional(),
6935
+ }).strict(),
6936
+ async run(input, ctx) {
6937
+ await ctx.desktop().requireCapability('visual-qa', VISUAL_QA);
6938
+ return ok(await ctx.desktop().get('/agent/timeline/visual-qa/runs', input));
6939
+ },
6940
+ };
6941
+ const V2V = 'stacked video edits';
6942
+ const V2V_KIND = z.enum(['swap-person', 'change-angle', 'change-location', 'move-camera', 'relight', 'video-brush']);
6943
+ const V2V_RECIPE = {
6944
+ model: z.string().min(1).optional().describe("The edit model; absent: the app's default."),
6945
+ prompt: z.string().optional(),
6946
+ params: z.record(z.unknown()).optional().describe('The kind\'s settings: subjectAssetId, locationAssetId, preset, directionDeg, colorTemp, diffusion, brushMode, videoResolution. Asset ids or badge codes.'),
6947
+ referenceAssetIds: z.array(z.string().min(1)).optional().describe('Asset ids or badge codes.'),
6948
+ startFrame: z.number().int().nonnegative().optional().describe('Timeline frame where the edited moment starts.'),
6949
+ endFrame: z.number().int().positive().optional().describe('Timeline frame where it ends (exclusive).'),
6950
+ };
6951
+ /** A pass's asset references (UUIDs or badge codes) resolved against the project at call time. */
6952
+ async function resolvePassAssets(ctx, projectId, input) {
6953
+ const params = input.params ?? {};
6954
+ const named = ['subjectAssetId', 'locationAssetId'].filter((k) => typeof params[k] === 'string');
6955
+ const refs = [...named.map((k) => params[k]), ...(input.referenceAssetIds ?? [])];
6956
+ if (!refs.length)
6957
+ return input;
6958
+ const resolved = await resolveAssetRefs(ctx, projectId, refs);
6959
+ const id = (ref) => resolved.id(ref);
6960
+ return {
6961
+ ...input,
6962
+ ...(input.params ? { params: { ...params, ...Object.fromEntries(named.map((k) => [k, id(params[k])])) } } : {}),
6963
+ ...(input.referenceAssetIds ? { referenceAssetIds: input.referenceAssetIds.map(id) } : {}),
6964
+ };
6965
+ }
6966
+ export const listV2vPasses = {
6967
+ id: 'slates_list_v2v_passes',
6968
+ description: "The stacked video edits on a timeline (or one clip), bottom first: each pass's kind, moment, settings, recipe ID, status, output and estimated credits. Free. Requires v2v-edits; update Slates on capability refusal.",
6969
+ input: z.object({ projectId: z.string().uuid(), timelineId: z.string().min(1), clipId: z.string().min(1).optional() }).strict(),
6970
+ async run(input, ctx) {
6971
+ await ctx.desktop().requireCapability('v2v-edits', V2V);
6972
+ return ok(await ctx.desktop().get('/agent/timeline/v2v', input));
6973
+ },
6974
+ };
6975
+ export const editV2vPass = {
6976
+ id: 'slates_edit_v2v_pass',
6977
+ description: "Add, change, remove or reorder a stacked video edit on a video clip's moment: swap the person, change the angle or location, move the camera, relight, or a brushed region. Each pass edits the output of the one under it. Saving a pass generates nothing; quote with slates_quote_v2v_passes, then run. Free. Requires v2v-edits; update Slates on capability refusal.",
6978
+ input: z.object({
6979
+ projectId: z.string().uuid(),
6980
+ action: z.enum(['create', 'update', 'delete', 'reorder']),
6981
+ input: z.object({ timelineId: z.string().min(1), clipId: z.string().min(1), kind: V2V_KIND, label: z.string().optional(), ...V2V_RECIPE }).strict().optional().describe('create: the new pass.'),
6982
+ passId: z.string().min(1).optional().describe('update and delete.'),
6983
+ patch: z.object({ label: z.string().optional(), enabled: z.boolean().optional(), orderIndex: z.number().int().nonnegative().optional(), ...V2V_RECIPE }).strict().optional().describe('update: the fields to change.'),
6984
+ timelineId: z.string().min(1).optional().describe('reorder.'),
6985
+ clipId: z.string().min(1).optional().describe('reorder.'),
6986
+ orderedIds: z.array(z.string().min(1)).optional().describe('reorder: every pass on the clip, bottom first.'),
6987
+ }).strict(),
6988
+ async run(input, ctx) {
6989
+ await ctx.desktop().requireCapability('v2v-edits', V2V);
6990
+ const body = {
6991
+ ...input,
6992
+ ...(input.input ? { input: await resolvePassAssets(ctx, input.projectId, input.input) } : {}),
6993
+ ...(input.patch ? { patch: await resolvePassAssets(ctx, input.projectId, input.patch) } : {}),
6994
+ };
6995
+ return ok(await ctx.desktop().post('/agent/timeline/v2v/pass', body));
6996
+ },
6997
+ };
6998
+ export const quoteV2vPasses = {
6999
+ id: 'slates_quote_v2v_passes',
7000
+ description: "Price stacked video edits before running them: per pass the billed seconds, credits, warnings or what blocks it, its recipe ID, and the total. Show the person the total; slates_run_v2v_passes takes it as maxCredits and quoteFingerprint as the quote it runs. Free. Requires v2v-edits; update Slates on capability refusal.",
7001
+ input: z.object({ projectId: z.string().uuid(), passIds: z.array(z.string().min(1)).min(1) }).strict(),
7002
+ async run(input, ctx) {
7003
+ await ctx.desktop().requireCapability('v2v-edits', V2V);
7004
+ return ok(await ctx.desktop().post('/agent/timeline/v2v/quote', input));
7005
+ },
7006
+ };
7007
+ export const runV2vPasses = {
7008
+ id: 'slates_run_v2v_passes',
7009
+ billable: true,
7010
+ description: "Run stacked video edits that slates_quote_v2v_passes priced and the person approved: each pass edits the output of the one under it, independent passes in parallel. maxCredits is the approved total and quoteFingerprint the quote's own; a run that would cost more, or whose passes changed since the quote, is refused before anything runs. Pass a requestId of your own: a retry with the same one returns the first run's result and spends nothing again. The answer's cost_credits is what the run charged. Spends credits. Requires v2v-edits; update Slates on capability refusal.",
7011
+ input: z.object({
7012
+ projectId: z.string().uuid(),
7013
+ timelineId: z.string().min(1).describe("The passes' timeline; every pass must be on it."),
7014
+ passIds: z.array(z.string().min(1)).min(1),
7015
+ maxCredits: z.number().int().nonnegative().describe("The quote's total the person approved."),
7016
+ quoteFingerprint: z.string().min(1).describe('quoteFingerprint from slates_quote_v2v_passes for these passes.'),
7017
+ requestId: z.string().min(1).max(200).optional().describe('Your idempotency key for this run; reuse it only to retry the same run.'),
7018
+ maxParallel: z.number().int().positive().optional(),
7019
+ }).strict(),
7020
+ async run(input, ctx) {
7021
+ const desktop = ctx.desktop();
7022
+ await desktop.requireCapability('v2v-edits', V2V);
7023
+ // Every selected pass must be on the named timeline: the model guides checked are those of exactly the passes run.
7024
+ const { passes } = await desktop.get('/agent/timeline/v2v', { projectId: input.projectId, timelineId: input.timelineId });
7025
+ const byId = new Map(passes.map((p) => [p.id, p]));
7026
+ const missing = input.passIds.filter((id) => !byId.has(id));
7027
+ if (missing.length)
7028
+ throw new Error(`These passes are not on timeline ${input.timelineId}: ${missing.join(', ')}. Run passes of one timeline at a time.`);
7029
+ for (const model of new Set(input.passIds.map((id) => byId.get(id).model)))
7030
+ requireGuideRead(ctx, model);
7031
+ approvedSpend(ctx);
7032
+ return ok(await desktop.post('/agent/timeline/v2v/run', input));
7033
+ },
7034
+ };
7035
+ export const v2vPassesToVariants = {
7036
+ id: 'slates_v2v_passes_to_variants',
7037
+ description: "Send finished video edits of one clip's moment to the variant grid: a slot on the timeline with one alternative per pass, each keeping its recipe ID, so they export as ad variants. Free. Requires v2v-edits; update Slates on capability refusal.",
7038
+ input: z.object({ projectId: z.string().uuid(), timelineId: z.string().min(1), passIds: z.array(z.string().min(1)).min(1), slotName: z.string().min(1).optional() }).strict(),
7039
+ async run(input, ctx) {
7040
+ await ctx.desktop().requireCapability('v2v-edits', V2V);
7041
+ return ok(await ctx.desktop().post('/agent/timeline/v2v/to-variants', input));
7042
+ },
7043
+ };
7044
+ export const getDiagnosticsStatus = {
7045
+ id: 'slates_get_diagnostics_status',
7046
+ description: "Whether this Slates shares crash and error reports and what it last caught, each marked captured locally / queued: delivery is never confirmed, so tell the person a bug was captured and queued, not that it arrived. Reads only. Free. Requires diagnostics; update Slates on capability refusal.",
7047
+ input: z.object({}).strict(),
7048
+ async run(_input, ctx) {
7049
+ await ctx.desktop().requireCapability('diagnostics', 'the diagnostics status');
7050
+ return ok(await ctx.desktop().get('/agent/diagnostics/status'));
7051
+ },
7052
+ };
7053
+ const WINNING_ADS = 'winning ads';
7054
+ export const findWinningAds = {
7055
+ id: 'slates_find_winning_ads',
7056
+ description: "Search proven ads: the ads that ran longest, by niche, platform, format and words in the advertiser, headline, body or button, each with how long it ran, its variations and its link. The answer says where the list came from and how fresh it is. Break one down into shots with slates_break_down_winning_ad. Free. Requires winning-ads; update Slates on capability refusal.",
7057
+ input: z.object({
7058
+ query: z.string().optional(),
7059
+ niche: z.string().optional().describe('A niche id from slates_list_winning_ad_niches.'),
7060
+ platform: z.enum(['all', 'meta', 'google']).optional(),
7061
+ minRunDays: z.number().int().nonnegative().optional(),
7062
+ format: z.enum(['all', 'video', 'image']).optional(),
7063
+ activeOnly: z.boolean().optional(),
7064
+ hasBreakdown: z.boolean().optional(),
7065
+ sort: z.enum(['run_length', 'variations', 'recent']).optional(),
7066
+ limit: z.number().int().positive().optional().describe("The app caps it."),
7067
+ offset: z.number().int().nonnegative().optional(),
7068
+ }).strict(),
7069
+ async run(input, ctx) {
7070
+ await ctx.desktop().requireCapability('winning-ads', WINNING_ADS);
7071
+ return ok(await ctx.desktop().get('/agent/reference/winning-ads', input));
7072
+ },
7073
+ };
7074
+ export const listWinningAdNiches = {
7075
+ id: 'slates_list_winning_ad_niches',
7076
+ description: 'The winning-ads niches and how many ads each holds, for slates_find_winning_ads. Free. Requires winning-ads; update Slates on capability refusal.',
7077
+ input: z.object({}).strict(),
7078
+ async run(_input, ctx) {
7079
+ await ctx.desktop().requireCapability('winning-ads', WINNING_ADS);
7080
+ return ok(await ctx.desktop().get('/agent/reference/winning-ads/niches'));
7081
+ },
7082
+ };
7083
+ export const breakDownWinningAd = {
7084
+ id: 'slates_break_down_winning_ad',
7085
+ description: "Break a winning ad from slates_find_winning_ads down into shots: one shot per cut with its words, built as a board in the project, the same run as slates_break_down_reference. The board copies the ad's structure and generates nothing; the ad's own footage is never used in it. Free. Requires winning-ads; update Slates on capability refusal.",
7086
+ input: z.object({
7087
+ projectId: z.string().uuid().optional().describe('Defaults to the open project.'),
7088
+ adId: z.string().min(1).describe('The adId from slates_find_winning_ads.'),
7089
+ platform: z.enum(['meta', 'google']).optional().describe('Default meta.'),
7090
+ build: z.boolean().optional().describe('As on slates_break_down_reference.'),
7091
+ name: z.string().optional(),
7092
+ model: z.string().optional(),
7093
+ jobId: z.string().optional(),
7094
+ }).strict(),
7095
+ async run(input, ctx) {
7096
+ await ctx.desktop().requireCapability('winning-ads', WINNING_ADS);
7097
+ return ok(await ctx.desktop().post('/agent/reference/winning-ads/breakdown', input));
7098
+ },
7099
+ };
6359
7100
  export const listTimelines = {
6360
7101
  id: 'slates_list_timelines', description: "List the independent named cuts in a project (not a slot's alternative timelines: slates_get_variants names those). Use the selected timelineId for edits, builds and exports.",
6361
7102
  input: z.object({ projectId: z.string().uuid() }),
@@ -7714,7 +8455,7 @@ export const createLibraryItem = {
7714
8455
  return ok(created);
7715
8456
  return ok(await ctx.desktop().post('/agent/library/items/update', {
7716
8457
  id: created.item.id,
7717
- data: { imageAssetId: resolved.get(imageAssetId).id },
8458
+ data: { imageAssetId: resolved.id(imageAssetId) },
7718
8459
  }));
7719
8460
  },
7720
8461
  };
@@ -7741,7 +8482,7 @@ export const updateLibraryItem = {
7741
8482
  }
7742
8483
  const refs = [input.imageAssetId, input.voiceAssetId, ...(input.extraAssetIds ?? [])].filter((r) => typeof r === 'string');
7743
8484
  const resolved = await resolveAssetRefs(ctx, input.projectId, refs);
7744
- const asset = (ref) => typeof ref === 'string' ? resolved.get(ref).id : ref;
8485
+ const asset = (ref) => typeof ref === 'string' ? resolved.id(ref) : ref;
7745
8486
  return ok(await ctx.desktop().post('/agent/library/items/update', {
7746
8487
  id: input.itemId,
7747
8488
  retagShots: input.retagShots,
@@ -7754,7 +8495,7 @@ export const updateLibraryItem = {
7754
8495
  // explicit null is the clear.
7755
8496
  ...(input.imageAssetId !== undefined ? { imageAssetId: asset(input.imageAssetId) } : {}),
7756
8497
  ...(input.voiceAssetId !== undefined ? { voiceAssetId: asset(input.voiceAssetId) } : {}),
7757
- ...(input.extraAssetIds !== undefined ? { extraAssetIds: input.extraAssetIds.map((ref) => resolved.get(ref).id) } : {}),
8498
+ ...(input.extraAssetIds !== undefined ? { extraAssetIds: input.extraAssetIds.map((ref) => resolved.id(ref)) } : {}),
7758
8499
  ...(input.palette !== undefined ? { palette: input.palette } : {}),
7759
8500
  },
7760
8501
  }));
@@ -7886,7 +8627,7 @@ export const getReferenceBreakdown = {
7886
8627
  .strict(),
7887
8628
  async run(input, ctx) {
7888
8629
  await ctx.desktop().requireCapability('reference-breakdown', 'breaking a reference ad into shots');
7889
- const assetId = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
8630
+ const assetId = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId);
7890
8631
  return ok(await ctx.desktop().get('/agent/reference/breakdown', { projectId: input.projectId, assetId }));
7891
8632
  },
7892
8633
  };
@@ -7950,7 +8691,7 @@ export const breakDownReference = {
7950
8691
  if ([input.assetId, input.filePath, input.url].filter(Boolean).length !== 1) {
7951
8692
  throw new Error('Give exactly one of assetId (a video or picture in the project), filePath or url.');
7952
8693
  }
7953
- const assetId = input.assetId ? (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id : input.assetId;
8694
+ const assetId = input.assetId ? (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).id(input.assetId) : input.assetId;
7954
8695
  // Every Shot is stored under this id, as the desktop knows it (`desktopModelId`).
7955
8696
  const seat = await desktopModelId(ctx.desktop(), input.model, `a breakdown's Shots on ${input.model}`);
7956
8697
  const r = await ctx.desktop().post('/agent/reference/breakdown', { ...input, assetId, model: seat.model, cancel: undefined });
@@ -8209,9 +8950,8 @@ const shotRefsSchemaTerse = z
8209
8950
  .optional()
8210
8951
  .describe(SEE_CREATE_SHOT + SHOT_REFS_LEAD);
8211
8952
  // The full ratio vocabulary a Shot can hold — image OR video, because a Shot is
8212
- // any generation. Per-model narrowing happens at create time for video (the same
8213
- // `assertVideoCapabilities` gate `slates_generate_video` uses) and at generate
8214
- // time for everything.
8953
+ // any generation. Per-model narrowing happens at save time through
8954
+ // `assertShotCapabilities`, the same gates the generate ops run.
8215
8955
  const SHOT_ASPECT_RATIOS = [...new Set([...VIDEO_ASPECT_RATIOS, ...IMAGE_ASPECT_RATIOS])];
8216
8956
  // 🚨 THE PER-MODEL CAPABILITY TABLES ARE DELIBERATELY NOT REPEATED HERE.
8217
8957
  // `slates_generate_video`'s param descriptions already carry them and are always
@@ -8348,33 +9088,13 @@ function shotParamsPatch(p) {
8348
9088
  for (const [k, v] of Object.entries(p))
8349
9089
  if (v !== undefined)
8350
9090
  out[k] = v;
8351
- if (p.seedanceDraft && p.videoResolution === undefined)
8352
- out.videoResolution = '480p';
8353
9091
  return out;
8354
9092
  }
8355
- /**
8356
- * `audioRefSpokenText` pairs POSITIONALLY with the audio references, so it can
8357
- * only be sent alongside them.
8358
- *
8359
- * Refused rather than truncated or silently re-keyed: the whole point of the
8360
- * field is that the WORDS are exact, and a misaligned array attaches one clip's
8361
- * line to another clip with nothing on screen to say so. Same rule
8362
- * `slates_generate_video` already applies.
8363
- */
9093
+ /** `audioRefSpokenText` pairs by position with the audio references: the
9094
+ * `slates_generate_video` rule, as a clarification before anything is written. */
8364
9095
  function checkSpokenTextAlignment(input) {
8365
- if (input.audioRefSpokenText === undefined)
8366
- return null;
8367
- const clips = input.refs?.['audio-reference'];
8368
- if (!clips || clips.length !== input.audioRefSpokenText.length) {
8369
- return ok({
8370
- requires_clarification: true,
8371
- missing: ['refs["audio-reference"]'],
8372
- message: `audioRefSpokenText pairs by position with refs["audio-reference"], so send both together ` +
8373
- `and at the same length (${input.audioRefSpokenText.length} line(s) vs ${clips?.length ?? 0} clip(s)). ` +
8374
- `Use "" for a clip with no speech.`,
8375
- });
8376
- }
8377
- return null;
9096
+ const message = spokenTextMisalignment(input.refs?.['audio-reference'], input.audioRefSpokenText, SHOT_SPOKEN_FIELDS);
9097
+ return message ? ok({ requires_clarification: true, missing: [SHOT_SPOKEN_FIELDS.clips], message }) : null;
8378
9098
  }
8379
9099
  /** Every asset reference a Shot input carries, flat, for one `resolveAssetRefs`
8380
9100
  * pass. Derived from the role list so a new role resolves badge codes too. */
@@ -8390,6 +9110,8 @@ function shotRefInputs(input) {
8390
9110
  out.push({ ref: input.lastFrameAssetId, role: 'last frame' });
8391
9111
  if (input.params?.voiceReferenceAssetId)
8392
9112
  out.push({ ref: input.params.voiceReferenceAssetId, role: 'voice reference' });
9113
+ if (input.posterAssetId)
9114
+ out.push({ ref: input.posterAssetId, role: 'poster' });
8393
9115
  return out;
8394
9116
  }
8395
9117
  /**
@@ -8413,13 +9135,7 @@ async function buildShotSpecInput(ctx, projectId, input) {
8413
9135
  // Positional in, KEYED out — the same re-keying `slates_generate_video` does,
8414
9136
  // and for the same reason: an index means different clips depending on how the
8415
9137
  // list was assembled, while an asset id cannot drift.
8416
- const audioIds = refs['audio-reference'] ?? [];
8417
- const spoken = {};
8418
- (input.audioRefSpokenText ?? []).forEach((text, i) => {
8419
- const id = audioIds[i];
8420
- if (id && text?.trim())
8421
- spoken[id] = text.trim();
8422
- });
9138
+ const spoken = spokenTextByAssetId(refs['audio-reference'], input.audioRefSpokenText, SHOT_SPOKEN_FIELDS) ?? {};
8423
9139
  return {
8424
9140
  spec: {
8425
9141
  prompt: input.prompt,
@@ -8444,6 +9160,8 @@ async function buildShotSpecInput(ctx, projectId, input) {
8444
9160
  },
8445
9161
  refEcho: describeResolvedRefs(refInputs, resolvedRefs),
8446
9162
  seatNote: seat.note,
9163
+ // null resets the poster to its default; undefined leaves it alone.
9164
+ posterAssetId: input.posterAssetId === undefined ? undefined : rid(input.posterAssetId ?? undefined),
8447
9165
  };
8448
9166
  }
8449
9167
  /**
@@ -8504,16 +9222,19 @@ function namedSpecPatch(input, spec) {
8504
9222
  /**
8505
9223
  * The capability gate, applied to a SAVED recipe.
8506
9224
  *
8507
- * It enforces exactly what the matching generate op enforces and no more: video
8508
- * goes through `assertVideoCapabilities` (the MODEL_CAPABILITIES SSOT), image
8509
- * does not, because `slates_generate_image`'s own per-model ratio check is the
8510
- * named open follow-up in the capability plan. A Shot that refused what
8511
- * `slates_generate_image` accepts would be a THIRD opinion about the same
8512
- * model, which is worse than the gap.
9225
+ * It enforces exactly what the matching generate op enforces and no more, from
9226
+ * the same functions: `assertVideoCapabilities` for a video seat,
9227
+ * `assertImageCapabilities` for an image seat. A Shot that refused what the
9228
+ * generate op accepts, or saved what it refuses, would be a third opinion
9229
+ * about the same model.
8513
9230
  */
8514
9231
  function assertShotCapabilities(model, params) {
8515
9232
  if (params?.seedanceDraft && model)
8516
9233
  draftResolution(model, params.videoResolution);
9234
+ if (model && IMAGE_MODELS.includes(model)) {
9235
+ const err = assertImageCapabilities({ model, aspectRatio: params?.aspectRatio, resolution: params?.imageResolution }, { resolution: 'imageResolution' });
9236
+ return err ? ok(err) : null;
9237
+ }
8517
9238
  if (!model || !VIDEO_MODELS.includes(model))
8518
9239
  return null;
8519
9240
  const err = assertVideoCapabilities({
@@ -8524,12 +9245,42 @@ function assertShotCapabilities(model, params) {
8524
9245
  });
8525
9246
  return err ? ok(err) : null;
8526
9247
  }
8527
- async function requireDraftShotDesktop(desktop, model, params, shotId) {
9248
+ const SHOT_PROJECT_DESCRIBE = "The Shot's project. A SHOT-A code is unique only within its project, so pass this with a code.";
9249
+ /**
9250
+ * The Shot a ref names, read at most once per call. A SHOT-A code is unique only
9251
+ * within its project, so it resolves against `projectId` whenever the caller has
9252
+ * one, and a Shot that lives in another project is refused rather than edited,
9253
+ * priced or billed.
9254
+ */
9255
+ function shotReader(desktop, ref, projectId) {
9256
+ let read;
9257
+ return () => (read ??= desktop
9258
+ .get('/agent/shots/get', projectId ? { id: ref, projectId } : { id: ref })
9259
+ .then(({ shot }) => {
9260
+ if (projectId && shot.projectId && shot.projectId !== projectId) {
9261
+ 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.`);
9262
+ }
9263
+ return shot;
9264
+ }));
9265
+ }
9266
+ /** The row id to send for a Shot ref: an id as given, a code resolved through its reader. */
9267
+ async function shotRowId(ref, read) {
9268
+ return UUID_RE.test(ref.trim()) ? ref : (await read()).id;
9269
+ }
9270
+ /** Params whose legality depends on the Shot's model. */
9271
+ const MODEL_BOUND_SHOT_PARAMS = ['aspectRatio', 'videoResolution', 'imageResolution', 'duration', 'seedanceDraft'];
9272
+ /** An edit that names no model is checked against the stored Shot's, the gate create runs. */
9273
+ async function assertStoredShotCapabilities(model, params, read) {
9274
+ if (model !== undefined || !MODEL_BOUND_SHOT_PARAMS.some((k) => params?.[k] !== undefined))
9275
+ return null;
9276
+ return assertShotCapabilities((await read()).model ?? undefined, params);
9277
+ }
9278
+ async function requireDraftShotDesktop(desktop, model, params, read) {
8528
9279
  if (params?.seedanceDraft) {
8529
9280
  await desktop.requireCapability('seedance-drafts', 'saving a Seedance 2.5 draft');
8530
9281
  }
8531
9282
  else if (params?.videoResolution === '4k') {
8532
- const target = model ?? (shotId ? (await desktop.get('/agent/shots/get', { id: shotId })).shot.model : undefined);
9283
+ const target = model ?? (read ? (await read()).model : undefined);
8533
9284
  if (target === 'seedance-2.5')
8534
9285
  await desktop.requireCapability('seedance-drafts', 'saving a native 4K Seedance Shot');
8535
9286
  }
@@ -8680,19 +9431,23 @@ export const updateShot = {
8680
9431
  return alignErr;
8681
9432
  const desktop = ctx.desktop();
8682
9433
  await desktop.requireCapability('shots', 'saved Shots');
8683
- await requireDraftShotDesktop(desktop, input.model, input.params, input.shotId);
8684
- const { spec, seatNote } = await buildShotSpecInput(ctx, input.projectId, input);
9434
+ const read = shotReader(desktop, input.shotId, input.projectId);
9435
+ const storedErr = await assertStoredShotCapabilities(input.model, input.params, read);
9436
+ if (storedErr)
9437
+ return storedErr;
9438
+ await requireDraftShotDesktop(desktop, input.model, input.params, read);
9439
+ const { spec, seatNote, posterAssetId } = await buildShotSpecInput(ctx, input.projectId, input);
8685
9440
  // Only send the halves the caller actually named; the route merges a PARTIAL
8686
9441
  // spec over the stored one, so an omitted field is never silently cleared.
8687
9442
  const patch = namedSpecPatch(input, spec);
8688
9443
  const r = await desktop.post('/agent/shots/update', {
8689
- id: input.shotId,
9444
+ id: await shotRowId(input.shotId, read),
8690
9445
  data: {
8691
9446
  name: input.name,
8692
9447
  ...(Object.keys(patch).length > 0 ? { spec: patch } : {}),
8693
9448
  attachFrameId: input.attachFrameId,
8694
9449
  detachFrameId: input.detachFrameId,
8695
- posterAssetId: input.posterAssetId,
9450
+ posterAssetId,
8696
9451
  },
8697
9452
  });
8698
9453
  // An edit to framing changes the counts, and the agent read them BEFORE it
@@ -8706,6 +9461,7 @@ export const duplicateShot = {
8706
9461
  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.',
8707
9462
  input: z.object({
8708
9463
  shotId: z.string().describe('The Shot id, or its SHOT-A code.'),
9464
+ projectId: z.string().uuid().optional().describe(SHOT_PROJECT_DESCRIBE),
8709
9465
  name: z.string().max(120).optional().describe('Name for the copy (default: the original plus "copy").'),
8710
9466
  prompt: z.string().max(4000).optional().describe('Replace the prompt on the copy. Omit to keep the original\'s.'),
8711
9467
  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.'),
@@ -8718,7 +9474,11 @@ export const duplicateShot = {
8718
9474
  return capErr;
8719
9475
  const desktop = ctx.desktop();
8720
9476
  await desktop.requireCapability('shots', 'saved Shots');
8721
- await requireDraftShotDesktop(desktop, input.model, input.params, input.shotId);
9477
+ const read = shotReader(desktop, input.shotId, input.projectId);
9478
+ const storedErr = await assertStoredShotCapabilities(input.model, input.params, read);
9479
+ if (storedErr)
9480
+ return storedErr;
9481
+ await requireDraftShotDesktop(desktop, input.model, input.params, read);
8722
9482
  // Only the halves actually named. The route merges two levels deep, so an
8723
9483
  // omitted param on the copy keeps the original's value rather than clearing it.
8724
9484
  const spec = {};
@@ -8730,8 +9490,7 @@ export const duplicateShot = {
8730
9490
  if (input.params !== undefined) {
8731
9491
  const voiceRef = input.params.voiceReferenceAssetId;
8732
9492
  if (voiceRef && !UUID_RE.test(voiceRef)) {
8733
- const { shot } = await desktop.get('/agent/shots/get', { id: input.shotId });
8734
- const built = await buildShotSpecInput(ctx, shot.projectId, { params: input.params });
9493
+ const built = await buildShotSpecInput(ctx, (await read()).projectId, { params: input.params });
8735
9494
  spec.params = built.spec.params;
8736
9495
  }
8737
9496
  else {
@@ -8739,7 +9498,7 @@ export const duplicateShot = {
8739
9498
  }
8740
9499
  }
8741
9500
  const r = await desktop.post('/agent/shots/duplicate', {
8742
- id: input.shotId,
9501
+ id: await shotRowId(input.shotId, read),
8743
9502
  name: input.name,
8744
9503
  ...(Object.keys(spec).length > 0 ? { spec } : {}),
8745
9504
  frameId: input.frameId,
@@ -8812,15 +9571,8 @@ export const listShots = {
8812
9571
  });
8813
9572
  const rows = r.shots ?? [];
8814
9573
  const projectId = input.projectId;
8815
- // The quote is a GET with every id in its query string, and Node refuses a
8816
- // request head over 16 KiB (about 345 ids), so a long board is quoted in
8817
- // chunks. Each Shot's price is its own; only this listing reads them.
8818
- const QUOTE_CHUNK = 150;
8819
- const chunks = [];
8820
- for (let i = 0; i < rows.length; i += QUOTE_CHUNK)
8821
- chunks.push(rows.slice(i, i + QUOTE_CHUNK).map(r => r.id));
8822
9574
  const quote = projectId && rows.length
8823
- ? { items: (await Promise.all(chunks.map((shotIds) => desktop.get('/agent/shots/quote', { input: JSON.stringify({ projectId, shotIds }) })))).flatMap((q) => q.items) }
9575
+ ? await desktop.quote('/agent/shots/quote', 'input', { projectId, shotIds: rows.map((r) => r.id) })
8824
9576
  : null;
8825
9577
  let total = 0;
8826
9578
  let unpriced = 0;
@@ -8894,14 +9646,18 @@ export const getShot = {
8894
9646
  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.',
8895
9647
  input: z.object({
8896
9648
  shotId: z.string().describe('The Shot id, or its SHOT-A code as shown on the row.'),
9649
+ projectId: z.string().uuid().optional().describe(SHOT_PROJECT_DESCRIBE),
8897
9650
  }),
8898
9651
  async run(input, ctx) {
8899
9652
  const desktop = ctx.desktop();
8900
9653
  await desktop.requireCapability('shots', 'saved Shots');
8901
9654
  // Prices come only from the desktop's quote; a 1.5.8 desktop has none.
8902
9655
  await desktop.requireCapability('board-quote', 'Shot prices');
8903
- const r = await desktop.get('/agent/shots/get', { id: input.shotId });
8904
- const quote = await desktop.get('/agent/shots/quote', { input: JSON.stringify({ projectId: r.shot.projectId, shotIds: [r.shot.id] }) });
9656
+ // A read by the Shot's own id needs no project: the project only says where a code is looked up, and a
9657
+ // default one (the CLI's `slates use`) must not refuse a Shot that lives elsewhere.
9658
+ const scope = UUID_RE.test(input.shotId.trim()) ? undefined : input.projectId;
9659
+ const r = { shot: await shotReader(desktop, input.shotId, scope)() };
9660
+ const quote = await desktop.quote('/agent/shots/quote', 'input', { projectId: r.shot.projectId, shotIds: [r.shot.id] });
8905
9661
  const q = quote.items[0];
8906
9662
  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'}, ` +
8907
9663
  (q.credits != null && !r.shot.blocked
@@ -8956,6 +9712,7 @@ export const splitShot = {
8956
9712
  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.',
8957
9713
  input: z.object({
8958
9714
  shotId: z.string().describe('The Shot id, or its SHOT-A code.'),
9715
+ projectId: z.string().uuid().optional().describe(SHOT_PROJECT_DESCRIBE),
8959
9716
  caret: z
8960
9717
  .number()
8961
9718
  .int()
@@ -8966,7 +9723,7 @@ export const splitShot = {
8966
9723
  async run(input, ctx) {
8967
9724
  const desktop = ctx.desktop();
8968
9725
  await desktop.requireCapability('shots', 'saved Shots');
8969
- const r = await desktop.post('/agent/shots/split', { id: input.shotId, caret: input.caret });
9726
+ const r = await desktop.post('/agent/shots/split', { id: await shotRowId(input.shotId, shotReader(desktop, input.shotId, input.projectId)), caret: input.caret });
8970
9727
  return ok(r, `Split into ${r.first?.code || 'the first Shot'} and ` +
8971
9728
  `${r.second?.code || 'a new Shot'}. Duration was INHERITED, not divided — ` +
8972
9729
  `set it on each if the chop changed how long they run.`);
@@ -9015,13 +9772,14 @@ export const mergeShots = {
9015
9772
  input: z.object({
9016
9773
  firstId: z.string().describe('The Shot that survives — its model and params win. Id or SHOT-A code.'),
9017
9774
  secondId: z.string().describe('The Shot folded into it. Id or SHOT-A code.'),
9775
+ projectId: z.string().uuid().optional().describe("The Shots' project. A SHOT-A code is unique only within its project, so pass this with codes."),
9018
9776
  }),
9019
9777
  async run(input, ctx) {
9020
9778
  const desktop = ctx.desktop();
9021
9779
  await desktop.requireCapability('shots', 'saved Shots');
9022
9780
  const r = await desktop.post('/agent/shots/merge', {
9023
- firstId: input.firstId,
9024
- secondId: input.secondId,
9781
+ firstId: await shotRowId(input.firstId, shotReader(desktop, input.firstId, input.projectId)),
9782
+ secondId: await shotRowId(input.secondId, shotReader(desktop, input.secondId, input.projectId)),
9025
9783
  });
9026
9784
  return ok(r.shot, `Merged into ${r.shot?.code || 'one Shot'} — ` +
9027
9785
  `${r.shot?.cuts ?? 1} cut(s), ${r.shot?.runtimeSeconds ?? 'no'} second(s).`);
@@ -9079,7 +9837,7 @@ async function resolveVariationRefs(input, ctx) {
9079
9837
  return input;
9080
9838
  const { storyboard } = await ctx.desktop().get('/agent/storyboards/get', { id: input.storyboardId });
9081
9839
  const assets = await resolveAssetRefs(ctx, storyboard.projectId, input.assetOverrides.flatMap(o => [o.from, o.to]));
9082
- return { ...input, assetOverrides: input.assetOverrides.map(o => ({ from: assets.get(o.from).id, to: assets.get(o.to).id })) };
9840
+ return { ...input, assetOverrides: input.assetOverrides.map(o => ({ from: assets.id(o.from), to: assets.id(o.to) })) };
9083
9841
  }
9084
9842
  export const getScriptUses = {
9085
9843
  id: 'slates_get_script_uses',
@@ -9106,7 +9864,7 @@ export const reuseShotTake = {
9106
9864
  async run(input, ctx) {
9107
9865
  await ctx.desktop().requireCapability('script-documents', 'script documents');
9108
9866
  const assets = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
9109
- return ok(await ctx.desktop().post('/agent/shots/reuse-take', { ...input, assetId: assets.get(input.assetId).id }));
9867
+ return ok(await ctx.desktop().post('/agent/shots/reuse-take', { ...input, assetId: assets.id(input.assetId) }));
9110
9868
  },
9111
9869
  };
9112
9870
  export const getScriptSections = {
@@ -9304,6 +10062,7 @@ export const generateFromShots = {
9304
10062
  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.',
9305
10063
  input: z.object({
9306
10064
  shotIds: z.array(z.string()).min(1).max(20),
10065
+ projectId: z.string().uuid().optional().describe("The Shots' project. A SHOT-A code is unique only within its project, so pass this with codes."),
9307
10066
  confirm: z.boolean().optional().describe(CONFIRM_PARAM + " Pass it with the quote's fingerprint."),
9308
10067
  fingerprint: z.string().optional(),
9309
10068
  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.'),
@@ -9314,16 +10073,22 @@ export const generateFromShots = {
9314
10073
  // Prices come only from the desktop's quote; a 1.5.8 desktop has none.
9315
10074
  await desktop.requireCapability('board-quote', 'Shot prices');
9316
10075
  // Resolved first so a SHOT-A code fails here, not halfway through a billed run.
9317
- const details = await Promise.all(input.shotIds.map((id) => desktop.get('/agent/shots/get', { id })));
10076
+ const details = await Promise.all(input.shotIds.map((id) => shotReader(desktop, id, input.projectId)()));
10077
+ // One quote, one board: Shots from two projects are never priced or billed together.
10078
+ const projects = new Set(details.map((shot) => shot.projectId));
10079
+ if (projects.size > 1) {
10080
+ throw new Error(`These Shots belong to ${projects.size} projects (${details.map((s) => `${s.code ?? s.id}: ${s.projectId}`).join(', ')}). ` +
10081
+ 'Pass projectId so each SHOT-A code resolves in that project, or generate each project\'s Shots separately.');
10082
+ }
9318
10083
  // Older desktops drop the draft flag when reading a saved recipe. Its persisted 480p
9319
10084
  // resolution survives, so require a capable desktop before firing an ambiguous video Shot.
9320
- if (!input.draft && details.some(({ shot }) => shot.model === 'seedance-2.5' &&
10085
+ if (!input.draft && details.some((shot) => shot.model === 'seedance-2.5' &&
9321
10086
  (shot.params?.seedanceDraft || ['480p', '4k'].includes(String(shot.params?.videoResolution))))) {
9322
10087
  await desktop.requireCapability('seedance-drafts', 'generating saved Seedance 2.5 preview or 4K Shots');
9323
10088
  }
9324
10089
  const { draft, note: seatNote } = await desktopDraft(desktop, input.draft);
9325
- const quote = await desktop.get('/agent/shots/quote', {
9326
- input: JSON.stringify({ projectId: details[0].shot.projectId, shotIds: details.map((d) => d.shot.id), draft }),
10090
+ const quote = await desktop.quote('/agent/shots/quote', 'input', {
10091
+ projectId: details[0].projectId, shotIds: details.map((d) => d.id), draft,
9327
10092
  });
9328
10093
  for (const model of new Set(quote.items.map((i) => i.model)))
9329
10094
  requireGuideRead(ctx, model);
@@ -9342,6 +10107,7 @@ export const generateFromShots = {
9342
10107
  '\nGet approval for these prices, then pass this fingerprint with confirm: true.' +
9343
10108
  (seatNote ? `\n${seatNote}` : ''));
9344
10109
  }
10110
+ approvedSpend(ctx);
9345
10111
  const ran = await desktop.post('/agent/shots/batch-generate', {
9346
10112
  shotIds: quote.items.map((i) => i.shotId),
9347
10113
  fingerprint: quote.fingerprint,
@@ -9365,7 +10131,7 @@ export const quoteBoard = {
9365
10131
  const desktop = ctx.desktop();
9366
10132
  await desktop.requireCapability('board-quote', 'the board prices');
9367
10133
  const { draft, note } = await desktopDraft(desktop, input.draft);
9368
- const quote = await desktop.get('/agent/shots/quote', { input: JSON.stringify({ ...input, draft }) });
10134
+ const quote = await desktop.quote('/agent/shots/quote', 'input', { ...input, draft });
9369
10135
  return note ? ok(quote, `${JSON.stringify(quote)}\n${note}`) : ok(quote);
9370
10136
  },
9371
10137
  };
@@ -9396,7 +10162,7 @@ export const quoteDraftFinish = {
9396
10162
  const desktop = ctx.desktop();
9397
10163
  await desktop.requireCapability('seedance-drafts', 'finishing draft takes');
9398
10164
  const refs = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
9399
- return ok(await desktop.get('/agent/assets/quote-draft-finish', { ...input, assetId: refs.get(input.assetId).id }));
10165
+ return ok(await desktop.get('/agent/assets/quote-draft-finish', { ...input, assetId: refs.id(input.assetId) }));
9400
10166
  },
9401
10167
  };
9402
10168
  export const finishDraft = {
@@ -9409,7 +10175,8 @@ export const finishDraft = {
9409
10175
  const desktop = ctx.desktop();
9410
10176
  await desktop.requireCapability('seedance-drafts', 'finishing draft takes');
9411
10177
  const refs = await resolveAssetRefs(ctx, input.projectId, [input.assetId]);
9412
- const receipt = await desktop.post('/agent/assets/finish-draft', { ...input, assetId: refs.get(input.assetId).id, background: true });
10178
+ approvedSpend(ctx);
10179
+ const receipt = await desktop.post('/agent/assets/finish-draft', { ...input, assetId: refs.id(input.assetId), background: true });
9413
10180
  if (!ctx.waitForCutFinish || receipt.status === 'completed')
9414
10181
  return ok(receipt);
9415
10182
  if (!receipt.generationId)
@@ -9457,6 +10224,7 @@ export const finishCutDrafts = {
9457
10224
  const desktop = ctx.desktop();
9458
10225
  await desktop.requireCapability('seedance-drafts', 'finishing drafts in a cut');
9459
10226
  const query = { projectId: input.projectId, timelineId: input.timelineId, quoteId: input.quoteId };
10227
+ approvedSpend(ctx);
9460
10228
  let receipt = await desktop.post('/agent/timeline/cut', {
9461
10229
  ...input, action: 'finishDrafts', background: true,
9462
10230
  });
@@ -9512,8 +10280,9 @@ export const editCut = {
9512
10280
  }),
9513
10281
  async run(input, ctx) {
9514
10282
  await ctx.desktop().requireCapability('cut-edit', 'editing a cut');
9515
- const refs = input.assetId ? await resolveAssetRefs(ctx, input.projectId, [input.assetId]) : new Map();
9516
- return ok(await ctx.desktop().post('/agent/timeline/cut', { ...input, assetId: input.assetId ? refs.get(input.assetId)?.id : undefined }));
10283
+ // A timeline clip is the one reference that may point into another project, so an id from one passes.
10284
+ const refs = input.assetId ? await resolveAssetRefs(ctx, input.projectId, [input.assetId], { anyProject: true }) : new AssetRefs();
10285
+ return ok(await ctx.desktop().post('/agent/timeline/cut', { ...input, assetId: input.assetId ? refs.id(input.assetId) : undefined }));
9517
10286
  },
9518
10287
  };
9519
10288
  export function resolveGuideTopic(topic) {
@@ -9623,12 +10392,6 @@ export function resolveGuideTopic(topic) {
9623
10392
  t.startsWith('h3-')) {
9624
10393
  return 'slates-prompting-minimax-h3';
9625
10394
  }
9626
- // LTX-2.5 — both seats share one skill. A PREFIX is right HERE (unlike every
9627
- // rate, key and endpoint lookup, which must be exact) precisely because both
9628
- // rows resolve to the same guide: `ltx-2-5-pro` matching the `ltx` prefix is
9629
- // the intended outcome, not a collision.
9630
- if (t.startsWith('ltx') || t === 'lightricks')
9631
- return 'slates-prompting-ltx-2-5';
9632
10395
  if (t.startsWith('kling-mc'))
9633
10396
  return 'slates-prompting-motion-transfer';
9634
10397
  if (t === 'edit-video' || t === 'video-edit' || t === 'edit video' || t === 'video edit')
@@ -10296,6 +11059,24 @@ export const ALL_OPERATIONS = [
10296
11059
  upscaleImage,
10297
11060
  getReviewPacket,
10298
11061
  resolveReviewNote,
11062
+ getAdWinners,
11063
+ getClientAdReport,
11064
+ setRecipeVerdict,
11065
+ moreLikeThis,
11066
+ planSplitTest,
11067
+ evaluateSplitTestWinner,
11068
+ visualQaSample,
11069
+ visualQaRecordRound,
11070
+ listVisualQaRuns,
11071
+ listV2vPasses,
11072
+ editV2vPass,
11073
+ quoteV2vPasses,
11074
+ runV2vPasses,
11075
+ v2vPassesToVariants,
11076
+ getDiagnosticsStatus,
11077
+ findWinningAds,
11078
+ listWinningAdNiches,
11079
+ breakDownWinningAd,
10299
11080
  getTimeline,
10300
11081
  getTimelineLoudness,
10301
11082
  addClipToTimeline,