@machinal/mcp 0.0.0-stage → 0.4.1

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 (174) hide show
  1. package/README.md +366 -2
  2. package/bin/machinal-mcp.mjs +19 -0
  3. package/bin/machinal-stdio.mjs +14 -0
  4. package/package.json +47 -4
  5. package/skills/machinal-cinema/SKILL.md +18 -0
  6. package/skills/machinal-cinema/references/film-library/DIRECTOR.md +149 -0
  7. package/skills/machinal-cinema/references/film-library/LICENSE +21 -0
  8. package/skills/machinal-cinema/references/film-library/MY-STYLES.md +139 -0
  9. package/skills/machinal-cinema/references/film-library/README.md +13 -0
  10. package/skills/machinal-cinema/references/film-library/TECHNIQUE.md +162 -0
  11. package/skills/machinal-cinema/references/film-library/core/lib.js +44 -0
  12. package/skills/machinal-cinema/references/film-library/core/post/crt.js +144 -0
  13. package/skills/machinal-cinema/references/film-library/core/three/post.js +102 -0
  14. package/skills/machinal-cinema/references/film-library/manifest.json +394 -0
  15. package/skills/machinal-cinema/references/film-library/styleboard/catalog.json +1128 -0
  16. package/skills/machinal-cinema/references/film-library/styles/README.md +126 -0
  17. package/skills/machinal-cinema/references/film-library/styles/archive-lighttable/STYLE.md +107 -0
  18. package/skills/machinal-cinema/references/film-library/styles/art-deco/STYLE.md +110 -0
  19. package/skills/machinal-cinema/references/film-library/styles/ascii-crt/STYLE.md +113 -0
  20. package/skills/machinal-cinema/references/film-library/styles/backrooms/STYLE.md +123 -0
  21. package/skills/machinal-cinema/references/film-library/styles/blueprint/STYLE.md +118 -0
  22. package/skills/machinal-cinema/references/film-library/styles/brick-toy/STYLE.md +112 -0
  23. package/skills/machinal-cinema/references/film-library/styles/briefing-board/STYLE.md +120 -0
  24. package/skills/machinal-cinema/references/film-library/styles/caption-news/STYLE.md +135 -0
  25. package/skills/machinal-cinema/references/film-library/styles/cel-anime-80s/STYLE.md +117 -0
  26. package/skills/machinal-cinema/references/film-library/styles/chalkboard/STYLE.md +153 -0
  27. package/skills/machinal-cinema/references/film-library/styles/circuit-board/STYLE.md +149 -0
  28. package/skills/machinal-cinema/references/film-library/styles/city-symphony/STYLE.md +140 -0
  29. package/skills/machinal-cinema/references/film-library/styles/countdown/STYLE.md +130 -0
  30. package/skills/machinal-cinema/references/film-library/styles/crayon-book/STYLE.md +107 -0
  31. package/skills/machinal-cinema/references/film-library/styles/dark-keynote/STYLE.md +115 -0
  32. package/skills/machinal-cinema/references/film-library/styles/data-physical/STYLE.md +117 -0
  33. package/skills/machinal-cinema/references/film-library/styles/dataviz/STYLE.md +121 -0
  34. package/skills/machinal-cinema/references/film-library/styles/desktop-flythrough/STYLE.md +145 -0
  35. package/skills/machinal-cinema/references/film-library/styles/engraving/STYLE.md +121 -0
  36. package/skills/machinal-cinema/references/film-library/styles/game-show/STYLE.md +116 -0
  37. package/skills/machinal-cinema/references/film-library/styles/glass-product/STYLE.md +108 -0
  38. package/skills/machinal-cinema/references/film-library/styles/halftone-dossier/STYLE.md +120 -0
  39. package/skills/machinal-cinema/references/film-library/styles/hd-2d/STYLE.md +109 -0
  40. package/skills/machinal-cinema/references/film-library/styles/hologram-hud/STYLE.md +127 -0
  41. package/skills/machinal-cinema/references/film-library/styles/impasto/STYLE.md +122 -0
  42. package/skills/machinal-cinema/references/film-library/styles/ink-wash/STYLE.md +118 -0
  43. package/skills/machinal-cinema/references/film-library/styles/iso-infographic/STYLE.md +115 -0
  44. package/skills/machinal-cinema/references/film-library/styles/isometric-picture-book/STYLE.md +130 -0
  45. package/skills/machinal-cinema/references/film-library/styles/kino-montage/STYLE.md +149 -0
  46. package/skills/machinal-cinema/references/film-library/styles/lidar-survey/STYLE.md +116 -0
  47. package/skills/machinal-cinema/references/film-library/styles/living-screencast/STYLE.md +122 -0
  48. package/skills/machinal-cinema/references/film-library/styles/lowpoly-island/STYLE.md +110 -0
  49. package/skills/machinal-cinema/references/film-library/styles/memphis-diorama/STYLE.md +142 -0
  50. package/skills/machinal-cinema/references/film-library/styles/microgame/STYLE.md +120 -0
  51. package/skills/machinal-cinema/references/film-library/styles/microscope/STYLE.md +106 -0
  52. package/skills/machinal-cinema/references/film-library/styles/midcentury-toon/STYLE.md +122 -0
  53. package/skills/machinal-cinema/references/film-library/styles/news-package/STYLE.md +156 -0
  54. package/skills/machinal-cinema/references/film-library/styles/newsreel/STYLE.md +134 -0
  55. package/skills/machinal-cinema/references/film-library/styles/one-line/STYLE.md +112 -0
  56. package/skills/machinal-cinema/references/film-library/styles/paper-lantern/STYLE.md +120 -0
  57. package/skills/machinal-cinema/references/film-library/styles/paper-popup/STYLE.md +117 -0
  58. package/skills/machinal-cinema/references/film-library/styles/papercut-red/STYLE.md +108 -0
  59. package/skills/machinal-cinema/references/film-library/styles/pictogram-motion/STYLE.md +119 -0
  60. package/skills/machinal-cinema/references/film-library/styles/pixel-rpg/STYLE.md +115 -0
  61. package/skills/machinal-cinema/references/film-library/styles/printed-long-take/STYLE.md +141 -0
  62. package/skills/machinal-cinema/references/film-library/styles/risograph/STYLE.md +123 -0
  63. package/skills/machinal-cinema/references/film-library/styles/rubber-hose/STYLE.md +110 -0
  64. package/skills/machinal-cinema/references/film-library/styles/satellite-briefing/STYLE.md +114 -0
  65. package/skills/machinal-cinema/references/film-library/styles/scifi-toon/STYLE.md +119 -0
  66. package/skills/machinal-cinema/references/film-library/styles/shadow-puppet/STYLE.md +122 -0
  67. package/skills/machinal-cinema/references/film-library/styles/silent-film/STYLE.md +107 -0
  68. package/skills/machinal-cinema/references/film-library/styles/silkscreen-poster/STYLE.md +138 -0
  69. package/skills/machinal-cinema/references/film-library/styles/spy-titles/STYLE.md +114 -0
  70. package/skills/machinal-cinema/references/film-library/styles/stained-glass/STYLE.md +121 -0
  71. package/skills/machinal-cinema/references/film-library/styles/swiss-motion/STYLE.md +113 -0
  72. package/skills/machinal-cinema/references/film-library/styles/teardown/STYLE.md +125 -0
  73. package/skills/machinal-cinema/references/film-library/styles/telestrator/STYLE.md +135 -0
  74. package/skills/machinal-cinema/references/film-library/styles/tilt-shift/STYLE.md +105 -0
  75. package/skills/machinal-cinema/references/film-library/styles/transit-map/STYLE.md +194 -0
  76. package/skills/machinal-cinema/references/film-library/styles/ukiyoe/STYLE.md +110 -0
  77. package/skills/machinal-cinema/references/film-library/styles/urban-sketch/STYLE.md +124 -0
  78. package/skills/machinal-cinema/references/film-library/styles/visual-investigation/STYLE.md +138 -0
  79. package/skills/machinal-cinema/references/film-library/styles/watercolor/STYLE.md +111 -0
  80. package/skills/machinal-cinema/references/film-library/styles/white-model/STYLE.md +113 -0
  81. package/skills/machinal-cinema/references/film-library/styles/whiteboard/STYLE.md +116 -0
  82. package/skills/machinal-cinema/references/film-library/styles/woodcut/STYLE.md +120 -0
  83. package/skills/machinal-cinema/references/film-library/upstream-skill.md +13 -0
  84. package/skills/machinal-cinema/references/film-styles.json +1322 -0
  85. package/skills/machinal-cinema/references/film-techniques.json +107 -0
  86. package/skills/machinal-cinema/references/workflow.md +58 -0
  87. package/skills/machinal-credits/SKILL.md +24 -0
  88. package/skills/machinal-editing/SKILL.md +43 -0
  89. package/skills/machinal-editing/references/brief.md +98 -0
  90. package/skills/machinal-editing/references/effects.md +58 -0
  91. package/skills/machinal-editing/references/looks-motion.md +37 -0
  92. package/skills/machinal-editing/references/styles.json +15 -0
  93. package/skills/machinal-editing/references/styles.md +16 -0
  94. package/skills/machinal-editing/references/transitions.md +46 -0
  95. package/skills/machinal-editing/references/workflow.md +43 -0
  96. package/skills/machinal-media/SKILL.md +23 -0
  97. package/skills/machinal-media/references/workflow.md +160 -0
  98. package/skills/machinal-recipes/SKILL.md +32 -0
  99. package/skills/machinal-recipes/references/catalog.v1.json +10445 -0
  100. package/skills/machinal-recipes/references/commands.md +45 -0
  101. package/skills/machinal-recipes/references/example.edit.yaml +26 -0
  102. package/skills/machinal-recipes/references/examples/caption-audio.yaml +28 -0
  103. package/skills/machinal-recipes/references/examples/cinematic-sequence.yaml +21 -0
  104. package/skills/machinal-recipes/references/examples/client-scene.yaml +26 -0
  105. package/skills/machinal-recipes/references/examples/generated-media.yaml +25 -0
  106. package/skills/machinal-recipes/references/examples/modify-snapshot.yaml +22 -0
  107. package/skills/machinal-recipes/references/examples/montage-v3.yaml +28 -0
  108. package/skills/machinal-recipes/references/examples/narrated-documentary.yaml +112 -0
  109. package/skills/machinal-recipes/references/examples/narration-timing.yaml +43 -0
  110. package/skills/machinal-recipes/references/examples/scene-edit.yaml +19 -0
  111. package/skills/machinal-recipes/references/examples/scene-generated-image.yaml +36 -0
  112. package/skills/machinal-recipes/references/examples/scene-generation.yaml +35 -0
  113. package/skills/machinal-recipes/references/examples/scene-image-insert.yaml +41 -0
  114. package/skills/machinal-recipes/references/examples/scene-three-explainer.yaml +38 -0
  115. package/skills/machinal-recipes/references/examples/social-hook.yaml +26 -0
  116. package/skills/machinal-recipes/references/examples/tutorial-clean.yaml +19 -0
  117. package/skills/machinal-recipes/references/examples.md +28 -0
  118. package/skills/machinal-recipes/references/jobs-scenes.md +206 -0
  119. package/skills/machinal-recipes/references/text-audio.md +118 -0
  120. package/skills/machinal-recipes/references/yaml.md +72 -0
  121. package/skills/machinal-review/SKILL.md +18 -0
  122. package/skills/machinal-review/references/production.md +146 -0
  123. package/skills/machinal-scenes/SKILL.md +44 -0
  124. package/skills/machinal-scenes/references/authoring.md +97 -0
  125. package/skills/machinal-scenes/references/runtime.md +136 -0
  126. package/skills/machinal-scenes/references/scene-templates/blueprint-mechanism.svelte +62 -0
  127. package/skills/machinal-scenes/references/scene-templates/glitch-handoff.svelte +30 -0
  128. package/skills/machinal-scenes/references/scene-templates/image-reveal.svelte +33 -0
  129. package/skills/machinal-scenes/references/scene-templates/kinetic-type.svelte +38 -0
  130. package/skills/machinal-scenes/references/scene-templates/layered-parallax.svelte +31 -0
  131. package/skills/machinal-scenes/references/scene-templates/lens-assembly-3d.svelte +57 -0
  132. package/skills/machinal-scenes/references/scene-templates/paper-stage-3d.svelte +83 -0
  133. package/skills/machinal-scenes/references/scene-templates/signal-diagram.svelte +43 -0
  134. package/skills/machinal-scenes/references/scene-templates/swiss-grid-motion.svelte +54 -0
  135. package/skills/machinal-scenes/references/scene-templates.json +178 -0
  136. package/skills/machinal-scenes/references/scene-templates.md +50 -0
  137. package/skills/machinal-scenes/references/workflow.md +206 -0
  138. package/skills/machinal-support/SKILL.md +42 -0
  139. package/src/bridge.mjs +287 -0
  140. package/src/cli.mjs +157 -0
  141. package/src/configuration.mjs +148 -0
  142. package/src/connection.mjs +187 -0
  143. package/src/credential-store.mjs +61 -0
  144. package/src/credits.mjs +86 -0
  145. package/src/docker.mjs +93 -0
  146. package/src/download.mjs +90 -0
  147. package/src/endpoints.mjs +3 -0
  148. package/src/errors.mjs +9 -0
  149. package/src/formats.mjs +140 -0
  150. package/src/keys.mjs +127 -0
  151. package/src/launch.mjs +29 -0
  152. package/src/local-setup.mjs +109 -0
  153. package/src/opencode-auth.mjs +246 -0
  154. package/src/opencode-checkpoints.mjs +90 -0
  155. package/src/opencode-configuration.mjs +53 -0
  156. package/src/opencode-media.mjs +139 -0
  157. package/src/opencode-plugin/index.mjs +7 -0
  158. package/src/opencode-plugin/package.json +5 -0
  159. package/src/opencode-recipes.mjs +130 -0
  160. package/src/opencode-routing.mjs +154 -0
  161. package/src/opencode-tools.mjs +30 -0
  162. package/src/opencode-workflow.mjs +32 -0
  163. package/src/presentation.mjs +31 -0
  164. package/src/prompts.mjs +32 -0
  165. package/src/reference-files.json +127 -0
  166. package/src/runtime.mjs +51 -0
  167. package/src/setup-options.mjs +69 -0
  168. package/src/setup-stdio.mjs +116 -0
  169. package/src/setup.mjs +173 -0
  170. package/src/skills.mjs +68 -0
  171. package/src/transfer-http.mjs +109 -0
  172. package/src/version.mjs +3 -0
  173. package/src/windows-key-prompt.mjs +37 -0
  174. package/src/windows-key-prompt.ps1 +77 -0
@@ -0,0 +1,206 @@
1
+ # Generation actions and scene direction
2
+
3
+ For MCP use **current-client scene authoring**: read `get_editing_reference(topic=scene-authoring)`, write Svelte with the AI already connected in the client, and call `compile_scene`. Client-authored CODE and source compilation have no server AI generation fee. Server scene frame rendering and final video encoding ARE billed at the configured render tariff, alongside approved images, speech and captions/transcription. A saved live source is not an encoded scene video. Call `get_credits` and obtain spending/source approval before server rendering or provider actions. Catalog support does not prove runtime/provider health.
4
+
5
+ The `scene.generate`/`scene.edit` job contracts and examples below document the shared **site/server-model compatibility** path, not the current MCP submission path. MCP rejects pending server scene jobs without fallback; reuse materialized results or place the asset returned by `compile_scene` in ordinary video tracks. See example `client-scene`. Source edits use `get_scene_source` then `compile_scene(sourceFile=...)`, preserving attachments. The current client repairs diagnostics without a server model. Server video/scene rendering still requires explicit authorization to use sources and spend credits.
6
+
7
+ ## Plan animated scenes proactively
8
+
9
+ Use `get_editing_reference(topic=production)` for the director/builder/critic workflow: define observable success in a production contract, critique it before writing source, then compare the implementation with `compile_recipe.editorialReview` before final rendering. This changes the harness, not scene-engine. Subject specificity and meaningful independent action are quality criteria, not a quota of shapes/effects. Keep scene-internal choreography distinct from recipe-level transitions and do not mistake compile/layout success for visual approval.
10
+
11
+ Before choosing a visual medium for a new video, read `get_editing_reference(topic=brief)` and resolve missing type, duration, aspect/output resolution, style/materials and audio choices with the user. Use the host's native question tool (OpenCode: `question`) with one `questions` array, not a numbered chat questionnaire; use an unnumbered fallback only if no interactive tool exists. In that form, recommend 1–2 relevant options such as an existing photo, a newly generated image, an animated scene or an image inside a scene, and explain the benefit. After the user answers, summarize the direction briefly and proceed immediately with the authorized work in the same turn, without a separate plan confirmation. Include known permissions as separate explicit questions in the same form where possible; never infer consent from a cancelled form or a creative preference. Respect already-specified choices and “you decide” delegation; do not ask the same questions for each beat. Do not automatically add production labels to scenes/captions or repeat them in chat. Keep generated media truthful and agree once on any requested or specifically required disclosure.
12
+
13
+ The MCP creates the same **animated Svelte components** as the editor. The host agent writes both the art direction and the actual Svelte source, sends it through `compile_scene`, and receives a pinned live `.scene.json` asset. Server export materializes it through scene-engine without another scene-model call. It is not an alias for image generation. `component` is a compile_scene tool field, not an inline recipe field.
14
+
15
+ When planning a video, evaluate **footage, still image, ordinary text and animated scene** per meaningful beat, without waiting for the user to explicitly request a scene. Make a compact beat sheet: timeline start/duration, message, visual choice, source/attachment and why motion helps. Look for:
16
+
17
+ - A process or cause/effect explanation: independently moving objects, arrows and successive states.
18
+ - A product/image reveal: use an actual uploaded image inside an animated layout, with independent labels or objects rather than baking everything into a still.
19
+ - A comparison, relationship, journey or supplied numeric progression: motion should explain the change, not manufacture data.
20
+ - An illustrative cutaway that makes narration clearer, with a readable hold and a deliberate return to footage.
21
+
22
+ Use the supplied script/copy, verified narration/cue times or sources actually inspected with approval. Metadata alone is not visual inspection and the reference tool does not watch/transcribe a video. If content/timings are unknown, ask for the relevant content or obtain it with the client's available approved inspection tools; mark proposed beat times as provisional. Never invent what happens at a source timestamp.
23
+
24
+ A pan/zoom over a still moves the entire image; it does not animate separate objects or embed a real image in an independently changing layout. Write Svelte in the current client and use `compile_scene` for those needs instead of defaulting every visual to `image.generate`. Do not silently replace requested animation with a slideshow. Reuse existing footage/text when equally effective, preserve footage-only/no-generation requests, and never impose a scene quota or generate images merely to demonstrate a capability. An unavailable compiler requires an explanation and user agreement before substituting another medium, never a server-model fallback.
25
+
26
+ For each selected scene, specify purpose, exact supplied copy, objects and hierarchy, real image IDs, palette, layout/safe areas and **scene-local choreography**: which object moves, direction/path, entrance time, reveal/change, readable hold and exit. Distinguish scene-local prompt times from the placement's global timeline time. Tie motion to a real communication need, avoid wall-clock animation and request frame-derived Svelte scene-runtime animation. For 3D, describe procedural geometry/camera in the prompt rather than inventing DSL fields. The backend, not the MCP client, owns compilation and sandbox execution.
27
+
28
+ Do not compress the scene brief to 'cinematic CSS', a generic heading or the documentary title. Name the visible subject and action, foreground/midground/background, material/light treatment, palette, scale, exact copy and what changes over the scene. A rich scene is a coherent piece of visual storytelling, not a count of shapes or effects; respect a deliberately minimal brief. For a spatial subject or an explicit Three.js request use `visualMode: 3d` and describe genuine meshes, lighting, camera target/path and deterministic mesh action. CSS perspective and a copied rotating demo primitive are not substitutes. For complex illustrative subjects, attach approved images and animate the subject, supporting diagram and labels independently rather than using a text-only card.
29
+
30
+ Visibility is part of the brief: keep the main subject legible during the central hold and most of the shot, not permanently at opacity 0, behind a backdrop, clipped offscreen or outside a Three.js camera. Specify separate reveal/hold/exit timing and sane contrast. Repairs preserve the artwork, motion and attachments rather than deleting complexity to pass compilation. No AI-production label, disclaimer or watermark belongs on screen: do not add 'AI illustration', 'AI-generated', 'Ilustrație AI', 'Generat cu AI' or 'Narațiune sintetică' to scene text, image prompts, CSS/SVG/canvas or textures. Explanations/provenance stay outside the video. Subject copy genuinely about artificial intelligence is different from an unsolicited production notice.
31
+
32
+ For example, a proposed 16-second edit could retain footage at 0–4s, insert a six-second animated explanation at 4–10s, and return to footage at 10–16s. A six-second scene brief can introduce a real image at local 0–1s, move objects/reveal labels at 1–3s, hold at 3–5s and settle at 5–6s. These are illustrative planning times, not observations about the user's media. Fetch `get_editing_reference(topic: examples, id: scene-image-insert)` for the complete compiler-tested YAML, including real-field image attachments and placements.
33
+
34
+ Fetch `scene-generation` for a more detailed portrait SVG storyboard, or `scene-three-explainer` for a complete procedural Three.js mechanism brief with staged assembly, linked mesh action, a camera orbit and stable final hold. They are synthetic pending-generation examples, not generated media or promises of visual quality; reading/compiling them does not call providers or authorize spending.
35
+
36
+ ## Complex scene assets: images and transparency by default
37
+
38
+ When a character, animal, plant, realistic product, detailed object, texture or illustration would not read well as procedural SVG/CSS, **default to an image-backed animated scene**. Reuse an approved suitable image first; otherwise plan `image.generate` within approved generation/spending scope, without waiting for an explicit image request. Do not force intricate subjects into fragile shape stacks or replace them with generic headings. Keep SVG/CSS for simple diagrams and genuine SceneThree geometry for spatial action. Images complement independent motion, not a slideshow replacement. Explicit no-generation, footage-only and `imagePolicy: procedural-only` choices override this default.
39
+
40
+ ### Visual coverage across the video
41
+
42
+ Make the same choice when SVG/CSS would be **overly simplistic**, not just technically difficult. A history/biography mini-documentary needs subject-specific contextual views, not one reused portrait plus text, lines and nodes. Cover relevant people, geographic context, environments and period-grounded illustrative scenes using verified narration/copy; do not invent historical events or present generated images as archival evidence. Simple, geographically accurate map diagrams remain useful alongside illustrations.
43
+
44
+ Keep a compact image-coverage list with the measured beat, narrative purpose, suitable approved existing asset or proposed new image, and destination scene. For example, a biography may need a portrait, a place-setting view, an illustrative historical environment and a relevant later-life context. These are coverage roles, not invented facts or a compulsory shot list. Reframing/recoloring one portrait does not add a distinct contextual view.
45
+
46
+ **5–10 distinct images per video can be appropriate**, neither a quota nor a cap. The **four-image attachment limit is per scene, not per video**: distribute images across `compile_scene` calls or ordinary image clips according to the approved presentation. Reuse suitable successful images, but do not collapse distinct narrative contexts into a simplistic infographic solely to make the video cheap. Respect the approved budget and generation scope; if needed coverage exceeds permission or a hard spending cap, explain the tradeoff and ask rather than silently downgrading or overspending. Minimal/no-generation/procedural-only briefs still win. This visual-source decision does not authorize changing narration, captions, pacing or transitions.
47
+
48
+ ### Select the tool for the missing capability
49
+
50
+ `image.generate` is a **YAML job type, not an MCP tool**. The current client selects tools; the free `suggest_tools` catalog and optional host routing only assist selection, never execute actions or grant consent.
51
+
52
+ | Need/current stage | Actual MCP tool and boundary |
53
+ | --- | --- |
54
+ | Decide whether SVG/CSS is too complex or overly simplistic | `get_editing_reference(topic=scenes)` and `get_capabilities`; plan meaningful image coverage within approval. |
55
+ | Create missing artwork | `generate_assets` with approved `image.generate` jobs in validated YAML, after the separate timing-first checkpoint when narrated. Do not rerun successful speech/captions. |
56
+ | Materialize and reuse generated images | `wait_for_job` until completed, then `get_job_result` for actual filenames, assets and resolved recipe; no guessed filenames or regeneration. |
57
+ | Compose/animate approved images | `compile_scene` with client-authored Svelte and up to four images per scene; compilation does not generate artwork or render a video. |
58
+ | Inspect an approved scene's actual frames | `get_scene_source` for its version, then bounded `inspect_scene`; not final-composition or audio inspection. |
59
+ | Export the resolved, reviewed composition | `validate_recipe`, `compile_recipe`, then approved paid `render_video`; not a way to discover missing artwork or timing. |
60
+
61
+ Choose only the relevant stage and prerequisites, not every tool on each beat. Keep existing successful assets and normal media/spending approvals; a routing recommendation is not authorization.
62
+
63
+ For **isolated foreground subjects, sprites, cutouts and independently composited layers**, default to **`background: transparent`** on `image.generate`. Use **`openai/gpt-image-2.5-sunburst`** unless the user selected another compatible model; **`openai/gpt-image-2.5-flare`** also supports transparent backgrounds. Respect explicit model choices; do not silently substitute an incompatible model. Request a complete isolated subject, clean edges and real alpha, with no painted checkerboard, solid backdrop, frame or baked-in labels. Use `background: opaque` for full-frame environments and images whose background is part of the story; not every image should be transparent.
64
+
65
+ Example image job fragment (not a complete recipe or permission to spend):
66
+
67
+ ```yaml
68
+ before:
69
+ - id: foreground-subject
70
+ type: image.generate
71
+ model: openai/gpt-image-2.5-sunburst
72
+ aspect: '1:1'
73
+ background: transparent
74
+ prompt: >-
75
+ A complete oak sapling with detailed leaves and exposed roots,
76
+ isolated on a transparent background with real alpha and clean edges.
77
+ No painted checkerboard, solid backdrop, frame, text or labels.
78
+ ```
79
+
80
+ After the timing-first checkpoint when applicable, generate the approved image, wait for completion and attach its actual returned filename to `compile_scene.images`. The image job field is `background`, not `transparent: true`; `compile_scene.transparent` controls the scene canvas separately and does not remove an opaque image background. Preserve PNG/WebP alpha; do not flatten onto a solid background or convert cutouts to JPEG. Use separate approved images for independently moving subjects/layers, within the four-image attachment limit; moving one bitmap does not articulate its internal parts or reconstruct 3D.
81
+
82
+ A transparency request alone does not verify returned alpha. Do not claim verification from a filename, metadata or a JPEG diagnostic thumbnail. If alpha is missing or unverified, report that limitation; do not automatically regenerate a paid asset or install local background-removal pipelines. Reuse existing scope approvals rather than reconfirming each covered asset; this default does not grant media access, paid generation or rendering permission.
83
+
84
+ ## Integrate images; raise the visual ambition
85
+
86
+ Image sourcing and presentation are separate choices. “Use/find/generate images for this video” is not an instruction to exclude scenes. If presentation is undecided, ask once in the native brief form whether approved images may be integrated into animated Svelte scenes, optionally with genuine Three.js where it adds spatial meaning. Recommend a concrete subject-specific treatment versus a photo-only montage; explain the additional scene-frame rendering cost separately from image generation and final encoding. Reuse an answered choice or “you decide” delegation, preserve explicit still-only/no-scenes/no-generation choices, and do not expand standalone image searches into video work. Image-search/download/use still requires the appropriate permissions and actually available tools; do not invent a search provider or rights to a found image.
87
+
88
+ Treat a selected image as a scene attachment and visual anchor, not a reason to abandon animation. Preserve its proportions, identity and key details. Compose independently animated frames, labels, diagram elements or other approved images around it, and match palette, framing and movement to the neighboring footage/scenes. Moving a full flat image is not internal subject animation or recovered 3D geometry. Do not claim parallax-separated subjects, hidden surfaces or a realistic 3D reconstruction without actual layers/assets. New generated layers or artwork need their own approval.
89
+
90
+ For expressive/bold briefs, design a **signature visual action** at a meaningful beat: what the viewer sees change, why it expresses this subject, how the action builds, and where it settles into a readable hold. This is a design criterion, not a scene quota. Avoid a sequence of identical centered cards, headings and zooms. Use stronger subject-specific staging, depth, lighting, asymmetric compositions and contrasting motion speeds rather than covering generic content in particles, glow or camera shake. Minimal briefs remain deliberately quiet.
91
+
92
+ Choose the medium by what actually moves:
93
+
94
+ - **2D/Svelte:** editorial image collage, framed image reveals, independently moving labels, relationship diagrams and comparison layouts. Useful depth cues do not require 3D.
95
+ - **Three.js/SceneThree:** spatial assembly/disassembly, a mechanical relationship, scale/depth comparison, or a camera move that reveals genuinely different geometry. Proactively recommend it when helpful; do not wait for the user to name Three.js. Use actual meshes/materials/lights, a framed camera target/path and deterministic object action, not CSS perspective, a rotating cube or a flat photo mislabeled 3D. Check sceneMode and the live runtime first; do not promise unsupported image textures or postprocessing. For mixed image/3D scenes, approved images may remain a supported 2D layout alongside genuine spatial geometry.
96
+
97
+ These are illustrative storyboards, not preset IDs or permission to render:
98
+
99
+ | Subject/intent | Image integration and signature action | Continuity/hold |
100
+ | --- | --- | --- |
101
+ | Biography/history from verified material | Use distinct approved portrait, geographic/environmental and period-grounded illustrative images for the relevant measured beats; animate image layers and short factual labels independently. Document cards can support the story, not substitute for all historical context. | Match neighboring frames/palette; preserve readable viewing holds. No invented depth inside a portrait or generated image presented as archival evidence. |
102
+ | Product/process | A genuine 3D mechanism separates into functional parts, then linked parts engage; an approved product image and independently revealed labels provide context. | Camera moves to reveal the relationship, then holds the working assembly. Do not invent product internals or capabilities; use an explicitly schematic mechanism when appropriate. |
103
+ | Comparison/explanation | Two approved images enter separate aligned panels; relevant diagram elements move between supplied states while a restrained focus accent directs attention. | Match scale and alignment; hold the result and carry a panel edge/direction into the next shot. No invented data. |
104
+
105
+ Add to the beat sheet the signature action, independent moving elements, 2D/3D rationale, entrance/action/hold/exit cues and adjacent-shot continuity. For narrated work, finalize all times from the measured timing checkpoint, not these illustrative descriptions. Write the complete Svelte source in the current client and compile it; none of these planning labels are YAML fields.
106
+
107
+ Coordinate an **effect score** with topic `effects`: selected clip/track accents, exact catalog IDs/params, supported ramps and junction timing. Implement them on the real resolved tracks instead of stopping at a prose plan or removing them during staging. Check for duplicate grading/texture, label blur and excessive motion; scene lighting is not an excuse to indiscriminately stack a global glow. Do not add unapproved image/provider actions or paid preview/re-render loops to increase spectacle.
108
+
109
+ Before export, review source choreography and available Directional diagnostics for reveal, action, central hold and exit: is the actual subject visible, does something meaningful change independently, is there contrast in pace, and do neighboring shots feel related? Inspect representative frames/output only with deployed tools and within approved processing/access/spending scope. Compilation/layout success does not prove visual ambition or quality; state when visual inspection is unavailable rather than claiming a verified spectacular result. Repairs preserve artwork, motion and approved attachments; never downgrade to a static title card merely to pass checks.
110
+
111
+ ## Legacy site/server-model job contracts
112
+
113
+ Read `get_workflow_preferences` and `get_editing_reference(topic: scene-runtime)` before choosing a treatment. The runtime contract supplies exact embedded font families, image bindings, imports and a genuine Three.js starter. For MCP, `sceneMode: 3d` becomes `visualMode: 3d` on compile_scene, and the current client writes the component. The following job-specific prompt fields describe legacy site generation, not pending MCP scene work.
114
+
115
+ For complex characters, animals, realistic objects, textures and artwork, prefer actual images over fragile stacks of CSS/SVG shapes. Keep the image visible and animate its wrapper and other objects independently. Obtain spending approval for a new image; current-client scene code and compilation are free. Preserve `imagePolicy: procedural-only`, explicit no-generation and footage-only briefs.
116
+
117
+ All jobs use a unique `id` and exact `type`. Prefer `before` + `placements` + `after` for new staged recipes. Legacy `jobs` remains supported, with `trackId` referencing an already declared track and explicit `start`/`duration` when placing results. `start: 0` on a legacy job with an occupied track is treated as append-to-track; staged placements make zero unambiguous.
118
+
119
+ | Type | Stage | Inputs and results |
120
+ | --- | --- | --- |
121
+ | `image.generate` | before or legacy jobs | Required `prompt`; optional configured `model`, `aspect`, `background`, `imageStyle`. Use `background: transparent` for isolated composited subjects with GPT Image 2.5 Sunburst/Flare; use `opaque` when the background belongs in the image. `imageStyle` is appended prompt text, not a catalog look or nested CSS. The orchestration passes `background` through to the configured image service; a request is not verification of returned alpha. Returns `resultAssetId`. |
122
+ | `speech.generate` | before or legacy jobs | Required `text` (legacy `input` fallback); `language: ro`/`en` for the spoken language; optional `instructions`, configured `model`, `voice`, `referenceName`, `referenceTranscript`. A reference is an uploaded project filename; never fabricate a speaker identity/consent or provider voice ID. Returned speech duration is measured, not predicted. |
123
+ | `scene.generate` | before or legacy jobs | Required `prompt`; duration 1–60s, or omit it with `narrationJob` to use the measured speech duration. Optional `text` is exact on-screen copy; `narrationJob` references an earlier before speech job, and `narrationFrom` selects source-audio seconds. Optional `aspect`, dimensions, `fps`, model, images and visualMode. Creates one live animated Svelte scene with relevant content, not an unrelated title card. |
124
+ | `scene.edit` | before or legacy jobs | Same duration/dimensions limits; required `assetId` of an existing server `.scene.json` video asset and edit `prompt`. Preserve existing media/narration. Do not pass new `images` on an edit. |
125
+ | `captions.generate` | after or legacy jobs | Real audio-bearing timeline, optional `assetId`, `language`, `maxWords`, caption TextStyle `style`; returns actual `resultTextIds` and text items. Read topic `text`. |
126
+ | `analysis.transcribe` | legacy jobs only | Recognized requirement type for transcription; do not promise that the existing orchestration materializes it into caption text automatically. Prefer `captions.generate` for automatic on-video captions. |
127
+
128
+ `resultAssetId`, `resultAudioAssetId`, `audioStart`, `resultTextIds` are returned/materialized state, not placeholders to invent to bypass a requirement. Preserve them together with actual assets/texts to avoid regeneration. `assetId` on a caption job selects source audio; on a scene edit it selects the existing live scene. They do not have the same meaning as `resultAssetId`.
129
+
130
+ ## Placements and materialization
131
+
132
+ ```yaml
133
+ before:
134
+ - id: opener
135
+ type: scene.generate
136
+ duration: 6s
137
+ aspect: portrait
138
+ fps: 30
139
+ prompt: >-
140
+ A clean editorial infographic, portrait framing. Show the user-supplied
141
+ three-step process as a vertical progression. Use restrained cobalt
142
+ and white, readable type, a short entrance, a stable reading hold,
143
+ and a quiet exit. Do not invent statistics or include external media.
144
+ placements:
145
+ - job: opener
146
+ track: {type: video, role: opener}
147
+ start: 0s
148
+ duration: 6s
149
+ ```
150
+
151
+ Generated image/scene results go on a `video` role; speech on `audio`. The compiler creates `recipe/<type>/<role>` tracks and deterministic placement clip IDs. Images require at least 100ms explicit duration. For audio/video, omitted duration uses the job duration or actual asset duration; never exceed the generated asset duration. A placement `transform` only applies to video tracks. Source scene narration returned by the backend is linked automatically; do not duplicate it with another voice track.
152
+
153
+ Before generation, compilation returns requirements, **not a renderable composition**. Staged preflight can use an empty base timeline, but rules/effects/commands that target nonexistent future clips can still fail before provider calls. Safest workflow: generate only after approval; retain resolved assets/document; then add the desired look/transitions/effects/text to real tracks/IDs, validate and compile again before rendering. Never silently discard the intended final treatment to make the pending stage pass.
154
+
155
+ ## Timing-first narration, captions and visuals
156
+
157
+ For narrated work use **separate submissions**, not a complete voice/image/scene/caption recipe submitted at once. Every `before` job runs before `after` captions in the same submission. Putting speech first in `before` therefore does **not** make measured captions available to subsequent visual jobs. Do not move captions into `before` or invent a dependency/stage field.
158
+
159
+ 1. **Timing pass:** after checking credits and obtaining source-use/spending approval, call `generate_assets` with only the requested speech, its audio placement and requested `after: captions.generate`. No `image.generate`, `scene.generate` or `scene.edit` jobs belong in this first submission. Example `narration-timing` is an audio-only timing recipe, not a final video.
160
+ 2. **Timing checkpoint:** use `wait_for_job` until `status=completed`, then read `get_job_result` once. Retain the resolved `recipeYaml`, measured audio asset duration, caption `texts`, cue-local `words`, `resultAssetId` and `resultTextIds`. If timing fails or is missing, stop dependent visuals and recover successful assets; never invent word times or start everything over.
161
+ 3. **Visual pass:** only now finalize the beat sheet and image/2D/Three.js scene briefs. Derive global image holds, scene start/duration and local entrance/reveal/hold/exit times from the measured speech/caption boundaries. Caption word times are relative to their text item's start; `narrationFrom` is relative to source audio, while placements are global timeline times. Include gaps and narration placement offsets. Keep each image/prompt tied to its actual spoken excerpt, not just the video title.
162
+ 4. Add approved visual jobs to the **returned resolved composition**, preserving audio tracks/assets, speech jobs, caption jobs and actual texts. Normalization may move materialized `before`/`after` jobs into `jobs`; do not recreate unmaterialized copies. `sourceJobId` replays an **unchanged** recipe, so adding visuals requires the edited `composition` YAML instead. Use a new stable idempotency key for this intentionally different operation. Example `narrated-documentary` demonstrates the second pass using explicitly synthetic resolved timing fixtures; never copy those fixtures into a real project.
163
+ 5. Generate approved images before scenes that attach them, resolve/validate the completed visual pass, and then `render_video`. Preserve the same narration and captions rather than paying for them again. Retiming/replacing audio invalidates its old captions and dependent visual timings: resolve that change before generating/rendering dependent work. An already-approved workflow need not ask again for each covered stage; new provider actions or changed scope require approval.
164
+
165
+ ### Narration overruns an approximate target: extend visuals, not speech work
166
+
167
+ A requested or AI-proposed runtime is approximate unless the user explicitly sets a hard duration cap. A planned 30-second video with 38–40 seconds of successful narration is valid: keep the successful audio/captions and extend the video to the measured narration end, including its placement offset. Do not regenerate, truncate or speed up narration solely to match the estimate; do not rewrite its script and pay for a second voice or rerun successful captions/images.
168
+
169
+ Lengthen suitable scene holds/actions or add relevant client-authored scenes within the approved visual scope. Recompile a scene whose source duration must grow; merely extending a placement beyond the pinned asset duration is invalid. Preserve attachments/artwork, keep each scene at most 60 seconds, update placements and transition overlaps, and validate continuous picture coverage through the full narration without a blank tail or audio cutoff. Keep actual caption words/timings unchanged when audio placement is unchanged. State the adjusted runtime and continue without reconfirmation within existing permissions. Resolve an explicit hard duration cap or spending limit before replacing paid narration or exceeding approval; a flexible runtime overrun alone is not failure or a reason to restart production.
170
+
171
+ Existing approved speech/captions can satisfy the timing checkpoint without regeneration. If TTS was not requested, use the approved existing audio and generate only requested captions. If captions were not requested, do not add paid transcription or on-screen subtitles unasked: use measured speech duration for whole-section scenes, and do not claim word-accurate timing. If neither narration nor captions is needed, skip the timing pass. Music-only or footage-only edits retain their existing workflow.
172
+
173
+ Bind `scene.generate.narrationJob` to an earlier `before` speech job or a materialized speech job retained in `jobs` from the timing pass. The backend gives the scene generator the actual spoken text and measured duration, without generating a duplicate voice track. A whole narration longer than 60 seconds must be split into meaningful sections. For a window of a longer narration, set `narrationFrom` plus `duration` only after captions with real word times have been materialized; missing cues fail instead of inventing a transcript. Exact scene-local cue times and narration content are passed to the component generator.
174
+
175
+ ## Scene layout checks and recovery
176
+
177
+ New scene generation and edits are checked in a real browser at multiple representative frames before they are accepted. Off-canvas/clipped text, illegible font sizes, colliding text blocks, text in the reserved caption band, recognized visible AI-production notices and no detectable foreground across the sampled frames produce repair diagnostics. Canvas/WebGL sampling detects nonblank artwork, not its meaning. The existing single repair attempt is bounded; persistent failures are reported, not rendered as if successful. When the timeline contains captions, reserve its bottom 24% for them. This is geometry/visibility validation, not OCR or a guarantee that an arbitrary image is semantically correct or aesthetically successful.
178
+
179
+ After generation use `get_job_result` once for `recipeYaml`, or pass `sourceJobId` for unchanged continuation. Prefer `wait_for_job(timeoutSeconds:120)` to repeated progress lookups or local sleep loops; it ignores heartbeat revisions. Keep recipes as `.edit.yaml` and reuse resolved assets.
180
+
181
+ Compact job summaries may include `timing.remainingSeconds` (processing) or `timing.estimatedQueueSeconds` (before processing). Both are approximate, based on live progress or recent successful jobs, never a completion deadline or a cost quote. Missing timing means no supported estimate is available. Final cloud publication may take additional time; only `status: completed` authorizes delivery, never a progress percentage alone. The signed-in `/jobs` page can recover jobs and issue fresh S3 download links without another render.
182
+
183
+ `stage.scope` distinguishes scene capture from whole-job video, caption, audio, encoding and publication phases. Terminal jobs omit active stage/ETA fields, including stale values from older snapshots. `performance` persists wall-clock phase durations and observed cache hits/misses; `truncated` discloses a capped phase history. These metrics identify bottlenecks but do not prove a speedup. Historical timing samples can be restored from scoped completed-job performance after worker restart. `timing.sampleCount`, `remainingRangeSeconds` and `estimateUnavailableReason` explain uncertainty; weighted progress is never used as a time fraction. With no supported history, keep the estimate unavailable instead of inventing one.
184
+
185
+ ## Select a scene by communication need
186
+
187
+ - **Infographic/process:** explain a real relationship or sequence; specify hierarchy, truthful values, visual metaphor, entrance/hold/exit and readable labels. Good for tutorials, not unsupported statistics.
188
+ - **Product reveal:** use supplied product/brand images visibly, preserve logos/aspect/alpha, specify an intentional reveal and a stable benefit/call-to-action hold. Do not replace real product evidence with invented claims.
189
+ - **Comparison/split layout:** two aligned panels and consistent scales, synchronized changes, user-provided labels/data; do not claim a new YAML `splitScreen` or `scenePreset` field.
190
+ - **Map/journey/timeline:** use verified locations/events and a coherent path; no external map URLs or fabricated coordinates. Schematic illustration is acceptable when explicitly described as such.
191
+ - **Diagram/3D explainer:** use `visualMode: 3d` for genuine SceneThree geometry, lighting and deterministic camera/update; auto/2d are also supported. Read topic `scene-runtime`, rather than guessing a Three.js API. scene.edit preserves its existing mode. The DSL does **not** expose `transparent`, `videos`, `audioFile` or arbitrary component source. `text` is supported for exact on-screen copy on scene.generate; narration is a separate narrationJob binding.
192
+ - **Quiet title/quote:** prefer normal `texts` and existing footage if that communicates the same idea without paid scene generation.
193
+
194
+ These are **scene briefs**, not registered preset IDs. There is no document-level `scenes` array in this DSL; place `scene.generate`/`scene.edit` jobs correctly.
195
+
196
+ ## Images, runtime and namespace limits
197
+
198
+ Scene `images` accepts at most four uploaded JPEG/PNG/WebP sources, with unique IDs `image_1` through `image_4`, `file`, human-readable `name`, optional `description` (up to 600 characters). Each input must be at most 5 MiB/40 million pixels. Metadata is not visual inspection. Scenes preserve real attachments; don't invent URLs or binary/base64 YAML payloads.
199
+
200
+ Describe how each attachment is used and animated: for example, keep `image_1` inside a product card while labels and schematic objects enter independently. Preserve the original image's proportions, existing alpha and truthful branding. Transparent image generation uses the existing `image.generate.background: transparent` field, not a new image-job `transparent` field or the scene-canvas setting. The uploaded image is supplied as a component prop by the backend, not fetched from an external URL. A scene can also be entirely procedural without an image-generation call.
201
+
202
+ For MCP asset preparation, a new image is the only paid generation stage: generate it first, wait for its actual project filename, then attach it with `file` to the free source compilation through compile_scene. Subsequent scene-frame rendering and final encoding remain billed. In the legacy site/server-model path there are two paid stages for generation: image.generate before scene.generate can attach `{id: image_1, job: artwork-job, name: Subject}`. That legacy `job` dependency must reference an earlier image.generate. It is not a compile_scene tool field. Read example `scene-generated-image` only as server-model compatibility guidance. Never put a guessed job ID into `file` or invent resultAssetId placeholders. Keep all resolved media for reuse.
203
+
204
+ On failure, inspect `result.recovery`: a resumable `{document, bindings, assets}` envelope retains successful prior outputs. Save it and resume missing stages after resolving the error; do not regenerate successful speech/images. Recovery does not grant unrelated media access or new spending permission.
205
+
206
+ The backend creates deterministic Svelte scene source using its existing renderer. Read `scene-runtime` for all embedded scene font families, supported image bindings and the exact SceneThree API; CSS family names are **not** recipe fontFamily IDs. SceneVideo look names are another namespace, not recipe look IDs or YAML job fields. Do not install libraries, access networks or introduce wall-clock animation as a workaround. The backend owns the component sandbox.
@@ -0,0 +1,42 @@
1
+ ---
2
+ name: machinal-support
3
+ description: Discover and troubleshoot machinal MCP, missing tools, disconnected servers, authentication and saved API keys in Windows Credential Manager. Use immediately when machinal tools are unavailable or a connection/key fails; recover the existing integration before asking for setup or a replacement key.
4
+ ---
5
+
6
+ # MCP discovery and credential recovery
7
+
8
+ Discover first; do not assume the MCP is missing because its tools are absent from the initial tool list. Use directly exposed native tools first, including `get_workflow_preferences` or `get_editing_reference`. Only for an unknown/missing tool, search the tool catalog in OpenCode Code Mode once, then reuse the exact returned namespace and signature for this session. Do not repeat discovery for every step or use web search for MCP tool names. Never invent a tool name or an API endpoint.
9
+
10
+ ## OpenCode automatic integration
11
+
12
+ With the default stdio adapter (all supported clients), the MCP `connection_status` tool stays available without backend login/network. It reports service states separately from `transport:connected`; `action:reconnect` reloads credentials and free discovery only, never job submissions. Missing credentials mean Login required; a network outage means Connection unavailable, not a failed local MCP handshake. Native client badge wording cannot be forced without OAuth. Independent local uses a generated device token and the user's OpenRouter settings, not a Machinal account key, subscription or wallet. Do not ask a local user to create a hosted key. Prefer the OpenCode companion recovery below when that tool is present; otherwise use the adapter's diagnostics before asking for reinstall/restart.
13
+
14
+ The local `machinal_connection` tool is independent of the remote MCP and remains available while it is disconnected:
15
+
16
+ 1. Call `machinal_connection(action: status)` to discover approved server names/endpoints, actual connection states and sanitized credential diagnostics. `machinal` is the default for new setups, but existing/custom registrations may use another name. If there are multiple registrations, select the user's intended connection; ask only if ambiguous.
17
+ 2. If discovery or connection/authentication fails, **immediately call `machinal_connection(action: reconnect, server: <registered name>)` once**. Do not first ask the user to locate a key, paste it, restart OpenCode or rerun the installer. The integration reloads and verifies the existing credential and reconnects the current service. It respects an explicitly chosen environment/session key.
18
+ 3. Rediscover the remote tool catalog and retry only a safe read-only lookup. A verified API probe is not proof that OpenCode's MCP is connected: inspect its actual connection state. If the failed request may have submitted paid work, recover the original job/idempotency before any retry; never create a new paid submission merely to test authentication.
19
+ 4. Follow the returned `code` / `nextAction`; report a persistent blocker rather than looping reconnects or silently replacing credentials.
20
+
21
+ ## Exact saved-key location
22
+
23
+ There is **one machinal application API key per Windows user**, not a separate OpenCode key or an AI-provider key:
24
+
25
+ | Windows Credential Manager field | Value |
26
+ | --- | --- |
27
+ | Service | `Machinal/mcp` |
28
+ | Account | `MACHINAL_API_KEY` |
29
+ | Windows target | `Machinal/mcp.MACHINAL_API_KEY` |
30
+
31
+ This is an OS credential, **not a project file**. The integration reads its secret through the native credential API into memory, supplying it only to the MCP name and endpoint approved during setup. Saved credentials take precedence over incidental environment values; explicit session/environment selections remain binding. Do not search `.env` files, dump environment values, extract secrets with `cmdkey`/PowerShell, inspect credential files or pass keys through chat/tool inputs/command arguments. A missing environment variable does not mean a saved key is missing.
32
+
33
+ ## Recovery decisions
34
+
35
+ - **`key-rejected` / HTTP 401, or `no-usable-key`:** after the recovery attempt, offer `replace` through the secure native window. It links to <https://machinal.app/api-keys>, verifies before changing the old credential and reconnects. Saving requires the user's separate approval; cancellation/rejection preserves the previous saved key. Do not open replacement automatically or request a key in chat.
36
+ - **`credential-store-unavailable`:** the vault could not be read; that is not evidence of an absent key. Retry under the same Windows account or explain the vault/access problem. Do not delete the credential or demand a replacement.
37
+ - **`connection-failed`:** check the approved URL, local API/container availability, TLS/network. A network failure is not a bad-key diagnosis. Do not start containers, install software or change endpoints without appropriate authorization.
38
+ - **`account-access` / HTTP 402 or 403:** check Premium/API access or origin restrictions. More keys do not fix account access.
39
+ - **`rate-limited` / HTTP 429:** retry later, without changing the key.
40
+ - **`server-required`, `server-not-registered` or `server-configuration`:** inspect the existing approved registration. Do not send the saved key to a guessed, overridden or unrelated endpoint. Use the existing setup only when genuinely needed and preserve unrelated configuration.
41
+
42
+ If `machinal_connection` itself is unavailable, inspect the client's MCP list/panel (`opencode mcp list` / `/mcps`, `claude mcp list`, or `codex mcp list`). The automatic vault/reconnect tool is specific to the installed Windows OpenCode integration; do not invent it for other clients. The installer/legacy launcher can read the saved credential on Windows without exposing it. Never reinstall, restart services or overwrite configuration just because Code Mode tools were initially hidden. Keep host approval controls enabled. Troubleshooting grants no media access or spending permission; after recovery, resume the original task within its existing consent scope.
package/src/bridge.mjs ADDED
@@ -0,0 +1,287 @@
1
+ import { readFile, mkdir, writeFile, lstat, rename, unlink } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { dirname } from 'node:path';
4
+ import { parseEnv } from 'node:util';
5
+ import { normalizeEndpoint, validateAPIKey, isLoopbackEndpoint } from './connection.mjs';
6
+ import { createCredentialStore } from './credential-store.mjs';
7
+ import { VERSION } from './version.mjs';
8
+ import { MACHINAL_SERVER_URL } from './endpoints.mjs';
9
+
10
+ const MAX_REQUEST = 4 * 1024 * 1024;
11
+ const MAX_RESPONSE = 2 * 1024 * 1024;
12
+ const PROTOCOL = '2025-11-25';
13
+ const VERSIONS = ['2025-03-26', '2025-06-18', PROTOCOL];
14
+ const CLIENT_VERSIONS = ['2024-11-05', ...VERSIONS];
15
+ export const STATUS_TOOL = Object.freeze({
16
+ name: 'connection_status',
17
+ description: 'Free connection diagnostics. Distinguishes login required, connection unavailable and account access from an MCP transport failure. Reconnect reloads credentials and tool discovery only; never retries submitted work. Never pass keys in tool arguments or chat.',
18
+ inputSchema: { type: 'object', properties: { action: { type: 'string', enum: ['status', 'reconnect'] } }, additionalProperties: false },
19
+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
20
+ });
21
+
22
+ async function privateFile(file, limit = MAX_RESPONSE) {
23
+ const stat = await lstat(file);
24
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > limit) throw new Error('Invalid connection file');
25
+ return readFile(file, 'utf8');
26
+ }
27
+
28
+ export async function cacheCatalog(file, data) {
29
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
30
+ const temporary = `${file}.${randomUUID()}.tmp`;
31
+ try {
32
+ await writeFile(temporary, JSON.stringify(data), { flag: 'wx', mode: 0o600 });
33
+ await rename(temporary, file);
34
+ } finally { await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; }); }
35
+ }
36
+
37
+ export async function localCredentials(file, endpoint) {
38
+ if (!isLoopbackEndpoint(endpoint)) throw new Error('Local credentials require loopback');
39
+ const values = parseEnv(await privateFile(file, 64 * 1024));
40
+ if (normalizeEndpoint(values.MACHINAL_LOCAL_URL) !== endpoint || !/^local_[a-f\d]{64}$/.test(values.MACHINAL_LOCAL_TOKEN ?? '')) {
41
+ throw new Error('Local connection profile mismatch');
42
+ }
43
+ return values.MACHINAL_LOCAL_TOKEN;
44
+ }
45
+
46
+ async function jsonResponse(response) {
47
+ if (!response.headers.get('content-type')?.startsWith('application/json')) {
48
+ await response.body?.cancel();
49
+ throw new Error('Invalid service response');
50
+ }
51
+ const reader = response.body?.getReader();
52
+ if (!reader) throw new Error('Empty service response');
53
+ let size = 0;
54
+ const chunks = [];
55
+ try {
56
+ while (true) {
57
+ const { value, done } = await reader.read();
58
+ if (done) break;
59
+ size += value.byteLength;
60
+ if (size > MAX_RESPONSE) { await reader.cancel(); throw new Error('Service response too large'); }
61
+ chunks.push(value);
62
+ }
63
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
64
+ } finally { reader.releaseLock(); }
65
+ }
66
+
67
+ export class MCPBridge {
68
+ constructor({ url, localConfig, catalogFile, env = process.env, credentialStore = createCredentialStore(), fetchImpl = fetch, signal, notify = () => {} }) {
69
+ this.url = normalizeEndpoint(url);
70
+ this.localConfig = localConfig;
71
+ this.catalogFile = catalogFile;
72
+ this.env = env;
73
+ this.credentialStore = credentialStore;
74
+ this.fetch = fetchImpl;
75
+ this.signal = signal;
76
+ this.notify = notify;
77
+ this.tools = [];
78
+ this.state = { status: 'unchecked', message: 'Connection has not been checked.' };
79
+ this.nextID = 0;
80
+ this.key = null;
81
+ }
82
+
83
+ status() {
84
+ return { ...this.state, transport: 'connected', mode: this.localConfig ? 'local' : 'server', endpoint: this.url,
85
+ service: this.localConfig ? 'Local' : this.url === MACHINAL_SERVER_URL ? 'Machinal Server' : 'Custom server',
86
+ toolCount: this.tools.length, nextAction: this.localConfig && this.state.status !== 'connected'
87
+ ? 'Check the saved independent local profile and Docker services. Rerun setup --mode local if its generated device token is invalid; a Machinal login is not needed.' : this.state.status === 'login_required'
88
+ ? `Run npx @machinal/mcp key set --url ${this.url} in a terminal, or provide MACHINAL_API_KEY in the client environment. Never paste it in chat.`
89
+ : this.state.status === 'connected' ? 'Ready.' : 'Check the configured API/container and network, then reconnect. Do not replace keys for network or account-access errors.' };
90
+ }
91
+
92
+ async loadCatalog() {
93
+ if (!this.catalogFile) return;
94
+ try {
95
+ const cached = JSON.parse(await privateFile(this.catalogFile));
96
+ if (cached.url === this.url) {
97
+ this.tools = validTools(cached.tools);
98
+ if (typeof cached.instructions === 'string') this.instructions = cached.instructions;
99
+ }
100
+ } catch { /* A cache is optional; never trust an unreadable or malformed one. */ }
101
+ }
102
+
103
+ async credentials() {
104
+ if (this.localConfig) return localCredentials(this.localConfig, this.url);
105
+ const environmentKey = this.env.MACHINAL_API_KEY || this.env.DIRECTION_API_KEY;
106
+ if (environmentKey) {
107
+ try { return validateAPIKey(environmentKey); } catch { throw Object.assign(new Error('Invalid credential'), { invalidKey: true }); }
108
+ }
109
+ const saved = await this.credentialStore?.read();
110
+ try { return saved ? validateAPIKey(saved) : null; } catch { throw Object.assign(new Error('Invalid credential'), { invalidKey: true }); }
111
+ }
112
+
113
+ async rpc(method, params, { timeout = 150_000, signal, notification = false } = {}) {
114
+ const id = notification ? undefined : ++this.nextID;
115
+ const signals = [AbortSignal.timeout(timeout), this.signal, signal].filter(Boolean);
116
+ const response = await this.fetch(this.url, {
117
+ method: 'POST', redirect: 'error', signal: AbortSignal.any(signals),
118
+ headers: { Authorization: `Bearer ${this.key}`, Accept: 'application/json, text/event-stream',
119
+ 'Content-Type': 'application/json', 'MCP-Protocol-Version': this.protocol ?? PROTOCOL },
120
+ body: JSON.stringify({ jsonrpc: '2.0', ...(id !== undefined ? { id } : {}), method, ...(params ? { params } : {}) }),
121
+ });
122
+ if (!response.ok) {
123
+ await response.body?.cancel();
124
+ throw Object.assign(new Error('Service unavailable'), { status: response.status });
125
+ }
126
+ if (notification) { await response.body?.cancel(); return; }
127
+ const reply = await jsonResponse(response);
128
+ if (reply.jsonrpc !== '2.0' || reply.id !== id || reply.error || !reply.result) throw Object.assign(new Error('Invalid MCP service response'), { protocolError: true });
129
+ return reply.result;
130
+ }
131
+
132
+ failure(error) {
133
+ const status = error.status === 401 ? 'login_required'
134
+ : [402, 403].includes(error.status) ? 'account_access_required'
135
+ : error.status === 429 ? 'rate_limited' : error.protocolError ? 'service_error' : 'connection_unavailable';
136
+ const messages = {
137
+ login_required: 'Login required: the Machinal API key is missing, invalid or rejected. The MCP adapter is running.',
138
+ account_access_required: 'Account access is unavailable. Check membership/permissions; do not create another key.',
139
+ rate_limited: 'The service is rate limited. Wait before reconnecting.',
140
+ service_error: 'The endpoint did not provide a compatible Machinal MCP service. Check its URL/version.',
141
+ connection_unavailable: 'Connection unavailable: check the API/container, URL, TLS and network. The MCP adapter is still running.',
142
+ };
143
+ this.state = { status, message: messages[status], ...(error.status ? { httpStatus: error.status } : {}) };
144
+ if (this.localConfig && error.status === 401) this.state = { status: 'local_configuration_required', message: 'The local device token was rejected. Rerun independent local setup; do not create a Machinal account key.' };
145
+ }
146
+
147
+ async connect() {
148
+ if (this.connecting) return this.connecting;
149
+ this.connecting = this.discover().finally(() => { this.connecting = null; });
150
+ return this.connecting;
151
+ }
152
+
153
+ async discover() {
154
+ try {
155
+ try { this.key = await this.credentials(); } catch (error) {
156
+ if (error.invalidKey) this.failure({ status: 401 });
157
+ else this.state = { status: 'credential_unavailable', message: 'Credential source could not be read. Check secure storage/environment; no credential was deleted.' };
158
+ return this.status();
159
+ }
160
+ if (!this.key) { this.failure({ status: 401 }); return this.status(); }
161
+ const initialized = await this.rpc('initialize', { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'machinal-mcp-adapter', version: VERSION } }, { timeout: 3000 });
162
+ if (initialized.serverInfo?.name?.toLowerCase() !== 'machinal' || !VERSIONS.includes(initialized.protocolVersion)) throw { protocolError: true };
163
+ this.protocol = initialized.protocolVersion;
164
+ await this.rpc('notifications/initialized', {}, { notification: true, timeout: 3000 });
165
+ const tools = [];
166
+ let cursor;
167
+ for (let page = 0; page < 10; page++) {
168
+ const catalog = await this.rpc('tools/list', cursor ? { cursor } : {}, { timeout: 3000 });
169
+ tools.push(...validTools(catalog.tools));
170
+ cursor = catalog.nextCursor;
171
+ if (!cursor) break;
172
+ }
173
+ if (cursor || !tools.some((tool) => tool.name === 'list_projects') || !tools.some((tool) => tool.name === 'get_recipe_schema')) throw { protocolError: true };
174
+ const changed = JSON.stringify(this.tools) !== JSON.stringify(tools);
175
+ this.tools = tools;
176
+ this.instructions = initialized.instructions;
177
+ this.state = { status: 'connected', message: 'Connected to the configured service.' };
178
+ if (this.catalogFile) {
179
+ try {
180
+ await cacheCatalog(this.catalogFile, { url: this.url, tools, instructions: this.instructions });
181
+ } catch { /* Losing the non-secret catalog cache must not break a live connection. */ }
182
+ }
183
+ if (changed) this.notify({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' });
184
+ } catch (error) { this.failure(error); }
185
+ return this.status();
186
+ }
187
+
188
+ async handle(method, params = {}, signal) {
189
+ if (method === 'initialize') return {
190
+ protocolVersion: CLIENT_VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : PROTOCOL,
191
+ serverInfo: { name: 'machinal', version: VERSION }, capabilities: { tools: { listChanged: true }, resources: {} },
192
+ instructions: ['Machinal MCP adapter. Call connection_status to distinguish login required, account restrictions or network problems. Never request keys in chat. Reconnect only retries free discovery, never jobs. Recover existing job IDs before retrying any ambiguous submission. User approval is still required for media access, generation, rendering and downloads.',
193
+ this.localConfig ? 'Independent local profile: no Machinal account, subscription or credits. AI usage is billed directly to the owner\'s provider key; local rendering uses their hardware. Use storage=volume for local media; there is no configured S3 bucket. Never fabricate a hosted credit balance.' : '', this.instructions].filter(Boolean).join('\n\n'),
194
+ };
195
+ if (method === 'ping') return {};
196
+ if (method === 'tools/list') {
197
+ if (this.state.status === 'unchecked') await this.connect();
198
+ return { tools: [STATUS_TOOL, ...this.tools] };
199
+ }
200
+ if (method === 'tools/call' && params.name === STATUS_TOOL.name) {
201
+ if (params.arguments?.action === 'reconnect' || this.state.status === 'unchecked') await this.connect();
202
+ return toolResult(this.status());
203
+ }
204
+ if (method === 'tools/call') {
205
+ if (this.state.status !== 'connected') await this.connect();
206
+ if (this.state.status !== 'connected') return toolResult(this.status(), true);
207
+ if (!this.tools.some((tool) => tool.name === params.name)) return toolResult({ message: 'Unknown tool. Refresh the Machinal catalog.' }, true);
208
+ try {
209
+ const result = await this.rpc(method, params, { signal });
210
+ if ([401, 402, 403, 429].includes(result.structuredContent?.statusCode)) this.failure({ status: result.structuredContent.statusCode });
211
+ return result;
212
+ } catch (error) {
213
+ this.failure(error);
214
+ return toolResult({ ...this.status(), submissionState: 'unknown',
215
+ warning: 'No automatic retry was made. The service may have accepted the operation before the connection was lost. Recover its existing job/idempotency key before resubmitting.' }, true);
216
+ }
217
+ }
218
+ if (method === 'prompts/list') return { prompts: [] };
219
+ if (['resources/list', 'resources/templates/list', 'resources/read'].includes(method)) {
220
+ if (this.state.status !== 'connected') await this.connect();
221
+ if (this.state.status === 'connected') return this.rpc(method, params, { signal });
222
+ if (method === 'resources/list') return { resources: [] };
223
+ if (method === 'resources/templates/list') return { resourceTemplates: [] };
224
+ throw Object.assign(new Error('Connection unavailable'), { rpcCode: -32000 });
225
+ }
226
+ throw Object.assign(new Error('Method not found'), { rpcCode: -32601 });
227
+ }
228
+ }
229
+
230
+ function validTools(tools) {
231
+ if (!Array.isArray(tools)) throw new Error('Invalid catalog');
232
+ return tools.filter((tool) => tool && typeof tool.name === 'string' && /^[\w-]{1,64}$/.test(tool.name) && tool.name !== STATUS_TOOL.name)
233
+ .map((tool) => ({ ...tool, inputSchema: tool.inputSchema ?? { type: 'object' } }));
234
+ }
235
+
236
+ function toolResult(value, isError = false) {
237
+ return { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value, ...(isError ? { isError: true } : {}) };
238
+ }
239
+
240
+ export async function serveBridge(options, { input = process.stdin, output = process.stdout, refreshMs = 15_000, ...runtime } = {}) {
241
+ const lifetime = new AbortController();
242
+ const send = (message) => { if (!lifetime.signal.aborted) output.write(`${JSON.stringify(message)}\n`); };
243
+ const bridge = new MCPBridge({ ...options, ...runtime, signal: lifetime.signal, notify: send });
244
+ await bridge.loadCatalog();
245
+ const calls = new Map();
246
+ let buffer = Buffer.alloc(0);
247
+ const refresh = setInterval(() => {
248
+ void (async () => {
249
+ if (bridge.state.status !== 'connected' || await bridge.credentials() !== bridge.key) await bridge.connect();
250
+ })().catch(() => {});
251
+ }, refreshMs);
252
+ const receive = async (message) => {
253
+ if (message?.method === 'notifications/cancelled') { calls.get(message.params?.requestId)?.abort(); return; }
254
+ if (message?.id === undefined) return;
255
+ const id = message.id;
256
+ if (message.jsonrpc !== '2.0' || typeof message.method !== 'string' || !['string', 'number'].includes(typeof id)) {
257
+ send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } }); return;
258
+ }
259
+ if (calls.size >= 8 || calls.has(id)) { send({ jsonrpc: '2.0', id, error: { code: -32000, message: 'Too many concurrent requests' } }); return; }
260
+ const controller = new AbortController();
261
+ calls.set(id, controller);
262
+ try { send({ jsonrpc: '2.0', id, result: await bridge.handle(message.method, message.params, controller.signal) }); } catch (error) {
263
+ send({ jsonrpc: '2.0', id, error: { code: error.rpcCode ?? -32603, message: error.rpcCode === -32601 ? 'Method not found' : 'Could not process the request. Use connection_status.' } });
264
+ } finally { calls.delete(id); }
265
+ };
266
+ try {
267
+ for await (const chunk of input) {
268
+ buffer = Buffer.concat([buffer, Buffer.from(chunk)]);
269
+ let end;
270
+ while ((end = buffer.indexOf(10)) >= 0) {
271
+ const line = buffer.subarray(0, end);
272
+ buffer = buffer.subarray(end + 1);
273
+ if (line.length > MAX_REQUEST) throw new Error('Request too large');
274
+ if (!line.toString('utf8').trim()) continue;
275
+ try { void receive(JSON.parse(line.toString('utf8'))); } catch {
276
+ send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
277
+ }
278
+ }
279
+ if (buffer.length > MAX_REQUEST) throw new Error('Request too large');
280
+ }
281
+ } finally {
282
+ clearInterval(refresh);
283
+ lifetime.abort();
284
+ for (const controller of calls.values()) controller.abort();
285
+ }
286
+ return 0;
287
+ }