@slatesvideo/shared 0.7.23 → 0.7.25

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.
@@ -1,3 +1,4 @@
1
+ import { CONFIRM_CREDITS } from './confirm-threshold.js';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { MAX_IMAGE_VARIATIONS, SHEET_TOOL_ASPECT_RATIO, SHEET_TOOL_GPT_QUALITY } from '../prompts/generation-policy.js';
3
4
  import { STYLE_LIBRARY, DEFAULT_STYLE_ID } from '../prompts/style-library.js';
@@ -57,6 +58,7 @@ import { describeBannedTokens, bannedTokenWarning, describeBannedTokensForSkill,
57
58
  // that make a shot good rather than merely un-bad — and it rides the estimate
58
59
  // RESULT, which the doctrine already makes the agent call before generating.
59
60
  // Zero prefix bytes, present at the moment the model has just been named.
61
+ import { hasReferenceMention } from '../prompts/reference-composer.js';
60
62
  import { describeCraftCard } from '../prompts/craft-cards.js';
61
63
  // ONE captioning rule for a generated asset, shared with the desktop gallery.
62
64
  import { assetCaption } from '../prompts/asset-label.js';
@@ -95,35 +97,62 @@ export class GuideNotReadError extends Error {
95
97
  model;
96
98
  guide;
97
99
  code = 'GUIDE_NOT_READ';
98
- constructor(model, guide) {
100
+ constructor(model, guide, full = false) {
101
+ const request = `topic "${guide}"${full ? ' and depth "full"' : ''}`;
99
102
  const head = `Refused: this session has not read ${guide}, the guide for ${model}. Nothing was generated or charged. `;
100
103
  const body = brainSkills().skills[guide];
101
104
  const served = servedBrain();
102
105
  const locked = body === undefined ? served.locked.find(entry => entry.name === guide) : undefined;
103
106
  super(body !== undefined
104
107
  ? head +
105
- `Call slates_get_prompting_guide with topic "${guide}", rewrite the prompt against it, then call this again. Its card:\n\n` +
108
+ `Call slates_get_prompting_guide with ${request}, rewrite the prompt against it, then call this again. Its card:\n\n` +
106
109
  // The card this user's brain serves, so a model guide from their My brain is the one in the refusal.
107
110
  describeCraftCard(guide, body)
108
111
  : locked
109
112
  ? // Past this account's tier: no body here, so the server's notice (its card included) is what it reads.
110
113
  head +
111
- `Call slates_get_prompting_guide with topic "${guide}", rewrite the prompt against what it says, then call this again. What it says:\n\n` +
114
+ `Call slates_get_prompting_guide with ${request}, rewrite the prompt against what it says, then call this again. What it says:\n\n` +
112
115
  (locked.notice ?? `${guide} is not open to this account. Run the job on the general rules.`)
113
116
  : // No copy here and none locked: the brain never arrived, so asking for the guide again cannot help.
114
117
  head +
115
118
  `The guide comes from the connected Slates account and is not on this machine (${served.problem ?? 'no brain received yet'}). ` +
116
- `${CONNECT_FOR_BRAIN}; then call slates_get_prompting_guide with topic "${guide}" and call this again.`);
119
+ `${CONNECT_FOR_BRAIN}; then call slates_get_prompting_guide with ${request} and call this again.`);
117
120
  this.model = model;
118
121
  this.guide = guide;
119
122
  }
120
123
  }
121
- /** Refuse the generation when the session keeps a ledger and `model`'s guide is not in it. A seat with no model id names its guide. */
122
- function requireGuideRead(ctx, model, guide = model ? resolveGuideTopic(model) : null) {
123
- if (!ctx?.guidesRead || !model)
124
+ /**
125
+ * Routine calls can use a delivered estimate card. Other calls and retries need the full guide.
126
+ * A locked guide's returned notice counts as the most this account can read.
127
+ */
128
+ export function recordGenerationRejection(ctx, fallbackOp, model, topics = new Set()) {
129
+ const rejected = ctx.guideEvidence?.rejected;
130
+ if (!rejected)
124
131
  return;
125
- if (guide && !ctx.guidesRead.has(guide))
126
- throw new GuideNotReadError(model, guide);
132
+ if (topics.size) {
133
+ for (const topic of topics)
134
+ rejected.add(topic);
135
+ }
136
+ else {
137
+ rejected.add((typeof model === 'string' && resolveGuideTopic(model)) || fallbackOp);
138
+ }
139
+ }
140
+ function requireGuideRead(ctx, model, guide = model ? resolveGuideTopic(model) : null, routineOp) {
141
+ if (!ctx || !model || !guide)
142
+ return;
143
+ ctx.onGenerationGuide?.(guide);
144
+ if (!ctx.guidesRead)
145
+ return;
146
+ const evidence = ctx.guideEvidence;
147
+ if (!evidence) {
148
+ if (!ctx.guidesRead.has(guide))
149
+ throw new GuideNotReadError(model, guide);
150
+ return;
151
+ }
152
+ const full = !routineOp || evidence.rejected.has(guide) || evidence.rejected.has(routineOp);
153
+ if (evidence.full.has(guide) || (!full && (evidence.cards.has(guide) || ctx.guidesRead.has(guide))))
154
+ return;
155
+ throw new GuideNotReadError(model, guide, full);
127
156
  }
128
157
  /** Throw if the caller has cancelled. Call between billable items, never inside one. */
129
158
  function throwIfCancelled(ctx, detail) {
@@ -172,7 +201,7 @@ function ok(data, text) {
172
201
  // the same credit value); balances the same. Read via creditCost(); display
173
202
  // via fmtCredits(). The confirm gate fires above CONFIRM_CREDITS (≈ the old
174
203
  // $0.50 gate at the 3¢/credit peg).
175
- export const CONFIRM_CREDITS = 17;
204
+ export { CONFIRM_CREDITS } from './confirm-threshold.js';
176
205
  const CENTS_PER_CREDIT = 3; // peg: 1 credit = 3¢ billed = 2¢ COGS (mirror of slates-api)
177
206
  /**
178
207
  * The desktop deviation guard's ceiling multiplier: the Studio Agent pauses and
@@ -2076,6 +2105,32 @@ export const estimateGenerationCost = {
2076
2105
  });
2077
2106
  }
2078
2107
  }
2108
+ // 3b) 5s-block tool keys (motion transfer & lip-sync): accept both dynamic
2109
+ // block keys (`kling-mc-std-10s`) and base stem + duration (`kling-mc-std`, 10).
2110
+ // Query the cloud's dynamic costKey endpoint first; fall back to scaling the
2111
+ // registry's 5s block row when a static price list does not synthesize rows.
2112
+ if (!key && !input.seedanceDraft) {
2113
+ const toolKeyMatch = /^(kling-lip-sync-(?:video|avatar|avatar-pro)|kling-mc-(?:std|pro))(?:-(?:(\d+)s))?$/.exec(input.model);
2114
+ if (toolKeyMatch) {
2115
+ const stem = toolKeyMatch[1];
2116
+ const secs = toolKeyMatch[2] ? Number(toolKeyMatch[2]) : input.duration;
2117
+ if (!secs) {
2118
+ return ok({
2119
+ requires_clarification: true,
2120
+ missing: ['duration'],
2121
+ message: `${stem} bills per 5-second block of the driving clip — pass duration in seconds (or a block key like ${stem}-10s).`,
2122
+ });
2123
+ }
2124
+ const blocks = Math.max(1, toolBlocks(secs));
2125
+ key = toolBlockKey(stem, blocks);
2126
+ await loadDynamicPrice(ctx, byKey, key);
2127
+ if (!byKey.has(key)) {
2128
+ const oneBlock = byKey.get(toolBlockKey(stem, 1));
2129
+ if (oneBlock != null)
2130
+ byKey.set(key, oneBlock * blocks);
2131
+ }
2132
+ }
2133
+ }
2079
2134
  await loadDynamicPrice(ctx, byKey, key);
2080
2135
  const perCredits = key != null ? byKey.get(key) : undefined;
2081
2136
  if (key != null && perCredits == null && key !== input.model) {
@@ -3492,7 +3547,8 @@ export const generateImage = {
3492
3547
  // A desktop before the folder rule ignores folderId and files at the root.
3493
3548
  if (input.folderId !== undefined)
3494
3549
  await ctx.desktop().requireCapability('media-folder', 'choosing the folder a result lands in');
3495
- requireGuideRead(ctx, imageModel);
3550
+ const multiReference = (input.referenceAssetIds?.length ?? 0) + (input.referenceImageUrls?.length ?? 0) > 1;
3551
+ requireGuideRead(ctx, imageModel, undefined, !multiReference && !hasReferenceMention(input.prompt) && (input.count ?? 1) === 1 ? generateImage.id : undefined);
3496
3552
  const promptWarning = bannedTokenWarning(input.prompt, 'image', promptingSkillFor(imageModel));
3497
3553
  input = { ...input, resolution: input.resolution ?? defaultImageResolutionFor(imageModel) };
3498
3554
  if (!input.aspectRatio || !input.resolution) {
@@ -4814,7 +4870,12 @@ export const generateVideo = {
4814
4870
  }
4815
4871
  if (input.seedanceDraft)
4816
4872
  input.videoResolution = draftResolution(input.model, input.videoResolution ?? resolved.videoResolution);
4817
- requireGuideRead(ctx, input.model);
4873
+ const imageRefs = (input.firstFrameAssetId ? 1 : 0) + (input.lastFrameAssetId ? 1 : 0) +
4874
+ (input.ingredientAssetIds?.length ?? 0) + (input.characterAssetIds?.length ?? 0) +
4875
+ (input.environmentAssetIds?.length ?? 0) + (input.styleAssetIds?.length ?? 0);
4876
+ const sceneReference = input.videoReferenceAssetId || input.videoReferenceAssetIds?.length ||
4877
+ input.audioReferenceAssetId || input.audioReferenceAssetIds?.length;
4878
+ requireGuideRead(ctx, input.model, undefined, imageRefs <= 1 && !input.lastFrameAssetId && !sceneReference && !hasReferenceMention(input.prompt ?? '') ? generateVideo.id : undefined);
4818
4879
  if (input.duration == null && resolved.duration != null)
4819
4880
  input.duration = resolved.duration;
4820
4881
  if (input.videoResolution == null && resolved.videoResolution != null)
@@ -5538,7 +5599,8 @@ export const generateAudio = {
5538
5599
  folderId: folderIdField,
5539
5600
  }),
5540
5601
  run: async (input, ctx) => {
5541
- requireGuideRead(ctx, input.model);
5602
+ const multiReference = (input.audioReferenceAssetIds?.length ?? 0) + (input.imageReferenceAssetId ? 1 : 0) > 1;
5603
+ requireGuideRead(ctx, input.model, undefined, multiReference ? undefined : generateAudio.id);
5542
5604
  const lengthError = promptLengthError(input.model, input.prompt);
5543
5605
  if (lengthError)
5544
5606
  throw new Error(lengthError);
@@ -6339,7 +6401,10 @@ export const getGenerationStatus = {
6339
6401
  const r = await desktop.get('/agent/generation/status', { id: input.generationId });
6340
6402
  const g = r.generation;
6341
6403
  const status = g?.status ?? r.status;
6342
- const terminal = status === 'completed' || status === 'failed' || status === 'cancelled';
6404
+ const failed = status === 'failed' || status === 'rejected';
6405
+ if (failed)
6406
+ recordGenerationRejection(ctx, getGenerationStatus.id, g?.model);
6407
+ const terminal = status === 'completed' || failed || status === 'cancelled';
6343
6408
  if (terminal || Date.now() >= deadline) {
6344
6409
  if (!g)
6345
6410
  return ok(r);
@@ -7899,12 +7964,29 @@ export const updateOverlayClip = {
7899
7964
  },
7900
7965
  };
7901
7966
  const KEYFRAME_PROPERTY_IDS = ['positionX', 'positionY', 'scale', 'rotation', 'opacity', 'cropLeft', 'cropTop', 'cropRight', 'cropBottom', 'focusX', 'focusY', 'zoom',
7902
- 'saturation', 'grain', 'exposure', 'pitch', 'yaw', 'perspective', 'radius', 'shadowX', 'shadowY', 'shadowBlur', 'shadowOpacity', 'borderWidth', 'borderOpacity',
7967
+ 'saturation', 'grain', 'exposure', 'contrast', 'temperature', 'tint', 'highlights', 'shadows',
7968
+ 'lutIntensity', 'matteFeather', 'chromaTolerance', 'chromaSoftness', 'chromaSpill',
7969
+ 'pitch', 'yaw', 'perspective', 'radius', 'shadowX', 'shadowY', 'shadowBlur', 'shadowOpacity', 'borderWidth', 'borderOpacity',
7903
7970
  'shadowRed', 'shadowGreen', 'shadowBlue', 'borderRed', 'borderGreen', 'borderBlue', 'blur'];
7904
7971
  /** The keys a desktop before layers and panels refuses. */
7905
7972
  const PANEL_KEY_IDS = new Set(KEYFRAME_PROPERTY_IDS.slice(KEYFRAME_PROPERTY_IDS.indexOf('saturation')));
7906
7973
  /** A panel colour's channels, which a desktop before panel colour keys refuses. */
7907
7974
  const PANEL_COLOUR_KEY_IDS = new Set(['shadowRed', 'shadowGreen', 'shadowBlue', 'borderRed', 'borderGreen', 'borderBlue']);
7975
+ /** Mirrors the grade, LUT and mask ranges in slate's KEYFRAME_PROPERTIES (lockstep check 12). */
7976
+ const GRADE_MASK_KEY_RANGES = {
7977
+ contrast: { min: -1, max: 1 },
7978
+ temperature: { min: -1, max: 1 },
7979
+ tint: { min: -1, max: 1 },
7980
+ highlights: { min: -1, max: 1 },
7981
+ shadows: { min: -1, max: 1 },
7982
+ lutIntensity: { min: 0, max: 1 },
7983
+ matteFeather: { min: 0, max: 1 },
7984
+ chromaTolerance: { min: 0, max: 1 },
7985
+ chromaSoftness: { min: 0, max: 1 },
7986
+ chromaSpill: { min: 0, max: 1 },
7987
+ };
7988
+ const GRADE_MASK_KEY_IDS = new Set(Object.keys(GRADE_MASK_KEY_RANGES));
7989
+ const GRADE_MASK_KEY_LIMITS = Object.entries(GRADE_MASK_KEY_RANGES).map(([id, { min, max }]) => `${id} ${min}..${max}`).join(', ');
7908
7990
  export const setClipKeyframes = {
7909
7991
  id: 'slates_set_clip_keyframes',
7910
7992
  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. The look and the panel key too, each key replacing the clip's own value: saturation 0..2 (1 as shot), grain 0..1, exposure -4..4 stops; pitch and yaw -85..85 degrees, perspective 0..1; radius 0..0.5, shadowX and shadowY -0.5..0.5, shadowBlur 0..0.25 and borderWidth 0..0.05, all in frame heights; shadowOpacity and borderOpacity 0..1 (a key above 0 draws a shadow or border the clip has none of); a shadow or border colour keys as its red, green and blue, each 0..1 (shadowRed, shadowGreen, shadowBlue; borderRed, borderGreen, borderBlue), keyed on the same frames so the colour eases from key to key; blur 0..1. 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.",
@@ -7916,7 +7998,7 @@ export const setClipKeyframes = {
7916
7998
  .object(Object.fromEntries(KEYFRAME_PROPERTY_IDS.map((id) => [id, keyframeList.optional()])))
7917
7999
  .strict()
7918
8000
  .refine((p) => Object.keys(p).length > 0, { message: 'name at least one property' })
7919
- .describe('Each property to set, with its keys. Example punch-in over one second at 24 fps: {"scale":[{"frame":0,"value":1,"easing":"ease-in-out"},{"frame":24,"value":1.25}]}.'),
8001
+ .describe(`Each property to set, with its keys. Grade, LUT and mask ranges: ${GRADE_MASK_KEY_LIMITS}. LUT and mask keys apply only while the corresponding LUT or mask is present. matteFeather is for subject or shape masks. Example punch-in over one second at 24 fps: {"scale":[{"frame":0,"value":1,"easing":"ease-in-out"},{"frame":24,"value":1.25}]}.`),
7920
8002
  }),
7921
8003
  async run(input, ctx) {
7922
8004
  const desktop = ctx.desktop();
@@ -7925,6 +8007,8 @@ export const setClipKeyframes = {
7925
8007
  await desktop.requireCapability('clip-panels', "keys on a clip's look, 3D, panel and blur");
7926
8008
  if (Object.keys(input.properties).some((id) => PANEL_COLOUR_KEY_IDS.has(id)))
7927
8009
  await desktop.requireCapability('panel-colour-keys', "keys on a panel's shadow and border colours");
8010
+ if (Object.keys(input.properties).some((id) => GRADE_MASK_KEY_IDS.has(id)))
8011
+ await desktop.requireCapability('grade-mask-keys', 'keys on grade, LUT strength and mask amounts');
7928
8012
  await requireKeysBetweenFrames(desktop, ...Object.values(input.properties));
7929
8013
  return ok(await desktop.post('/agent/timeline/keyframes', input));
7930
8014
  },
@@ -10008,6 +10092,57 @@ export const writeScriptDocument = {
10008
10092
  return ok(data, 'Script document updated.');
10009
10093
  },
10010
10094
  };
10095
+ // The document capability predates the Markdown and breakdown routes.
10096
+ const SCRIPT_MARKDOWN_MIN_VERSION = '1.6.15';
10097
+ export const readScriptMarkdown = {
10098
+ id: 'slates_read_script_markdown',
10099
+ description: 'Read the board script as anchored Markdown, with its revision, scene and block offsets, Shot ranges, and new human edits. Advances the reader’s cursor. For edits or a shot breakdown, open the job’s playbook first, then read the script. Use slates_get_script_document for structured text and formatting without advancing the cursor.',
10100
+ input: z.object({
10101
+ storyboardId: z.string().uuid(),
10102
+ readerId: z.string().refine(id => id.trim().length > 0).optional()
10103
+ .describe('Reuse a stable reader ID to track human edits independently. Defaults to default.'),
10104
+ }),
10105
+ async run(input, ctx) {
10106
+ await ctx.desktop().requireCapability('script-documents', 'Reading script Markdown', SCRIPT_MARKDOWN_MIN_VERSION);
10107
+ return ok(await ctx.desktop().post('/agent/script/read', input), 'Script Markdown read and reader cursor advanced.');
10108
+ },
10109
+ };
10110
+ export const proposeScriptMarkdown = {
10111
+ id: 'slates_propose_script_markdown',
10112
+ description: 'Propose changes to the board’s anchored Markdown as a group of text and formatting suggestions for review. Returns the group ID and redlines, or a null group ID if nothing changed. Read with slates_read_script_markdown first and preserve scene anchors in order. For exact passage suggestions use slates_update_script_suggestions. For a direct text edit use slates_edit_script.',
10113
+ input: z.object({
10114
+ storyboardId: z.string().uuid(),
10115
+ boardRevision: z.number().int().nonnegative().describe('The revision returned by slates_read_script_markdown. Stale revisions are refused.'),
10116
+ markdown: z.string().describe('The full revised Markdown, with the scene anchor comments in their original order.'),
10117
+ }),
10118
+ async run(input, ctx) {
10119
+ await ctx.desktop().requireCapability('script-documents', 'Proposing script Markdown edits', SCRIPT_MARKDOWN_MIN_VERSION);
10120
+ const data = await ctx.desktop().post('/agent/script/write', input);
10121
+ return ok(data, data.groupId ? 'Script Markdown edits proposed for review.' : 'The proposed Markdown matches the script.');
10122
+ },
10123
+ };
10124
+ const shotBreakdownInput = z.object({
10125
+ storyboardId: z.string().uuid(),
10126
+ boardRevision: z.number().int().nonnegative().describe('The revision returned by slates_read_script_markdown. Stale revisions are refused.'),
10127
+ ranges: z.array(z.object({ sceneId: z.string().uuid(), start: z.number().int().nonnegative(), end: z.number().int().positive() })).min(1)
10128
+ .describe('Non-overlapping UTF-16 ranges [start, end) in scene text. Include each affected Shot in full.'),
10129
+ options: z.array(z.object({
10130
+ name: z.string().refine(name => name.trim().length > 0),
10131
+ rationale: z.string(),
10132
+ cuts: z.array(z.object({ sceneId: z.string().uuid(), at: z.number().int().positive() }))
10133
+ .describe('UTF-16 cut offsets between words inside the affected ranges. An empty list leaves each range as one segment.'),
10134
+ })).min(2).refine(options => new Set(options.map(option => option.name)).size === options.length)
10135
+ .describe('At least two distinctly named cut options.'),
10136
+ });
10137
+ export const proposeShotBreakdown = {
10138
+ id: 'slates_propose_shot_breakdown',
10139
+ description: 'Save alternative ways to cut script passages into Shots for the creator to review in Slates. Returns the proposal ID, options, existing Shot ranges and a preview of settings each merge would discard. The script and Shots change only when the creator applies an option. For immediate Shot creation from ranges, use slates_update_script_document.',
10140
+ input: shotBreakdownInput,
10141
+ async run(input, ctx) {
10142
+ await ctx.desktop().requireCapability('script-documents', 'Proposing a shot breakdown', SCRIPT_MARKDOWN_MIN_VERSION);
10143
+ return ok(await ctx.desktop().post('/agent/script/propose-breakdown', input), 'Shot breakdown proposed for review.');
10144
+ },
10145
+ };
10011
10146
  export const editScript = {
10012
10147
  id: 'slates_edit_script',
10013
10148
  description: "One text replacement in one scene (for several edits, formatting or scene changes in one write, use slates_update_script_document): one contiguous replacement — `removed` characters at `at` become `text` (insert: removed 0; delete: text ''). Every Shot's range follows the way comment anchors follow a document: text before a Shot moves it, text after leaves it, an edit inside grows or shrinks it, typing at its end extends it unless the text starts a new line, and deleting all of a Shot's words leaves it with no words and no place on the page. Every affected Shot's `line` changes at once: this is editing the Shots. Read slates_get_script first; offsets are into that text. Pass its `rev` (or the document `revision` as `expectedRevision`): when the Script page or anything else changed the words since, the edit is refused ('the script changed since you read it', or SCRIPT_CONFLICT for a stale revision), and you re-read and measure again. The result carries the new `rev` and `revision` for a following edit.",
@@ -10141,8 +10276,12 @@ export const generateFromShots = {
10141
10276
  const quote = await desktop.quote('/agent/shots/quote', 'input', {
10142
10277
  projectId: details[0].projectId, shotIds: details.map((d) => d.id), draft,
10143
10278
  });
10144
- for (const model of new Set(quote.items.map((i) => i.model)))
10145
- requireGuideRead(ctx, model);
10279
+ const shot = details.length === 1 ? details[0] : undefined;
10280
+ const routine = shot?.cuts === 1 && shot.referenceCount <= 1 && Array.isArray(shot.references) &&
10281
+ shot.references.length <= 1 && shot.references.every((ref) => ref.kind === 'image');
10282
+ for (const model of new Set(quote.items.map((i) => i.model))) {
10283
+ requireGuideRead(ctx, model, undefined, routine ? generateFromShots.id : undefined);
10284
+ }
10146
10285
  const total = quote.items.reduce((n, i) => n + (i.credits ?? 0), 0);
10147
10286
  const largest = Math.max(0, ...quote.items.map((i) => i.credits ?? 0));
10148
10287
  // ONE approval for the set, on the STATED total; a stale fingerprint is a
@@ -10164,6 +10303,11 @@ export const generateFromShots = {
10164
10303
  fingerprint: quote.fingerprint,
10165
10304
  draft,
10166
10305
  });
10306
+ for (const item of ran.results ?? []) {
10307
+ if (item.status === 'failed' || item.status === 'rejected') {
10308
+ recordGenerationRejection(ctx, generateFromShots.id, quote.items.find((shot) => shot.shotId === item.shotId)?.model);
10309
+ }
10310
+ }
10167
10311
  return seatNote ? ok(ran, `${JSON.stringify(ran)}\n${seatNote}`) : ok(ran);
10168
10312
  },
10169
10313
  };
@@ -10681,6 +10825,7 @@ export const getPromptingGuide = {
10681
10825
  const guide = locked.notice ?? `${locked.name} is not open to this account. Run the job on the general rules.`;
10682
10826
  // The guide gate makes an agent read what this account holds; a guide it cannot open never blocks a generation.
10683
10827
  ctx?.guidesRead?.add(locked.name);
10828
+ ctx?.guideEvidence?.full.add(locked.name);
10684
10829
  return { text: guide, data: { topic: locked.name, tier: locked.tier, locked: true, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
10685
10830
  }
10686
10831
  // The shared brain with the user's My brain laid over it; theirs wins on a conflict (skills/my-brain.ts).
@@ -10716,8 +10861,10 @@ export const getPromptingGuide = {
10716
10861
  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.`;
10717
10862
  // A locked guide's notice carries its craft card (slates-api lib/brain.ts lockedNotice), so it counts as read; a
10718
10863
  // guide that never arrived does not, so no generation runs without the card (Eric, 2026-10-23: a hard blocker).
10719
- if (lockedAlias)
10864
+ if (lockedAlias) {
10720
10865
  ctx?.guidesRead?.add(resolved);
10866
+ ctx?.guideEvidence?.full.add(resolved);
10867
+ }
10721
10868
  return { text: guide, data: { topic: resolved, ...(lockedAlias ? { tier: lockedAlias.tier, locked: true } : { unavailable: true }), bytes: Buffer.byteLength(guide, 'utf8'), guide } };
10722
10869
  }
10723
10870
  if (resolved) {
@@ -10731,8 +10878,12 @@ export const getPromptingGuide = {
10731
10878
  // router with the preload only to a connection that has not opened it, so this answer is the agent's one copy.
10732
10879
  const preload = resolved === BRAIN_ROUTER ? myBrainPreload() : '';
10733
10880
  const guide = `${preload ? `${preload}\n\n` : ''}${own}${retrieveGuide(resolved, brain.skills[resolved], depth, input.query)}`;
10734
- ctx?.guidesRead?.add(resolved);
10735
- return { text: guide, data: { topic: resolved, tier: 'free', ...(mine ? { source: 'my-brain' } : {}), depth: servedDepth(resolved, depth, input.query), bytes: Buffer.byteLength(guide, 'utf8'), guide } };
10881
+ const deliveredDepth = servedDepth(resolved, depth, input.query);
10882
+ if (deliveredDepth === 'full' || (deliveredDepth === 'card' && !input.query?.trim()))
10883
+ ctx?.guidesRead?.add(resolved);
10884
+ if (deliveredDepth === 'full')
10885
+ ctx?.guideEvidence?.full.add(resolved);
10886
+ return { text: guide, data: { topic: resolved, tier: 'free', ...(mine ? { source: 'my-brain' } : {}), depth: deliveredDepth, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
10736
10887
  }
10737
10888
  const member = await memberGuideCatalog(ctx);
10738
10889
  const privateEntry = member.entries.find(entry => entry.name === topic);
@@ -10749,7 +10900,10 @@ export const getPromptingGuide = {
10749
10900
  throw new Error('Invalid member guide body');
10750
10901
  const depth = input.depth ?? 'card';
10751
10902
  const guide = retrieveGuide(privateEntry.name, result.markdown, depth, input.query);
10752
- ctx?.guidesRead?.add(privateEntry.name);
10903
+ if (depth === 'full' || (depth === 'card' && !input.query))
10904
+ ctx?.guidesRead?.add(privateEntry.name);
10905
+ if (depth === 'full')
10906
+ ctx?.guideEvidence?.full.add(privateEntry.name);
10753
10907
  return { text: guide, data: { topic: privateEntry.name, tier: 'paid', depth, bytes: Buffer.byteLength(guide, 'utf8'), guide } };
10754
10908
  }
10755
10909
  // Slates' guides first, then HyperFrames' (they carry the craft for HTML layers and editing).
@@ -10799,9 +10953,9 @@ export const loadTools = {
10799
10953
  // Worded to be true on both surfaces: the desktop agent must load an
10800
10954
  // extended tool before calling it, while the MCP server lists every tool, so
10801
10955
  // "missing from your list" never happens there by default.
10802
- description: 'Find Slates tools by task. query searches tool names and descriptions and returns a compact list. names returns up to five exact tools with their schemas; group returns a whole task group. Call the tools by their own names. If a tool you need is missing from your tool list, a names or group load adds it; a load replaces the previous optional selection, and query alone does not change it. Groups: ' + Object.entries(GROUP_SUMMARY).map(([g, s]) => `${g}: ${s}`).join('; '),
10956
+ description: 'Find Slates tools by task. query searches names and descriptions. names loads up to five exact schemas; group loads a task group. Each load replaces the previous optional selection. Search alone leaves it in place. Groups: ' + Object.entries(GROUP_SUMMARY).map(([g, s]) => `${g}: ${s}`).join('; '),
10803
10957
  input: z.object({
10804
- group: z.enum(['script', 'library', 'timeline', 'admin', 'blender']).optional(),
10958
+ group: z.enum(Object.keys(GROUP_SUMMARY)).optional(),
10805
10959
  query: z.string().min(1).max(160).optional().describe('Search for a task such as generate image, create shot, or edit video.'),
10806
10960
  names: z.array(z.string()).min(1).max(5).optional().describe('Exact operation names to load after discovery. Their permission annotations remain separate.'),
10807
10961
  }).refine((v) => [v.group, v.query, v.names].filter(Boolean).length === 1, 'Pass exactly one of query, names, or group.'),
@@ -11220,6 +11374,9 @@ export const ALL_OPERATIONS = [
11220
11374
  getScriptSuggestions,
11221
11375
  changeScriptSuggestions,
11222
11376
  getScriptDocument,
11377
+ readScriptMarkdown,
11378
+ proposeScriptMarkdown,
11379
+ proposeShotBreakdown,
11223
11380
  writeScriptDocument,
11224
11381
  editScript,
11225
11382
  makeShotFromScript,
@@ -36,8 +36,7 @@ export declare function annotate(id: string, billable: boolean | undefined): Ope
36
36
  */
37
37
  export declare const OPERATION_GROUPS: Record<OperationGroup, readonly string[]>;
38
38
  export declare function groupFor(id: string): OperationGroup | undefined;
39
- /** `extended` iff the op names a group. Absent from every group ⇒ `core`, so a
40
- * new op is visible until someone deliberately defers it. */
39
+ /** Only the explicit startup set appears in every Slates Basic prompt. */
41
40
  export declare const STARTUP_TOOL_IDS: Set<string>;
42
41
  export declare function tierFor(id: string): OperationTier;
43
42
  /** One-line summary of each group, for `slates_load_tools`' own description. */
@@ -178,7 +178,13 @@ export const OPERATION_GROUPS = {
178
178
  'slates_link_asset_source',
179
179
  ],
180
180
  // The cut and the export. A generation session never touches these.
181
- script: ['slates_get_script_document', 'slates_update_script_document', 'slates_get_script_sections', 'slates_update_script_section', 'slates_get_script_suggestions', 'slates_update_script_suggestions', 'slates_get_script_uses', 'slates_preview_script_variation', 'slates_create_script_variation', 'slates_get_shot_inputs', 'slates_reuse_shot_take'],
181
+ script: [
182
+ 'slates_get_script_document', 'slates_update_script_document', 'slates_read_script_markdown',
183
+ 'slates_propose_script_markdown', 'slates_propose_shot_breakdown', 'slates_get_script_sections',
184
+ 'slates_update_script_section', 'slates_get_script_suggestions', 'slates_update_script_suggestions',
185
+ 'slates_get_script_uses', 'slates_preview_script_variation', 'slates_create_script_variation',
186
+ 'slates_get_shot_inputs', 'slates_reuse_shot_take',
187
+ ],
182
188
  timeline: [
183
189
  'slates_list_timelines', 'slates_save_timeline', 'slates_export_cuts',
184
190
  'slates_quote_cut_drafts', 'slates_finish_cut_drafts', 'slates_get_cut_draft_status',
@@ -238,7 +244,6 @@ export const OPERATION_GROUPS = {
238
244
  ],
239
245
  // Rename, delete, reorder. The 63-op CRUD tail the review measured at 39.5 KB.
240
246
  admin: [
241
- 'slates_get_client_ad_report',
242
247
  'slates_update_project',
243
248
  'slates_update_asset',
244
249
  'slates_delete_project',
@@ -263,6 +268,17 @@ export const OPERATION_GROUPS = {
263
268
  'slates_get_spend_limits',
264
269
  'slates_set_spend_limits',
265
270
  ],
271
+ ads: [
272
+ 'slates_get_client_ad_report',
273
+ 'slates_get_ad_winners',
274
+ 'slates_set_recipe_verdict',
275
+ 'slates_more_like_this',
276
+ 'slates_plan_split_test',
277
+ 'slates_evaluate_split_test_winner',
278
+ 'slates_find_winning_ads',
279
+ 'slates_list_winning_ad_niches',
280
+ 'slates_break_down_winning_ad',
281
+ ],
266
282
  // A third transport nobody without Blender installed can reach.
267
283
  blender: [
268
284
  'slates_blender_status',
@@ -281,8 +297,7 @@ for (const [group, ids] of Object.entries(OPERATION_GROUPS)) {
281
297
  export function groupFor(id) {
282
298
  return GROUP_BY_OP.get(id);
283
299
  }
284
- /** `extended` iff the op names a group. Absent from every group ⇒ `core`, so a
285
- * new op is visible until someone deliberately defers it. */
300
+ /** Only the explicit startup set appears in every Slates Basic prompt. */
286
301
  export const STARTUP_TOOL_IDS = new Set([
287
302
  'slates_load_tools', 'slates_get_prompting_guide', 'slates_get_workspace_state',
288
303
  'slates_list_projects', 'slates_create_project', 'slates_list_assets',
@@ -296,6 +311,7 @@ export const GROUP_SUMMARY = {
296
311
  library: 'folders, favorites, pins, the Library (user-named categories of saved references: characters, locations, products, looks) and styles, templates (list, export, import), exporting original asset files, moving and copying assets and Library items between projects, moving a project into the current projects folder, revealing files on disk',
297
312
  script: 'rich script documents, anchored sections and their saved versions, reusable passages, variations and take input history',
298
313
  timeline: 'named cuts and exporting several at once, what made an exported ad (its recipe ID); the timeline (tracks, clips, markers, settings), text, picture and HTML motion layers, captions, video export and FCP7 XML export for DaVinci Resolve or Premiere, clip trimming',
314
+ ads: 'ad accounts, split tests and winning ads',
299
315
  admin: 'rename / delete / reorder for projects, characters, locations, looks, boards, scenes and frames; shot duplicate, split and merge; spend limits',
300
316
  blender: 'the Blender previs bridge — scene inspection, bpy execution, API docs, grey-box render',
301
317
  };
@@ -80,7 +80,7 @@ export function buildSkillIndex() {
80
80
  // pointer to the full method. mcp-instructions-smoke asserts these lines and
81
81
  // that pointer land inside the cut when UPDATE AVAILABLE follows the first
82
82
  // doctrine paragraph.
83
- const PREAMBLE = fork(`You are Slates Director — a production assistant living inside Slates, the AI video creation studio. Turn the user's vision into finished work using the optional Slates tools and relevant production craft. Choose the workflow for the brief; start from the user's existing material and bring results into their project or timeline when asked.`, `Turn the user's vision into finished work in Slates. Start every job at slates_get_prompting_guide(topic: "${BRAIN_ROUTER}"). Tools generate real media and spend credits. Before generation, estimate every step, show the itemized total and wait for approval.
83
+ const PREAMBLE = fork(`You are Slates Director — a production assistant living inside Slates, the AI video creation studio. Turn the user's vision into finished work using the optional Slates tools and relevant production craft. Choose the workflow for the brief; start from the user's existing material and bring results into their project or timeline when asked.`, `Turn the user's vision into finished work in Slates. First, use slates_get_prompting_guide to read "${BRAIN_ROUTER}" or the job's playbook. Generation tools spend credits. Before generation, estimate every step, show the itemized total and wait for approval.
84
84
 
85
85
  ## Essentials
86
86
 
@@ -88,7 +88,7 @@ const PREAMBLE = fork(`You are Slates Director — a production assistant living
88
88
  - SPENDING: before ANY generation, price every step with slates_estimate_generation_cost, show the user the itemized total in ONE message, and wait for their OK. Pass confirm: true only to relay an explicit user OK for that exact spend.
89
89
  - REAL NUMBERS ONLY: every cost, balance or count you state is copied from a tool result in this session. Never describe how a generation looks unless you fetched it this session.
90
90
  - PROJECT: call slates_get_workspace_state once and work in the user's current project; never create one unless asked. Read any shot or board they name before answering.
91
- - CRAFT: before a model's first generation this session, read its guide (slates_get_prompting_guide, topic: the model); an estimate's card or guidance in context doesn't count. UI help: topic "app-manual".
91
+ - CRAFT: read the job's playbook before using script, timeline, or edit tools. Estimate cards cover single shots; full guide (depth: full) for multi-ref, previs, edits, lip-sync, motion transfer or retries. UI: "app-manual".
92
92
  - Speak in the app's words and name assets by code and label (IMG-A12), never by tool name or UUID.`);
93
93
  // ── The working method ─────────────────────────────────────────────
94
94
  export const WORKING_METHOD = [
@@ -99,7 +99,7 @@ export const WORKING_METHOD = [
99
99
  // so its agent must load before calling. The MCP server lists every tool and
100
100
  // the host decides what to show (Essentials, FINDING TOOLS), so telling an MCP
101
101
  // client to load first costs it a turn for a tool it already has.
102
- fork(`3. LOAD KNOWLEDGE ON DEMAND: discover craft from the brief with slates_get_prompting_guide(query: the need); no topic returns ranked guides, no query returns the catalog. With a topic, read a short card or query a section/technique when needed. Use slates_load_tools with query to find a capability, then names to load its exact schema. A load replaces the previous optional selection. Before quoting a model, load its tool schema or routing guide. Use workspace generationDefaults when the user has no preference. Before a model's first generation in this chat, read its guide (slates_get_prompting_guide, topic: the model); the estimate's card and guidance already in context do not count, and the generation is refused until then. Then fetch a section or full guide for an unfamiliar mode or missing detail.`, `3. LOAD KNOWLEDGE ON DEMAND: discover craft from the brief with slates_get_prompting_guide(query: the need); no topic returns ranked guides, no query returns the catalog. With a topic, read a short card or query a section/technique when needed. Before quoting a model, read its tool schema or routing guide. Use workspace generationDefaults when the user has no preference. Before a model's first generation, read its guide (CRAFT); the estimate's card and guidance in context do not count. Then fetch a section or full guide for an unfamiliar mode or missing detail.`),
102
+ fork(`3. LOAD KNOWLEDGE ON DEMAND: discover craft from the brief with slates_get_prompting_guide(query: the need); no topic returns ranked guides, no query returns the catalog. With a topic, read a short card or query a section/technique when needed. Use slates_load_tools with query to find a capability, then names to load its exact schema. A load replaces the previous optional selection. Before quoting a model, load its tool schema or routing guide. Use workspace generationDefaults when the user has no preference. Read the job's playbook before advising or building. Use the estimate's craft card for a routine single shot. Fetch the model's full guide (depth: full) for complex references, previs, edits and retries after a refusal.`, `3. LOAD KNOWLEDGE ON DEMAND: discover craft from the brief with slates_get_prompting_guide(query: the need); no topic returns ranked guides, no query returns the catalog. With a topic, read a short card or query a section/technique when needed. Before quoting a model, read its tool schema or routing guide. Use workspace generationDefaults when the user has no preference. Read the job's playbook before advising or building. Use the estimate's craft card for a routine single shot. Fetch the model's full guide (depth: full) for complex references, previs, edits and retries after a refusal.`),
103
103
  // FORKED: `present_plan` is a loop-level DESKTOP tool, deliberately not in
104
104
  // ALL_OPERATIONS, so MCP never sees it and has no plan gate at all. Its
105
105
  // substitute is the itemized quote and explicit user approval in chat,
@@ -181,7 +181,7 @@ export const HARD_RULES = [
181
181
  // record, so this paragraph would be dead weight in its cached prefix.
182
182
  const MCP_FOOTER = `## Working without skill files
183
183
 
184
- If slates-* skill files are not installed in this client, every one of them is still reachable as data: call slates_get_prompting_guide with the skill name. Query the brief or browse topic "catalog" for generated discovery and entitled member playbooks. "No skill installed" is never a reason to prompt a model blind.
184
+ If slates-* skill files are missing, fetch them by name with slates_get_prompting_guide. Query with the brief or browse topic "catalog" for generated discovery and entitled member playbooks. "No skill installed" is never a reason to prompt a model blind.
185
185
  `;
186
186
  // ── The MCP instructions: what every request needs ────────────────
187
187
  //
@@ -9,7 +9,7 @@
9
9
  * Only explicit Ban and Warn rows declare literals. Conditions live on those rows.
10
10
  */
11
11
  import { brainFiles, servedBrain } from '../skills/served.js';
12
- import { parseGuideBans } from './guide-bans.js';
12
+ import { matcherFor, parseGuideBans } from './guide-bans.js';
13
13
  // Read from the brain this process holds (skills/served.ts) and rebuilt when it changes: the model guides that
14
14
  // carry the @banned blocks are served by the account's tier.
15
15
  let built;
@@ -31,16 +31,6 @@ export const BANNED_PROMPT_TOKENS = Object.freeze([]);
31
31
  export function bannedTokensFor(_scope) { return BANNED_PROMPT_TOKENS; }
32
32
  export function describeBannedTokens(_scope) { return ''; }
33
33
  export function bannedTokensForSkill(skill) { return bannedBySkill().get(skill) ?? []; }
34
- const matchers = new Map();
35
- function matcherFor(token) {
36
- let matcher = matchers.get(token);
37
- if (!matcher) {
38
- const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
39
- matcher = new RegExp(`(?<!\\w)${escaped}(?!\\w)`, 'i');
40
- matchers.set(token, matcher);
41
- }
42
- return matcher;
43
- }
44
34
  export function findBannedTokens(prompt, _scope, skill) {
45
35
  return skill ? bannedTokensForSkill(skill).filter((b) => matcherFor(b.token).test(prompt)) : [];
46
36
  }
@@ -13,4 +13,5 @@ export interface BannedToken {
13
13
  when?: BannedTokenCondition;
14
14
  }
15
15
  export declare function parseGuideBans(skill: string, content: string, strict?: boolean): BannedToken[];
16
+ export declare function matcherFor(token: string): RegExp;
16
17
  //# sourceMappingURL=guide-bans.d.ts.map
@@ -37,4 +37,14 @@ export function parseGuideBans(skill, content, strict = false) {
37
37
  }
38
38
  return tokens;
39
39
  }
40
+ const matchers = new Map();
41
+ export function matcherFor(token) {
42
+ let matcher = matchers.get(token);
43
+ if (!matcher) {
44
+ const escaped = token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
45
+ matcher = new RegExp(`(?<!\\w)${escaped}(?!\\w)`, 'i');
46
+ matchers.set(token, matcher);
47
+ }
48
+ return matcher;
49
+ }
40
50
  //# sourceMappingURL=guide-bans.js.map
@@ -74,6 +74,7 @@ export interface ComposedReferences {
74
74
  */
75
75
  unresolvedTokens: string[];
76
76
  }
77
+ export declare function hasReferenceMention(prompt: string): boolean;
77
78
  /**
78
79
  * 🚨 A HEX COLOUR IS NOT A TAG. `#000000` is to `#` what `eric@gmail.com` is to
79
80
  * `@`: an everyday literal that happens to open with our sigil, written by
@@ -92,6 +92,9 @@ function joinNums(nums) {
92
92
  * capability attaches to the primitive, it does not stand in the way of it.
93
93
  */
94
94
  const TOKEN_RE = /(?<![\w.@#])([@#])([\w-]+(?:\.[\w-]+)*)/g;
95
+ export function hasReferenceMention(prompt) {
96
+ return prompt.search(TOKEN_RE) !== -1;
97
+ }
95
98
  /**
96
99
  * 🚨 A HEX COLOUR IS NOT A TAG. `#000000` is to `#` what `eric@gmail.com` is to
97
100
  * `@`: an everyday literal that happens to open with our sigil, written by
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slatesvideo/shared",
3
- "version": "0.7.23",
3
+ "version": "0.7.25",
4
4
  "description": "Shared operations layer for the Slates MCP server and CLI: auth, cloud/desktop clients, and the single tool surface both consume. Most users want @slatesvideo/mcp-server or @slatesvideo/cli instead.",
5
5
  "license": "MIT",
6
6
  "type": "module",