@slatesvideo/shared 0.7.7 → 0.7.9

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.
Files changed (122) hide show
  1. package/README.md +3 -6
  2. package/dist/analytics/events.d.ts +1 -1
  3. package/dist/analytics/events.js +7 -0
  4. package/dist/auth.d.ts +2 -0
  5. package/dist/auth.js +5 -0
  6. package/dist/clients/cloud.d.ts +2 -0
  7. package/dist/clients/cloud.js +5 -1
  8. package/dist/clients/desktop.js +6 -1
  9. package/dist/index.d.ts +7 -3
  10. package/dist/index.js +7 -3
  11. package/dist/manual/content.d.ts +1 -1
  12. package/dist/manual/content.js +1 -1
  13. package/dist/operations/index.d.ts +724 -173
  14. package/dist/operations/index.js +875 -65
  15. package/dist/operations/surface.d.ts +2 -2
  16. package/dist/operations/surface.js +26 -6
  17. package/dist/prompts/agent-doctrine.d.ts +12 -2
  18. package/dist/prompts/agent-doctrine.js +56 -28
  19. package/dist/prompts/banned-tokens.js +23 -13
  20. package/dist/prompts/brain.d.ts +29 -0
  21. package/dist/prompts/brain.js +72 -0
  22. package/dist/prompts/craft-cards.d.ts +15 -4
  23. package/dist/prompts/craft-cards.js +71 -9
  24. package/dist/prompts/generation-policy.d.ts +1 -1
  25. package/dist/prompts/guide-discovery.d.ts +6 -6
  26. package/dist/prompts/guide-retrieval.d.ts +7 -1
  27. package/dist/prompts/guide-retrieval.js +33 -5
  28. package/dist/prompts/partials.generated.js +1 -13
  29. package/dist/prompts/shot-grammar.d.ts +1 -1
  30. package/dist/prompts/shot-grammar.js +1 -1
  31. package/dist/skills/brain-check.d.ts +44 -0
  32. package/dist/skills/brain-check.js +174 -0
  33. package/dist/skills/content.d.ts +3 -0
  34. package/dist/skills/content.js +81 -44
  35. package/dist/skills/hyperframes-content.js +4 -4
  36. package/dist/skills/my-brain.d.ts +52 -0
  37. package/dist/skills/my-brain.js +218 -0
  38. package/dist/skills/served.d.ts +56 -0
  39. package/dist/skills/served.js +232 -0
  40. package/package.json +2 -4
  41. package/skills/hyperframes/NOTICE +19 -3
  42. package/skills/hyperframes/SLATES-MAPPING.md +1 -1
  43. package/skills/hyperframes/embedded-captions/CATALOG.md +3 -0
  44. package/skills/hyperframes/embedded-captions/SKILL.md +6 -6
  45. package/skills/hyperframes/embedded-captions/assets/fonts/char-widths.json +227 -1
  46. package/skills/hyperframes/embedded-captions/modes/standard/fonts/build-fonts-css.cjs +19 -2
  47. package/skills/hyperframes/embedded-captions/modes/standard/fonts/files/archivo-latin-wdth-italic.woff2 +0 -0
  48. package/skills/hyperframes/embedded-captions/modes/standard/fonts/files/archivo-latin-wdth-normal.woff2 +0 -0
  49. package/skills/hyperframes/embedded-captions/scripts/make-theme.cjs +438 -3
  50. package/skills/hyperframes/embedded-captions/scripts/make-theme.test.mjs +1 -0
  51. package/skills/hyperframes/embedded-captions/themes/README.md +26 -1
  52. package/skills/hyperframes/embedded-captions/themes/lesson.json +31 -0
  53. package/skills/slates-start-here.md +78 -0
  54. package/exports/slates-chatgpt-images/generated/SKILL.md +0 -113
  55. package/exports/slates-chatgpt-images/generated/slates-chatgpt-images.skill +0 -0
  56. package/exports/slates-prompt-builder/generated/SKILL.md +0 -71
  57. package/exports/slates-prompt-builder/generated/reference-character.md +0 -92
  58. package/exports/slates-prompt-builder/generated/reference-content-policy.md +0 -81
  59. package/exports/slates-prompt-builder/generated/reference-gpt-image-2-5.md +0 -191
  60. package/exports/slates-prompt-builder/generated/reference-kling.md +0 -295
  61. package/exports/slates-prompt-builder/generated/reference-nano-banana.md +0 -240
  62. package/exports/slates-prompt-builder/generated/reference-omni-flash.md +0 -97
  63. package/exports/slates-prompt-builder/generated/reference-seedance-2-5.md +0 -392
  64. package/exports/slates-prompt-builder/generated/reference-seedance.md +0 -441
  65. package/exports/slates-prompt-builder/generated/slates-prompt-builder-manifest.json +0 -133
  66. package/exports/slates-prompt-builder/generated/slates-prompt-builder.skill +0 -0
  67. package/skills/_partials/blender-action-curves.md +0 -24
  68. package/skills/_partials/cinematic-card.md +0 -8
  69. package/skills/_partials/decision-log.md +0 -1
  70. package/skills/_partials/image-defaults.md +0 -9
  71. package/skills/_partials/iteration-diagnosis.md +0 -5
  72. package/skills/_partials/living-performance.md +0 -22
  73. package/skills/_partials/model-routing.md +0 -35
  74. package/skills/_partials/references-read-literally.md +0 -11
  75. package/skills/_partials/seedance-25-timestamps.md +0 -34
  76. package/skills/_partials/sheet-tool-defaults.md +0 -6
  77. package/skills/_partials/still-gate.md +0 -3
  78. package/skills/_partials/thresholds.md +0 -19
  79. package/skills/slates-blocking-to-prompt.md +0 -279
  80. package/skills/slates-camera-language.md +0 -234
  81. package/skills/slates-captions.md +0 -81
  82. package/skills/slates-character-identity.md +0 -117
  83. package/skills/slates-chatgpt-images.md +0 -113
  84. package/skills/slates-cinematic-look.md +0 -237
  85. package/skills/slates-content-policy.md +0 -88
  86. package/skills/slates-cost-discipline.md +0 -150
  87. package/skills/slates-cuts.md +0 -46
  88. package/skills/slates-dialogue-blocking.md +0 -134
  89. package/skills/slates-direct-response-ad.md +0 -26
  90. package/skills/slates-edit-and-iterate.md +0 -76
  91. package/skills/slates-layer-brand-captions.md +0 -87
  92. package/skills/slates-layer-lower-third.md +0 -85
  93. package/skills/slates-layer-title.md +0 -82
  94. package/skills/slates-model-selection.md +0 -129
  95. package/skills/slates-motion.md +0 -57
  96. package/skills/slates-one-prompt-film.md +0 -38
  97. package/skills/slates-previs-blocking.md +0 -186
  98. package/skills/slates-project-organization.md +0 -42
  99. package/skills/slates-prompting-elevenlabs.md +0 -128
  100. package/skills/slates-prompting-flux-3.md +0 -157
  101. package/skills/slates-prompting-gpt-image-2-5.md +0 -196
  102. package/skills/slates-prompting-inworld-tts.md +0 -174
  103. package/skills/slates-prompting-kling-v3.md +0 -303
  104. package/skills/slates-prompting-lip-sync.md +0 -216
  105. package/skills/slates-prompting-ltx-2-5.md +0 -245
  106. package/skills/slates-prompting-minimax-h3.md +0 -383
  107. package/skills/slates-prompting-motion-transfer.md +0 -202
  108. package/skills/slates-prompting-nano-banana-2-1.md +0 -250
  109. package/skills/slates-prompting-omni-flash.md +0 -117
  110. package/skills/slates-prompting-seed-audio.md +0 -168
  111. package/skills/slates-prompting-seedance-2-5.md +0 -420
  112. package/skills/slates-prompting-seedance.md +0 -462
  113. package/skills/slates-prompting-seedream-5-lite.md +0 -122
  114. package/skills/slates-prompting-wan-3.md +0 -143
  115. package/skills/slates-restyle-from-blocking.md +0 -121
  116. package/skills/slates-script-craft.md +0 -45
  117. package/skills/slates-shot-variety.md +0 -24
  118. package/skills/slates-storyboard-from-script.md +0 -32
  119. package/skills/slates-style-prompting.md +0 -56
  120. package/skills/slates-transitions.md +0 -40
  121. package/skills/slates-ugc-influencer-ad.md +0 -32
  122. package/skills/slates-vision-feedback-loop.md +0 -118
@@ -1,7 +1,8 @@
1
1
  import { MAX_IMAGE_VARIATIONS } from '../prompts/generation-policy.js';
2
2
  import { STYLE_LIBRARY, DEFAULT_STYLE_ID } from '../prompts/style-library.js';
3
3
  import { discoverGuides, guideCatalog } from '../prompts/guide-discovery.js';
4
- import { retrieveGuide } from '../prompts/guide-retrieval.js';
4
+ import { retrieveGuide, servedDepth } from '../prompts/guide-retrieval.js';
5
+ import { BRAIN_ROUTER, MY_BRAIN_TOPIC, ROUTER_ALIASES } from '../prompts/brain.js';
5
6
  import { MINIMAX_MAX_REFERENCE, minimaxMaxReferenceTokens, MODEL_CAPABILITIES, RETIRED_MODELS, retiredModelOfKey, GPT_QUALITY_TIERS, DEFAULT_GPT_QUALITY, GPT_BACKGROUNDS } from '../prompts/model-capabilities.js';
6
7
  // Operations layer — the ONE place every Slates agent tool is defined.
7
8
  // Both the MCP server and the CLI register these as their tool / command
@@ -19,6 +20,8 @@ import { SlatesCloudClient, SlatesCloudHttpError } from '../clients/cloud.js';
19
20
  import { SlatesDesktopClient } from '../clients/desktop.js';
20
21
  import { BlenderBridgeClient, BLENDER_SETUP_HINT, RENDER_TIMEOUT_MS } from '../clients/blender.js';
21
22
  import { SKILLS } from '../skills/content.js';
23
+ import { brainSkills, myBrainDir, myBrainPreload, noteUsed } from '../skills/my-brain.js';
24
+ import { brainFiles, refreshServedBrain, servedBrain } from '../skills/served.js';
22
25
  import { HYPERFRAMES_MAPPING, findHyperframesGuide, hyperframesCard, hyperframesCatalog, hyperframesFilesOf, hyperframesGuideHeader, hyperframesSkillBodies, loadHyperframes } from '../skills/hyperframes.js';
23
26
  import { appManualIndex, appManualSections } from '../manual/index.js';
24
27
  // Reference-capacity prose is DERIVED, never hand-typed — root CLAUDE.md:
@@ -84,16 +87,31 @@ export class OperationCancelledError extends Error {
84
87
  * Eric, 2026-10-23, after a Seedance test was prompted before its guide was
85
88
  * read: *"That needs to be a hard blocker."* Nothing was generated or charged.
86
89
  */
90
+ /** How a machine with no brain gets one: the desktop app signed in here writes it, or a CLI login fetches it. */
91
+ export const CONNECT_FOR_BRAIN = 'Have the user open the Slates app signed in on this machine (it brings the brain here), or run `slates login`';
87
92
  export class GuideNotReadError extends Error {
88
93
  model;
89
94
  guide;
90
95
  code = 'GUIDE_NOT_READ';
91
96
  constructor(model, guide) {
92
- super(`Refused: this session has not read ${guide}, the guide for ${model}. Nothing was generated or charged. ` +
93
- `Call slates_get_prompting_guide with topic "${guide}", rewrite the prompt against it, then call this again. Its card:
94
-
95
- ` +
96
- describeCraftCard(guide));
97
+ const head = `Refused: this session has not read ${guide}, the guide for ${model}. Nothing was generated or charged. `;
98
+ const body = brainSkills().skills[guide];
99
+ const served = servedBrain();
100
+ const locked = body === undefined ? served.locked.find(entry => entry.name === guide) : undefined;
101
+ super(body !== undefined
102
+ ? head +
103
+ `Call slates_get_prompting_guide with topic "${guide}", rewrite the prompt against it, then call this again. Its card:\n\n` +
104
+ // The card this user's brain serves, so a model guide from their My brain is the one in the refusal.
105
+ describeCraftCard(guide, body)
106
+ : locked
107
+ ? // Past this account's tier: no body here, so the server's notice (its card included) is what it reads.
108
+ head +
109
+ `Call slates_get_prompting_guide with topic "${guide}", rewrite the prompt against what it says, then call this again. What it says:\n\n` +
110
+ (locked.notice ?? `${guide} is not open to this account. Run the job on the general rules.`)
111
+ : // No copy here and none locked: the brain never arrived, so asking for the guide again cannot help.
112
+ head +
113
+ `The guide comes from the connected Slates account and is not on this machine (${served.problem ?? 'no brain received yet'}). ` +
114
+ `${CONNECT_FOR_BRAIN}; then call slates_get_prompting_guide with topic "${guide}" and call this again.`);
97
115
  this.model = model;
98
116
  this.guide = guide;
99
117
  }
@@ -449,32 +467,39 @@ export const getSelection = {
449
467
  };
450
468
  // 1.6.1: what is ticked. Mirrors slate's `SELECTION_TARGETS` and `SELECTION_MODES` in `@shared/types/view`
451
469
  // (lockstep check 12), which this package cannot import.
452
- const SELECTION_TARGETS = ['media', 'board'];
470
+ const SELECTION_TARGETS = ['media', 'board', 'timeline'];
453
471
  const SELECTION_MODES = ['replace', 'add', 'remove', 'clear', 'all'];
454
472
  /**
455
- * SET what is selected, as the user's clicks do: the cards ticked in Media, the Shots ticked on the Board.
473
+ * SET what is selected, as the user's clicks do: the cards ticked in Media, the Shots ticked on the Board, the
474
+ * clips selected on the timeline (which also opens the Cut on them, scrolls to them and opens the Inspector).
456
475
  * Pairs with `slates_get_selection`, which reads it: "tick the shots with no clip, then price them" is this op
457
476
  * and then the quote. The desktop applies it through the stores the grids write and answers with what SETTLED.
458
477
  */
459
478
  export const setSelection = {
460
479
  id: 'slates_set_selection',
461
- description: "Tick or untick cards in Media or Shots on the Board, as clicks, Shift-click, Escape and Ctrl/Cmd+A do: replace makes the ids the whole selection, add and remove change only them, clear empties it, all ticks everything the tab shows (Media: the grid as filtered, folded rounds left out; Board: every Shot on the open board). Media needs its grid showing and the Board needs the Board or Script tab; slates_set_view switches. Ids are asset ids or badge codes (Media) or Shot ids or SHOT-A codes (Board). Answers with the selection as it settled and names any id it could not tick. slates_get_selection reads it back; what is selected is what the user means by 'these'.",
480
+ description: "Select cards in Media, Shots on the Board or clips on the timeline, as clicks, Shift-click, Escape and Ctrl/Cmd+A do: replace makes the ids the whole selection, add and remove change only them, clear empties it, all ticks everything the tab shows (Media: the grid as filtered, folded rounds left out; Board: every Shot on the open board; timeline: every clip on the open timeline). Every surface needs a project open in the window, Media its grid showing and the Board the Board or Script tab; slates_set_view opens and switches. On the timeline, clip ids open the Cut on their timeline, scroll to them and open the Inspector on the last, so use it to show the user a clip instead of asking them to click it; all, or replace with no ids, needs a timeline open (slates_set_view cut.timelineId). Ids are asset ids or badge codes (Media), Shot ids or SHOT-A codes (Board) or clip ids from slates_get_timeline (timeline, all on one timeline). Answers with the selection as it settled and names any id it could not select. slates_get_selection reads it back (timeline clips under timeline.selectedClips); what is selected is what the user means by 'these'.",
462
481
  input: z
463
482
  .object({
464
483
  surface: z.enum(SELECTION_TARGETS),
465
484
  mode: z.enum(SELECTION_MODES),
466
- ids: z.array(z.string().min(1)).max(500).optional().describe('Asset ids or codes (media) or Shot ids or codes (board). Not used by clear or all.'),
485
+ ids: z.array(z.string().min(1)).max(500).optional().describe('Asset ids or codes (media), Shot ids or codes (board) or clip ids (timeline). Not used by clear or all.'),
467
486
  })
468
487
  .strict(),
469
488
  async run(input, ctx) {
470
489
  await ctx.desktop().requireCapability('selection-set', 'setting what is selected');
490
+ if (input.surface === 'timeline')
491
+ await ctx.desktop().requireCapability('timeline-select', 'selecting timeline clips');
471
492
  if ((input.mode === 'add' || input.mode === 'remove') && !input.ids?.length)
472
493
  throw new Error(`${input.mode} needs ids.`);
473
494
  const r = await ctx.desktop().post('/agent/selection', input);
474
495
  if (!r.selection)
475
496
  return { text: `Nothing was changed (${r.reason ?? 'no answer'}).`, data: { selection: null } };
476
- const where = r.selection.surface === 'media' ? 'Media' : 'the Board';
477
- const named = (row) => (row.code ? (row.label ? `${row.code} — ${row.label}` : row.code) : row.id);
497
+ const where = r.selection.surface === 'media' ? 'Media' : r.selection.surface === 'timeline' ? 'the timeline' : 'the Board';
498
+ const named = (row) => {
499
+ const coded = row.code ? (row.label ? `${row.code} — ${row.label}` : row.code) : null;
500
+ // A timeline row appends its id, so its label may stand in for a code; a Media or Board row without one is named by its id.
501
+ return row.track && row.start ? `${coded ?? row.label ?? row.id} (${row.track}, ${row.start.timecode}, ${row.id})` : coded ?? row.id;
502
+ };
478
503
  const notes = r.notes?.length ? ` Not applied: ${r.notes.join('; ')}.` : '';
479
504
  return {
480
505
  text: (r.selection.items.length ? `${r.selection.items.length} selected on ${where}: ${r.selection.items.map(named).join(', ')}.` : `Nothing is selected on ${where}.`) + notes,
@@ -490,6 +515,8 @@ const VIEW_CUT_SIDES = ['bottom', 'left', 'right'];
490
515
  const VIEW_DOCK_SECTIONS = ['storyboards', 'library', 'folders', 'pinned'];
491
516
  // W3: the one window's two layouts (`WINDOW_LAYOUTS`).
492
517
  const VIEW_WINDOW_LAYOUTS = ['plan', 'edit'];
518
+ // What the timeline's Viewer shows (`VIEWER_MODES`).
519
+ const VIEW_VIEWER_MODES = ['source', 'timeline'];
493
520
  // 1.6.1: what the user is looking at. Mirrors slate's `@shared/types/view` (lockstep check 12).
494
521
  const VIEW_BOARD_LEVELS = ['film', 'scenes', 'shot'];
495
522
  const VIEW_BOARD_FILTERS = ['all', 'with-clip', 'without-clip'];
@@ -708,7 +735,14 @@ export const setView = {
708
735
  .strict()
709
736
  .optional(),
710
737
  library: z.object({ categoryId: z.string().nullable() }).strict().optional().describe("Open a Library category's page in Media's place; null goes back to the grid."),
711
- viewer: z.object({ assetId: z.string().nullable() }).strict().optional().describe("A picture opens in the picture viewer; a clip plays in the timeline's Viewer (Source), on desktops after 1.6.2. null closes the picture viewer."),
738
+ viewer: z
739
+ .object({
740
+ assetId: z.string().nullable().optional().describe("A picture opens in the picture viewer; a clip plays in the timeline's Viewer (Source), on desktops after 1.6.2. null closes the picture viewer."),
741
+ mode: z.enum(VIEW_VIEWER_MODES).optional().describe("What the timeline's Viewer shows: source (a clip opened to watch) or timeline (the timeline). Compare opens through compare.open. Desktops from 1.6.3."),
742
+ })
743
+ .strict()
744
+ .refine((v) => v.assetId !== undefined || v.mode !== undefined, { message: 'viewer: name assetId or mode' })
745
+ .optional(),
712
746
  compare: z
713
747
  .object({ open: z.boolean().optional(), assetIds: z.array(z.string()).max(4).optional().describe('The compare set, two to four items.') })
714
748
  .strict()
@@ -1007,6 +1041,35 @@ export const setAppSettings = {
1007
1041
  return ok(await ctx.desktop().post('/agent/app-settings', input));
1008
1042
  },
1009
1043
  };
1044
+ const SPEND_LIMIT = z.number().int().min(0).nullable();
1045
+ export const getSpendLimits = {
1046
+ id: 'slates_get_spend_limits',
1047
+ description: "The project's spend limit and this session's budget, in credits, where a session is this MCP connection or CLI run and a new one starts at the full default budget: each limit (null is none), what is spent against it and what is left, as shown beside Generate. A generation over either one is refused with its cost and what is left; read this before a run of generations.",
1048
+ input: z.object({ projectId: z.string().uuid().optional().describe('Defaults to the open project.') }).strict(),
1049
+ async run(input, ctx) {
1050
+ await ctx.desktop().requireCapability('spend-limits', 'spend limits');
1051
+ return ok(await ctx.desktop().get('/agent/spend-limits', { projectId: input.projectId }));
1052
+ },
1053
+ };
1054
+ export const setSpendLimits = {
1055
+ id: 'slates_set_spend_limits',
1056
+ description: "Set the project's spend limit or this session's budget (per MCP connection or CLI run, not across them), in credits; null removes one. Lowering a limit is yours to do. Raising or removing one, the session budget included, needs the user's OK in chat first: without confirm it changes nothing and returns requires_confirm. Pass confirm=true only after the user says yes, never on your own.",
1057
+ input: z
1058
+ .object({
1059
+ projectId: z.string().uuid().optional().describe('Defaults to the open project.'),
1060
+ projectLimitCredits: SPEND_LIMIT.optional().describe('What this project may spend in all, by hand and by every agent.'),
1061
+ sessionBudgetCredits: SPEND_LIMIT.optional().describe('What this MCP connection or CLI run may spend.'),
1062
+ confirm: z.boolean().optional().describe("Set true only to relay the user's explicit OK to raise or remove a limit."),
1063
+ })
1064
+ .strict(),
1065
+ async run(input, ctx) {
1066
+ if (input.projectLimitCredits === undefined && input.sessionBudgetCredits === undefined) {
1067
+ throw new Error('Pass projectLimitCredits, sessionBudgetCredits or both.');
1068
+ }
1069
+ await ctx.desktop().requireCapability('spend-limits', 'spend limits');
1070
+ return ok(await ctx.desktop().post('/agent/spend-limits', input));
1071
+ },
1072
+ };
1010
1073
  export const getAsset = {
1011
1074
  id: 'slates_get_asset',
1012
1075
  description: 'One asset in full (UUID or badge code): its recorded prompt, model, settings and inputs, its source picture and linked clips, and how many clips and board shots use it. slates_list_assets rows are compact; read this before reusing or explaining one card.',
@@ -1091,6 +1154,156 @@ export const editAssetTranscript = {
1091
1154
  return ok(summary, `Saved: ${c.corrected} corrected, ${c.added} added, ${c.removed} removed.${r.recaptioned.length ? ` Remade ${r.recaptioned.length} caption clip${r.recaptioned.length === 1 ? '' : 's'}: ${r.recaptioned.join(', ')}.` : ''}`);
1092
1155
  },
1093
1156
  };
1157
+ // Cut by transcript (slate roadmap item 13): the desktop route is POST /agent/timeline/cut-transcript, the same
1158
+ // core as the transcript page's Cut (slate `src/main/editor/transcriptCut.ts`).
1159
+ export const cutByTranscript = {
1160
+ id: 'slates_cut_by_transcript',
1161
+ billable: false,
1162
+ description: "Cut words or pauses out of a video or audio clip on the timeline by its transcript, as Cut on the clip's Transcript page does: each stretch leaves the clip, which splits around it, and the gap closes (ripple), at the clip's own in point and speed. Name words by their index in slates_get_asset_transcript's words (from and to, inclusive), pauses by the index of the word each follows, or stretches of the file's own seconds. A word's cut reaches up to 60 ms before it and 100 ms after it into silence, never into a neighbouring word; a pause keeps 100 ms after the word before and 60 ms before the word after, so no word loses its first or last sound. The clip's linked sound and the captions heard from it are cut the same way; trackIds adds more lanes (a picture above it, a music bed) to keep in sync; linked false cuts only the clip's lane. Words an earlier cut left in later pieces are found there. Returns the clips written, ids deleted, durationFrames, each stretch cut in timeline seconds (latest first), removedSec, and timing: aligned words land within a frame or two, recognizer words within about a quarter second (transcribe again with force first). Free. Requires transcript-cut; update Slates on capability refusal.",
1163
+ input: z
1164
+ .object({
1165
+ projectId: z.string().uuid(),
1166
+ clipId: z.string().uuid().describe('The video or audio clip on the timeline whose words to cut.'),
1167
+ words: z.array(z.object({ from: z.number().int().min(0), to: z.number().int().min(0) }).strict()).min(1).optional()
1168
+ .describe("Runs of words to cut, by index in the asset's transcript words, from and to inclusive."),
1169
+ pauses: z.array(z.number().int().min(0)).min(1).optional().describe('Pauses to cut, each by the index of the word it follows.'),
1170
+ ranges: z.array(z.object({ startSec: z.number().min(0), endSec: z.number().min(0) }).strict()).min(1).optional()
1171
+ .describe("Stretches of the file's own seconds to cut, as the transcript counts them."),
1172
+ linked: z.boolean().optional().describe("False: cut only the clip's lane, not its linked sound's. Default true."),
1173
+ trackIds: z.array(z.string().uuid()).min(1).optional().describe('More lanes to cut and close up the same way, to keep them in sync.'),
1174
+ })
1175
+ .strict(),
1176
+ async run(input, ctx) {
1177
+ if (!input.words && !input.pauses && !input.ranges)
1178
+ throw new Error('Name words, pauses or ranges to cut.');
1179
+ await ctx.desktop().requireCapability('transcript-cut', 'cut by transcript');
1180
+ const r = await ctx.desktop().post('/agent/timeline/cut-transcript', input);
1181
+ const rough = r.timing === 'recognizer' ? " These words have the recognizer's rough timing: transcribe again with force for aligned edges." : '';
1182
+ return ok(r, `Cut ${r.cut.length} stretch${r.cut.length === 1 ? '' : 'es'}, ${r.removedSec.toFixed(2)} s in all; the timeline is now ${r.durationFrames} frames.${rough}`);
1183
+ },
1184
+ };
1185
+ // A music clip's beat grid (slate 1.6.4 plan step 3): the desktop routes are /agent/timeline/beats (GET reads,
1186
+ // POST finds), /agent/timeline/beats/edit and /agent/timeline/cut-to-beats, the same core as the Inspector's
1187
+ // Beat grid section (slate `src/main/beats/service.ts`, `src/main/editor/beatCuts.ts`).
1188
+ const beatTarget = {
1189
+ assetId: z.string().min(1).optional().describe('An audio or video asset: its code (AUD-A2) or id. Or name clipId.'),
1190
+ clipId: z.string().uuid().optional().describe('A clip on the timeline: the grid of its file, plus where each beat lands on the cut (onTimeline, in frames).'),
1191
+ };
1192
+ async function beatTargetBody(ctx, input) {
1193
+ if (input.clipId)
1194
+ return { projectId: input.projectId, clipId: input.clipId };
1195
+ if (!input.assetId)
1196
+ throw new Error('Name assetId or clipId.');
1197
+ return { projectId: input.projectId, assetId: (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id };
1198
+ }
1199
+ function beatGridWords(r) {
1200
+ if (!r.beats || !r.summary)
1201
+ return r.hint ?? 'No beat grid yet.';
1202
+ const s = r.summary;
1203
+ const spans = r.lowConfidence?.length ?? 0;
1204
+ const spots = spans ? ` ${spans} span${spans === 1 ? '' : 's'} to check (lowConfidence).` : '';
1205
+ const edits = r.edits?.length ? ` ${r.edits.length} hand edit${r.edits.length === 1 ? '' : 's'} kept.` : '';
1206
+ return `${s.bpm ?? '?'} BPM, ${s.beatsPerBar ?? '?'} beats a bar, ${s.beats} beats${s.tempoChanges ? ', the tempo changes' : ''}.${spots}${edits}${r.picture ? ` Picture: ${r.picture}` : ''}`;
1207
+ }
1208
+ export const getBeatGrid = {
1209
+ id: 'slates_get_beat_grid',
1210
+ description: "Read a music file's beat grid, to check it before cutting to it: every beat in the file's own seconds with its downbeat flag and a confidence from 0 to 1 (hand-placed beats read 1), a summary (BPM, beats a bar, the tempo sections, whether the tempo changes), lowConfidence (the spans to check: runs of unsure beats, and gaps where the tempo says a beat belongs) and the hand edits kept on it. With a clipId it also gives onTimeline: where each beat lands on the cut, in frames, at the clip's in point and speed. picture true saves a PNG of the grid over the waveform (downbeats bright with bar numbers, unsure beats amber) and returns its path; fromSec and toSec frame a stretch. Look at it to judge a span. Never finds beats: beats null with a hint means none yet (slates_find_beats, free). Fix a wrong beat with slates_edit_beat_grid. Requires beat-grid; update Slates on capability refusal.",
1211
+ input: z
1212
+ .object({
1213
+ projectId: z.string().uuid(),
1214
+ ...beatTarget,
1215
+ picture: z.boolean().optional().describe('Save a picture of the grid over the waveform and return its path.'),
1216
+ fromSec: z.number().min(0).optional().describe("The picture's first second, in the file's own time."),
1217
+ toSec: z.number().min(0).optional().describe("The picture's last second, in the file's own time."),
1218
+ })
1219
+ .strict(),
1220
+ async run(input, ctx) {
1221
+ await ctx.desktop().requireCapability('beat-grid', 'beat grids');
1222
+ const body = await beatTargetBody(ctx, input);
1223
+ const r = await ctx.desktop().get('/agent/timeline/beats', {
1224
+ ...body, ...(input.picture ? { picture: true } : {}), fromSec: input.fromSec, toSec: input.toSec,
1225
+ });
1226
+ return ok(r, `${beatGridWords(r)} ${JSON.stringify(r)}`);
1227
+ },
1228
+ };
1229
+ export const findBeats = {
1230
+ id: 'slates_find_beats',
1231
+ billable: false,
1232
+ description: "Find a music file's beats, downbeats and tempo on the user's machine, as Find beats in the clip's Inspector does. Free: it spends no credits and nothing leaves the machine. The first run downloads the beat model once (the result's downloadedModelMB says how much) and can take a few minutes; if the call times out, the desktop keeps working, so read slates_get_beat_grid before trying again. Hand edits already on the grid are kept and applied over the new beats. Returns the grid as slates_get_beat_grid does; read its lowConfidence spans before you cut. Requires beat-grid; update Slates on capability refusal.",
1233
+ input: z.object({ projectId: z.string().uuid(), ...beatTarget }).strict(),
1234
+ async run(input, ctx) {
1235
+ await ctx.desktop().requireCapability('beat-grid', 'finding beats');
1236
+ const r = await ctx.desktop().post('/agent/timeline/beats', await beatTargetBody(ctx, input));
1237
+ const model = r.downloadedModelMB ? ` Downloaded the ${r.downloadedModelMB} MB beat model first.` : '';
1238
+ return ok(r, `Found the beats.${model} ${beatGridWords(r)} ${JSON.stringify(r)}`);
1239
+ },
1240
+ };
1241
+ const beatEditInput = z.discriminatedUnion('kind', [
1242
+ z.object({ kind: z.literal('shift'), sec: z.number().describe('Seconds to move every beat; negative is earlier.') }).strict(),
1243
+ z.object({
1244
+ kind: z.literal('downbeat'),
1245
+ at: z.number().min(0).describe('The beat nearest this second starts a bar; the bars around it follow.'),
1246
+ beatsPerBar: z.number().int().min(1).max(16).optional().describe('Also set the meter, in beats a bar.'),
1247
+ }).strict(),
1248
+ z.object({
1249
+ kind: z.literal('tempo'),
1250
+ fromSec: z.number().min(0),
1251
+ toSec: z.number().min(0),
1252
+ bpm: z.number().min(30).max(300).describe('Lay beats at this tempo over the span, from the beat nearest fromSec (or fromSec itself).'),
1253
+ }).strict(),
1254
+ z.object({ kind: z.literal('add'), at: z.number().min(0), downbeat: z.boolean().optional() }).strict(),
1255
+ z.object({ kind: z.literal('move'), from: z.number().min(0).describe('The beat nearest this second moves...'), to: z.number().min(0).describe('...to this second.') }).strict(),
1256
+ z.object({ kind: z.literal('delete'), at: z.number().min(0).describe('The beat nearest this second goes.') }).strict(),
1257
+ ]);
1258
+ export const editBeatGrid = {
1259
+ id: 'slates_edit_beat_grid',
1260
+ billable: false,
1261
+ description: "Correct a music file's beat grid by hand, as the Beat grid controls in the clip's Inspector do: shift the whole grid (sec), set the downbeat (the beat at a second starts a bar; beatsPerBar sets the meter), lay a tempo over a span (fromSec, toSec, bpm; it works with no grid yet, so a known tempo needs no detection), or add, move or delete one beat. Times are the file's own seconds, as slates_get_beat_grid gives them; a beat is named by the nearest one within 0.15 s. Edits apply in order and are kept: finding the beats again never overwrites them. undo takes back the last edit; clearEdits drops them all. The marks on the clip and the snapping follow at once. Free. Returns the grid as slates_get_beat_grid does. Requires beat-grid; update Slates on capability refusal.",
1262
+ input: z
1263
+ .object({
1264
+ projectId: z.string().uuid(),
1265
+ ...beatTarget,
1266
+ edits: z.array(beatEditInput).min(1).optional().describe('Edits to apply, in order.'),
1267
+ undo: z.boolean().optional().describe('Take back the last hand edit.'),
1268
+ clearEdits: z.boolean().optional().describe('Drop every hand edit and show the found beats.'),
1269
+ })
1270
+ .strict(),
1271
+ async run(input, ctx) {
1272
+ if (!input.edits && !input.undo && !input.clearEdits)
1273
+ throw new Error('Send edits, undo: true or clearEdits: true.');
1274
+ await ctx.desktop().requireCapability('beat-grid', 'editing a beat grid');
1275
+ const r = await ctx.desktop().post('/agent/timeline/beats/edit', {
1276
+ ...(await beatTargetBody(ctx, input)),
1277
+ ...(input.undo ? { undo: true } : input.clearEdits ? { clearEdits: true } : { edits: input.edits }),
1278
+ });
1279
+ return ok(r, `Saved. ${beatGridWords(r)} ${JSON.stringify(r)}`);
1280
+ },
1281
+ };
1282
+ export const cutToBeats = {
1283
+ id: 'slates_cut_to_beats',
1284
+ billable: false,
1285
+ description: "Cut a lane to the music, so its cuts land on the beats of a music clip's grid. mode snap (default) rolls each existing cut on the lane (two clips that meet) to the nearest chosen beat within reachFrames (default half a beat), so the edit keeps its order and its length; mode split cuts the lane's clips at every chosen beat. on downbeat uses only the first beat of each bar; every 2 takes every second one; fromFrame and toFrame hold it to a stretch of the timeline. trackId names the lane (default: the first unlocked video lane with clips). Read the grid first (slates_get_beat_grid) and fix any lowConfidence span it lists, or cuts land on wrong beats. Returns the clips written, cuts (clipId, fromFrame, toFrame), skipped (each cut left where it was, and why) and beatFrames. Free. Requires beat-grid; update Slates on capability refusal.",
1286
+ input: z
1287
+ .object({
1288
+ projectId: z.string().uuid(),
1289
+ musicClipId: z.string().uuid().describe('The music clip on the timeline whose beats the cuts land on.'),
1290
+ trackId: z.string().uuid().optional().describe('The lane to cut. Default: the first unlocked video lane with clips.'),
1291
+ mode: z.enum(['snap', 'split']).optional().describe('snap: move the existing cuts onto beats (default). split: cut the clips at every chosen beat.'),
1292
+ on: z.enum(['beat', 'downbeat']).optional().describe('Every beat (default) or only downbeats.'),
1293
+ every: z.number().int().min(1).max(64).optional().describe('Use every Nth chosen beat. Default 1.'),
1294
+ fromFrame: z.number().min(0).optional().describe('Only beats from this timeline frame on.'),
1295
+ toFrame: z.number().min(0).optional().describe('Only beats up to this timeline frame.'),
1296
+ reachFrames: z.number().min(0).optional().describe('snap: how far a cut may move to reach a beat, in frames. Default half a beat.'),
1297
+ })
1298
+ .strict(),
1299
+ async run(input, ctx) {
1300
+ await ctx.desktop().requireCapability('beat-grid', 'cutting to the beat');
1301
+ const r = await ctx.desktop().post('/agent/timeline/cut-to-beats', input);
1302
+ const split = input.mode === 'split';
1303
+ const skipped = r.skipped.length ? ` ${r.skipped.length} left where ${r.skipped.length === 1 ? 'it was' : 'they were'}: ${r.skipped[0].reason}.` : '';
1304
+ return ok(r, `${split ? 'Cut at' : 'Moved'} ${r.cuts.length} ${split ? 'beat' : 'cut'}${r.cuts.length === 1 ? '' : 's'}${split ? '' : ' onto the beat'}.${skipped}`);
1305
+ },
1306
+ };
1094
1307
  export const extractVideoFrame = {
1095
1308
  id: 'slates_extract_video_frame',
1096
1309
  description: "Save one frame of a clip as a new picture in Media, as the clip card's camera does: at 'first', 'last' (default 'first') or a second. Free. The usual continuity move: extract a clip's last frame and use it as the next clip's first frame. To only look at a clip, use slates_get_asset_video_frames; this one adds a picture to the project.",
@@ -1523,7 +1736,8 @@ export const estimateGenerationCost = {
1523
1736
  // paid for on every turn of every session and read once — this is paid for
1524
1737
  // only by the call that is about to use the model.
1525
1738
  const skill = promptingSkillFor(input.model);
1526
- const card = describeCraftCard(skill);
1739
+ // From the user's brain: their My brain card for this model rides first when they wrote one (craft-cards.ts).
1740
+ const card = describeCraftCard(skill, brainSkills().skills[skill]);
1527
1741
  const banned = describeBannedTokensForSkill(skill);
1528
1742
  // Before the card on purpose: the desktop strips a repeated card by cutting
1529
1743
  // the text at "--- HOW TO PROMPT", and this line must survive that.
@@ -1873,7 +2087,7 @@ export const saveExternalImage = {
1873
2087
  };
1874
2088
  export const uploadReferenceImage = {
1875
2089
  id: 'slates_upload_reference_image',
1876
- description: 'Add a reference image, video clip, or audio file to a Slates project from disk. Pass either filePath (absolute path to a local file) or dataUrl (base64 data: URL) — exactly one. Set type:"video" to bring in a clip (the user\'s own footage to edit/relocate/trim) or type:"audio" for music/VO/SFX they already have; both are probed on ingest, so duration (and for video, dimensions) are available immediately, and audio gets its waveform. Default type is "image". dataUrl is image-only. Pass label to name it and note to record what it is; without them it is "Imported file". A picture derived from a project asset (edited, masked, upscaled or converted outside Slates) belongs in slates_save_external_image with referenceAssetIds, so its source and prompt are recorded.',
2090
+ description: 'Add a reference image, video clip, or audio file to a Slates project from disk. Pass either filePath (absolute path to a local file) or dataUrl (base64 data: URL) — exactly one. Set type:"video" to bring in a clip (the user\'s own footage to edit/relocate/trim) or type:"audio" for music/VO/SFX they already have; both are probed on ingest, so duration (and for video, dimensions) are available immediately, and audio gets its waveform. A camera clip the timeline cannot play smoothly (ProRes, HEVC, 4K, sparse keyframes) answers playableCopy {state:"making", percent}: the timeline plays that copy once it is made, while export and generation read the original, so nothing waits on it. Default type is "image". dataUrl is image-only. Pass label to name it and note to record what it is; without them it is "Imported file". A picture derived from a project asset (edited, masked, upscaled or converted outside Slates) belongs in slates_save_external_image with referenceAssetIds, so its source and prompt are recorded.',
1877
2091
  input: z
1878
2092
  .object({
1879
2093
  projectId: z.string().uuid(),
@@ -5074,13 +5288,18 @@ export const listGenerations = {
5074
5288
  const legacyExportCutsInput = z.object({ projectId: z.string().uuid(), directory: z.string(), manifestId: z.string().min(1),
5075
5289
  action: z.enum(['start', 'status', 'cancel']).optional().describe('start (default) begins, or re-attaches to a running export; status reads it; cancel stops after the output being rendered.'),
5076
5290
  items: z.array(z.object({ timelineId: z.string().uuid(), format: z.enum(['mp4', 'xml']) }).strict()).min(1).optional().describe('Required to start.') }).strict();
5291
+ // A pick from a cut's variant grid (desktop engine plan E3b; slate shared/variantSlots.ts normalizeVariantGridPick).
5292
+ const variantGridPicks = z.record(z.string().uuid(), z.array(z.string().uuid())).describe('Slot id to the alternative ids picked in it; a slot left out takes all its alternatives.');
5293
+ const variantGridAspects = z.array(deliveryAspectInput).min(1).describe("Delivery format ids; default the cut's own formats, else master.");
5077
5294
  const adCopyInput = z.object({ destinationUrl: z.string().optional(), primaryText: z.string().optional(), headline: z.string().optional(), cta: z.string().optional() }).strict();
5078
5295
  const batchExportCutsInput = z.object({
5079
5296
  version: z.literal(2).describe('Use version 2 with batchId and items for delivery-format batches. Omit version for legacy directory/manifestId requests.'),
5080
5297
  projectId: z.string().uuid(), batchId: z.string().min(1).describe('Required for version 2. Reuse this id and the same items to reattach or retry.'),
5081
5298
  exportRoot: z.string().optional().describe('Optional export root; the desktop remembers it and creates a fresh batch folder.'),
5082
5299
  items: z.array(z.object({ timelineId: z.string().uuid(), aspects: z.array(deliveryAspectInput).min(1).optional(),
5083
- formats: z.array(z.enum(['mp4', 'xml'])).min(1).optional(), taxonomy: taxonomyInput.optional() }).strict()).min(1),
5300
+ formats: z.array(z.enum(['mp4', 'xml'])).min(1).optional(), taxonomy: taxonomyInput.optional() }).strict()),
5301
+ variants: z.object({ timelineId: z.string().uuid().describe('The cut with the slots, or any timeline of its family.'), picks: variantGridPicks.optional(), aspects: variantGridAspects.optional() }).strict()
5302
+ .describe('A grid pick to export: each combination gets a variant row if it has none, and every variant exports in every format, beside any items. Requires variant-grid.').optional(),
5084
5303
  copy: adCopyInput.optional().describe('User-entered batch ad copy and destination defaults. Omission leaves them empty; never copy script or video text here.'),
5085
5304
  outputCopy: z.record(adCopyInput).optional().describe('Per-output ad copy overrides keyed by the desktop receipt output key.'),
5086
5305
  }).strict();
@@ -5090,15 +5309,17 @@ const exportCutsInput = z.object({
5090
5309
  ...legacyExportCutsInput.partial().shape,
5091
5310
  ...batchExportCutsInput.partial().shape,
5092
5311
  projectId: z.string().uuid(),
5093
- items: z.array(z.union([batchExportCutsInput.shape.items.element, legacyExportCutsInput.shape.items.unwrap().element])).min(1).optional().describe('Required for version 2 start/retry and legacy start. Version 2 selects existing timelineIds with aspects/formats/taxonomy; legacy selects timelineId/format.'),
5312
+ items: z.array(z.union([batchExportCutsInput.shape.items.element, legacyExportCutsInput.shape.items.unwrap().element])).optional().describe('Required for version 2 start/retry (may be [] beside variants) and legacy start. Version 2 selects existing timelineIds with aspects/formats/taxonomy; legacy selects timelineId/format.'),
5094
5313
  }).strict().superRefine((input, ctx) => {
5095
5314
  const parsed = (input.version === 2 ? batchExportCutsInput : legacyExportCutsInput).safeParse(input);
5096
5315
  if (!parsed.success)
5097
5316
  for (const issue of parsed.error.issues)
5098
5317
  ctx.addIssue(issue);
5318
+ if (input.items?.length === 0 && !(input.version === 2 && input.variants))
5319
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['items'], message: 'items needs at least one cut, unless version 2 names variants' });
5099
5320
  });
5100
5321
  export const exportCuts = {
5101
- id: 'slates_export_cuts', description: 'Start or retry a background export of existing named cuts to local files without generating media or spending credits. Version 2 selects cuts × delivery aspects from slates_get_variant_grid and returns batchId, manifestPath and frozen named outputs immediately; poll slates_get_export_batch. Repeating the same batchId and selection reattaches or retries unfinished outputs; completed files are checked and never overwritten. Naming, delivery and provenance are frozen by the desktop. CSV contains completed MP4s only and is unverified against a live Meta import. Missing takes are reported per cut, never filled. Version 2 requires ad-variant-export; update Slates on capability refusal. Legacy directory/manifestId/items/action requests remain supported. For one cut, slates_export_video is enough.',
5322
+ id: 'slates_export_cuts', description: 'Start or retry a background export of existing named cuts to local files without generating media or spending credits. Version 2 selects cuts × delivery aspects from slates_get_variant_grid and returns batchId, manifestPath and frozen named outputs immediately; poll slates_get_export_batch. Version 2 with variants (a pick read through slates_get_variants grid) and items [] exports every variant of a cut\'s slots in every picked format in one request, adding the rows a combination lacks: one body and ten hooks in four formats is forty named files. Each variant\'s picture is joined from parts rendered once per format and kept, so a shared body renders once and an unchanged export again renders nothing; an output cut at a seam carries segments (parts, reused), and one that rendered whole says why. Variants requires variant-grid. Repeating the same batchId and selection reattaches or retries unfinished outputs; completed files are checked and never overwritten. Naming, delivery and provenance are frozen by the desktop. CSV contains completed MP4s only and is unverified against a live Meta import. Missing takes are reported per cut, never filled. Version 2 requires ad-variant-export; update Slates on capability refusal. Legacy directory/manifestId/items/action requests remain supported. For one cut, slates_export_video is enough.',
5102
5323
  billable: false,
5103
5324
  input: exportCutsInput,
5104
5325
  async run(input, ctx) {
@@ -5106,6 +5327,8 @@ export const exportCuts = {
5106
5327
  await desktop.requireCapability('named-cuts', 'named cuts');
5107
5328
  if (input.version === 2)
5108
5329
  await desktop.requireCapability('ad-variant-export', 'ad variant batch export and retry');
5330
+ if (input.variants !== undefined)
5331
+ await desktop.requireCapability('variant-grid', 'exporting a variant grid pick');
5109
5332
  return ok(await desktop.post('/agent/timeline/export-cuts', input));
5110
5333
  },
5111
5334
  };
@@ -5131,7 +5354,7 @@ export const cancelExportBatch = {
5131
5354
  },
5132
5355
  };
5133
5356
  export const getVariantGrid = {
5134
- id: 'slates_get_variant_grid', description: 'Read the variant grid of existing named cuts, recorded slot choices, missing takes and delivery format ids with actual dimensions. Shows absent combinations without creating them; missing-take prices are local quotes, never generation requests. Select existing timelineIds and returned aspects for slates_export_cuts. Requires ad-variant-export; update Slates on capability refusal.',
5357
+ id: 'slates_get_variant_grid', description: 'Read the variant grid of existing named cuts, recorded slot choices, missing takes and delivery format ids with actual dimensions. Shows absent combinations without creating them; missing-take prices are local quotes, never generation requests. Select existing timelineIds and returned aspects for slates_export_cuts. For a cut\'s slots (hooks, body, end card) crossed with formats, read slates_get_variants with grid. Requires ad-variant-export; update Slates on capability refusal.',
5135
5358
  billable: false,
5136
5359
  input: z.object({ projectId: z.string().uuid() }).strict(),
5137
5360
  async run(input, ctx) {
@@ -5139,6 +5362,103 @@ export const getVariantGrid = {
5139
5362
  return ok(await ctx.desktop().get('/agent/timeline/variant-grid', input));
5140
5363
  },
5141
5364
  };
5365
+ // Ad variants on one shared body (desktop engine plan E3b; the design heads slate's main/editor/variants.ts).
5366
+ // The desktop's normalizeSeamSetting (slate shared/variantSlots.ts): frames 1 to 600 for j, l and crossfade; a cut takes none.
5367
+ const seamSetting = z.union([
5368
+ z.literal('auto'),
5369
+ z.object({ kind: z.literal('cut'), frames: z.number().optional() }).strict(),
5370
+ z.object({ kind: z.enum(['j', 'l', 'crossfade']), frames: z.number().int().min(1).max(600) }).strict(),
5371
+ ]).describe("'auto' for the automatic pick, { kind: 'cut' }, or { kind, frames } with frames 1 to 600: j (the next slot's sound leads by frames), l (this slot's sound runs on), crossfade (its length).");
5372
+ const variantChoices = z.record(z.string().uuid(), z.string().uuid()).describe('Slot id to alternative id. A slot left out plays its first alternative.');
5373
+ const variantSeams = z.record(z.string().uuid(), seamSetting).describe('Keyed by the slot AFTER the seam.');
5374
+ const getVariantsInput = z.object({
5375
+ projectId: z.string().uuid(),
5376
+ timelineId: z.string().uuid(),
5377
+ grid: z.object({ picks: variantGridPicks.optional(), aspects: variantGridAspects.optional() }).strict().optional()
5378
+ .describe("Add the grid for this pick: {} for every alternative in the cut's formats. Requires variant-grid."),
5379
+ }).strict();
5380
+ export const getVariants = {
5381
+ id: 'slates_get_variants',
5382
+ description: "Read a cut's ad variants: hooks, a shared body and an end card as slots laid end to end, each slot's alternatives (each a timeline: sequenceId, its length), and the variant rows, one alternative per slot, each built into an ordinary timeline (cutId) with its seams (J-cut, L-cut, crossfade or cut, who picked it and why, and what the media held back) and its state: current, edited by hand and left alone, or unbuilt, with behind once its sources changed since its timeline was built. The cut's own lanes are the bed under every variant. Any timeline of the family answers: the cut, a slot's sequence or a variant's timeline. With grid, it adds the grid for a pick of alternatives per slot and of delivery formats: each combination (name, variantId and cutId, null when no row has it yet), files (combinations × formats), the formats offered with their sizes, and missingTakes (shotIds of intended takes the picked alternatives lack; credits, what making them bills in all, the figure to quote; costs, dollars per take request; both null when unpriceable; the grid never generates). Export that pick with slates_export_cuts variants. Reading writes nothing: a behind variant catches up when its timeline is opened (slates_get_timeline) or exported, after any slates_edit_variant_slots or slates_edit_variants call, and on rebuild, which also drops hand edits. Requires ad-variants; update Slates on capability refusal.",
5383
+ billable: false,
5384
+ input: getVariantsInput,
5385
+ async run(input, ctx) {
5386
+ const desktop = ctx.desktop();
5387
+ await desktop.requireCapability('ad-variants', 'ad variants on one shared body');
5388
+ const { grid, ...ids } = input;
5389
+ if (grid === undefined)
5390
+ return ok(await desktop.get('/agent/timeline/variants', ids));
5391
+ await desktop.requireCapability('variant-grid', 'the variant grid: combinations, files and missing takes');
5392
+ return ok(withGridCredits(await desktop.get('/agent/timeline/variants', { ...ids, grid: true,
5393
+ picks: grid.picks === undefined ? undefined : JSON.stringify(grid.picks), aspects: grid.aspects?.join(',') })));
5394
+ },
5395
+ };
5396
+ /** The grid's missing takes in credits. A desktop before slate 9f9b9ea sends only `costs`, dollars per request,
5397
+ * so their credits are summed here, each request rounded alone as it bills. */
5398
+ function withGridCredits(answer) {
5399
+ const takes = answer?.grid?.missingTakes;
5400
+ if (takes && takes.credits === undefined) {
5401
+ takes.credits = Array.isArray(takes.costs) ? takes.costs.reduce((sum, cost) => sum + creditsFromDollars(cost), 0) : null;
5402
+ }
5403
+ return answer;
5404
+ }
5405
+ const variantSlotsInput = z.object({
5406
+ projectId: z.string().uuid(),
5407
+ action: z.enum(['add', 'update', 'remove', 'add-alternative', 'update-alternative', 'remove-alternative']),
5408
+ timelineId: z.string().uuid().optional().describe('The cut: for add, and for add-alternative with slotName instead of slotId.'),
5409
+ slotId: z.string().uuid().optional().describe('For update, remove and add-alternative.'),
5410
+ slotName: z.string().min(1).max(80).optional().describe('add-alternative without slotId: makes this slot first.'),
5411
+ alternativeId: z.string().uuid().optional().describe('For update-alternative and remove-alternative.'),
5412
+ name: z.string().min(1).max(80).optional().describe("A slot's or an alternative's name. Defaults: Hook, Body, End card; '<slot> 1'."),
5413
+ at: z.number().int().min(0).optional().describe('add: the position among the slots.'),
5414
+ orderIndex: z.number().int().min(0).optional().describe('update or update-alternative: move it to this position.'),
5415
+ bedFrame: z.number().int().min(0).nullable().optional().describe("update: the bed frame this slot's first frame meets in every variant (one slot per cut); null clears it."),
5416
+ clipIds: z.array(z.string().uuid()).min(1).optional().describe('add-alternative: move these clips (and their linked sound) off the cut into a new sequence; what stays is the bed.'),
5417
+ sequenceId: z.string().uuid().optional().describe('add-alternative: an existing timeline of this project to hold as it is.'),
5418
+ }).strict();
5419
+ export const editVariantSlots = {
5420
+ id: 'slates_edit_variant_slots',
5421
+ description: "Add, rename, move or remove a cut's ad-variant slots (hook, body, end card: names, never types) and their alternatives, as the Ad variants view in the Inspector does. add-alternative with clipIds collapses those clips off the cut into a new nested sequence, so the body exists once and a fix to it shows in every variant; the first slot made from clips, or one named Body, anchors the bed where its clips sat. Without clipIds or sequenceId it makes an empty sequence to fill with slates_add_clip_to_timeline (its sequenceId is the timelineId). Removing an alternative also removes the variant rows that pick it (removedVariantIds), each with its timeline unless edited by hand; removing a slot drops each row's pick for it. A removed slot's or alternative's own sequence stays, as an ordinary cut. Every unedited variant rebuilds after. Returns the whole set as slates_get_variants does, with the new slotId or alternativeId. Requires ad-variants; update Slates on capability refusal.",
5422
+ billable: false,
5423
+ input: variantSlotsInput,
5424
+ async run(input, ctx) {
5425
+ await ctx.desktop().requireCapability('ad-variants', 'ad variants on one shared body');
5426
+ return ok(await ctx.desktop().post('/agent/timeline/variant-slots', input));
5427
+ },
5428
+ };
5429
+ const variantsInput = z.object({
5430
+ projectId: z.string().uuid(),
5431
+ action: z.enum(['add', 'update', 'remove', 'rebuild']),
5432
+ timelineId: z.string().uuid().optional().describe('add: the cut with the slots.'),
5433
+ variantId: z.string().uuid().optional().describe('update, remove and rebuild.'),
5434
+ combinations: z.boolean().optional().describe("add: one row per combination of the slots' alternatives not already a row."),
5435
+ rows: z.array(z.object({ name: z.string().min(1).max(80).optional(), choices: variantChoices.optional(), seams: variantSeams.optional() }).strict()).optional().describe('add: the rows to add; omit for one row of first alternatives.'),
5436
+ name: z.string().min(1).max(80).optional().describe('update: the row and its timeline take it.'),
5437
+ choices: variantChoices.optional().describe('update: merged into the row.'),
5438
+ seams: variantSeams.optional().describe("update: merged; 'auto' gives a seam back to the automatic pick."),
5439
+ }).strict();
5440
+ export const editVariants = {
5441
+ id: 'slates_edit_variants',
5442
+ description: "Add, change, rebuild or remove ad variant rows on a cut's slots, as the Ad variants view does. Each row picks one alternative per slot and is built into an ordinary timeline (cutId), named for ad export, ready for slates_export_cuts. Seams: the picture always cuts where slots meet; the sound is picked from the transcripts (L-cut when the outgoing line runs past its picture, J-cut when the next slot opens on speech, a short crossfade when both sides have sound on audio lanes, else a cut, a picture cut over the bed with no dialogue), or set by hand per seam; either way held to the media past the cut, with the reason in the result. A row's timeline catches up with its sources when opened, exported or after any slot or row action, unless edited by hand; rebuild takes the sources and drops the hand edits. remove deletes the row and its timeline unless edited by hand. Returns the whole set and the new variantIds. Requires ad-variants; update Slates on capability refusal.",
5443
+ billable: false,
5444
+ input: variantsInput,
5445
+ async run(input, ctx) {
5446
+ await ctx.desktop().requireCapability('ad-variants', 'ad variants on one shared body');
5447
+ return ok(await ctx.desktop().post('/agent/timeline/variants', input));
5448
+ },
5449
+ };
5450
+ export const getRecipe = {
5451
+ id: 'slates_get_recipe', description: 'Find what made an exported ad from its recipe ID, its full ad name or its file name (anything holding __r-<id>). Returns every export that carried the recipe (batch, export time, ad name, files per format, the timeline id and name, its taxonomy); then each clip with its timing and asset and, when generated, the model, prompt, references and key settings frozen at export, and the Shot and board it came from (Shot, board and asset names and labels are read as they are now, not frozen); then any timeline that still renders the recipe. Searches every project unless projectId is given. When nothing matches, notFound says why: exported before ad names carried a recipe ID, or the timeline changed and its export folder is unreachable. Read-only; never generates or spends. Requires recipe-lookup; update Slates on capability refusal.',
5452
+ billable: false,
5453
+ input: z.object({
5454
+ recipe: z.string().min(1).describe('The recipe ID (the characters after __r-), or a whole ad name, file name or path containing __r-<id>.'),
5455
+ projectId: z.string().uuid().optional().describe('Search only this project; omit to search every project.'),
5456
+ }).strict(),
5457
+ async run(input, ctx) {
5458
+ await ctx.desktop().requireCapability('recipe-lookup', 'looking up the recipe behind an exported ad');
5459
+ return ok(await ctx.desktop().get('/agent/timeline/recipe', input));
5460
+ },
5461
+ };
5142
5462
  const reframeReportInput = z.object({ projectId: z.string().uuid(), timelineId: z.string().uuid(), aspect: deliveryAspectInput, clipId: z.string().uuid().optional() }).strict();
5143
5463
  export const getReframeReport = {
5144
5464
  id: 'slates_get_reframe_report', description: 'Inspect effective delivery framing, computed dimensions, kept frame percentage, upscale and stale-take or missing-media warnings for a cut or one clip. Read before reframing; warnings never trigger generation or disable export. Requires ad-variant-export; update Slates on capability refusal.',
@@ -5152,18 +5472,23 @@ export const getReframeReport = {
5152
5472
  const reframeClipInput = reframeReportInput.extend({ clipId: z.string().uuid(), framing: z.object({
5153
5473
  mode: z.enum(['fill', 'fit']).optional(), focusX: z.number().min(0).max(1).optional(),
5154
5474
  focusY: z.number().min(0).max(1).optional(), zoom: z.number().min(1).optional(),
5155
- }).strict().nullable().describe('Normalized focus and zoom for this clip/aspect. Null resets the override; the desktop binds it to the current take.') });
5475
+ }).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.'),
5476
+ follow: z.enum(['face', 'off']).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); "off" removes those keys. Runs on the computer and spends nothing.') });
5156
5477
  export const reframeClip = {
5157
- 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. Requires ad-variant-export; update Slates on capability refusal.',
5478
+ 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 (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.',
5158
5479
  billable: false,
5159
5480
  input: reframeClipInput,
5160
5481
  async run(input, ctx) {
5161
5482
  await ctx.desktop().requireCapability('ad-variant-export', 'clip delivery reframing');
5483
+ if (input.follow)
5484
+ await ctx.desktop().requireCapability('reframe-follow', 'following a face');
5485
+ else if (input.framing === undefined)
5486
+ throw new Error('Send framing (null resets it) or follow');
5162
5487
  return ok(await ctx.desktop().post('/agent/timeline/reframe', input));
5163
5488
  },
5164
5489
  };
5165
5490
  export const listTimelines = {
5166
- id: 'slates_list_timelines', description: 'List the independent named cuts in a project. Use the selected timelineId for edits, builds and exports.',
5491
+ 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.",
5167
5492
  input: z.object({ projectId: z.string().uuid() }),
5168
5493
  async run(input, ctx) {
5169
5494
  await ctx.desktop().requireCapability('named-cuts', 'named cuts');
@@ -5212,9 +5537,63 @@ export const getTimeline = {
5212
5537
  JSON.stringify(r, null, 2));
5213
5538
  },
5214
5539
  };
5540
+ const loudnessInput = z.object({
5541
+ projectId: z.string().uuid(),
5542
+ timelineId: z.string().uuid().optional().describe("The cut to measure; absent: the project's default timeline."),
5543
+ fromSec: z.number().min(0).optional().describe('Measure from here (timeline seconds), as if the span were exported alone.'),
5544
+ toSec: z.number().positive().optional().describe('Measure to here (timeline seconds); absent: the end.'),
5545
+ trackId: z.string().min(1).optional().describe('Read this one lane alone (with the mix); absent: every lane heard.'),
5546
+ });
5547
+ export const getTimelineLoudness = {
5548
+ id: 'slates_get_timeline_loudness',
5549
+ description: "Measure a timeline's loudness as its export writes it: integrated LUFS (gated, ITU-R BS.1770), loudness range (LRA, LU), " +
5550
+ 'true peak (dBTP, read 4x oversampled) and sample peak of the whole mix, the same for each lane alone (every other lane muted), ' +
5551
+ 'and a short-term (3 s) and momentary (400 ms) reading per second in `mix.trace`. Read-only: the desktop renders the sound to a ' +
5552
+ 'temporary file and measures it; nothing is saved and nothing is spent. Check a mix against its bar before exporting: a short for ' +
5553
+ 'social is -14 LUFS integrated with a true peak of -1 dBTP or under (`target` in the answer, shown, never enforced). To move the ' +
5554
+ 'integrated level by D dB, multiply masterVolume by 10^(D/20) with slates_update_timeline_settings, then measure again and check the ' +
5555
+ 'true peak. fromSec and toSec measure one span alone; trackId reads one lane. Null means silence, or a span too short (range and ' +
5556
+ "short-term need 3 s). Same numbers as the Output level popover's Measure. Requires the desktop's loudness capability; update Slates on refusal.",
5557
+ billable: false,
5558
+ input: loudnessInput,
5559
+ async run(input, ctx) {
5560
+ const desktop = ctx.desktop();
5561
+ await desktop.requireCapability('loudness', 'the loudness meter');
5562
+ await requireNamedCut(desktop, input.timelineId);
5563
+ const r = await desktop.get('/agent/timeline/loudness', input);
5564
+ const show = (n, unit) => (n == null ? '-' : `${n} ${unit}`);
5565
+ const lanes = (r.lanes ?? []).map((l) => `${l.name} ${show(l.integratedLufs, 'LUFS')}`).join(', ');
5566
+ return ok(r, `Mix: ${show(r.mix?.integratedLufs, 'LUFS')} integrated, range ${show(r.mix?.loudnessRangeLu, 'LU')}, true peak ${show(r.mix?.truePeakDbtp, 'dBTP')} ` +
5567
+ `(target ${r.target?.integratedLufs ?? '?'} LUFS, ${r.target?.truePeakDbtp ?? '?'} dBTP).${lanes ? ` Lanes: ${lanes}.` : ''}\n\n` +
5568
+ JSON.stringify(r, null, 2));
5569
+ },
5570
+ };
5571
+ // ── Sound to the sample (music edits between frames) ───────────
5572
+ // Mirrors of slate's limits, held equal by lockstep check 12: the rate a sound clip set to the sample counts
5573
+ // its file in (`AUDIO_SOURCE_FPS`, src/shared/clipTiming.ts), the crossfade's millisecond range and curves
5574
+ // (src/shared/transitions.ts) and the export's sound bitrates (src/shared/audioBitrate.ts).
5575
+ const SOUND_SAMPLE_RATE = 48000;
5576
+ const SOUND_CROSSFADE_MS = { min: 1, max: 10000 };
5577
+ const SOUND_CURVES = ['equal-power', 'linear'];
5578
+ const AUDIO_BITRATES = [128, 192, 256, 320];
5579
+ const AUDIO_BITRATE_DEFAULT = 320;
5580
+ const audioBitrateInput = z.union(AUDIO_BITRATES.map((kbps) => z.literal(kbps)));
5581
+ const soundEdgesInput = {
5582
+ startSec: z.number().min(0).optional().describe('Audio lane: where its sound starts on the timeline, in seconds to the sample; it may fall between frames.'),
5583
+ sourceInSec: z.number().min(0).optional().describe('Audio lane: where in its file the sound starts, in seconds, to the sample.'),
5584
+ sourceOutSec: z.number().positive().optional().describe('Audio lane: where in its file the sound ends, in seconds, to the sample.'),
5585
+ sourceInSample: z.number().int().min(0).optional().describe(`The media in as a sample count at ${SOUND_SAMPLE_RATE} Hz, instead of sourceInSec.`),
5586
+ sourceOutSample: z.number().int().positive().optional().describe(`The media out as a sample count at ${SOUND_SAMPLE_RATE} Hz, instead of sourceOutSec.`),
5587
+ };
5588
+ const SOUND_EDGE_FIELDS = Object.keys(soundEdgesInput);
5589
+ const asksSoundEdges = (input) => SOUND_EDGE_FIELDS.some((field) => input[field] !== undefined);
5590
+ /** An older desktop drops the fields and keeps the clip on its frames; this one refuses instead. */
5591
+ async function requireSoundPrecision(desktop) {
5592
+ await desktop.requireCapability('sound-precision', 'sound edges to the sample, millisecond crossfades and the sound bitrate');
5593
+ }
5215
5594
  export const addClipToTimeline = {
5216
5595
  id: 'slates_add_clip_to_timeline',
5217
- description: "Append a video or audio asset from the project to the project's timeline (or place it at an explicit startFrame). Defaults match the desktop UI: video clips go to the end of the first video track; audio clips (music, voiceover, AI audio) go after the last clip on the first AUDIO track and are mixed under the video on export. An empty timeline auto-adopts the first video clip's resolution and frame rate; later higher-resolution clips raise the canvas. Overlapping video clips resolve top-track-wins. Optionally trim with sourceInFrame/sourceOutFrame (frames at the SOURCE fps). Use slates_get_timeline first to see current clips and pick positions. To lay a board's chosen clips in board order, use slates_edit_cut (build) instead.",
5596
+ description: "Append a video or audio asset from the project to the project's timeline (or place it at an explicit startFrame). Defaults match the desktop UI: video clips go to the end of the first video track; audio clips (music, voiceover, AI audio) go after the last clip on the first AUDIO track and are mixed under the video on export. An empty timeline auto-adopts the first video clip's resolution and frame rate; later higher-resolution clips raise the canvas. Overlapping video clips resolve top-track-wins. Optionally trim with sourceInFrame/sourceOutFrame (frames at the SOURCE fps). An audio asset may instead take startSec, sourceInSec and sourceOutSec (or sourceInSample/sourceOutSample) to the sample, for a music edit between frames; with no startSec it starts where the lane's last sound ends, so clips appended in turn butt exactly. Use slates_get_timeline first to see current clips and pick positions. To lay a board's chosen clips in board order, use slates_edit_cut (build) instead.",
5218
5597
  input: z.object({
5219
5598
  projectId: z.string().uuid(), timelineId: z.string().uuid().optional(),
5220
5599
  assetId: z.string().uuid().describe('Video or audio asset already in the project.'),
@@ -5222,11 +5601,18 @@ export const addClipToTimeline = {
5222
5601
  startFrame: z.number().int().min(0).optional().describe('Timeline frame to place the clip at. Default: append after the last clip.'),
5223
5602
  sourceInFrame: z.number().int().min(0).optional(),
5224
5603
  sourceOutFrame: z.number().int().min(1).optional(),
5604
+ ...soundEdgesInput,
5225
5605
  }),
5226
5606
  async run(input, ctx) {
5227
5607
  const desktop = ctx.desktop();
5228
5608
  await desktop.requireCapability('timeline', 'timeline editing');
5229
5609
  await requireNamedCut(desktop, input.timelineId);
5610
+ const precise = asksSoundEdges(input);
5611
+ if (precise && (input.startFrame !== undefined || input.sourceInFrame !== undefined || input.sourceOutFrame !== undefined)) {
5612
+ throw new Error("Send the clip's edges in frames or in seconds and samples, not both.");
5613
+ }
5614
+ if (precise)
5615
+ await requireSoundPrecision(desktop);
5230
5616
  const r = await desktop.post('/agent/timeline/add-clip', {
5231
5617
  projectId: input.projectId, timelineId: input.timelineId,
5232
5618
  assetId: input.assetId,
@@ -5234,6 +5620,7 @@ export const addClipToTimeline = {
5234
5620
  startFrame: input.startFrame,
5235
5621
  sourceInFrame: input.sourceInFrame,
5236
5622
  sourceOutFrame: input.sourceOutFrame,
5623
+ ...Object.fromEntries(SOUND_EDGE_FIELDS.map((field) => [field, input[field]])),
5237
5624
  });
5238
5625
  const clip = r.clip ?? {};
5239
5626
  // Code + label for the chat reference: prefer fields on the clip, fall
@@ -5288,10 +5675,12 @@ const transitionShape = {
5288
5675
  durationSec: z.number().positive().optional().describe('The same, in seconds.'),
5289
5676
  alignment: z.enum(['center', 'start', 'end']).optional().describe('center (default) straddles the cut; start begins at the cut; end finishes at it.'),
5290
5677
  params: z.record(z.string(), z.unknown()).optional().describe("The kind's settings. freeze: true holds the edge frame where the media runs short. On a picture transition, audio: false stops the clips' sound crossfading with it."),
5678
+ durationMs: z.number().min(SOUND_CROSSFADE_MS.min).max(SOUND_CROSSFADE_MS.max).optional().describe(`Audio lane: the crossfade's length in milliseconds (${SOUND_CROSSFADE_MS.min} to ${SOUND_CROSSFADE_MS.max}), placed to the sample, so it may be shorter than a frame. Instead of durationFrames or durationSec.`),
5679
+ curve: z.enum(SOUND_CURVES).optional().describe("Audio lane: 'equal-power' (default) for two different sounds, 'linear' (straight lines, a triangular crossfade) for a join inside one piece of music."),
5291
5680
  };
5292
5681
  export const addTransition = {
5293
5682
  id: 'slates_add_transition',
5294
- description: "Put a transition (dissolve, wipe, crossfade and the other kinds) on a cut between two clips that meet on one lane, as the Cut's clip menu does. Name the cut by fromClipId and toClipId, or by one clipId and side ('end' runs this clip into the next, 'start' the last clip into this one). A cut holds one transition, so adding where one exists changes it. It never refuses short media: the result's shortHandles says how many frames are missing and offers the fixes (slates_update_transition fix: freeze or shorten). For a fade to or from black, set the clip's fades with slates_update_clip instead. The open Cut shows the change.",
5683
+ description: "Put a transition (dissolve, wipe, crossfade and the other kinds) on a cut between two clips that meet on one lane, as the Cut's clip menu does. Name the cut by fromClipId and toClipId, or by one clipId and side ('end' runs this clip into the next, 'start' the last clip into this one). A cut holds one transition, so adding where one exists changes it. It never refuses short media: the result's shortHandles says how many frames are missing and offers the fixes (slates_update_transition fix: freeze or shorten). On an audio lane, durationMs sets a crossfade to the millisecond and curve how the sounds cross: a 10 ms linear crossfade with alignment 'end' joins two cuts of one song as a triangular crossfade does. For a fade to or from black, set the clip's fades with slates_update_clip instead. The open Cut shows the change.",
5295
5684
  input: z.object({
5296
5685
  projectId: z.string().uuid(),
5297
5686
  fromClipId: z.string().uuid().optional().describe('The clip before the cut.'),
@@ -5305,12 +5694,14 @@ export const addTransition = {
5305
5694
  await desktop.requireCapability('timeline-transitions', 'transitions');
5306
5695
  if (!input.fromClipId && !input.toClipId && !input.clipId)
5307
5696
  throw new Error('Name the cut: fromClipId and toClipId, or clipId with side.');
5697
+ if (input.durationMs !== undefined || input.curve !== undefined)
5698
+ await requireSoundPrecision(desktop);
5308
5699
  return ok(await desktop.post('/agent/timeline/add-transition', input));
5309
5700
  },
5310
5701
  };
5311
5702
  export const updateTransition = {
5312
5703
  id: 'slates_update_transition',
5313
- description: "Change a transition's kind, length, alignment or settings by its id (slates_get_timeline lists them under transitions), or apply one of the two fixes for short media: fix 'freeze' holds the edge frame for the missing frames, fix 'shorten' cuts it to the longest the media covers. Only the fields you name change. Returns the transition with its span and any frames still missing.",
5704
+ description: "Change a transition's kind, length, alignment or settings by its id (slates_get_timeline lists them under transitions), or apply one of the two fixes for short media: fix 'freeze' holds the edge frame for the missing frames, fix 'shorten' cuts it to the longest the media covers. Only the fields you name change; on an audio lane durationMs and curve set a crossfade to the millisecond, and a length in frames or seconds replaces one in milliseconds. Returns the transition with its span (durationSec, curve) and any frames still missing.",
5314
5705
  input: z.object({
5315
5706
  projectId: z.string().uuid(),
5316
5707
  transitionId: z.string().uuid(),
@@ -5320,6 +5711,8 @@ export const updateTransition = {
5320
5711
  async run(input, ctx) {
5321
5712
  const desktop = ctx.desktop();
5322
5713
  await desktop.requireCapability('timeline-transitions', 'transitions');
5714
+ if (input.durationMs !== undefined || input.curve !== undefined)
5715
+ await requireSoundPrecision(desktop);
5323
5716
  return ok(await desktop.post('/agent/timeline/update-transition', input));
5324
5717
  },
5325
5718
  };
@@ -5375,9 +5768,42 @@ export const editTimelineClips = {
5375
5768
  return ok(await desktop.post('/agent/timeline/split-clip', body));
5376
5769
  },
5377
5770
  };
5771
+ const keyframeEasing = z.union([
5772
+ z.enum(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'hold']),
5773
+ z.object({ cubicBezier: z.tuple([z.number().min(0).max(1), z.number(), z.number().min(0).max(1), z.number()]) }).strict(),
5774
+ ]);
5775
+ const keyframeKeys = z.array(z
5776
+ .object({
5777
+ frame: z.number().finite().min(0).describe("Frames from the clip's start, at the timeline's frame rate; may fall between frames, read at that exact time (110.4 is 4.6 s at 24 fps)."),
5778
+ value: z.number().finite(),
5779
+ easing: keyframeEasing.optional().describe('The curve from this key to the next. Default linear; hold jumps at the next key.'),
5780
+ })
5781
+ .strict());
5782
+ const keyframeList = keyframeKeys.max(500);
5783
+ /** Any key off a whole frame, in any of these key lists or effect lists' keys. */
5784
+ function keysBetweenFrames(...lists) {
5785
+ return lists.some((list) => (list ?? []).some((item) => 'frame' in item ? !Number.isInteger(item.frame) : Object.values(item.keyframes ?? {}).some((keys) => keys.some((k) => !Number.isInteger(k.frame)))));
5786
+ }
5787
+ /** An older desktop refuses a key that is not a whole frame; ask first, so the refusal names the update. */
5788
+ async function requireKeysBetweenFrames(desktop, ...lists) {
5789
+ if (keysBetweenFrames(...lists))
5790
+ await desktop.requireCapability('keys-between-frames', 'keys between frames (a frame such as 110.4)');
5791
+ }
5792
+ /** An effect list as the desktop stores it (`slate/src/shared/audioEffects.ts`); slates_get_timeline's audioEffects lists each type's parameters and ranges. */
5793
+ const audioEffectList = z
5794
+ .array(z
5795
+ .object({
5796
+ id: z.string().max(64).optional().describe('Kept when sent back; a new effect gets one.'),
5797
+ type: z.enum(['volume', 'eq']).describe("volume: gain in dB (param gainDb, -60 silent to +12). eq: its low-pass (params 'lowpass.frequency' in Hz, 20 to 20000, swept by octave; 'lowpass.q', 0.1 to 10, 0.71 flat)."),
5798
+ bypass: z.boolean().optional(),
5799
+ params: z.record(z.number()).optional().describe('Fixed values by parameter name.'),
5800
+ keyframes: z.record(keyframeKeys.max(4000)).optional().describe('Keys by parameter name; a keyed parameter reads its keys instead of its fixed value.'),
5801
+ })
5802
+ .strict())
5803
+ .max(16);
5378
5804
  export const updateClip = {
5379
5805
  id: 'slates_update_clip',
5380
- description: "Set a timeline clip's own speed, volume, split edit (J-cut or L-cut) and fades, as the Cut's Inspector does. Only the fields you name change; null puts one back to the default. speed keeps the clip's media in and out points and its start and changes its length (2 is twice as fast, half as long); with ripple: true the lane's later clips move by the change, otherwise a longer clip covers what follows. audioOffsetFrames, on a video clip, moves its own sound against its picture in sync: below 0 is a J-cut (the sound starts first), above 0 an L-cut (it runs on). Fades are frames: fadeIn/fadeOut for the picture, audioFadeIn/audioFadeOut for the sound. volume is linear gain (1 = 0 dB, 0 = silent). look, on a clip with a picture, is the Inspector's Blend, Grain and Colour, sent whole: blend mixes the picture with what is under it (multiply darkens, screen lightens, overlay and soft-light add contrast), grain is film grain from 0 to 1, saturation is colour from 0 (black and white) through 1 (as shot) to 2; null clears the look.",
5806
+ description: "Set a timeline clip's own speed, volume, split edit (J-cut or L-cut) and fades, as the Cut's Inspector does. Only the fields you name change; null puts one back to the default. speed keeps the clip's media in and out points and its start and changes its length (2 is twice as fast, half as long); with ripple: true the lane's later clips move by the change, otherwise a longer clip covers what follows. audioOffsetFrames, on a video clip, moves its own sound against its picture in sync: below 0 is a J-cut (the sound starts first), above 0 an L-cut (it runs on). Fades are frames: fadeIn/fadeOut for the picture, audioFadeIn/audioFadeOut for the sound. volume is linear gain (1 = 0 dB, 0 = silent). look, on a clip with a picture, is the Inspector's Blend, Grain and Colour, sent whole: blend mixes the picture with what is under it (multiply darkens, screen lightens, overlay and soft-light add contrast), grain is film grain from 0 to 1, saturation is colour from 0 (black and white) through 1 (as shot) to 2; null clears the look. effects is the clip's sound effects, sent whole, in order: a volume (gain in dB) and an eq (its low-pass), each fixed or keyed in frames from the clip's start, the same in preview and export. speedRamp keys the speed over the clip (a slow-motion ramp): media in and out stay, the length becomes what the keys take, and the sound follows tape-style; not with speed. speedSound 'tape' makes a constant speed's sound change pitch with it. On an audio lane, startSec, sourceInSec and sourceOutSec (or sourceInSample and sourceOutSample) set where its sound starts and its media in and out to the sample, for a music edit between frames; a longer clip covers what follows unless ripple; not with speed in the same call.",
5381
5807
  input: z.object({
5382
5808
  projectId: z.string().uuid(),
5383
5809
  clipId: z.string().uuid(),
@@ -5393,16 +5819,31 @@ export const updateClip = {
5393
5819
  grain: z.number().min(0).max(1).optional(),
5394
5820
  saturation: z.number().min(0).max(2).optional(),
5395
5821
  }).strict().nullable().optional().describe('The whole look, at least one field; a field left out is its default (normal, no grain, colour 1). null clears it.'),
5396
- ripple: z.boolean().optional().describe("With speed: move the lane's later clips instead of covering them."),
5822
+ effects: audioEffectList.nullable().optional().describe("A clip with sound: its effect list, sent whole; null clears it. A split picture's go to its sound clip."),
5823
+ speedRamp: keyframeKeys.max(4000).nullable().optional().describe("Speeds (0.05 to 20) keyed in frames from the clip's start; null goes back to one speed. Its linked sound follows."),
5824
+ speedSound: z.enum(['tape', 'keep-pitch']).nullable().optional().describe("How a constant speed's sound plays: tape moves pitch with speed; keep-pitch (or null) holds it. A ramp's is always tape."),
5825
+ ripple: z.boolean().optional().describe("With speed, speedRamp or a sound clip's new media out: move the lane's later clips instead of covering them."),
5826
+ ...soundEdgesInput,
5397
5827
  }),
5398
5828
  async run(input, ctx) {
5399
5829
  const desktop = ctx.desktop();
5400
5830
  await desktop.requireCapability('timeline-editing', "a clip's speed, volume, split edit and fades");
5831
+ if (input.speed !== undefined && input.speedRamp !== undefined)
5832
+ throw new Error('Send speed (one speed) or speedRamp (keyed), not both.');
5833
+ if (input.effects !== undefined || input.speedRamp !== undefined || input.speedSound !== undefined) {
5834
+ await desktop.requireCapability('audio-effects', 'audio effects and speed ramps');
5835
+ await requireKeysBetweenFrames(desktop, input.speedRamp, input.effects);
5836
+ }
5401
5837
  // An empty look would clear the clip's look without saying so; null is how to ask for that.
5402
5838
  if (input.look && Object.keys(input.look).length === 0)
5403
5839
  throw new Error('look needs at least one of blend, grain or saturation; send look: null to clear it');
5404
5840
  if (input.look !== undefined)
5405
5841
  await desktop.requireCapability('clip-look', "a clip's blend, grain and colour");
5842
+ if (asksSoundEdges(input)) {
5843
+ if (input.speed !== undefined || input.speedRamp !== undefined)
5844
+ throw new Error("Set a clip's speed and its edges in seconds or samples in two calls.");
5845
+ await requireSoundPrecision(desktop);
5846
+ }
5406
5847
  return ok(await desktop.post('/agent/timeline/update-clip', input));
5407
5848
  },
5408
5849
  };
@@ -5450,7 +5891,18 @@ export const addTimelineTrack = {
5450
5891
  // and the batch cap slate's `src/main/agent/routes-editor.ts`, which this package cannot import;
5451
5892
  // lockstep check 12 fails when they differ. The 0..1 position and
5452
5893
  // opacity are fractions by definition, not a desktop choice.
5453
- const TEXT_STYLE_IDS = ['word-pop', 'keyword', 'subtitle', 'headline', 'clean'];
5894
+ const TEXT_STYLE_IDS = ['word-pop', 'keyword', 'subtitle', 'headline', 'clean', 'plain'];
5895
+ // A text clip set exactly (slate 1.6.x, capability text-fonts): the fonts Slates carries, the exact size,
5896
+ // the picture before the words and a line of clips, mirrored from slate's `src/shared/textStyles.ts` and
5897
+ // `src/shared/overlays.ts` like the rest (lockstep check 12).
5898
+ const TEXT_FONT_IDS = ['bebas-neue', 'montserrat-medium', 'montserrat-bold', 'montserrat-extrabold', 'montserrat-black',
5899
+ 'geist-regular', 'geist-medium', 'geist-semibold', 'geist-bold'];
5900
+ const TEXT_FONT_SIZE_RANGE = { min: 0.005, max: 0.5 };
5901
+ const TEXT_PICTURE_HEIGHT_RANGE = { min: 0.1, max: 5 };
5902
+ const TEXT_PICTURE_GAP_RANGE = { min: 0, max: 2 };
5903
+ const TEXT_LINE_GAP_RANGE = { min: 0, max: 4 };
5904
+ const TEXT_LINE_NAME_MAX = 40;
5905
+ const TEXT_LINE_PLACE_MAX = 99;
5454
5906
  const TEXT_STYLE_DEFAULT = 'subtitle';
5455
5907
  const OVERLAY_TEXT_MAX = 2000;
5456
5908
  const OVERLAY_WORDS_MAX = 2000;
@@ -5484,6 +5936,53 @@ const textLookInput = {
5484
5936
  size: textSizeInput.optional(),
5485
5937
  color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional().describe('The text colour as #rrggbb. Default: the style\'s.'),
5486
5938
  };
5939
+ /** The fields of a text clip set exactly; each is checked by the desktop again. */
5940
+ const textSetInput = {
5941
+ font: z.enum(TEXT_FONT_IDS).describe("A font Slates carries, drawn the same in preview and export on any machine. Default: the style's font."),
5942
+ fontSize: z.number().min(TEXT_FONT_SIZE_RANGE.min).max(TEXT_FONT_SIZE_RANGE.max)
5943
+ .describe("The exact size as a fraction of the frame's height (72 px on a 1920-high frame is 0.0375); replaces size."),
5944
+ pictureAssetId: z.string().min(1).describe('An image asset in the project (code IMG-A12 or id) drawn before the words, centred on them.'),
5945
+ pictureHeight: z.number().min(TEXT_PICTURE_HEIGHT_RANGE.min).max(TEXT_PICTURE_HEIGHT_RANGE.max)
5946
+ .describe("The picture's height as a multiple of the font size. Default: the capitals' height."),
5947
+ pictureGap: z.number().min(TEXT_PICTURE_GAP_RANGE.min).max(TEXT_PICTURE_GAP_RANGE.max)
5948
+ .describe('The space after the picture, a multiple of the font size. Default: 0.25.'),
5949
+ line: z
5950
+ .object({
5951
+ name: z.string().max(TEXT_LINE_NAME_MAX).regex(/\S/, 'must not be blank'),
5952
+ place: z.number().int().min(0).max(TEXT_LINE_PLACE_MAX).optional().describe('Left to right, lowest first. Default: 0; a tie keeps the lower lane first.'),
5953
+ })
5954
+ .strict()
5955
+ .describe("Text clips on screen together with one line name are set side by side, centred as one on the first clip's x and y."),
5956
+ gap: z.number().min(TEXT_LINE_GAP_RANGE.min).max(TEXT_LINE_GAP_RANGE.max)
5957
+ .describe('In a line: the space before this clip, a multiple of its font size. Default: 0.25.'),
5958
+ };
5959
+ const TEXT_SET_FIELDS = Object.keys(textSetInput);
5960
+ /** The plain style came with text-fonts (slate 22f76ea), so a desktop without the token lacks it. */
5961
+ const TEXT_FONTS_STYLE = 'plain';
5962
+ /**
5963
+ * Items setting a text clip exactly, or in the plain style, need a desktop that takes them (an older one
5964
+ * would drop the fields and draw in the style's font, or not know the style), and their pictures named by
5965
+ * code become asset ids.
5966
+ */
5967
+ async function textSetItems(ctx, desktop, projectId, items) {
5968
+ const needsFonts = (item) => item.style === TEXT_FONTS_STYLE
5969
+ || TEXT_SET_FIELDS.some((field) => item[field] !== undefined);
5970
+ if (!items.some(needsFonts))
5971
+ return items;
5972
+ await desktop.requireCapability('text-fonts', 'bundled fonts, exact sizes, pictures and lines on text clips');
5973
+ const named = items.flatMap((item) => (typeof item.pictureAssetId === 'string' ? [item.pictureAssetId] : []));
5974
+ if (named.length === 0)
5975
+ return items;
5976
+ const refs = await resolveAssetRefs(ctx, projectId, named);
5977
+ return items.map((item, i) => {
5978
+ if (typeof item.pictureAssetId !== 'string')
5979
+ return item;
5980
+ const asset = refs.get(item.pictureAssetId);
5981
+ if (!asset)
5982
+ throw new Error(`items[${i}].pictureAssetId "${item.pictureAssetId}" is not an asset in this project (slates_list_assets).`);
5983
+ return { ...item, pictureAssetId: asset.id };
5984
+ });
5985
+ }
5487
5986
  const overlayWordsInput = z
5488
5987
  .array(z
5489
5988
  .object({ text: overlayText(OVERLAY_WORD_TEXT_MAX), start: z.number().min(0), end: z.number().min(0) })
@@ -5508,7 +6007,7 @@ const overlayCount = (r, what) => {
5508
6007
  };
5509
6008
  export const addTextClip = {
5510
6009
  id: 'slates_add_text_clip',
5511
- description: "Put text on the timeline: captions, a headline, a keyword, a call to action. Each item is one text clip on an overlay track, drawn over the video in preview and export; a batch lands in one transaction, all or none. Captions that follow the voice: one clip per line, with each word's timing in words. Read slates_get_timeline first for the frame rate and where clips sit. Returns the clips and the timeline. Change one later with slates_update_overlay_clip, remove it with slates_remove_clip.",
6010
+ description: "Put text on the timeline: captions, a headline, a keyword, a call to action, a title-card label, a logo with words. Each item is one text clip on an overlay track, drawn over the video in preview and export; a batch lands in one transaction, all or none. Captions that follow the voice: one clip per line, with each word's timing in words. Set a label exactly with font (a font Slates carries) and fontSize (a fraction of the frame's height); it then centres the middle of its capitals on x, y. pictureAssetId draws an image before the words; clips sharing a line name are set side by side and centred as one, so a logo strip such as 'Blender + slates' is three items in one line (needs text-fonts; update Slates on refusal). Read slates_get_timeline first for the frame rate, where clips sit and textFonts. Returns the clips and the timeline. Change one later with slates_update_overlay_clip, remove it with slates_remove_clip.",
5512
6011
  input: z.object({
5513
6012
  projectId: z.string().uuid(), timelineId: z.string().uuid().optional(),
5514
6013
  items: z
@@ -5517,6 +6016,13 @@ export const addTextClip = {
5517
6016
  text: overlayText(OVERLAY_TEXT_MAX).describe('What it says.'),
5518
6017
  words: overlayWordsInput.optional(),
5519
6018
  ...textLookInput,
6019
+ font: textSetInput.font.optional(),
6020
+ fontSize: textSetInput.fontSize.optional(),
6021
+ pictureAssetId: textSetInput.pictureAssetId.optional(),
6022
+ pictureHeight: textSetInput.pictureHeight.optional(),
6023
+ pictureGap: textSetInput.pictureGap.optional(),
6024
+ line: textSetInput.line.optional(),
6025
+ gap: textSetInput.gap.optional(),
5520
6026
  ...overlayPlacementInput,
5521
6027
  })
5522
6028
  .strict())
@@ -5528,7 +6034,8 @@ export const addTextClip = {
5528
6034
  await desktop.requireCapability('timeline-overlays', 'text and image overlays');
5529
6035
  await requireNamedCut(desktop, input.timelineId);
5530
6036
  requireOverlayStart(input.items);
5531
- const r = await desktop.post('/agent/timeline/add-text', input);
6037
+ const items = await textSetItems(ctx, desktop, input.projectId, input.items);
6038
+ const r = await desktop.post('/agent/timeline/add-text', { ...input, items });
5532
6039
  return ok(r, `${overlayCount(r, 'text clip')} ${JSON.stringify(r)}`);
5533
6040
  },
5534
6041
  };
@@ -5568,7 +6075,7 @@ export const addImageOverlay = {
5568
6075
  };
5569
6076
  export const updateOverlayClip = {
5570
6077
  id: 'slates_update_overlay_clip',
5571
- description: "Change a text clip's words or look, or an image overlay's place, size and opacity. Only the fields you name change; null puts one back to the style's or the default. words replaces a text clip's timings, and [] drops them; new text keeps the old timings, so send words with it. When the clip shows does not change here: to move one, remove it (slates_remove_clip) and add it again. A batch lands in one transaction, all or none. Returns the changed clips.",
6078
+ description: "Change a text clip's words or look, or an image overlay's place, size and opacity. Only the fields you name change; null puts one back to the style's or the default. A text clip also takes font, fontSize, pictureAssetId (null takes the picture away), pictureHeight, pictureGap, line and gap, as slates_add_text_clip describes (needs text-fonts); in a line, x and y are read from its first clip. words replaces a text clip's timings, and [] drops them; new text keeps the old timings, so send words with it. When the clip shows does not change here: to move one, remove it (slates_remove_clip) and add it again. A batch lands in one transaction, all or none. Returns the changed clips.",
5572
6079
  input: z.object({
5573
6080
  projectId: z.string().uuid(),
5574
6081
  items: z
@@ -5584,6 +6091,13 @@ export const updateOverlayClip = {
5584
6091
  color: z.string().regex(/^#[0-9a-fA-F]{6}$/).nullable().optional().describe('Text clips: #rrggbb.'),
5585
6092
  width: imageWidthInput.nullable().optional().describe(`Image clips: ${imageWidthInput.description}`),
5586
6093
  opacity: z.number().min(0).max(1).nullable().optional().describe('Image clips.'),
6094
+ font: textSetInput.font.nullable().optional(),
6095
+ fontSize: textSetInput.fontSize.nullable().optional(),
6096
+ pictureAssetId: textSetInput.pictureAssetId.nullable().optional().describe(`${textSetInput.pictureAssetId.description} null: none.`),
6097
+ pictureHeight: textSetInput.pictureHeight.nullable().optional(),
6098
+ pictureGap: textSetInput.pictureGap.nullable().optional(),
6099
+ line: textSetInput.line.nullable().optional().describe(`${textSetInput.line.description} null: out of the line.`),
6100
+ gap: textSetInput.gap.nullable().optional(),
5587
6101
  })
5588
6102
  .strict()
5589
6103
  .refine((item) => Object.keys(item).some((k) => k !== 'clipId'), { message: 'name at least one field to change besides clipId' }))
@@ -5593,26 +6107,14 @@ export const updateOverlayClip = {
5593
6107
  async run(input, ctx) {
5594
6108
  const desktop = ctx.desktop();
5595
6109
  await desktop.requireCapability('timeline-overlays', 'text and image overlays');
5596
- return ok(await desktop.post('/agent/timeline/update-overlay', input));
6110
+ const items = await textSetItems(ctx, desktop, input.projectId, input.items);
6111
+ return ok(await desktop.post('/agent/timeline/update-overlay', { ...input, items }));
5597
6112
  },
5598
6113
  };
5599
6114
  const KEYFRAME_PROPERTY_IDS = ['positionX', 'positionY', 'scale', 'rotation', 'opacity', 'cropLeft', 'cropTop', 'cropRight', 'cropBottom', 'focusX', 'focusY', 'zoom'];
5600
- const keyframeEasing = z.union([
5601
- z.enum(['linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'hold']),
5602
- z.object({ cubicBezier: z.tuple([z.number().min(0).max(1), z.number(), z.number().min(0).max(1), z.number()]) }).strict(),
5603
- ]);
5604
- const keyframeList = z
5605
- .array(z
5606
- .object({
5607
- frame: z.number().int().min(0).describe("Frames from the clip's start, at the timeline's frame rate."),
5608
- value: z.number().finite(),
5609
- easing: keyframeEasing.optional().describe('The curve from this key to the next. Default linear; hold jumps at the next key.'),
5610
- })
5611
- .strict())
5612
- .max(500);
5613
6115
  export const setClipKeyframes = {
5614
6116
  id: 'slates_set_clip_keyframes',
5615
- description: "Animate or set a timeline clip's transform with keyframes: a punch-in, a slow push, a Ken Burns move, a slide, a spin, a fade, a crop. Each property you name gets exactly the keys you send ([] clears it back to its static value); properties you leave out keep theirs, and all of them land in one transaction. One key holds a value for the whole clip. Frames count from the clip's start. Units: positionX/positionY move the picture's centre in frame widths/heights (0.1 = a tenth of the frame right or down, -4..4); scale multiplies the framed size about the frame's centre (1 = as framed, 0.01..20); rotation is degrees clockwise; opacity 0..1; cropLeft/Top/Right/Bottom remove that fraction of the source from its side (0..0.99); focusX/focusY (0..1) and zoom (1..20) animate the clip's reframe for the aspect being exported. Drawn by the Cut's monitor and its export alike, both the timeline engine. Returns the clip's keys; slates_get_timeline lists every clip's keys in timeline.keyframes. Requires timeline-keyframes; update Slates on capability refusal.",
6117
+ description: "Animate or set a timeline clip's transform with keyframes: a punch-in, a slow push, a Ken Burns move, a slide, a spin, a fade, a crop. Each property you name gets exactly the keys you send ([] clears it back to its static value); properties you leave out keep theirs, and all of them land in one transaction. One key holds a value for the whole clip. Frames count from the clip's start and may fall between frames (110.4), read at that exact time. Units: positionX/positionY move the picture's centre in frame widths/heights (0.1 = a tenth of the frame right or down, -4..4); scale multiplies the framed size about the frame's centre (1 = as framed, 0.01..20); rotation is degrees clockwise; opacity 0..1; cropLeft/Top/Right/Bottom remove that fraction of the source from its side (0..0.99); focusX/focusY (0..1) and zoom (1..20) animate the clip's reframe for the aspect being exported. Drawn by the Cut's monitor and its export alike, both the timeline engine. Returns the clip's keys; slates_get_timeline lists every clip's keys in timeline.keyframes. Requires timeline-keyframes; update Slates on capability refusal.",
5616
6118
  input: z.object({
5617
6119
  projectId: z.string().uuid(),
5618
6120
  timelineId: z.string().uuid(),
@@ -5626,6 +6128,7 @@ export const setClipKeyframes = {
5626
6128
  async run(input, ctx) {
5627
6129
  const desktop = ctx.desktop();
5628
6130
  await desktop.requireCapability('timeline-keyframes', 'clip keyframes');
6131
+ await requireKeysBetweenFrames(desktop, ...Object.values(input.properties));
5629
6132
  return ok(await desktop.post('/agent/timeline/keyframes', input));
5630
6133
  },
5631
6134
  };
@@ -5642,7 +6145,7 @@ const CAPTION_COMPONENTS = [
5642
6145
  'caption-neon-accent', 'caption-editorial-emphasis',
5643
6146
  ];
5644
6147
  const htmlCompositionInput = z.string().min(1).describe('A composition: a whole HTML document whose GSAP timeline is registered on window.__timelines.');
5645
- const htmlVariablesInput = z.record(z.union([z.string(), z.number(), z.boolean()])).describe("Values for the composition's or block's declared variables, by name: text, numbers or true/false.");
6148
+ const htmlVariablesInput = z.record(z.union([z.string(), z.number(), z.boolean()])).describe("Values for the composition's or block's declared variables, by name: text, numbers or true/false. A picture (declared type image) takes an image asset id (UUID) of this project, or \"\" for the layer's own picture, and reads back as its path in the project folder (images/logo.png); a web address or another project's picture is refused.");
5646
6149
  export const addCaptions = {
5647
6150
  id: 'slates_add_captions',
5648
6151
  billable: false,
@@ -5676,6 +6179,8 @@ export const addCaptions = {
5676
6179
  await ctx.desktop().requireCapability('caption-components', 'caption components');
5677
6180
  if (input.html !== undefined)
5678
6181
  await ctx.desktop().requireCapability('caption-html', 'caption layers of your own');
6182
+ if (input.style === TEXT_FONTS_STYLE)
6183
+ await ctx.desktop().requireCapability('text-fonts', 'the plain text style');
5679
6184
  if (input.html !== undefined && input.component)
5680
6185
  throw new Error('html is your own caption layer and component a ready one. Pass one or the other.');
5681
6186
  if (input.html !== undefined && input.style)
@@ -5709,7 +6214,7 @@ const describeFindings = (f) => {
5709
6214
  };
5710
6215
  export const addHtmlClip = {
5711
6216
  id: 'slates_add_html_clip',
5712
- description: "Put an HTML motion layer on the timeline: an animated caption, lower third, end card, title, logo sting or background plate, drawn on an overlay track in preview and export. An HTML clip is a composition, an HTML document with a GSAP timeline registered on window.__timelines. Pass your own html, or block with the name of a registry block (slates_list_motion_blocks) and its variables; html with block replaces the block's document and keeps its files. Slates' composition check runs before the clip lands and its findings come back here: fix every error with slates_update_html_clip before moving on. Keep a transparent foreground and a background plate on separate tracks. Free. Read slates_get_timeline first for the frame rate and where clips sit. Craft: slates_get_prompting_guide (topic: slates-motion).",
6217
+ description: "Put an HTML motion layer on the timeline: an animated caption, lower third, end card, title, logo sting or background plate, drawn on an overlay track in preview and export. An HTML clip is a composition, an HTML document with a GSAP timeline registered on window.__timelines. Pass your own html, or block with the name of a registry block (slates_list_motion_blocks) and its variables; html with block replaces the block's document and keeps its files. It loads the project's own pictures, SVGs and fonts by their path in the project's folder (images/logo.svg, fonts/Brand.woff2; the folder is projectsFolder from slates_get_app_settings, then the project id) and no other file; an export fails, naming the font, when a declared font does not load. Slates' composition check runs before the clip lands and its findings come back here: fix every error with slates_update_html_clip before moving on. Keep a transparent foreground and a background plate on separate tracks. Free. Read slates_get_timeline first for the frame rate and where clips sit. Craft: slates_get_prompting_guide (topic: slates-motion).",
5713
6218
  input: z
5714
6219
  .object({
5715
6220
  projectId: z.string().uuid(),
@@ -5782,7 +6287,7 @@ export const listMotionBlocks = {
5782
6287
  };
5783
6288
  export const updateTimelineTrack = {
5784
6289
  id: 'slates_update_timeline_track',
5785
- description: 'Update a timeline track: rename, mute/unmute, lock/unlock, or set its volume fader (linear gain, -∞ to +12 dB). Track volume applies to both preview and MP4 export — audio-track clips are mixed at this gain; a muted video track still shows video but its embedded audio is silenced.',
6290
+ description: 'Update a timeline track: rename, mute/unmute, lock/unlock, or set its volume fader (linear gain, -∞ to +12 dB). Track volume applies to both preview and MP4 export — audio-track clips are mixed at this gain; a muted video track still shows video but its embedded audio is silenced. effects puts an effect list on a sound lane, heard after its clips\' own (the same shape as slates_update_clip, keys in frames from the timeline start).',
5786
6291
  input: z.object({
5787
6292
  projectId: z.string().uuid(),
5788
6293
  trackId: z.string().uuid(),
@@ -5790,10 +6295,14 @@ export const updateTimelineTrack = {
5790
6295
  muted: z.boolean().optional(),
5791
6296
  locked: z.boolean().optional(),
5792
6297
  volume: z.number().min(0).max(4).optional().describe('Track fader as LINEAR gain: 0 = -∞ (silent), 1 = 0 dB (unity), ~3.98 = +12 dB (max boost).'),
6298
+ effects: audioEffectList.nullable().optional().describe('A video or audio lane: its effect list, sent whole; null clears it.'),
5793
6299
  }),
5794
6300
  async run(input, ctx) {
5795
6301
  const desktop = ctx.desktop();
5796
6302
  await desktop.requireCapability('timeline-tracks', 'timeline tracks + audio mixing');
6303
+ if (input.effects !== undefined)
6304
+ await desktop.requireCapability('audio-effects', 'audio effects on a lane');
6305
+ await requireKeysBetweenFrames(desktop, input.effects);
5797
6306
  return ok(await desktop.post('/agent/timeline/update-track', input));
5798
6307
  },
5799
6308
  };
@@ -5812,18 +6321,25 @@ export const removeTimelineTrack = {
5812
6321
  };
5813
6322
  export const updateTimelineSettings = {
5814
6323
  id: 'slates_update_timeline_settings',
5815
- description: "Update a timeline's output settings: resolution, frame rate (24/30/60; all clips are conformed to it on export), masterVolume, or delivery formats, naming taxonomy and explicit variant grid bindings. New fields require ad-variant-export; null clears them. Read aspects and dimensions from slates_get_variant_grid. Delivery-only updates on an explicit timeline return the computed formats. masterVolume is the output fader (linear gain: 0 is silent, 1 is unity, 4 is the maximum boost) applied to the preview and the final mix; use it to prevent clipping when stacking loud tracks. These are normally auto-managed: the first video clip sets fps and resolution, higher-res clips raise the canvas, and delivery preserves the master aspect. Changing frameRate keeps clip positions, lengths and markers in seconds, rounded to the nearest new frame.",
6324
+ description: "Update a timeline's output settings: resolution, frame rate (24/30/60; all clips are conformed to it on export), masterVolume, or delivery formats, naming taxonomy and explicit variant grid bindings. New fields require ad-variant-export; null clears them. Read aspects and dimensions from slates_get_variant_grid. Delivery-only updates on an explicit timeline return the computed formats. masterVolume is the output fader (linear gain: 0 is silent, 1 is unity, 4 is the maximum boost) applied to the preview and the final mix; use it to prevent clipping when stacking loud tracks. These are normally auto-managed: the first video clip sets fps and resolution, higher-res clips raise the canvas, and delivery preserves the master aspect. Changing frameRate keeps clip positions, lengths and markers in seconds, rounded to the nearest new frame. effects puts an effect list on the master, after the output fader (the same shape as slates_update_clip, keys in frames from the timeline start). audioBitrate is the exported MP4's sound in kb/s, the Sound bitrate the settings button shows.",
5816
6325
  input: z.object({
5817
6326
  projectId: z.string().uuid(), timelineId: z.string().uuid().optional(),
5818
6327
  width: z.number().int().min(16).optional(),
5819
6328
  height: z.number().int().min(16).optional(),
5820
6329
  frameRate: z.union([z.literal(24), z.literal(30), z.literal(60)]).optional(),
5821
6330
  masterVolume: z.number().min(0).max(4).optional().describe('Output fader as LINEAR gain: 0 = -∞ (silent), 1 = 0 dB (unity), ~3.98 = +12 dB (max boost).'),
6331
+ effects: audioEffectList.nullable().optional().describe("The master's effect list, sent whole; null clears it."),
6332
+ audioBitrate: audioBitrateInput.nullable().optional().describe(`The export's AAC sound in kb/s: ${AUDIO_BITRATES.join(', ')}; null goes back to the default ${AUDIO_BITRATE_DEFAULT}.`),
5822
6333
  ...cutOptionsInput,
5823
6334
  }),
5824
6335
  async run(input, ctx) {
5825
6336
  const desktop = ctx.desktop();
5826
6337
  await desktop.requireCapability('timeline-tracks', 'timeline tracks + audio mixing');
6338
+ if (input.effects !== undefined)
6339
+ await desktop.requireCapability('audio-effects', 'audio effects on the master');
6340
+ await requireKeysBetweenFrames(desktop, input.effects);
6341
+ if (input.audioBitrate !== undefined)
6342
+ await requireSoundPrecision(desktop);
5827
6343
  await requireNamedCut(desktop, input.timelineId);
5828
6344
  if (input.delivery !== undefined || input.taxonomy !== undefined || input.gridBinding !== undefined) {
5829
6345
  await desktop.requireCapability('ad-variant-export', 'cut delivery, naming and grid bindings');
@@ -5839,7 +6355,7 @@ const ABSOLUTE_PATH_RE = /^([A-Za-z]:[\\/]|\/)/;
5839
6355
  export const exportVideo = {
5840
6356
  id: 'slates_export_video',
5841
6357
  billable: false,
5842
- description: "Render the project's timeline to an MP4 file on disk through the desktop app's timeline engine, the renderer its monitor shows, so the file matches the preview (H.264 + AAC, every video lane composited with its transitions, fades and keyframes, gaps rendered as black; the Slates window must be open). No dialogs — pass an absolute outputPath ending in .mp4. Fails if the file exists unless overwrite=true. Blocks until encoding finishes (can take minutes for long timelines) and returns the real file size and probed duration. After success, consider slates_reveal_file to show the file to the user. Requires at least one video clip on the timeline. Pass exactly one of projectId (the project's default timeline) or timelineId (a named cut).",
6358
+ description: "Render the project's timeline to an MP4 file on disk through the desktop app's timeline engine, the renderer its monitor shows, so the file matches the preview (H.264 + AAC, every video lane composited with its transitions, fades and keyframes, gaps rendered as black; the Slates window must be open). No dialogs — pass an absolute outputPath ending in .mp4. Fails if the file exists unless overwrite=true. Blocks until encoding finishes (can take minutes for long timelines) and returns the real file size and probed duration. After success, consider slates_reveal_file to show the file to the user. Requires at least one video clip on the timeline. The sound is AAC at the timeline's Sound bitrate (slates_update_timeline_settings audioBitrate; default 320 kb/s) unless audioBitrate names one for this file. Pass exactly one of projectId (the project's default timeline) or timelineId (a named cut).",
5843
6359
  input: z
5844
6360
  .object({
5845
6361
  projectId: z.string().uuid().optional(),
@@ -5851,6 +6367,7 @@ export const exportVideo = {
5851
6367
  .describe('Absolute path for the rendered file, ending in .mp4 (e.g. C:\\Users\\you\\Videos\\ad.mp4 or /Users/you/ad.mp4). slates_get_project_directory gives a sensible default folder.'),
5852
6368
  overwrite: z.boolean().optional(),
5853
6369
  aspect: deliveryAspectInput.optional().describe('Optional delivery aspect from slates_get_variant_grid; requires ad-variant-export. Omission keeps existing export behavior.'),
6370
+ audioBitrate: audioBitrateInput.optional().describe(`This file's AAC sound in kb/s (${AUDIO_BITRATES.join(', ')}); omit for the timeline's Sound bitrate.`),
5854
6371
  })
5855
6372
  .refine((d) => !!d.projectId !== !!d.timelineId, {
5856
6373
  message: 'Pass exactly one of projectId or timelineId',
@@ -5860,12 +6377,15 @@ export const exportVideo = {
5860
6377
  await desktop.requireCapability('export', 'video export');
5861
6378
  if (input.aspect !== undefined)
5862
6379
  await desktop.requireCapability('ad-variant-export', 'single video delivery export');
6380
+ if (input.audioBitrate !== undefined)
6381
+ await requireSoundPrecision(desktop);
5863
6382
  const r = await desktop.post('/agent/timeline/export-video', {
5864
6383
  projectId: input.projectId,
5865
6384
  timelineId: input.timelineId,
5866
6385
  outputPath: input.outputPath,
5867
6386
  overwrite: input.overwrite,
5868
6387
  aspect: input.aspect,
6388
+ audioBitrate: input.audioBitrate,
5869
6389
  });
5870
6390
  const mb = r.fileSizeBytes != null ? (r.fileSizeBytes / (1024 * 1024)).toFixed(1) : '?';
5871
6391
  return ok(r, `Exported ${r.durationSec ?? '?'}s MP4 (${mb} MB) to ${r.outputPath ?? input.outputPath}.`);
@@ -6174,7 +6694,7 @@ export const createLibraryItem = {
6174
6694
  };
6175
6695
  export const updateLibraryItem = {
6176
6696
  id: 'slates_update_library_item',
6177
- description: "Update a Library item: rename it, move it to another category (categoryId), bind its picture (imageAssetId) or its voice (voiceAssetId, an audio asset; a thing in a location category composes as an environment and carries none). null clears an asset; the asset itself stays. Moving between a 'thing' and a 'look' category flips the sigil (@ ↔ #), and moving a thing into or out of a 'location'-template category changes what it composes as. A rename changes its handle. In every case each saved Shot that mentions the item is rewritten to match (the mention in its prompt, and its mention id), and the result's `move` reports `shotsMentioning`, `shotsRetagged` and the old and new `mention`: tell the user what changed. Pass retagShots:false to leave Shots alone; they then show the item as missing until it is mentioned again. Moving it back, or renaming it back, undoes the rewrite.",
6697
+ description: "Update a Library item: rename it, move it to another category (categoryId), bind its picture (imageAssetId) or its voice (voiceAssetId, an audio asset; a thing in a location category composes as an environment and carries none). null clears an asset; the asset itself stays. Moving between a 'thing' and a 'look' category flips the sigil (@ ↔ #), and moving a thing into or out of a 'location'-template category changes what it composes as. A rename changes its handle. In every case each saved Shot that mentions the item is rewritten to match (the mention in its prompt, and its mention id), and the result's `move` reports `shotsMentioning`, `shotsRetagged` and the old and new `mention`: tell the user what changed. Pass retagShots:false to leave Shots alone; they then show the item as missing until it is mentioned again. Moving it back, or renaming it back, undoes the rewrite. extraAssetIds sets the item's extra pictures (the whole ordered list; [] clears; a mention still sends only its picture) and palette its colours (up to six; [] clears; shown and read, never sent to a model).",
6178
6698
  input: z.object({
6179
6699
  projectId: z.string().uuid().describe('The project the item is in — asset codes resolve against it.'),
6180
6700
  itemId: z.string().uuid(),
@@ -6185,10 +6705,15 @@ export const updateLibraryItem = {
6185
6705
  retagShots: z.boolean().optional().describe('Only with categoryId or name. Default true: Shots that mention the item follow a move or a rename that changes how it is mentioned.'),
6186
6706
  imageAssetId: z.string().min(1).nullable().optional().describe('UUID or badge code; null clears.'),
6187
6707
  voiceAssetId: z.string().min(1).nullable().optional().describe('An AUDIO asset, UUID or badge code; null detaches.'),
6708
+ extraAssetIds: z.array(z.string().min(1)).max(24).optional().describe('More pictures of it, in order: UUIDs or badge codes of pictures in this project. [] clears.'),
6709
+ palette: z.array(z.string().min(1)).max(6).optional().describe('Its colours: #rrggbb, #rgb or rgb(r, g, b). [] clears.'),
6188
6710
  }),
6189
6711
  async run(input, ctx) {
6190
6712
  await ctx.desktop().requireCapability('library', 'the Library');
6191
- const refs = [input.imageAssetId, input.voiceAssetId].filter((r) => typeof r === 'string');
6713
+ if (input.extraAssetIds !== undefined || input.palette !== undefined) {
6714
+ await ctx.desktop().requireCapability('product-intake', "a Library item's extra pictures and colours");
6715
+ }
6716
+ const refs = [input.imageAssetId, input.voiceAssetId, ...(input.extraAssetIds ?? [])].filter((r) => typeof r === 'string');
6192
6717
  const resolved = await resolveAssetRefs(ctx, input.projectId, refs);
6193
6718
  const asset = (ref) => typeof ref === 'string' ? resolved.get(ref).id : ref;
6194
6719
  return ok(await ctx.desktop().post('/agent/library/items/update', {
@@ -6203,6 +6728,8 @@ export const updateLibraryItem = {
6203
6728
  // explicit null is the clear.
6204
6729
  ...(input.imageAssetId !== undefined ? { imageAssetId: asset(input.imageAssetId) } : {}),
6205
6730
  ...(input.voiceAssetId !== undefined ? { voiceAssetId: asset(input.voiceAssetId) } : {}),
6731
+ ...(input.extraAssetIds !== undefined ? { extraAssetIds: input.extraAssetIds.map((ref) => resolved.get(ref).id) } : {}),
6732
+ ...(input.palette !== undefined ? { palette: input.palette } : {}),
6206
6733
  },
6207
6734
  }));
6208
6735
  },
@@ -6262,7 +6789,7 @@ export const copyLibraryItemToProject = {
6262
6789
  // mention. It holds no takes, and importing one generates and spends nothing.
6263
6790
  export const getTemplate = {
6264
6791
  id: 'slates_get_template',
6265
- description: "Read a Slates template file without changing anything. With `path`: what it holds (scenes, shots, library items, the models its shots are set to) and its SWAP SLOTS — every Library item (`item:i1`, labelled with its mention, e.g. @candle) and every directly attached reference (`asset:a3`, with its roles) that slates_import_template can point at one of the project's own assets instead. Without `path`: the templates in the user's templates folder, plus any starter templates the app ships.",
6792
+ description: "Read a Slates template file without changing anything. With `path`: what it holds (scenes, shots, library items, the models its shots are set to) and its SWAP SLOTS — every Library item (`item:i1`, labelled with its mention, e.g. @candle, with `extras` (its count of extra pictures) and `palette`) and every directly attached reference (`asset:a3`, with its roles) that slates_import_template can point at one of the project's own assets instead. Without `path`: the templates in the user's templates folder, plus any starter templates the app ships.",
6266
6793
  input: z.object({ path: z.string().min(1).optional().describe('Absolute path of a .slatestemplate file. Omit to list saved templates.') }),
6267
6794
  async run(input, ctx) {
6268
6795
  await ctx.desktop().requireCapability('templates', 'templates');
@@ -6273,7 +6800,7 @@ export const getTemplate = {
6273
6800
  };
6274
6801
  export const exportTemplate = {
6275
6802
  id: 'slates_export_template',
6276
- description: "Save a board, a scene or one Shot as a template file someone else can start from. Give exactly one of storyboardId, sceneId or shotId. The file carries each Shot's full recipe (prompt, model, settings, reference roles, script words) plus the reference files and the Library items the Shots mention; it carries no takes. The project is untouched. A file saved outside the user's templates folder is not in the template list (slates_get_template without path); the user opens it with Open a file. Returns the path, the counts and a warning for any reference whose file is missing.",
6803
+ description: "Save a board, a scene or one Shot as a template file someone else can start from. Give exactly one of storyboardId, sceneId or shotId. The file carries each Shot's full recipe (prompt, model, settings, reference roles, script words) plus the reference files and the Library items the Shots mention, each with its picture, extra pictures and colours; it carries no takes. The project is untouched. A file saved outside the user's templates folder is not in the template list (slates_get_template without path); the user opens it with Open a file. Returns the path, the counts and a warning for any reference whose file is missing.",
6277
6804
  input: z.object({
6278
6805
  projectId: z.string().uuid(),
6279
6806
  path: z.string().min(1).describe('Absolute path to write, ending in .slatestemplate. Its folder is created if needed.'),
@@ -6300,7 +6827,7 @@ export const importTemplate = {
6300
6827
  sceneIndices: z.array(z.number().int().min(0)).min(1).optional().describe('Import only these scene indices from the inspected parts, preserving their order. Omit for the whole template.'),
6301
6828
  storyboardId: z.string().uuid().optional(),
6302
6829
  sceneId: z.string().uuid().optional(),
6303
- swaps: z.record(z.string().min(1)).optional().describe('{ "item:i1": "IMG-A12", "asset:a3": "<asset id>" }'),
6830
+ swaps: z.record(z.string().min(1)).optional().describe('{ "item:i1": "IMG-A12", "asset:a3": "<asset id>" }. An item swap also leaves out the template\'s extra pictures and colours for it.'),
6304
6831
  useTemplateCategories: z
6305
6832
  .boolean()
6306
6833
  .optional()
@@ -6317,6 +6844,149 @@ export const importTemplate = {
6317
6844
  return ok(await ctx.desktop().post('/agent/templates/import', { ...input, swaps }));
6318
6845
  },
6319
6846
  };
6847
+ // ── Start from a reference ad ───────────────────────────────────────────
6848
+ // A finished ad becomes an ordinary board: one Shot per cut, each postered with
6849
+ // its keyframe, the heard words on the Script page. Local and free, and the
6850
+ // board generates nothing. Read and write are two tools so a host can
6851
+ // auto-approve the read (mcp-server-design § Annotations).
6852
+ export const getReferenceBreakdown = {
6853
+ id: 'slates_get_reference_breakdown',
6854
+ description: "Read a reference ad's cuts and words without changing anything: each cut's start, end and seconds, the words heard in it, and the reference's size, frame rate and form (a still, no voice, soft cuts). When slates_break_down_reference already saved this asset's frames, they come back too (framesSaved: true, each cut's keyframeCode and compositeCode, the first and last frame side by side); otherwise there are no pictures and the words are the stored transcript only. Free; writes nothing. To start from a reference, read it here, then break it down.",
6855
+ input: z
6856
+ .object({
6857
+ projectId: z.string().uuid(),
6858
+ assetId: z.string().min(1).describe('The reference video or picture in the project: its code (VID-V3) or id.'),
6859
+ })
6860
+ .strict(),
6861
+ async run(input, ctx) {
6862
+ await ctx.desktop().requireCapability('reference-breakdown', 'breaking a reference ad into shots');
6863
+ const assetId = (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id;
6864
+ return ok(await ctx.desktop().get('/agent/reference/breakdown', { projectId: input.projectId, assetId }));
6865
+ },
6866
+ };
6867
+ export const breakDownReference = {
6868
+ id: 'slates_break_down_reference',
6869
+ billable: false,
6870
+ description: "Start from a reference ad: break a finished video into a new board with one Shot per cut, as the clip's Break down into shots command does, so the user can remake it with their own product. Each Shot is postered with its cut's keyframe (a poster only, never a reference or first frame), named by its seconds in the reference, and holds the words heard in that cut on the Script page. Nothing is generated and nothing spends: the result carries the board's quote, the Shot codes and each timing gap in words (a cut shorter than the model's shortest length). Local and free; the first transcription can take minutes. Name the reference by assetId, filePath or url, one of them: a url is fetched into the project's Media first, and works for a Meta Ad Library ad link (facebook.com/ads/library/?id=...) or a direct link to a video file; TikTok Creative Center, YouTube and TikTok post links are refused with the reason (download the video, then pass filePath). The result's source names the link, its kind and the video file it fetched. build false saves each cut's keyframe and first-and-last composite to a frames folder and returns the cuts, without a board: look at them with slates_get_asset_image, then call again with build (the frames are reused) and `cuts` (each cut's description, written for the user's product, becomes its Shot's prompt; onScreenText becomes a direction line), `sections` (headings) and `roles` (who or what recurs; itemId points the role at the user's own Library item). A still becomes one Shot. Generate only after the user approves the quote (slates_generate_from_shots). To be able to stop a run, name it with jobId; cancel true with that jobId (and projectId, nothing else) stops it at its next step, removing its frames and any video it fetched, until its board build starts (too late then: the board is kept).",
6871
+ input: z
6872
+ .object({
6873
+ projectId: z.string().uuid(),
6874
+ assetId: z.string().min(1).optional().describe('A video or picture already in the project: its code (VID-V3) or id. Give this, filePath or url.'),
6875
+ filePath: z.string().min(1).optional().describe('An absolute path to a video or picture on this computer; it is imported first.'),
6876
+ url: z
6877
+ .string()
6878
+ .url()
6879
+ .optional()
6880
+ .describe('A link to the reference: a Meta Ad Library ad or a direct video file link, fetched and imported first. Creative Center and post links are refused with the reason.'),
6881
+ build: z.boolean().optional().describe('false: save the frames and return the cuts, with no board. Default true.'),
6882
+ transcribe: z.boolean().optional().describe('Hear the words when no transcript is stored. Default true.'),
6883
+ name: z.string().min(1).max(80).optional().describe("The board's name. Defaults to the reference's."),
6884
+ model: z.string().min(1).optional().describe("A video model id for every Shot; defaults to the app's default video model."),
6885
+ cuts: z
6886
+ .array(z
6887
+ .object({
6888
+ index: z.number().int().min(0).describe("The cut's index from the breakdown's segments."),
6889
+ description: z.string().max(4000).optional().describe("What this Shot shows, for the user's product: its prompt."),
6890
+ onScreenText: z.string().max(500).optional().describe('Words on screen in this cut, kept as a direction line, never sent as action.'),
6891
+ })
6892
+ .strict())
6893
+ .optional(),
6894
+ sections: z
6895
+ .array(z.object({ label: z.string().min(1).max(120), fromCut: z.number().int().min(0) }).strict())
6896
+ .optional()
6897
+ .describe('Headings on the Script page, each before the cut it starts at (hook, problem, offer...).'),
6898
+ roles: z
6899
+ .array(z
6900
+ .object({
6901
+ name: z.string().min(1).max(80),
6902
+ kind: z.enum(['person', 'location', 'product']).optional(),
6903
+ itemId: z.string().min(1).optional().describe('A Library item of this project (slates_list_library) to use for the role.'),
6904
+ cuts: z.array(z.number().int().min(0)).describe('The cut indices the role appears in.'),
6905
+ })
6906
+ .strict())
6907
+ .optional()
6908
+ .describe('Who or what recurs. Without itemId a role becomes a new Library item to fill in.'),
6909
+ jobId: z.string().min(1).max(120).optional().describe('A name for this run, so a later call with cancel can stop it.'),
6910
+ cancel: z.boolean().optional().describe('true: stop the run named by jobId instead of starting one.'),
6911
+ })
6912
+ .strict(),
6913
+ async run(input, ctx) {
6914
+ await ctx.desktop().requireCapability('reference-breakdown', 'breaking a reference ad into shots');
6915
+ if (input.cancel) {
6916
+ if (!input.jobId)
6917
+ throw new Error('cancel stops a run by its jobId: give the jobId the breakdown was started with.');
6918
+ await ctx.desktop().requireCapability('reference-cancel', 'stopping a reference breakdown');
6919
+ const c = await ctx.desktop().post('/agent/reference/cancel', { jobId: input.jobId });
6920
+ return ok(c, c.cancelled ? `Stopping breakdown ${c.jobId}: it ends at its next step, its frames and any fetched video removed.` : `Nothing to stop: no breakdown named ${c.jobId} is running, or it has reached its board build, which finishes and keeps the board.`);
6921
+ }
6922
+ if (input.jobId)
6923
+ await ctx.desktop().requireCapability('reference-cancel', 'naming a reference breakdown so it can be stopped');
6924
+ if ([input.assetId, input.filePath, input.url].filter(Boolean).length !== 1) {
6925
+ throw new Error('Give exactly one of assetId (a video or picture in the project), filePath or url.');
6926
+ }
6927
+ const assetId = input.assetId ? (await resolveAssetRefs(ctx, input.projectId, [input.assetId])).get(input.assetId).id : input.assetId;
6928
+ const r = await ctx.desktop().post('/agent/reference/breakdown', { ...input, assetId, cancel: undefined });
6929
+ const cuts = r.breakdown.segments.length;
6930
+ const fetched = r.source ? `Fetched the ${r.source.kind === 'meta' ? 'Meta Ad Library ad' : 'video link'} into Media as ${r.breakdown.sourceCode ?? 'a video'}. ` : '';
6931
+ const head = r.board
6932
+ ? `Board ${r.board.storyboardId} built: ${r.board.shotCodes.length} Shot${r.board.shotCodes.length === 1 ? '' : 's'} (${r.board.shotCodes.join(', ')}), nothing generated.${r.board.timing.length ? ` Timing: ${r.board.timing.join(' ')}` : ''}`
6933
+ : `${cuts} cut${cuts === 1 ? '' : 's'} found in ${r.breakdown.sourceCode ?? 'the reference'}; frames saved, no board yet.`;
6934
+ return ok(r, `${fetched}${head} ${JSON.stringify(r)}`);
6935
+ },
6936
+ };
6937
+ // ── Product intake ──────────────────────────────────────────────────────
6938
+ // A product page becomes Library items a remade ad's roles can use: the product
6939
+ // (a thing, with its pictures) and its brand (a look, with its logo and colours).
6940
+ // Read and write are two tools so a host can auto-approve the read.
6941
+ export const getProductPage = {
6942
+ id: 'slates_get_product_page',
6943
+ description: "Read a product page without changing anything: the product's name, description, brand, slogan, price, pictures, logo candidates, the brand's declared colours and the page's bullet points, each with where it came from (json-ld product data, a Shopify store's product data, open-graph sharing tags, other meta tags, or the page's own pictures by size), plus notes on what the page lacks. The desktop fetches the page itself (public addresses only, no browser, nothing signed in). A page that builds itself with JavaScript, an ad library link, a post, or a link to a picture or video file is refused with the reason. Free; writes nothing. Read here first when the user names a product page, then make the product with slates_import_product.",
6944
+ input: z
6945
+ .object({
6946
+ url: z.string().url().describe("The product page, such as a shop's /products/... page."),
6947
+ })
6948
+ .strict(),
6949
+ async run(input, ctx) {
6950
+ await ctx.desktop().requireCapability('product-intake', 'reading product pages');
6951
+ return ok(await ctx.desktop().get('/agent/library/intake', { url: input.url }));
6952
+ },
6953
+ };
6954
+ export const importProduct = {
6955
+ id: 'slates_import_product',
6956
+ billable: false,
6957
+ description: "Add a product to the Library from its page, as the app's Add as product does: the product becomes a thing (in Products, or the things categoryId given) with the page's first picture as its picture, the next ones as its extra pictures and the page's bullet points, price and link as its notes; its brand becomes a look with the brand's logo as its picture and the page's and logo's colours as its palette. A look of the same name already in the Library is filled in where empty, never overwritten. Pictures land in a Media folder named after the product. Give url, filePaths (absolute paths to pictures on this computer, the product's first), or both. html is the page's HTML when you already have it (a page that builds itself with JavaScript, read in your own browser); url still names the page and its pictures are still fetched. itemId fills a thing already in the Library instead of making a product, as the card's Fill from the copied product page… does: the page's pictures go after its extra pictures (the first becomes its picture when it has none; a picture it holds is not added twice), its notes are filled only when empty, and its name and category stay; not with categoryId or name. Free; nothing is generated. The result gives the product and the brand with their mention (@name, #name) for prompts and for slates_break_down_reference roles (itemId), each picture and where it came from, each picture left out with its reason, and notes on what the page lacked.",
6958
+ input: z
6959
+ .object({
6960
+ projectId: z.string().uuid(),
6961
+ url: z.string().url().optional().describe('The product page.'),
6962
+ html: z.string().min(1).optional().describe("The page's HTML, read instead of fetching the page. Needs url."),
6963
+ filePaths: z.array(z.string().min(1)).optional().describe('Absolute paths to pictures of the product on this computer, first in the order given.'),
6964
+ name: z.string().min(1).max(120).optional().describe("The product's name. Defaults to the page's, else the first file's."),
6965
+ categoryId: z.string().uuid().optional().describe('A things category (slates_list_library) to file the product in. Defaults to Products.'),
6966
+ itemId: z.string().uuid().optional().describe('A thing already in the Library (slates_list_library) to fill from the page instead of making a product.'),
6967
+ brand: z.boolean().optional().describe('false: make no look for the brand. Default true.'),
6968
+ maxPictures: z.number().int().min(1).optional().describe('How many pictures to fetch from the page. Default 6; the desktop takes at most 12.'),
6969
+ })
6970
+ .strict(),
6971
+ async run(input, ctx) {
6972
+ await ctx.desktop().requireCapability('product-intake', 'adding products from their pages');
6973
+ if (!input.url && !input.filePaths?.length)
6974
+ throw new Error('Give url (the product page), filePaths (pictures on this computer), or both.');
6975
+ if (input.html && !input.url)
6976
+ throw new Error('html needs url: the address the page came from.');
6977
+ if (input.itemId) {
6978
+ await ctx.desktop().requireCapability('product-fill', 'filling an item already in the Library from a product page');
6979
+ if (input.categoryId || input.name)
6980
+ throw new Error('itemId fills an item that keeps its name and category: leave out categoryId and name.');
6981
+ }
6982
+ const r = await ctx.desktop().post('/agent/library/intake', input);
6983
+ const brand = r.brand ? ` Its brand ${r.brand.mention} ${r.brandReused ? 'was already in the Library and was filled in' : 'is a new look'}.` : '';
6984
+ const left = r.skipped.length ? ` ${r.skipped.length} picture${r.skipped.length === 1 ? '' : 's'} left out (see skipped).` : '';
6985
+ const pictures = `${r.pictures.length} ${r.filled ? 'more ' : ''}picture${r.pictures.length === 1 ? '' : 's'}`;
6986
+ const head = `${r.filled ? `Filled ${r.product.mention} with` : `Added ${r.product.mention} with`} ${pictures}.${brand}${left}${r.notes.length ? ` ${r.notes.join(' ')}` : ''}`;
6987
+ return ok(r, `${head} ${JSON.stringify(r)}`);
6988
+ },
6989
+ };
6320
6990
  export const updateStoryboard = {
6321
6991
  id: 'slates_update_storyboard',
6322
6992
  description: 'Update a board\'s name and/or description.',
@@ -7686,6 +8356,9 @@ export function resolveGuideTopic(topic) {
7686
8356
  const t = topic.trim().toLowerCase();
7687
8357
  if (Object.hasOwn(SKILLS, t))
7688
8358
  return t;
8359
+ // The brain's front door: the Director card and the router (prompts/brain.ts).
8360
+ if (ROUTER_ALIASES.includes(t))
8361
+ return BRAIN_ROUTER;
7689
8362
  if (t === 'slates-character-turnaround' || t === 'character-turnaround') {
7690
8363
  return 'slates-character-identity';
7691
8364
  }
@@ -7707,8 +8380,13 @@ export function resolveGuideTopic(topic) {
7707
8380
  // Timeline craft: placing transitions, and the cutting pass (trim, roll, slip, J- and L-cuts).
7708
8381
  if (t === 'transition' || t === 'transitions' || t === 'dissolve' || t === 'crossfade' || t === 'wipe')
7709
8382
  return 'slates-transitions';
8383
+ // Starting from a finished ad: the breakdown and the remake.
8384
+ if (t === 'remake' || t === 'reference ad' || t === 'reference-ad' || t === 'breakdown' || t === 'break down')
8385
+ return 'slates-storyboard-from-script';
7710
8386
  if (t === 'cut' || t === 'cuts' || t === 'cutting' || t === 'editing' || t === 'pacing' || t === 'trim' || t === 'j-cut' || t === 'l-cut' || t === 'split-edit' || t === 'split edit')
7711
8387
  return 'slates-cuts';
8388
+ if (['variants', 'variant', 'ad-variants', 'ad variants', 'hook variants', 'variant grid', 'variant-grid'].includes(t))
8389
+ return 'slates-ad-variants';
7712
8390
  if (['captions', 'caption', 'subtitles', 'subtitle', 'transcribe', 'transcript', 'transcription'].includes(t))
7713
8391
  return 'slates-captions';
7714
8392
  // `motion-graphics` is HyperFrames' own guide, matched by name before these aliases.
@@ -7853,6 +8531,60 @@ export function resolveGuideTopic(topic) {
7853
8531
  }
7854
8532
  return null;
7855
8533
  }
8534
+ /** Edits between two names: insert, delete, substitute or swap two neighbours (optimal string alignment). */
8535
+ function editDistance(a, b) {
8536
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
8537
+ for (let j = 1; j <= b.length; j++)
8538
+ d[0][j] = j;
8539
+ for (let i = 1; i <= a.length; i++) {
8540
+ for (let j = 1; j <= b.length; j++) {
8541
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
8542
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
8543
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
8544
+ }
8545
+ }
8546
+ return d[a.length][b.length];
8547
+ }
8548
+ /**
8549
+ * The one guide a near-miss name means: the name without its `slates-` prefix, or a typo of one name
8550
+ * ("slaes-direct-response-ad"). Two names equally close come back as `tied`, for the caller to name rather
8551
+ * than pick. Only the guide op uses it: a model id resolves exactly or not at all (resolveGuideTopic), since
8552
+ * a near guess there would gate a generation on another model's guide.
8553
+ */
8554
+ export function nearestGuideName(topic, names) {
8555
+ const t = topic.trim().toLowerCase().replace(/[\s_]+/g, '-');
8556
+ if (!t || t.length > 128)
8557
+ return null;
8558
+ if (names.includes(t))
8559
+ return { name: t };
8560
+ if (names.includes(`slates-${t}`))
8561
+ return { name: `slates-${t}` };
8562
+ // Two edits in a long name, one in a short one, none under four letters: past that it is another guide.
8563
+ const core = t.replace(/^slates-/, '').length;
8564
+ const allowed = core >= 8 ? 2 : core >= 4 ? 1 : 0;
8565
+ // A version is not a typo: seedance-2-0 is not seedance-2-5, and kling-v2 is not kling-v3.
8566
+ const digits = (s) => (s.match(/\d+/g) ?? []).join('.');
8567
+ const version = digits(t);
8568
+ let best = allowed + 1;
8569
+ let closest = [];
8570
+ for (const name of new Set(names)) {
8571
+ if (digits(name) !== version)
8572
+ continue;
8573
+ // A length gap past the budget, against the name as typed or prefixed, is past it in edits too.
8574
+ if (Math.abs(name.length - t.length) > allowed && Math.abs(name.length - t.length - 7) > allowed)
8575
+ continue;
8576
+ const d = Math.min(editDistance(t, name), editDistance(`slates-${t}`, name));
8577
+ if (d < best) {
8578
+ best = d;
8579
+ closest = [name];
8580
+ }
8581
+ else if (d === best && d <= allowed)
8582
+ closest.push(name);
8583
+ }
8584
+ if (!closest.length)
8585
+ return null;
8586
+ return closest.length === 1 ? { name: closest[0] } : { tied: closest.sort() };
8587
+ }
7856
8588
  // Discovery is the first call of most briefs: a slow or unentitled member check
7857
8589
  // must not cost every call a round trip, or hang free craft behind a 30s read.
7858
8590
  const MEMBER_CATALOG_TTL_MS = 60_000;
@@ -7910,6 +8642,10 @@ export const getPromptingGuide = {
7910
8642
  if (topic === WORKING_METHOD_TOPIC) {
7911
8643
  // Imported here: agent-doctrine imports this module at load.
7912
8644
  const { buildAgentDoctrine } = await import('../prompts/agent-doctrine.js');
8645
+ // Its per-model guide line reads the served brain, so the brain is checked first: a signed-in user whose brain
8646
+ // is not cached yet is otherwise told to connect.
8647
+ if (ctx?.cloud)
8648
+ await refreshServedBrain(ctx.cloud);
7913
8649
  const content = buildAgentDoctrine({ surface: 'mcp' });
7914
8650
  return { text: content, data: { topic: WORKING_METHOD_TOPIC, bytes: Buffer.byteLength(content, 'utf8'), guide: content } };
7915
8651
  }
@@ -7917,9 +8653,31 @@ export const getPromptingGuide = {
7917
8653
  const content = input.query || input.depth === 'full' ? appManualSections(input.query) : appManualIndex();
7918
8654
  return { text: content, data: { topic: 'app-manual', bytes: Buffer.byteLength(content, 'utf8'), guide: content } };
7919
8655
  }
8656
+ if (topic === MY_BRAIN_TOPIC) {
8657
+ // What an agent reads of the user's own brain before the router, on request: the router's answer carries it
8658
+ // too, and so does the router the MCP server sends a connection that has not opened it.
8659
+ const content = myBrainPreload() || `The user's own brain (My brain) is empty: no files in ${myBrainDir()}. Each file there is a markdown guide in the shared skills' shape (frontmatter, then an operative summary); a file named like a shared guide adds their rules to it, a new name adds a guide, and profile.md is read first.`;
8660
+ return { text: content, data: { topic: MY_BRAIN_TOPIC, bytes: Buffer.byteLength(content, 'utf8'), guide: content } };
8661
+ }
7920
8662
  const hyperframes = await loadHyperframes();
8663
+ // The playbooks, rules and model guides come from the account's tier (skills/served.ts): checked against the
8664
+ // server at most every ten minutes, the cache when it cannot be reached.
8665
+ if (ctx?.cloud)
8666
+ await refreshServedBrain(ctx.cloud);
8667
+ const served = servedBrain();
8668
+ // A playbook past the account's tier: the job still runs, on the general rules, and the user hears once where
8669
+ // the playbook lives (the server's own words).
8670
+ const locked = topic ? served.locked.find(entry => entry.name === topic || entry.name === `slates-${topic}`) : undefined;
8671
+ if (locked) {
8672
+ const guide = locked.notice ?? `${locked.name} is not open to this account. Run the job on the general rules.`;
8673
+ // The guide gate makes an agent read what this account holds; a guide it cannot open never blocks a generation.
8674
+ ctx?.guidesRead?.add(locked.name);
8675
+ return { text: guide, data: { topic: locked.name, tier: locked.tier, locked: true, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
8676
+ }
8677
+ // The shared brain with the user's My brain laid over it; theirs wins on a conflict (skills/my-brain.ts).
8678
+ const brain = brainSkills();
7921
8679
  // A motion skill or file by its exact name wins over an alias (`motion-audio` is not `audio`).
7922
- const hf = topic && !Object.hasOwn(SKILLS, topic) ? findHyperframesGuide(hyperframes, topic) : null;
8680
+ const hf = topic && !Object.hasOwn(brain.skills, topic) ? findHyperframesGuide(hyperframes, topic) : null;
7923
8681
  if (hf) {
7924
8682
  const depth = input.depth ?? 'card';
7925
8683
  const body = depth === 'card' && !input.query?.trim() ? hyperframesCard(hf.content) : retrieveGuide(hf.key, hf.content, depth, input.query);
@@ -7927,12 +8685,37 @@ export const getPromptingGuide = {
7927
8685
  const guide = `${hyperframesGuideHeader(hf.key)}${body}${others.length ? `\n\nIts other files (request each as a topic): ${others.join(', ')}` : ''}`;
7928
8686
  return { text: guide, data: { topic: hf.key, tier: 'free', source: 'motion', depth, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
7929
8687
  }
7930
- const resolved = topic ? resolveGuideTopic(topic) : null;
8688
+ // The user's file by its exact name wins over an alias (their `flux-portraits` is theirs, not the FLUX guide);
8689
+ // the router's names are reserved in the loader, so none of them reaches here as a local file. A name missing
8690
+ // its `slates-` prefix is that guide, resolved here so it never waits on the member check.
8691
+ // With no brain on this machine, an exact `slates-*` name (the one a guide-gate refusal gives) is that guide, not
8692
+ // an unknown topic: it answers with how to get the brain instead of the catalog, and so never loops.
8693
+ const unheld = topic && served.source === 'none' && /^slates-[a-z0-9-]+$/.test(topic) ? topic : null;
8694
+ const resolved = topic ? (Object.hasOwn(brain.skills, topic) ? topic : resolveGuideTopic(topic) ?? (Object.hasOwn(brain.skills, `slates-${topic}`) ? `slates-${topic}` : unheld)) : null;
8695
+ if (resolved && !Object.hasOwn(brain.skills, resolved)) {
8696
+ // An alias named a guide this process does not hold: a locked one, or no brain at all (not connected, and
8697
+ // nothing cached yet).
8698
+ const lockedAlias = served.locked.find(entry => entry.name === resolved);
8699
+ const guide = lockedAlias?.notice ?? `The guide ${resolved} comes from the connected Slates account and is not on this machine (${served.problem ?? 'no brain received yet'}). ${CONNECT_FOR_BRAIN}, then ask again.`;
8700
+ // A locked guide's notice carries its craft card (slates-api lib/brain.ts lockedNotice), so it counts as read; a
8701
+ // guide that never arrived does not, so no generation runs without the card (Eric, 2026-10-23: a hard blocker).
8702
+ if (lockedAlias)
8703
+ ctx?.guidesRead?.add(resolved);
8704
+ return { text: guide, data: { topic: resolved, ...(lockedAlias ? { tier: lockedAlias.tier, locked: true } : { unavailable: true }), bytes: Buffer.byteLength(guide, 'utf8'), guide } };
8705
+ }
7931
8706
  if (resolved) {
7932
8707
  const depth = input.depth ?? 'card';
7933
- const guide = retrieveGuide(resolved, SKILLS[resolved], depth, input.query);
8708
+ const mine = brain.mine.has(resolved);
8709
+ if (mine)
8710
+ noteUsed(resolved);
8711
+ // A file laid over a shared guide says so itself (prompts/brain.ts, overlayGuide); a new name needs the line.
8712
+ const own = mine && !Object.hasOwn(brainFiles(), resolved) ? "From the user's own brain (My brain).\n\n" : '';
8713
+ // The router's answer carries the user's brain in front, as Director's prompt does: the MCP server sends the
8714
+ // router with the preload only to a connection that has not opened it, so this answer is the agent's one copy.
8715
+ const preload = resolved === BRAIN_ROUTER ? myBrainPreload() : '';
8716
+ const guide = `${preload ? `${preload}\n\n` : ''}${own}${retrieveGuide(resolved, brain.skills[resolved], depth, input.query)}`;
7934
8717
  ctx?.guidesRead?.add(resolved);
7935
- return { text: guide, data: { topic: resolved, tier: 'free', depth, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
8718
+ return { text: guide, data: { topic: resolved, tier: 'free', ...(mine ? { source: 'my-brain' } : {}), depth: servedDepth(resolved, depth, input.query), bytes: Buffer.byteLength(guide, 'utf8'), guide } };
7936
8719
  }
7937
8720
  const member = await memberGuideCatalog(ctx);
7938
8721
  const privateEntry = member.entries.find(entry => entry.name === topic);
@@ -7953,13 +8736,24 @@ export const getPromptingGuide = {
7953
8736
  return { text: guide, data: { topic: privateEntry.name, tier: 'paid', depth, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
7954
8737
  }
7955
8738
  // Slates' guides first, then HyperFrames' (they carry the craft for HTML layers and editing).
7956
- const catalog = [...[...guideCatalog(SKILLS), ...member.entries].sort((a, b) => a.name.localeCompare(b.name)), ...hyperframesCatalog(hyperframes)];
7957
- const result = discoverGuides(catalog, { ...SKILLS, ...hyperframesSkillBodies(hyperframes) }, input.query ?? (topic && topic !== 'catalog' && topic !== 'index' ? input.topic : undefined), input.limit, input.offset);
7958
- const label = (entry) => (entry.source === 'motion' ? 'motion' : entry.tier);
8739
+ const own = guideCatalog(brain.skills).map(entry => (brain.mine.has(entry.name) ? { ...entry, source: 'my-brain' } : entry));
8740
+ // Locked playbooks stay listed, so an agent can tell the user where one lives.
8741
+ const lockedEntries = served.locked.map(entry => ({ name: entry.name, description: `(not open to this account) ${entry.description}`, tier: 'paid' }));
8742
+ const catalog = [...[...own, ...member.entries, ...lockedEntries].sort((a, b) => a.name.localeCompare(b.name)), ...hyperframesCatalog(hyperframes)];
8743
+ // A typo of one guide's name serves that guide; a name as close to two is answered with both, never a guess.
8744
+ const near = topic && topic !== 'catalog' && topic !== 'index' ? nearestGuideName(topic, catalog.map(entry => entry.name)) : null;
8745
+ if (near && 'name' in near) {
8746
+ const served = await getPromptingGuide.run({ ...input, topic: near.name }, ctx);
8747
+ // Said first, so the agent sees the substitution and learns the real name.
8748
+ return { ...served, text: `Served ${near.name} for "${input.topic}", the closest guide name.\n\n${served.text}` };
8749
+ }
8750
+ const tied = near && 'tied' in near ? near.tied : [];
8751
+ const result = discoverGuides(catalog, { ...brain.skills, ...hyperframesSkillBodies(hyperframes) }, input.query ?? (topic && topic !== 'catalog' && topic !== 'index' ? input.topic : undefined), input.limit, input.offset);
8752
+ const label = (entry) => (entry.source === 'motion' ? 'motion' : entry.source === 'my-brain' ? 'yours' : entry.tier);
7959
8753
  const guide = result.guides.map(entry => `${entry.name} (${label(entry)}): ${entry.description}${entry.sections.length ? `\n Matching sections: ${entry.sections.join('; ')}` : ''}`).join('\n\n');
7960
8754
  const rest = result.rest.length ? `\n\nEvery other guide (keyword hints above only see shared words; choose by the brief):\n${result.rest.map(entry => `- ${entry.name} (${label(entry)}): ${entry.description}`).join('\n')}` : '';
7961
- const text = `${result.fallback ? 'No keyword match; choose relevant craft from the catalog.\n\n' : ''}${guide}${rest}\n\n${result.total} ${result.query && !result.fallback ? 'keyword matches' : 'guides'}; nextOffset: ${result.nextOffset ?? 'none'}. Member guides: ${member.access}. Retrieve a name with depth card/index or query for a section. Motion guides are the motion engine's own; topic motion/${HYPERFRAMES_MAPPING} maps their CLI and Studio onto Slates. The user does not need to choose guides.`;
7962
- return { text, data: { ...result, memberAccess: member.access, bytes: Buffer.byteLength(text, 'utf8') } };
8755
+ const text = `${tied.length ? `"${input.topic}" is equally close to ${tied.join(' and ')}; request one of them by name.\n\n` : ''}${result.fallback ? 'No keyword match; choose relevant craft from the catalog.\n\n' : ''}${guide}${rest}\n\n${result.total} ${result.query && !result.fallback ? 'keyword matches' : 'guides'}; nextOffset: ${result.nextOffset ?? 'none'}. Member guides: ${member.access}. Retrieve a name with depth card/index or query for a section. Motion guides are the motion engine's own; topic motion/${HYPERFRAMES_MAPPING} maps their CLI and Studio onto Slates. The user does not need to choose guides.`;
8756
+ return { text, data: { ...result, ...(tied.length ? { tied } : {}), memberAccess: member.access, bytes: Buffer.byteLength(text, 'utf8') } };
7963
8757
  },
7964
8758
  };
7965
8759
  /**
@@ -8165,11 +8959,18 @@ export const ALL_OPERATIONS = [
8165
8959
  getUsage,
8166
8960
  getAppSettings,
8167
8961
  setAppSettings,
8962
+ getSpendLimits,
8963
+ setSpendLimits,
8168
8964
  getAsset,
8169
8965
  linkAssetSource,
8170
8966
  transcribeAsset,
8171
8967
  getAssetTranscript,
8172
8968
  editAssetTranscript,
8969
+ cutByTranscript,
8970
+ getBeatGrid,
8971
+ findBeats,
8972
+ editBeatGrid,
8973
+ cutToBeats,
8173
8974
  extractVideoFrame,
8174
8975
  getMe,
8175
8976
  getCreditBalance,
@@ -8229,9 +9030,14 @@ export const ALL_OPERATIONS = [
8229
9030
  getExportBatch,
8230
9031
  cancelExportBatch,
8231
9032
  getVariantGrid,
9033
+ getVariants,
9034
+ editVariantSlots,
9035
+ editVariants,
9036
+ getRecipe,
8232
9037
  reframeClip,
8233
9038
  getReframeReport,
8234
9039
  getTimeline,
9040
+ getTimelineLoudness,
8235
9041
  addClipToTimeline,
8236
9042
  reorderClips,
8237
9043
  removeClip,
@@ -8283,6 +9089,10 @@ export const ALL_OPERATIONS = [
8283
9089
  getTemplate,
8284
9090
  exportTemplate,
8285
9091
  importTemplate,
9092
+ getReferenceBreakdown,
9093
+ breakDownReference,
9094
+ getProductPage,
9095
+ importProduct,
8286
9096
  updateStoryboard,
8287
9097
  deleteStoryboard,
8288
9098
  updateScene,