@machinal/mcp 0.6.2 → 0.6.3

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.
package/README.md CHANGED
@@ -19,10 +19,15 @@ the same client-owned components.
19
19
  `get_hyperframes_source` on the Machinal adapter.
20
20
  - Catalog/source reads work offline without a key. Exact IDs load source;
21
21
  discovery stays paginated. Files are pinned by the library manifest.
22
- - For an animated treatment, search with `topic: "component-discovery"` and an
23
- action query such as `"kinetic type"`. The default response ranks two native
24
- candidates without source payloads. Pass the selected result's `source` back
25
- to the library to open its exact Svelte template.
22
+ - Search each distinct animated beat with `topic: "component-discovery"`.
23
+ For example: `query: "cronologie", role: "timeline",
24
+ profiles: ["educational", "social"], aspect: "portrait"`. Romanian and English
25
+ aliases and partial action matches are supported. Profiles (`educational`,
26
+ `social`, `documentary`, `product`) and aspect boost matches; they do not filter.
27
+ Use a scene `role` alone to browse after a miss. The default response ranks two
28
+ installable candidates with match reasons, format evidence, and editable
29
+ parameters, without source payloads. Read the selected `source`, compile with
30
+ its `compileInput`, and place the returned pinned asset in the timeline.
26
31
  - Legacy `get_editing_reference` authoring calls and resource URIs are served
27
32
  locally by the adapter/OpenCode companion. The direct API returns only a
28
33
  compatibility notice for moved authoring guides, not the source.
@@ -87,11 +87,11 @@ Ask the user which direction they prefer before locking an undecided visual appr
87
87
 
88
88
  Include the desired visual intensity in the style question when it is unknown: quiet/minimal, expressive editorial, or bold/cinematic. For an open creative brief, recommend an expressive, polished treatment with motivated accents rather than silently choosing the least animated option. For “more spectacular”, propose a subject-specific reveal, transformation or spatial action, not merely extra particles, glow or rapid cuts. Respect an explicitly quiet/minimal style and accessibility needs; no effect or scene quota.
89
89
 
90
- For an agreed new animated treatment, search `get_library_reference(topic: component-discovery, query: ...)` (OpenCode: `machinal_library`) before writing the scene. Search for the visible action, such as `kinetic type` for a hook or `panel reveal` for a comparison, rather than a video title or unrelated template. Compare up to two relevant candidates and open the chosen exact `scene-templates` ID to read its Svelte, media slots and timing. If none fits, try one shorter query or author from scratch; no required component count and no extra user approval for implementation IDs. Do not repeat discovery for unchanged scenes. On older installs, use a targeted `scene-templates` or `hyperframes-components` lookup.
90
+ For an agreed animated treatment, search `get_library_reference(topic: component-discovery, query: ...)` (OpenCode: `machinal_library`) once per distinct animated beat before writing its scene. Search for the visible action (Romanian or English), not the whole video's subject. For example, use `query: "cronologie", role: "timeline", profiles: ["educational", "social"], aspect: "portrait"`; search separately for the opening title. Profiles and format rank matches, not exclude them. Compare the returned match reasons, recorded format evidence, media requirements and editable parameters. Open the chosen exact `scene-templates` ID. If a query misses, browse its broader `role` without the query once. If nothing can depict the beat, record why and author it from scratch. There is no required component count or extra user approval for implementation IDs. Do not repeat discovery for unchanged scenes. On older installs, use a targeted `scene-templates` or `hyperframes-components` lookup.
91
91
 
92
92
  Read only the relevant editing/scene references once the direction is known. Summarize the agreed brief as a progress update, not an approval gate: type/goal, duration, aspect and resolution, visual sources/treatment, narration/captions/music/sound effects. Then start the next authorized action immediately. For narration-led work, proposed beat times remain provisional until the speech duration and cues are measured.
93
93
 
94
- For a fitting beat pass the discovered `templateId` and context-specific `templateEdits` into `compile_scene`. Preserve the template's signature motion; adapt actual copy, colors, framing and demo content. Use the compiled asset in the final recipe. For a custom beat, record why the candidates did not fit; do not count a lookup as reuse.
94
+ For a fitting beat pass the discovered `templateId` and context-specific `templateEdits` into `compile_scene`. Preserve the template's signature motion; adapt actual copy, colors, framing and demo content. Record beat → template ID → returned asset version → timeline clip in the production notes, and verify that clip in the final recipe. For a custom beat, record why the candidates did not fit (`customSceneReason` in OpenCode); do not count a lookup or even a compiled but unused asset as reuse.
95
95
 
96
96
  ## Let finished narration set an approximate runtime
97
97
 
@@ -20,7 +20,7 @@ After timing, inspect captionContentReview against approved narration, especiall
20
20
 
21
21
  Narration uses a timing-first submission: approved speech plus requested captions ONLY; wait, read resolved recipeYaml and measured timings, then add visuals without rerunning successful jobs. Before NEW TTS read list_speech_models and ask model choice in the same brief unless chosen/delegated; respect the exact model/language/compatible voice. For Romanian recommend Gemini 3.8 Flash, offer Flash-Lite; for English offer Kokoro, Flash-Lite and Flash. Approximate runtime follows successful measured narration; an explicit hard cap requires resolution.
22
22
 
23
- Before new scene code, search the local library with topic=component-discovery using short terms for the intended visible action. Compare up to two relevant native results and read the chosen exact scene-templates source; if no fit after one refinement, write native Svelte instead. Do not force a component or ask approval for implementation IDs. Read production and scene-runtime; use focused animation skills and the exact film style as needed. The CURRENT client writes/repairs Svelte/SceneThree. OpenCode compile_scene accepts inline component or absolute local componentFile, not both. Preserve animation during repairs; no server-model fallback or local production renderer. Use approved images for complex subjects and keep layouts caption-safe. Compare exact source/YAML against the production contract; use plan_scene_review and consent-bound inspect_scene for diagnostic frames when available. No automatic paid preview loop or production-process labels.
23
+ Before new scene code, use topic=component-discovery per distinct animated beat, not for the video title or whole video. Supply its visible action (Romanian or English), role, applicable profiles and output aspect. After a miss, browse the broader role once. Read the chosen exact scene-templates source; use templateId for a fitting beat and record the actual placed clip. If the candidates cannot depict the beat, record the specific reason and write native Svelte instead. Do not force a component or ask approval for implementation IDs. Read production and scene-runtime; use focused animation skills and the exact film style as needed. The CURRENT client writes/repairs Svelte/SceneThree. OpenCode compile_scene accepts inline component or absolute local componentFile, not both. Preserve animation during repairs; no server-model fallback or local production renderer. Use approved images for complex subjects and keep layouts caption-safe. Compare exact source/YAML against the production contract; use plan_scene_review and consent-bound inspect_scene for diagnostic frames when available. No automatic paid preview loop or production-process labels.
24
24
 
25
25
  For each fitting scene, compile the actual discovered Svelte via templateId and optional templateEdits (or edit the source directly on older clients). Compile new scenes sequentially. On an explicit pre-submission 429 respect Retry-After; after a source fix use a new idempotency key. Put each successful pinned asset in the timeline. Preflight the exact final YAML: validate_recipe, resolve diagnostics and requirements, compile_recipe for the reviewed checkpoint, then render_video with the same unchanged recipe and approval. For image.generate use an accepted ratio such as '9:16', not the output alias portrait. When generating images without a positive existing timeline, place at least one image with a positive duration to avoid a post-generation invalid_duration; reuse materialized assets from failed jobs before retrying.
26
26
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "format": 1,
3
- "version": "sha256:717736f26030cb4e4f89268aea0ff2eb3417c43b830a8149ecc33b316d655601",
3
+ "version": "sha256:24495c29436996fc7edb46d9894cba46978cc05478e92a2726a306410fbb5f22",
4
4
  "files": {
5
5
  "animation-skills/machinal-choreography.md": {
6
6
  "bytes": 3449,
@@ -455,12 +455,12 @@
455
455
  "sha256": "a7d922aa3184f9b33b503906d2989cf75c37cea64ba693aaf23dc807a2a4f5f9"
456
456
  },
457
457
  "guides/brief.md": {
458
- "bytes": 17250,
459
- "sha256": "12a84b20975e3e51c98fb8314939d34a2a242a4e0b122fbcc673dfae01f5f062"
458
+ "bytes": 17692,
459
+ "sha256": "9b6572a41cc8666d426408ae7fb6272e65f7b817c6d00e494b275c86de99e47a"
460
460
  },
461
461
  "guides/client-bootstrap.md": {
462
- "bytes": 8299,
463
- "sha256": "5856a16c4aa4e3e194d852aba8963a085a64c73d357117d3755f8224d764cf50"
462
+ "bytes": 8492,
463
+ "sha256": "ea227bf1d9180735347ecea034cc016f05e4a26f2d020d8602d0a443e81ba77f"
464
464
  },
465
465
  "guides/commands.md": {
466
466
  "bytes": 4194,
@@ -13435,8 +13435,8 @@
13435
13435
  "sha256": "d72ec78e93934f74d5e85cd382d3c0283e65609b3af543adede3c46198b8db90"
13436
13436
  },
13437
13437
  "skills/machinal-editing.md": {
13438
- "bytes": 15076,
13439
- "sha256": "f42bb12ae7dd7a759ca4667da58561972036a40c0f97e0e70c4b4f0ab0da42a2"
13438
+ "bytes": 15229,
13439
+ "sha256": "066d99248d4f8cad6fce8448462e144311d29d692ac4960d38c8341997c5d6bd"
13440
13440
  },
13441
13441
  "skills/machinal-hyperframes-cli.md": {
13442
13442
  "bytes": 2505,
@@ -11,7 +11,7 @@ description: Clarify the video brief, integrate images with animated Svelte/Thre
11
11
 
12
12
  **Requested sound effects must reach the mix.** Load `machinal-sound` alongside editing whenever sound effects are requested or already approved; do not wait for another request. Narration, music and sound effects are separate choices. Use `search_sound_effects`, approved exact-source/licence/project `import_sound_effect`, `get_asset_metadata` and real YAML audio tracks synchronized to visible actions. Search consent is not named-source use consent; ask only for genuinely missing permission and reuse covered approvals. Before final rendering compare every promised cue with actual returned assets, measured source ranges, timeline placement, nonzero clip/track gain, no mute and supported fades. Never silently deliver an effects-free substitute; report the precise source/licence/tool blocker. Metadata/import/preflight is not listening. Preserve successful narration, captions and unrelated audio.
13
13
 
14
- If an open brief does not specify effects, include a separate “effects or no effects?” question in the same native form. For an agreed animated treatment, use local `component-discovery` with short action keywords; compare up to two candidates, read the chosen exact `scene-templates` source, and author from scratch if neither is suitable.
14
+ If an open brief does not specify effects, include a separate “effects or no effects?” question in the same native form. For each distinct animated beat, use local `component-discovery` with a visible action, role, profiles and aspect. Read the chosen exact `scene-templates` source, compile via `templateId` and place the pinned result in the timeline. On a miss, browse the broader role once, then author from scratch if no candidate fits. Record reuse against actual clips, not search hits.
15
15
 
16
16
  **Choose visual sources before procedural shortcuts.** For complex or overly simplistic SVG/CSS subjects, prefer approved image-backed scenes over token shapes. A documentary/biography may need 5–10 distinct images per video for people, geographic context, environments and period-grounded illustrations, not one repeated portrait with more labels. This is not a quota or cap; the four-image attachment limit is per scene, not per video. Read topic `scenes` for image coverage and tool selection: `generate_assets` creates approved `image.generate` artwork after the timing checkpoint, `compile_scene` composes/animates it. Do not simplify solely to make the video cheap; reuse suitable successful assets, respect the approved budget and no-generation/procedural-only constraints. This does not authorize unrelated narration, caption, pacing or transition changes.
17
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@machinal/mcp",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "Resilient Machinal MCP setup for Codex, Claude Code and OpenCode: independent local or hosted server",
5
5
  "type": "module",
6
6
  "exports": {
@@ -11,7 +11,7 @@ description: Clarify the video brief, integrate images with animated Svelte/Thre
11
11
 
12
12
  **Requested sound effects must reach the mix.** Load `machinal-sound` alongside editing whenever sound effects are requested or already approved; do not wait for another request. Narration, music and sound effects are separate choices. Use `search_sound_effects`, approved exact-source/licence/project `import_sound_effect`, `get_asset_metadata` and real YAML audio tracks synchronized to visible actions. Search consent is not named-source use consent; ask only for genuinely missing permission and reuse covered approvals. Before final rendering compare every promised cue with actual returned assets, measured source ranges, timeline placement, nonzero clip/track gain, no mute and supported fades. Never silently deliver an effects-free substitute; report the precise source/licence/tool blocker. Metadata/import/preflight is not listening. Preserve successful narration, captions and unrelated audio.
13
13
 
14
- If an open brief does not specify effects, include a separate “effects or no effects?” question in the same native form. For an agreed animated treatment, use local `component-discovery` with short action keywords; compare up to two candidates, read the chosen exact `scene-templates` source, and author from scratch if neither is suitable.
14
+ If an open brief does not specify effects, include a separate “effects or no effects?” question in the same native form. For each distinct animated beat, use local `component-discovery` with a visible action, role, profiles and aspect. Read the chosen exact `scene-templates` source, compile via `templateId` and place the pinned result in the timeline. On a miss, browse the broader role once, then author from scratch if no candidate fits. Record reuse against actual clips, not search hits.
15
15
 
16
16
  **Choose visual sources before procedural shortcuts.** For complex or overly simplistic SVG/CSS subjects, prefer approved image-backed scenes over token shapes. A documentary/biography may need 5–10 distinct images per video for people, geographic context, environments and period-grounded illustrations, not one repeated portrait with more labels. This is not a quota or cap; the four-image attachment limit is per scene, not per video. Read topic `scenes` for image coverage and tool selection: `generate_assets` creates approved `image.generate` artwork after the timing checkpoint, `compile_scene` composes/animates it. Do not simplify solely to make the video cheap; reuse suitable successful assets, respect the approved budget and no-generation/procedural-only constraints. This does not authorize unrelated narration, caption, pacing or transition changes.
17
17
 
@@ -87,11 +87,11 @@ Ask the user which direction they prefer before locking an undecided visual appr
87
87
 
88
88
  Include the desired visual intensity in the style question when it is unknown: quiet/minimal, expressive editorial, or bold/cinematic. For an open creative brief, recommend an expressive, polished treatment with motivated accents rather than silently choosing the least animated option. For “more spectacular”, propose a subject-specific reveal, transformation or spatial action, not merely extra particles, glow or rapid cuts. Respect an explicitly quiet/minimal style and accessibility needs; no effect or scene quota.
89
89
 
90
- For an agreed new animated treatment, search `get_library_reference(topic: component-discovery, query: ...)` (OpenCode: `machinal_library`) before writing the scene. Search for the visible action, such as `kinetic type` for a hook or `panel reveal` for a comparison, rather than a video title or unrelated template. Compare up to two relevant candidates and open the chosen exact `scene-templates` ID to read its Svelte, media slots and timing. If none fits, try one shorter query or author from scratch; no required component count and no extra user approval for implementation IDs. Do not repeat discovery for unchanged scenes. On older installs, use a targeted `scene-templates` or `hyperframes-components` lookup.
90
+ For an agreed animated treatment, search `get_library_reference(topic: component-discovery, query: ...)` (OpenCode: `machinal_library`) once per distinct animated beat before writing its scene. Search for the visible action (Romanian or English), not the whole video's subject. For example, use `query: "cronologie", role: "timeline", profiles: ["educational", "social"], aspect: "portrait"`; search separately for the opening title. Profiles and format rank matches, not exclude them. Compare the returned match reasons, recorded format evidence, media requirements and editable parameters. Open the chosen exact `scene-templates` ID. If a query misses, browse its broader `role` without the query once. If nothing can depict the beat, record why and author it from scratch. There is no required component count or extra user approval for implementation IDs. Do not repeat discovery for unchanged scenes. On older installs, use a targeted `scene-templates` or `hyperframes-components` lookup.
91
91
 
92
92
  Read only the relevant editing/scene references once the direction is known. Summarize the agreed brief as a progress update, not an approval gate: type/goal, duration, aspect and resolution, visual sources/treatment, narration/captions/music/sound effects. Then start the next authorized action immediately. For narration-led work, proposed beat times remain provisional until the speech duration and cues are measured.
93
93
 
94
- For a fitting beat pass the discovered `templateId` and context-specific `templateEdits` into `compile_scene`. Preserve the template's signature motion; adapt actual copy, colors, framing and demo content. Use the compiled asset in the final recipe. For a custom beat, record why the candidates did not fit; do not count a lookup as reuse.
94
+ For a fitting beat pass the discovered `templateId` and context-specific `templateEdits` into `compile_scene`. Preserve the template's signature motion; adapt actual copy, colors, framing and demo content. Record beat → template ID → returned asset version → timeline clip in the production notes, and verify that clip in the final recipe. For a custom beat, record why the candidates did not fit (`customSceneReason` in OpenCode); do not count a lookup or even a compiled but unused asset as reuse.
95
95
 
96
96
  ## Let finished narration set an approximate runtime
97
97
 
@@ -0,0 +1,142 @@
1
+ export const DISCOVERY_PROFILES = ['educational', 'social', 'documentary', 'product'];
2
+ export const DISCOVERY_ASPECTS = ['portrait', 'landscape', 'square'];
3
+
4
+ const roles = {
5
+ title: {
6
+ profiles: ['educational', 'social', 'documentary', 'product'],
7
+ names: /kinetic type|title ?card|text stagger|per word rise/,
8
+ aliases: ['titlu', 'titlu animat', 'text cinetic', 'animated title', 'kinetic typography', 'opening title', 'hook'],
9
+ },
10
+ diagram: {
11
+ profiles: ['educational', 'product'],
12
+ names: /signal diagram|flowchart|decision tree|exploded stack|hw pipeline/,
13
+ aliases: ['diagram', 'diagrama', 'flowchart', 'schema animata', 'process diagram'],
14
+ },
15
+ comparison: {
16
+ profiles: ['educational', 'product'],
17
+ names: /comparison|before after|split screen|panel reveal/,
18
+ aliases: ['comparatie', 'compara', 'inainte si dupa', 'before and after', 'side by side'],
19
+ },
20
+ timeline: {
21
+ profiles: ['educational', 'documentary'],
22
+ names: /timeline|chronology|chronological/,
23
+ aliases: ['cronologie', 'linie temporala', 'chronology', 'timeline'],
24
+ },
25
+ chart: {
26
+ profiles: ['educational', 'documentary', 'product'],
27
+ names: /chart|count up|graph|stat callout/,
28
+ aliases: ['grafic', 'grafice', 'diagrama cu bare', 'statistici', 'data chart', 'bar chart', 'line graph'],
29
+ },
30
+ recap: {
31
+ profiles: ['educational', 'social', 'documentary'],
32
+ names: /recap|summary|end card|titlecard lockup|takeaway/,
33
+ aliases: ['recapitulare', 'rezumat', 'concluzie', 'concluzii', 'key takeaway', 'summary card'],
34
+ },
35
+ showcase: {
36
+ profiles: ['product', 'social'],
37
+ names: /showcase|product promo|device splay/,
38
+ aliases: ['prezentare produs', 'demo produs', 'product demo', 'product showcase'],
39
+ },
40
+ };
41
+
42
+ export const DISCOVERY_ROLES = Object.keys(roles);
43
+ const stopWords = new Set(['a', 'an', 'the', 'of', 'in', 'on', 'to', 'for', 'with', 'and', 'or',
44
+ 'de', 'din', 'la', 'pe', 'cu', 'si', 'un', 'o', 'pentru', 'intre', 'care', 'prin']);
45
+ const hasPhrase = (text, phrase) => text === phrase || ` ${text} `.includes(` ${phrase} `);
46
+ const normalize = text => text.toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu)?.join(' ') ?? '';
47
+ const words = text => text ? text.split(' ') : [];
48
+ const aspect = ({ width, height }) => height > width ? 'portrait' : width > height ? 'landscape' : 'square';
49
+
50
+ export function validDiscoveryContext(input) {
51
+ if (input.profiles !== undefined && (!Array.isArray(input.profiles) || input.profiles.length > DISCOVERY_PROFILES.length
52
+ || new Set(input.profiles).size !== input.profiles.length || !input.profiles.every(profile => DISCOVERY_PROFILES.includes(profile)))) return false;
53
+ if (input.aspect !== undefined && !DISCOVERY_ASPECTS.includes(input.aspect)) return false;
54
+ if (input.role !== undefined && !DISCOVERY_ROLES.includes(input.role)) return false;
55
+ return input.topic === 'component-discovery' || [input.profiles, input.aspect, input.role].every(value => value === undefined);
56
+ }
57
+
58
+ function formatEvidence(template, port) {
59
+ const config = template.config;
60
+ const defaultAspect = config?.width && config?.height ? aspect(config) : undefined;
61
+ const checks = (port?.verification?.runtimeCapture?.checks ?? port?.verification?.checks ?? [])
62
+ .filter(check => check.rendered === true && check.width > 0 && check.height > 0);
63
+ return {
64
+ ...(defaultAspect ? { defaultAspect } : {}),
65
+ verifiedAspects: DISCOVERY_ASPECTS.filter(value => checks.some(check => aspect(check) === value)),
66
+ ...(typeof config?.duration === 'number' ? { defaultDuration: config.duration } : {}),
67
+ ...(typeof config?.captionSafeArea === 'boolean' ? { captionSafeArea: config.captionSafeArea } : {}),
68
+ };
69
+ }
70
+
71
+ export function buildDiscoveryIndex(templates, hyperframes, native, files) {
72
+ const ports = new Map(hyperframes.filter(entry => entry.nativeStatus === 'ported').map(entry => [entry.nativeTemplateId, entry]));
73
+ const evidence = new Map(native.filter(entry => entry.status === 'ported').map(entry => [entry.nativeTemplateId, entry]));
74
+ return templates.flatMap(template => {
75
+ const port = ports.get(template.id);
76
+ if (!files[`scene-templates/${template.id}.svelte`] || (template.id.startsWith('hyperframes-') && !port)) return [];
77
+ const id = normalize(template.id.replace(/^hyperframes-(?:blocks-|components-|examples-)?/, ''));
78
+ const label = normalize(template.label.replace(/^Hyperframes:\s*/i, ''));
79
+ const tags = new Set(words(normalize((port?.tags ?? []).join(' '))));
80
+ const details = new Set(words(normalize(`${template.description ?? ''} ${(template.whenToUse ?? []).join(' ')}`)));
81
+ const entryRoles = DISCOVERY_ROLES.filter(role => roles[role].names.test(`${id} ${label}`) || template.category === role);
82
+ return [{
83
+ id, label, name: new Set(words(`${normalize(template.id)} ${label}`)), tags, details, roles: entryRoles,
84
+ profiles: DISCOVERY_PROFILES.filter(profile => entryRoles.some(role => roles[role].profiles.includes(profile))),
85
+ candidate: {
86
+ id: template.id, label: template.label, description: template.description,
87
+ family: port ? 'hyperframes' : 'machinal', status: 'installed-template',
88
+ visualMode: template.visualMode, requiredImages: template.requiredImages ?? [], requiredVideos: template.requiredVideos ?? [],
89
+ format: formatEvidence(template, evidence.get(template.id)),
90
+ editableParameters: (template.parameters ?? []).map(parameter => typeof parameter === 'string' ? parameter : parameter.path).filter(Boolean),
91
+ source: { topic: 'scene-templates', id: template.id },
92
+ compileInput: { templateId: template.id },
93
+ },
94
+ }];
95
+ });
96
+ }
97
+
98
+ function scoreCandidate(entry, search) {
99
+ const { phrase, terms, matchedRoles, role, profiles, aspect: requestedAspect } = search;
100
+ const hits = terms.map(term => entry.name.has(term) ? 6 : entry.tags.has(term) ? 3 : entry.details.has(term) ? 1 : 0);
101
+ const coverage = hits.filter(Boolean).length;
102
+ const exact = phrase && (entry.id === phrase || entry.label === phrase || normalize(entry.candidate.id) === phrase);
103
+ const phraseMatch = phrase && [entry.id, entry.label].some(name => hasPhrase(name, phrase));
104
+ const matchingRoles = entry.roles.filter(value => matchedRoles.includes(value));
105
+ const matchingRole = matchingRoles.includes(role);
106
+ const matchingProfiles = profiles.filter(profile => entry.profiles.includes(profile));
107
+ const partial = coverage >= Math.min(2, terms.length) && coverage > 0
108
+ && (coverage === terms.length || hits.some(value => value >= 3) || coverage / terms.length >= 0.5);
109
+ if (!(exact || phraseMatch || partial || matchingRoles.length)) return null;
110
+ const { format } = entry.candidate;
111
+ const verifiedAspect = format.verifiedAspects.includes(requestedAspect);
112
+ const defaultAspect = requestedAspect && format.defaultAspect === requestedAspect;
113
+ const reasons = [
114
+ ...(exact ? ['Exact template name'] : phraseMatch ? ['Action phrase in template name'] : []),
115
+ ...(matchingRoles.length ? [`Scene role: ${matchingRoles.join(', ')}`] : []),
116
+ ...(coverage ? [`Matched action terms: ${terms.filter((_, index) => hits[index]).join(', ')}`] : []),
117
+ ...(matchingProfiles.length ? [`Profile fit: ${matchingProfiles.join(', ')}`] : []),
118
+ ...(defaultAspect ? [`Default layout: ${requestedAspect}`] : []),
119
+ ...(verifiedAspect ? [`Recorded runtime capture: ${requestedAspect}`] : []),
120
+ ];
121
+ const score = (exact ? 45 : phraseMatch ? 22 : 0)
122
+ + hits.reduce((total, value) => total + value, 0)
123
+ + (terms.length ? 10 * coverage / terms.length : 0)
124
+ + (matchingRole ? 17 : matchingRoles.length ? 14 : 0)
125
+ + matchingProfiles.length * 2 + (verifiedAspect ? 5 : 0) + (defaultAspect ? 8 : 0)
126
+ + (entry.candidate.editableParameters.length ? 2 : 0);
127
+ return { score, candidate: { ...entry.candidate, roles: entry.roles, profiles: entry.profiles, matchReasons: reasons } };
128
+ }
129
+
130
+ export function rankComponents(index, { query, role, profiles = [], aspect }) {
131
+ const phrase = normalize(query ?? '');
132
+ const terms = [...new Set(words(phrase).filter(word => !stopWords.has(word)))];
133
+ if (!terms.length && !role) throw new Error('Use an action query or a scene role for component-discovery; read exact IDs via scene-templates.');
134
+ const aliases = DISCOVERY_ROLES.filter(value => roles[value].aliases.some(alias => hasPhrase(phrase, alias)));
135
+ // An explicit role can boost relevant matches, but must not turn an unrelated query into a match.
136
+ const matchedRoles = terms.length ? (role && aliases.includes(role) ? [role] : aliases) : [role];
137
+ return index.map(entry => scoreCandidate(entry, { phrase, terms, matchedRoles, role, profiles, aspect }))
138
+ .filter(Boolean)
139
+ .sort((a, b) => b.score - a.score || Number(b.candidate.family === 'hyperframes') - Number(a.candidate.family === 'hyperframes')
140
+ || a.candidate.id.localeCompare(b.candidate.id, 'en'))
141
+ .map(({ candidate }) => candidate);
142
+ }
@@ -18,6 +18,10 @@ export async function installSceneLibrary(ctx, servers = []) {
18
18
  const original = tool.execute;
19
19
  const topic = tool.input?.properties?.topic;
20
20
  if (topic?.enum) topic.enum = [...new Set([...topic.enum, ...LIBRARY_TOPICS])];
21
+ if (tool.input?.properties) {
22
+ const { role, profiles, aspect } = LIBRARY_TOOLS[0].inputSchema.properties;
23
+ Object.assign(tool.input.properties, { role, profiles, aspect });
24
+ }
21
25
  tool.execute = async (input, context) => {
22
26
  if (!library.handles('get_editing_reference', input)) return original(input, context);
23
27
  const result = await library.call('get_editing_reference', input);
@@ -9,7 +9,7 @@ import { hasSceneCandidates, clearSceneCandidates } from './opencode-library.mjs
9
9
  export const productionSkills = ['machinal-editing', 'machinal-recipes', 'machinal-scenes', 'machinal-cinema', 'machinal-review', 'machinal-credits', 'machinal-motion', 'machinal-choreography', 'machinal-spatial', 'machinal-visual-review', 'machinal-sound'];
10
10
  export const startupSkills = ['machinal-editing', 'machinal-cinema'];
11
11
 
12
- const briefAndComponents = 'In an open video brief ask explicitly “sound effects or no sound effects?” in the same native form, separately from voice/captions and licensed music. Reuse explicit choices. Before writing a new animated treatment, search the local library with topic=component-discovery and short terms for the intended action. Compare up to two relevant native candidates; read the chosen exact scene-templates source. Do not force a component when none fits or ask the user to choose implementation IDs.';
12
+ const briefAndComponents = 'In an open video brief ask explicitly “sound effects or no sound effects?” in the same native form, separately from voice/captions and licensed music. Reuse explicit choices. Before writing each distinct animated beat, search the local library with topic=component-discovery and its visible action, role, applicable profiles and aspect. Compare two relevant native candidates by default; after a miss, browse the broader role once. Read the chosen exact scene-templates source, compile via the candidate’s templateId, and place the returned pinned scene on the timeline. Record beat → templateId → placed clip, or use customSceneReason to explain the specific mismatch. A catalog hit is not reuse. Do not force a component when none fits or ask the user to choose implementation IDs.';
13
13
  const maxComponentBytes = 64000;
14
14
 
15
15
  async function installedSkills(ctx) {
package/src/runtime.mjs CHANGED
@@ -11,7 +11,8 @@ export { stateDirectory } from './paths.mjs';
11
11
  const ROOT = fileURLToPath(new URL('../', import.meta.url));
12
12
  const FILES = ['bin/machinal-stdio.mjs', 'src/bridge.mjs', 'src/connection.mjs', 'src/credential-store.mjs',
13
13
  'src/credits.mjs', 'src/endpoints.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/paths.mjs',
14
- 'src/private-json.mjs', 'src/request-scheduler.mjs', 'src/scene-library.mjs', 'src/template-compile.mjs', 'src/version.mjs', 'package.json'];
14
+ 'src/private-json.mjs', 'src/request-scheduler.mjs', 'src/scene-library.mjs', 'src/component-discovery.mjs',
15
+ 'src/template-compile.mjs', 'src/version.mjs', 'package.json'];
15
16
 
16
17
  export function isManagedRuntimeCommand(command, context = {}) {
17
18
  if (!Array.isArray(command) || !isAbsolute(command[1] ?? '')) return false;
@@ -2,6 +2,7 @@ import { readFile, realpath, lstat } from 'node:fs/promises';
2
2
  import { createHash } from 'node:crypto';
3
3
  import { join, relative, isAbsolute } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { buildDiscoveryIndex, rankComponents, validDiscoveryContext, DISCOVERY_PROFILES, DISCOVERY_ROLES, DISCOVERY_ASPECTS } from './component-discovery.mjs';
5
6
 
6
7
  export const LIBRARY_ROOT = fileURLToPath(new URL('../library/', import.meta.url));
7
8
  const GUIDE_TOPICS = {
@@ -37,14 +38,17 @@ export const LIBRARY_SCHEMA = {
37
38
  properties: {
38
39
  topic: { type: 'string', enum: LIBRARY_TOPICS },
39
40
  id: { type: 'string', maxLength: 128 },
40
- query: { type: 'string', maxLength: 80, description: 'Literal substring, except component-discovery: short motion/visual terms (e.g. "kinetic type", "panel reveal"), ranked across native scene templates and Hyperframes.' },
41
+ query: { type: 'string', maxLength: 80, description: 'Literal substring except for component-discovery: describe one visible action in Romanian or English (e.g. "cronologie", "kinetic type").' },
42
+ role: { type: 'string', enum: DISCOVERY_ROLES, description: 'Component discovery only: scene role. Use alone to browse a role or with an action query to prioritize relevant matches.' },
43
+ profiles: { type: 'array', uniqueItems: true, maxItems: DISCOVERY_PROFILES.length, items: { type: 'string', enum: DISCOVERY_PROFILES }, description: 'Component discovery only: combine video profiles to boost relevant roles; does not filter out other results.' },
44
+ aspect: { type: 'string', enum: DISCOVERY_ASPECTS, description: 'Component discovery only: prioritize a matching default layout or recorded capture. Does not guarantee adapted framing.' },
41
45
  offset: { type: 'integer', minimum: 0 },
42
46
  limit: { type: 'integer', minimum: 1, maximum: 25 },
43
47
  includeGuide: { type: 'boolean' },
44
48
  },
45
49
  };
46
50
  export const LIBRARY_TOOLS = [
47
- { name: 'get_library_reference', description: 'Read the installed scene/Hyperframes library offline. For a new animated treatment, start with topic=component-discovery and a short query describing the action; get two ranked native candidates by default. Read the chosen source with topic=scene-templates and its exact template ID. Compilation/rendering still use the configured renderer. Not permission for media use or paid work.',
51
+ { name: 'get_library_reference', description: 'Read the installed scene/Hyperframes library offline. Before writing each distinct animated beat, use topic=component-discovery with its visible action or role, applicable profiles and aspect. Get two ranked installable candidates by default. Read the chosen source via scene-templates and pass its compileInput to compile_scene. Compilation/rendering still use the configured renderer. Not permission for media use or paid work.',
48
52
  inputSchema: LIBRARY_SCHEMA, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false } },
49
53
  { name: 'get_hyperframes_source', description: 'Read an installed, pinned Hyperframes source by a discovered file ID. UTF-8 byte chunks, up to 48 KiB; continue with sourceNextOffset. No execution, user-media access or spending.',
50
54
  inputSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string', maxLength: 128 }, offset: { type: 'integer', minimum: 0 } }, additionalProperties: false },
@@ -57,11 +61,8 @@ function validateInput(input) {
57
61
  || input.query !== undefined && (typeof input.query !== 'string' || input.query.length > 80)
58
62
  || input.offset !== undefined && (!Number.isSafeInteger(input.offset) || input.offset < 0)
59
63
  || input.limit !== undefined && (!Number.isInteger(input.limit) || input.limit < 1 || input.limit > 25)
60
- || input.includeGuide !== undefined && typeof input.includeGuide !== 'boolean') throw new Error('Use a supported local library topic and valid ID/query/pagination.');
61
- }
62
-
63
- function searchWords(text) {
64
- return text.toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) ?? [];
64
+ || input.includeGuide !== undefined && typeof input.includeGuide !== 'boolean'
65
+ || !validDiscoveryContext(input)) throw new Error('Use a supported local library topic and valid ID/query/pagination. Role, profiles and aspect are only for component-discovery.');
65
66
  }
66
67
 
67
68
  export class SceneLibrary {
@@ -133,34 +134,18 @@ export class SceneLibrary {
133
134
  }
134
135
 
135
136
  async discoverComponents(input) {
136
- const terms = searchWords(input.query ?? '');
137
- if (!terms.length || input.id !== undefined) throw new Error('Use a short motion query for component-discovery; read exact IDs via scene-templates.');
138
- const [templates, hyperframes] = await Promise.all([this.catalog('scene-templates'), this.catalog('hyperframes-components')]);
139
- const ports = new Map(hyperframes.filter(entry => entry.nativeStatus === 'ported').map(entry => [entry.nativeTemplateId, entry]));
140
- const phrase = terms.join(' ');
141
- const matches = templates.flatMap(template => {
142
- const port = ports.get(template.id);
143
- const name = searchWords(`${template.id} ${template.label}`);
144
- const tags = new Set(searchWords((port?.tags ?? []).join(' ')));
145
- const details = new Set(searchWords(`${template.description ?? ''} ${(template.whenToUse ?? []).join(' ')}`));
146
- const rank = terms.map(term => name.includes(term) ? 6 : tags.has(term) ? 3 : details.has(term) ? 1 : 0);
147
- if (rank.includes(0)) return [];
148
- const score = rank.reduce((total, value) => total + value, 0)
149
- + (name.join(' ').includes(phrase) ? 6 : 0)
150
- + (searchWords(template.id).join(' ') === phrase ? 10 : 0);
151
- return [{ score, candidate: {
152
- id: template.id, label: template.label, description: template.description,
153
- visualMode: template.visualMode, requiredImages: template.requiredImages ?? [], requiredVideos: template.requiredVideos ?? [],
154
- source: { topic: 'scene-templates', id: template.id },
155
- compileInput: { templateId: template.id },
156
- } }];
157
- }).sort((a, b) => b.score - a.score || a.candidate.id.localeCompare(b.candidate.id, 'en'));
137
+ if (input.id !== undefined) throw new Error('Use an action query or a scene role for component-discovery; read exact IDs via scene-templates.');
138
+ const manifest = await this.manifest();
139
+ this.discoveryIndex ??= Promise.all([
140
+ this.catalog('scene-templates'), this.catalog('hyperframes-components'), this.catalog('hyperframes-native'),
141
+ ]).then(([templates, ports, native]) => buildDiscoveryIndex(templates, ports, native, manifest.files));
142
+ const matches = rankComponents(await this.discoveryIndex, input);
158
143
  const start = Math.min(input.offset ?? 0, matches.length);
159
144
  const end = Math.min(start + (input.limit ?? 2), matches.length);
160
- return { topic: input.topic, origin: 'installed-client-library', libraryVersion: (await this.manifest()).version,
161
- entries: matches.slice(start, end).map(match => match.candidate), total: matches.length,
145
+ return { topic: input.topic, origin: 'installed-client-library', libraryVersion: manifest.version,
146
+ entries: matches.slice(start, end), total: matches.length,
162
147
  ...(end < matches.length ? { nextOffset: end } : {}),
163
- next: matches.length ? 'For each fitting beat, open candidate.source, use its compileInput in compile_scene and add templateEdits for copy, palette and framing. Pin the returned scene in YAML. Reading a candidate alone is not reuse. If the exposed compiler lacks templateId, adapt the returned component source instead.' : 'Try another short motion term once; if nothing fits, author native Svelte without forcing an unrelated template.',
148
+ next: matches.length ? 'For a fitting beat, open candidate.source and use its compileInput in compile_scene. Adapt copy, palette and framing, verify caption clearance, and pin the returned scene in YAML. Reading a candidate alone is not reuse. If the exposed compiler lacks templateId, adapt the returned component source instead.' : 'Try the broader scene role once (role without query). If it cannot explain the beat, record why and author native Svelte without forcing a template.',
164
149
  };
165
150
  }
166
151