@machinal/mcp 0.0.0-stage → 0.4.0

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 (173) hide show
  1. package/README.md +361 -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 +285 -0
  140. package/src/cli.mjs +155 -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/errors.mjs +9 -0
  148. package/src/formats.mjs +140 -0
  149. package/src/keys.mjs +127 -0
  150. package/src/launch.mjs +29 -0
  151. package/src/local-setup.mjs +109 -0
  152. package/src/opencode-auth.mjs +246 -0
  153. package/src/opencode-checkpoints.mjs +90 -0
  154. package/src/opencode-configuration.mjs +53 -0
  155. package/src/opencode-media.mjs +139 -0
  156. package/src/opencode-plugin/index.mjs +7 -0
  157. package/src/opencode-plugin/package.json +5 -0
  158. package/src/opencode-recipes.mjs +130 -0
  159. package/src/opencode-routing.mjs +154 -0
  160. package/src/opencode-tools.mjs +30 -0
  161. package/src/opencode-workflow.mjs +32 -0
  162. package/src/presentation.mjs +30 -0
  163. package/src/prompts.mjs +32 -0
  164. package/src/reference-files.json +127 -0
  165. package/src/runtime.mjs +51 -0
  166. package/src/setup-options.mjs +64 -0
  167. package/src/setup-stdio.mjs +114 -0
  168. package/src/setup.mjs +173 -0
  169. package/src/skills.mjs +68 -0
  170. package/src/transfer-http.mjs +109 -0
  171. package/src/version.mjs +3 -0
  172. package/src/windows-key-prompt.mjs +37 -0
  173. package/src/windows-key-prompt.ps1 +77 -0
@@ -0,0 +1,130 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { lstat, open, realpath, unlink } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, basename } from 'node:path';
4
+
5
+ const maxRecipeBytes = 2 * 1024 * 1024;
6
+ const recipeTools = ['validate_recipe', 'compile_recipe', 'generate_assets', 'render_video'];
7
+
8
+ function recipePath(path) {
9
+ if (typeof path !== 'string' || !isAbsolute(path) || !/\.edit\.ya?ml$/i.test(path)) {
10
+ throw new Error('Use an absolute client-local .edit.yaml path. This transfers recipe text only, not local media.');
11
+ }
12
+ return path;
13
+ }
14
+
15
+ export async function filePermission(ctx, context, action, path) {
16
+ await ctx.permission.assert({
17
+ sessionID: context.sessionID, agent: context.agent,
18
+ source: { type: 'tool', messageID: context.messageID, id: context.id },
19
+ action, resources: [path], save: [path],
20
+ });
21
+ }
22
+
23
+ export async function readBoundedUTF8(path, signal) {
24
+ const info = await lstat(path);
25
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error('Recipe must be a regular file, not a symbolic link.');
26
+ const file = await open(path, 'r');
27
+ try {
28
+ const actual = await file.stat();
29
+ if (!actual.isFile() || actual.size > maxRecipeBytes || actual.ino !== info.ino || actual.dev !== info.dev) throw new Error('Recipe changed or exceeds the 2 MiB limit.');
30
+ // Bound the read even if another process grows the file after stat.
31
+ const buffer = Buffer.alloc(maxRecipeBytes + 1);
32
+ let length = 0;
33
+ while (length < buffer.length) {
34
+ signal?.throwIfAborted();
35
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length);
36
+ if (!bytesRead) break;
37
+ length += bytesRead;
38
+ }
39
+ if (length > maxRecipeBytes) throw new Error('Recipe exceeds the 2 MiB limit.');
40
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, length));
41
+ } finally { await file.close(); }
42
+ }
43
+
44
+ export function resultJSON(result) {
45
+ if (result.output && typeof result.output === 'object') return result.output;
46
+ const content = typeof result.content === 'string' ? result.content
47
+ : result.content?.filter(part => part.type === 'text').map(part => part.text).join('\n');
48
+ try { return JSON.parse(content); } catch { return undefined; }
49
+ }
50
+
51
+ export async function saveUTF8(path, recipe, signal) {
52
+ const bytes = Buffer.from(recipe, 'utf8');
53
+ if (bytes.length > maxRecipeBytes) throw new Error('Resolved recipe exceeds the 2 MiB limit.');
54
+ const file = await open(path, 'wx', 0o600);
55
+ try { await file.writeFile(bytes, { signal }); }
56
+ catch (error) { await file.close(); await unlink(path); throw error; }
57
+ await file.close();
58
+ return { path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
59
+ }
60
+
61
+ export async function installRecipeFiles(ctx, servers) {
62
+ const names = [...servers];
63
+ await ctx.tool.transform(editor => {
64
+ for (const server of names) {
65
+ for (const name of recipeTools) {
66
+ editor.update(`${server}_${name}`.replace(/[^a-z\d_-]/gi, '_'), tool => {
67
+ const original = tool.execute;
68
+ tool.input = { ...tool.input,
69
+ required: (tool.input.required ?? []).filter(key => key !== 'composition'),
70
+ properties: { ...tool.input.properties,
71
+ compositionFile: { type: 'string', description: 'Absolute client-local .edit.yaml to send verbatim as UTF-8 instead of composition or sourceJobId. Uses host file permission and the original MCP executor; no local media upload.' },
72
+ ...(['validate_recipe', 'compile_recipe'].includes(name) ? {
73
+ captionBaselineRecipeFile: { type: 'string', description: 'Intact resolved baseline .edit.yaml for complete caption comparison. With authorized captionTextEdits, verifies only those exact text replacements and preserves every timing, ID, cue and style.' },
74
+ } : {}),
75
+ },
76
+ };
77
+ tool.description += ' OpenCode: use compositionFile to submit a local recipe without copying/retyping it into tool arguments. Existing consent, validation, idempotency and spending rules still apply.';
78
+ tool.execute = async (input, context) => {
79
+ const { compositionFile, captionBaselineRecipeFile, ...args } = input;
80
+ if (captionBaselineRecipeFile !== undefined) {
81
+ if (!['validate_recipe', 'compile_recipe'].includes(name) || args.captionBaseline !== undefined) throw new Error('Use one caption baseline source on free recipe preflight only.');
82
+ args.captionBaseline = await readRecipe(ctx, context, captionBaselineRecipeFile);
83
+ }
84
+ if (compositionFile !== undefined) {
85
+ if (args.composition !== undefined || args.sourceJobId !== undefined) throw new Error('Choose compositionFile, composition or sourceJobId, not multiple recipe sources.');
86
+ args.composition = await readRecipe(ctx, context, compositionFile);
87
+ }
88
+ return original(args, context);
89
+ };
90
+ });
91
+ }
92
+ editor.update(`${server}_get_job_result`.replace(/[^a-z\d_-]/gi, '_'), tool => {
93
+ const original = tool.execute;
94
+ tool.input = { ...tool.input, properties: { ...tool.input.properties,
95
+ recipeFile: { type: 'string', description: 'Optional absolute new .edit.yaml path. Save returned resolved recipe verbatim in UTF-8, without overwriting, and return a compact receipt. No media download.' },
96
+ } };
97
+ tool.description += ' OpenCode: recipeFile saves resolved YAML directly to a new local file; patch it and submit with compositionFile. No manual JSON/YAML conversion, compression or repeated result retrieval is needed.';
98
+ tool.execute = async (input, context) => {
99
+ const { recipeFile, ...args } = input;
100
+ if (recipeFile === undefined) return original(args, context);
101
+ const path = recipePath(recipeFile);
102
+ await filePermission(ctx, context, 'edit', path);
103
+ const canonical = join(await realpath(dirname(path)), basename(path));
104
+ if (canonical !== path) await filePermission(ctx, context, 'edit', canonical);
105
+ const result = await original(args, context);
106
+ const output = resultJSON(result);
107
+ const data = output?.data;
108
+ if (typeof data?.recipeYaml !== 'string') return result;
109
+ let receipt;
110
+ try { receipt = await saveUTF8(canonical, data.recipeYaml, context.signal); }
111
+ catch (error) {
112
+ // Keep the intact result available if local saving fails; never rerun generation to recover text.
113
+ return { ...result, metadata: { ...result.metadata, recipeFileError: error.code === 'EEXIST' ? 'Destination exists; no overwrite. Use the returned YAML or a new filename.' : 'Could not save the recipe. Use the intact returned YAML; no generation was repeated.' } };
114
+ }
115
+ const { recipeYaml: _recipe, ...summary } = data;
116
+ const saved = { ...output, data: { ...summary, recipeFile: receipt } };
117
+ return { ...result, ...(result.output === undefined ? {} : { output: saved }), content: JSON.stringify(saved) };
118
+ };
119
+ });
120
+ }
121
+ });
122
+ }
123
+
124
+ async function readRecipe(ctx, context, file) {
125
+ const path = recipePath(file);
126
+ await filePermission(ctx, context, 'read', path);
127
+ const canonical = await realpath(path);
128
+ if (canonical !== path) await filePermission(ctx, context, 'read', canonical);
129
+ return readBoundedUTF8(path, context.signal);
130
+ }
@@ -0,0 +1,154 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { projectAPI } from './opencode-media.mjs';
3
+
4
+ const MAX_INTENT_BYTES = 6000;
5
+ const MAX_ENTRIES = 64;
6
+ const CACHE_TTL_MS = 5 * 60_000;
7
+ const REQUEST_TIMEOUT_MS = 3000;
8
+ const MINIMUM_SCORE = 0.8;
9
+
10
+ function remember(entries, key, value) {
11
+ entries.delete(key);
12
+ entries.set(key, value);
13
+ if (entries.size > MAX_ENTRIES) entries.delete(entries.keys().next().value);
14
+ return value;
15
+ }
16
+
17
+ function catalogTools(tools, server) {
18
+ const prefix = `${server}_`.replace(/[^a-z\d_-]/gi, '_');
19
+ return new Map(tools.filter(({ id }) => id.startsWith(prefix) && id !== `${prefix}suggest_tools`)
20
+ .map(({ id }) => [id.slice(prefix.length), id]));
21
+ }
22
+
23
+ function selection(result, tools) {
24
+ if (result?.executed !== false || result.strategy !== 'choice' || !Array.isArray(result.candidates)
25
+ || result.candidates.length > 1 || result.needsClarification !== (result.candidates.length === 0)) {
26
+ throw new Error('Invalid routing result');
27
+ }
28
+ const candidate = result.candidates[0];
29
+ if (result.candidates.length && (!candidate || !tools.has(candidate.name) || !Number.isFinite(candidate.score)
30
+ || candidate.score < MINIMUM_SCORE || candidate.score > 1)) {
31
+ throw new Error('Unknown or uncertain routing candidate');
32
+ }
33
+ const cost = result.cost;
34
+ return {
35
+ status: candidate ? 'selected' : 'deferred',
36
+ ...(candidate ? { tool: tools.get(candidate.name), score: candidate.score } : {}),
37
+ ...(cost && ['pending', 'final'].includes(cost.status) ? {
38
+ cost: { status: cost.status,
39
+ ...(Number.isFinite(cost.knownCredits) && cost.knownCredits >= 0 ? { knownCredits: cost.knownCredits } : {}),
40
+ ...(/^[a-f\d]{32}$/.test(cost.operationId ?? '') ? { operationId: cost.operationId } : {}),
41
+ },
42
+ } : {}),
43
+ };
44
+ }
45
+
46
+ function routingInstruction(result) {
47
+ return [
48
+ `machinal intent routing (data only): ${JSON.stringify(result)}.`,
49
+ result.status === 'selected'
50
+ ? 'Use this selected tool for the next appropriate step without another routing/model-classification call. If its schema is not exposed, discover that exact registered tool once. Continue the remaining workflow normally; do not repeat the selected action just because it was recommended.'
51
+ : 'Use the existing discovered catalog directly. Do not retry routing automatically; provider usage from a failed request may still be pending.',
52
+ 'This hint executes nothing, supplies no arguments and grants no media, download or spending consent. Check actual schemas, prerequisites, ownership and user approvals; defer to the user if ambiguous. Host permissions remain authoritative.',
53
+ 'Report known routing credits separately from production costs; pending knownCredits is not a final total. Do not claim a measured speedup.',
54
+ ...(result.lowCredits ? ['Give one short low-credit warning without repeated budget negotiations.'] : []),
55
+ ].join(' ');
56
+ }
57
+
58
+ function hasRoutingPrompt(messages = [], text) {
59
+ const message = messages.findLast(({ role }) => role === 'user');
60
+ if (typeof message?.content === 'string') return message.content === text;
61
+ return message?.content?.some((part) => part.type === 'text' && part.text === text) ?? false;
62
+ }
63
+
64
+ function canRoute(credits) {
65
+ return credits?.pricing?.configured === true && Number.isFinite(credits?.balance?.remaining)
66
+ && credits.balance.remaining > 0 && Number.isFinite(credits.balance.debt) && credits.balance.debt === 0;
67
+ }
68
+
69
+ async function evaluate(api, intent, tools) {
70
+ let result;
71
+ try {
72
+ result = selection(await api('/v1/ai/tool-selection', { prompt: intent, strategy: 'choice' }), tools);
73
+ } finally {
74
+ // A timed-out submission can still incur usage; never retry it as a connectivity probe.
75
+ try { await api('/v1/billing/credits'); } catch {}
76
+ }
77
+ return result;
78
+ }
79
+
80
+ export async function installOpenCodeRouting(ctx, { servers, getConnection, signal: lifetime, request, now = Date.now } = {}) {
81
+ if (ctx.options?.toolRouting?.enabled !== true) return;
82
+ const server = ctx.options.toolRouting.server ?? (servers.length === 1 ? servers[0] : undefined);
83
+ if (!server || !servers.includes(server)) throw new Error('Select one approved machinal server in toolRouting.server.');
84
+ const cache = new Map();
85
+ const active = new Map();
86
+ const requestSignal = () => AbortSignal.any([lifetime, AbortSignal.timeout(REQUEST_TIMEOUT_MS)].filter(Boolean));
87
+
88
+ async function route(sessionID, intent) {
89
+ let connection;
90
+ let tools;
91
+ try {
92
+ tools = catalogTools(await ctx.tool.list(), server);
93
+ for (const [name, id] of tools) {
94
+ if (intent === name || intent === id) return { status: 'selected', tool: id, routing: 'explicit-tool', cost: { status: 'final', knownCredits: 0 } };
95
+ }
96
+ connection = await getConnection(server);
97
+ } catch {
98
+ return { status: 'unavailable' };
99
+ }
100
+ if (!tools.size) return { status: 'unavailable' };
101
+ const key = createHash('sha256').update(JSON.stringify([sessionID, connection.endpoint, connection.key,
102
+ intent, [...tools].sort()])).digest('hex');
103
+ const cached = cache.get(key);
104
+ if (cached && now() - cached.created < CACHE_TTL_MS) return { ...await cached.result, cached: true };
105
+
106
+ let credits;
107
+ try { credits = await projectAPI(connection, requestSignal(), request)('/v1/billing/credits'); } catch {
108
+ return { status: 'unavailable' };
109
+ }
110
+ if (!canRoute(credits)) return { status: 'unavailable' };
111
+
112
+ // Rejections propagate before a provider submission instead of becoming a successful fallback.
113
+ await ctx.permission.assert({ sessionID, action: 'machinal_route', resources: [server], save: [server],
114
+ metadata: { availableCredits: credits.balance.remaining,
115
+ description: 'Send this command’s text to the configured intent router. Routing consumes API credits; no media is accessed and no suggested tool is executed.' },
116
+ });
117
+ // A concurrent command may have completed its permission prompt while this one was waiting.
118
+ const pending = cache.get(key);
119
+ if (pending && now() - pending.created < CACHE_TTL_MS) return { ...await pending.result, cached: true };
120
+ const started = now();
121
+ const result = evaluate(projectAPI(connection, requestSignal(), request), intent, tools)
122
+ .catch(() => ({ status: 'unavailable' }))
123
+ .then((value) => ({ ...value, elapsedMs: Math.max(0, now() - started),
124
+ ...(credits.balance.remaining < 30 ? { lowCredits: true } : {}),
125
+ }));
126
+ remember(cache, key, { created: started, result });
127
+ return result;
128
+ }
129
+
130
+ await ctx.command.transform((editor) => {
131
+ editor.add({ name: 'machinal-route',
132
+ description: 'Route one concise machinal intent before the main model runs. Optional paid routing, native approval, no media access or action execution. Do not include secrets or file contents.',
133
+ async execute({ sessionID, prompt, delivery }) {
134
+ const intent = prompt.text?.trim();
135
+ if (!intent || Buffer.byteLength(intent, 'utf8') > MAX_INTENT_BYTES) {
136
+ throw new Error(`Provide a concise routing intent of 1-${MAX_INTENT_BYTES} UTF-8 bytes.`);
137
+ }
138
+ const result = await route(sessionID, intent);
139
+ remember(active, sessionID, { text: prompt.text, result });
140
+ await ctx.session.prompt({ ...prompt, sessionID, delivery });
141
+ },
142
+ });
143
+ });
144
+
145
+ await ctx.session.hook('prompt', (event) => {
146
+ if (active.get(event.sessionID)?.text !== event.prompt.text) active.delete(event.sessionID);
147
+ });
148
+ await ctx.session.hook('context', (event) => {
149
+ const entry = active.get(event.sessionID);
150
+ if (!entry || !hasRoutingPrompt(event.messages, entry.text)) return;
151
+ active.delete(event.sessionID);
152
+ event.system.push({ type: 'text', text: routingInstruction(entry.result) });
153
+ });
154
+ }
@@ -0,0 +1,30 @@
1
+ export const DIRECT_TOOLS = [
2
+ 'list_projects', 'get_workflow_preferences', 'get_credits', 'get_capabilities',
3
+ 'get_recipe_schema', 'get_editing_reference', 'wait_for_job', 'get_job_result',
4
+ ];
5
+
6
+ export async function installDirectTools(ctx, servers) {
7
+ const names = [...servers];
8
+ await ctx.tool.transform((editor) => {
9
+ for (const server of names) {
10
+ for (const name of DIRECT_TOOLS) {
11
+ const id = `${server}_${name}`.replace(/[^a-z\d_-]/gi, '_');
12
+ editor.update(id, (tool) => {
13
+ const { pinned: _pinned, ...options } = tool.options ?? {};
14
+ tool.options = { ...options, codemode: false };
15
+ tool.description = `${tool.description ?? ''} OpenCode routing: this is the direct native tool ${id}; it is not callable through tools.${server}.${name} inside execute. Call the exposed native tool instead.`;
16
+ });
17
+ }
18
+ }
19
+ });
20
+ await ctx.session.hook('context', (event) => {
21
+ event.system.push({ type: 'text', text: 'machinal quick path: common project/preferences/credits/schema/reference/job-wait/result tools are exposed directly, so call their registered native tools without a Code Mode search. Discover only unknown tools and reuse their exact paths/signatures for this session; do not rediscover per step or use web search for MCP tool names. Read independent guides concurrently, and reuse unchanged schema/reference knowledge until schemaHash changes. For explicitly approved client-local downloads prefer machinal_download with projectId + jobId/file, or a public HTTPS url + directory + filename. It streams natively, with no PowerShell/curl/shell scripts, no key in arguments and no overwrite. A requested link stays a link; do not download unasked. Public internet downloads authorize neither project import nor media use/spending. Web search latency itself is controlled by the host search provider, not machinal.' });
22
+ });
23
+ await ctx.session.hook('context', (event) => {
24
+ event.system.push({ type: 'text', text: `machinal direct/native tool IDs (NOT Code Mode paths): ${names.flatMap(server => DIRECT_TOOLS.map(name => `${server}_${name}`.replace(/[^a-z\d_-]/gi, '_'))).join(', ')}. Use the native tool names actually exposed by the host; never call these through tools.* in execute. All other tools require one catalog discovery. A missing Code Mode path is a routing issue, not evidence of lost authentication.` });
25
+ event.system.push({ type: 'text', text: 'machinal recipe transfer in OpenCode: get_job_result accepts optional recipeFile (absolute new .edit.yaml path) to save resolved YAML verbatim as UTF-8 without overwriting. validate_recipe, compile_recipe, generate_assets and render_video accept compositionFile (absolute existing .edit.yaml) instead of composition/sourceJobId. These local integration fields use normal host file permissions and the original MCP execution/approval path; they transfer recipe text, not local media. Prefer this path for large recipes: patch the saved file, then send compositionFile. Never invent compression/base64/LZW transfer workarounds, reconstruct captions, switch to a guessed old namespace or stop merely because Code Mode lacks filesystem access. Direct tools are called directly; discover only the other required signatures once.' });
26
+ event.system.push({ type: 'text', text: 'machinal continuity: carry actual source/generation/rendering approval through every covered stage to terminal completion and the requested delivery. userApproved asserts existing permission; do not ask again or stop for a continue message after timing/images/scenes. Ask only for missing permission, genuinely changed scope, exceeded hard budget or a precise persistent blocker. Host permission controls remain enabled and separate; never auto-approve them. Repair actual 422 source diagnostics within scope, but scene-render EACCES is infrastructure, not a reason to rewrite Svelte or regenerate successful assets.' });
27
+ event.system.push({ type: 'text', text: 'machinal deterministic checkpoints: get_job_result and free validate_recipe/compile_recipe accept checkpointFile to save compact project/job IDs, exact compositionVersion and captionVersion. Save the timing baseline alongside recipeFile. When adding only visuals, use captionBaselineFile for deterministic comparison of every text entry and caption resultTextIds. Save a new preflight checkpoint after each recipe edit; paid calls can read checkpointFile to apply the reviewed hash automatically, without manual copying. These are tool inputs, not YAML fields; host file permissions and spending approval remain required. Summary preflight is the default; use fullResult=true only when the normalized document/plan is needed.' });
28
+ event.system.push({ type: 'text', text: 'For authorized caption name/spelling corrections, preflight with the intact captionBaselineRecipeFile, exact captionTextEdits and captionEditsApproved=true; require captionReview.status=preserved before establishing a new baseline. Never drop the original comparison merely because a text edit was authorized. Preflight checkpoints explicitly record visualInspection=false: compilation is not pixel/video/audio inspection. Loopback delivery reachability=same-machine must be disclosed; cross-device links require configured HTTPS PUBLIC_API_URL, not a rewritten URL or another render.' });
29
+ });
30
+ }
@@ -0,0 +1,32 @@
1
+ const productionSkills = ['machinal-editing', 'machinal-recipes', 'machinal-scenes', 'machinal-cinema', 'machinal-review', 'machinal-credits'];
2
+ const videoIntent = /\b(video|film|documentar\w*|cinematic\w*|montaj|reel|tiktok|animation|animație|animatie)\b/iu;
3
+ const implementationIntent = /\b(renderer|plugin|bug|codul|code|test\w*|repar\w*|debug\w*|fix|refactor\w*)\b/iu;
4
+ const productionIntent = /\b(creează|creeaza|realizează|realizeaza|generează|genereaza|create|make|produce|render|randează|randeaza|editează|editeaza|edit)\b/iu;
5
+
6
+ export async function installWorkflowStartup(ctx) {
7
+ if (ctx.skill?.transform) {
8
+ await ctx.skill.transform(editor => {
9
+ for (const id of [...productionSkills, 'machinal-media', 'machinal-support']) {
10
+ const legacy = id.replace('machinal-', 'directional-');
11
+ if (editor.get(id) && editor.get(legacy)) editor.remove(legacy);
12
+ }
13
+ });
14
+ }
15
+ await ctx.session.hook('prompt', async event => {
16
+ const prompt = event.prompt;
17
+ if (!prompt) return;
18
+ const selected = new Set((prompt.skills ?? []).map(skill => skill.id));
19
+ const explicit = productionSkills.some(id => selected.has(id));
20
+ const text = (prompt.text ?? '').normalize('NFD').replace(/\p{M}/gu, '');
21
+ if (!explicit && !(videoIntent.test(text) && productionIntent.test(text) && !implementationIntent.test(text))) return;
22
+ const available = new Set((await ctx.skill.list()).map(skill => skill.id));
23
+ for (const id of productionSkills) {
24
+ if (available.has(id) && !selected.has(id)) {
25
+ (prompt.skills ??= []).push({ id });
26
+ }
27
+ }
28
+ });
29
+ await ctx.session.hook('context', event => {
30
+ event.system.push({ type: 'text', text: 'machinal production startup: relevant installed production skills, including machinal-cinema, are attached through the native prompt skill resolver for explicit video creation/edit requests or selected machinal production skills. For ambiguous requests, load them before planning. Read the exact chosen film-style source with get_editing_reference(topic=film-styles,id=...) before the production contract; a style name alone is not direction. Skill loading grants no source-use or spending permission. Save production state, sources, resolved recipeFile and job IDs as checkpoints; resume the existing jobs/assets after interruption, not new paid submissions.' });
31
+ });
32
+ }
@@ -0,0 +1,30 @@
1
+ import { styleText } from 'node:util';
2
+
3
+ export const API_KEYS_URL = 'https://direction.al/api-keys';
4
+ export const MEMBERSHIP_URL = 'https://direction.al/membership';
5
+ export const DOCKER_URL = 'https://docs.docker.com/get-started/get-docker/';
6
+
7
+ export function terminalStyle({ stream = process.stdout, env = process.env } = {}) {
8
+ const color = Boolean(stream.isTTY && !Object.hasOwn(env, 'NO_COLOR') && env.TERM !== 'dumb');
9
+ return (role, text) => color ? styleText(role, text, { validateStream: false }) : text;
10
+ }
11
+
12
+ export function createLogger({ write = console.log, stream = process.stdout, env = process.env } = {}) {
13
+ const style = terminalStyle({ stream, env });
14
+ return (message, kind) => {
15
+ if (!message) return;
16
+ if (kind === 'heading') return write(`\n${style('bold', message)}`);
17
+ if (kind === 'error') return write(`${style('red', 'Error:')} ${message}`);
18
+ const label = message.match(/^(Warning:|Low balance:|Usage awaiting payment:|[^:]*unavailable:)/)?.[0];
19
+ if (label) return write(style('yellow', label) + message.slice(label.length));
20
+ write(message);
21
+ };
22
+ }
23
+
24
+ export function backupSummary(configuration, skills, root) {
25
+ const count = (configuration.backup ? 1 : 0) + (skills?.backups.length ?? 0);
26
+ if (!count) return null;
27
+ const details = [configuration.backup ? `Configuration: ${configuration.backup}` : null,
28
+ skills?.backups.length ? `Skills: ${skills.backups.length} files under ${root}` : null].filter(Boolean);
29
+ return `Backups: ${count} original files preserved. ${details.join('; ')}. Skill backups are beside each original, named <filename>.machinal-backup-<timestamp>-<id>; restore by copying the backup over its original. Backups may contain existing secrets; keep them private.`;
30
+ }
@@ -0,0 +1,32 @@
1
+ import { terminalStyle } from './presentation.mjs';
2
+
3
+ export function createPromptUI(prompts, options = {}) {
4
+ const style = terminalStyle(options);
5
+ const stream = options.stream ?? process.stdout;
6
+ const theme = {
7
+ prefix: { idle: '?', done: '-' },
8
+ spinner: { interval: 120, frames: ['-', '\\', '|', '/'] },
9
+ icon: { cursor: '>' },
10
+ style: {
11
+ message: (text, status) => status === 'done' ? text : style('bold', text),
12
+ answer: (text) => text,
13
+ highlight: (text) => style('cyan', text),
14
+ description: (text) => text,
15
+ help: (text) => text,
16
+ disabled: (text) => text,
17
+ defaultAnswer: (text) => `(${text})`,
18
+ confirmDefault: (text) => text.toUpperCase(),
19
+ key: (text) => `<${text}>`,
20
+ error: (text) => `${style('red', 'Error:')} ${text}`,
21
+ keysHelpTip: () => stream.columns < 60
22
+ ? ' Up/down · Enter · Ctrl+C cancels'
23
+ : ' Up/down to move · Enter to select · Ctrl+C to cancel',
24
+ },
25
+ };
26
+ return Object.fromEntries(Object.entries(prompts).map(([name, prompt]) => [name, (config, context) => prompt({
27
+ ...config,
28
+ ...(name === 'select' ? { pageSize: 5, loop: false } : {}),
29
+ ...(name === 'password' ? { toggleMask: false } : {}),
30
+ theme: name === 'password' ? { ...theme, style: { ...theme.style, answer: () => '[hidden]' } } : theme,
31
+ }, context)]));
32
+ }
@@ -0,0 +1,127 @@
1
+ [
2
+ "machinal-cinema/references/film-library/DIRECTOR.md",
3
+ "machinal-cinema/references/film-library/LICENSE",
4
+ "machinal-cinema/references/film-library/MY-STYLES.md",
5
+ "machinal-cinema/references/film-library/README.md",
6
+ "machinal-cinema/references/film-library/TECHNIQUE.md",
7
+ "machinal-cinema/references/film-library/core/lib.js",
8
+ "machinal-cinema/references/film-library/core/post/crt.js",
9
+ "machinal-cinema/references/film-library/core/three/post.js",
10
+ "machinal-cinema/references/film-library/manifest.json",
11
+ "machinal-cinema/references/film-library/styleboard/catalog.json",
12
+ "machinal-cinema/references/film-library/styles/README.md",
13
+ "machinal-cinema/references/film-library/styles/archive-lighttable/STYLE.md",
14
+ "machinal-cinema/references/film-library/styles/art-deco/STYLE.md",
15
+ "machinal-cinema/references/film-library/styles/ascii-crt/STYLE.md",
16
+ "machinal-cinema/references/film-library/styles/backrooms/STYLE.md",
17
+ "machinal-cinema/references/film-library/styles/blueprint/STYLE.md",
18
+ "machinal-cinema/references/film-library/styles/brick-toy/STYLE.md",
19
+ "machinal-cinema/references/film-library/styles/briefing-board/STYLE.md",
20
+ "machinal-cinema/references/film-library/styles/caption-news/STYLE.md",
21
+ "machinal-cinema/references/film-library/styles/cel-anime-80s/STYLE.md",
22
+ "machinal-cinema/references/film-library/styles/chalkboard/STYLE.md",
23
+ "machinal-cinema/references/film-library/styles/circuit-board/STYLE.md",
24
+ "machinal-cinema/references/film-library/styles/city-symphony/STYLE.md",
25
+ "machinal-cinema/references/film-library/styles/countdown/STYLE.md",
26
+ "machinal-cinema/references/film-library/styles/crayon-book/STYLE.md",
27
+ "machinal-cinema/references/film-library/styles/dark-keynote/STYLE.md",
28
+ "machinal-cinema/references/film-library/styles/data-physical/STYLE.md",
29
+ "machinal-cinema/references/film-library/styles/dataviz/STYLE.md",
30
+ "machinal-cinema/references/film-library/styles/desktop-flythrough/STYLE.md",
31
+ "machinal-cinema/references/film-library/styles/engraving/STYLE.md",
32
+ "machinal-cinema/references/film-library/styles/game-show/STYLE.md",
33
+ "machinal-cinema/references/film-library/styles/glass-product/STYLE.md",
34
+ "machinal-cinema/references/film-library/styles/halftone-dossier/STYLE.md",
35
+ "machinal-cinema/references/film-library/styles/hd-2d/STYLE.md",
36
+ "machinal-cinema/references/film-library/styles/hologram-hud/STYLE.md",
37
+ "machinal-cinema/references/film-library/styles/impasto/STYLE.md",
38
+ "machinal-cinema/references/film-library/styles/ink-wash/STYLE.md",
39
+ "machinal-cinema/references/film-library/styles/iso-infographic/STYLE.md",
40
+ "machinal-cinema/references/film-library/styles/isometric-picture-book/STYLE.md",
41
+ "machinal-cinema/references/film-library/styles/kino-montage/STYLE.md",
42
+ "machinal-cinema/references/film-library/styles/lidar-survey/STYLE.md",
43
+ "machinal-cinema/references/film-library/styles/living-screencast/STYLE.md",
44
+ "machinal-cinema/references/film-library/styles/lowpoly-island/STYLE.md",
45
+ "machinal-cinema/references/film-library/styles/memphis-diorama/STYLE.md",
46
+ "machinal-cinema/references/film-library/styles/microgame/STYLE.md",
47
+ "machinal-cinema/references/film-library/styles/microscope/STYLE.md",
48
+ "machinal-cinema/references/film-library/styles/midcentury-toon/STYLE.md",
49
+ "machinal-cinema/references/film-library/styles/news-package/STYLE.md",
50
+ "machinal-cinema/references/film-library/styles/newsreel/STYLE.md",
51
+ "machinal-cinema/references/film-library/styles/one-line/STYLE.md",
52
+ "machinal-cinema/references/film-library/styles/paper-lantern/STYLE.md",
53
+ "machinal-cinema/references/film-library/styles/paper-popup/STYLE.md",
54
+ "machinal-cinema/references/film-library/styles/papercut-red/STYLE.md",
55
+ "machinal-cinema/references/film-library/styles/pictogram-motion/STYLE.md",
56
+ "machinal-cinema/references/film-library/styles/pixel-rpg/STYLE.md",
57
+ "machinal-cinema/references/film-library/styles/printed-long-take/STYLE.md",
58
+ "machinal-cinema/references/film-library/styles/risograph/STYLE.md",
59
+ "machinal-cinema/references/film-library/styles/rubber-hose/STYLE.md",
60
+ "machinal-cinema/references/film-library/styles/satellite-briefing/STYLE.md",
61
+ "machinal-cinema/references/film-library/styles/scifi-toon/STYLE.md",
62
+ "machinal-cinema/references/film-library/styles/shadow-puppet/STYLE.md",
63
+ "machinal-cinema/references/film-library/styles/silent-film/STYLE.md",
64
+ "machinal-cinema/references/film-library/styles/silkscreen-poster/STYLE.md",
65
+ "machinal-cinema/references/film-library/styles/spy-titles/STYLE.md",
66
+ "machinal-cinema/references/film-library/styles/stained-glass/STYLE.md",
67
+ "machinal-cinema/references/film-library/styles/swiss-motion/STYLE.md",
68
+ "machinal-cinema/references/film-library/styles/teardown/STYLE.md",
69
+ "machinal-cinema/references/film-library/styles/telestrator/STYLE.md",
70
+ "machinal-cinema/references/film-library/styles/tilt-shift/STYLE.md",
71
+ "machinal-cinema/references/film-library/styles/transit-map/STYLE.md",
72
+ "machinal-cinema/references/film-library/styles/ukiyoe/STYLE.md",
73
+ "machinal-cinema/references/film-library/styles/urban-sketch/STYLE.md",
74
+ "machinal-cinema/references/film-library/styles/visual-investigation/STYLE.md",
75
+ "machinal-cinema/references/film-library/styles/watercolor/STYLE.md",
76
+ "machinal-cinema/references/film-library/styles/white-model/STYLE.md",
77
+ "machinal-cinema/references/film-library/styles/whiteboard/STYLE.md",
78
+ "machinal-cinema/references/film-library/styles/woodcut/STYLE.md",
79
+ "machinal-cinema/references/film-library/upstream-skill.md",
80
+ "machinal-cinema/references/film-styles.json",
81
+ "machinal-cinema/references/film-techniques.json",
82
+ "machinal-cinema/references/workflow.md",
83
+ "machinal-editing/references/brief.md",
84
+ "machinal-editing/references/effects.md",
85
+ "machinal-editing/references/looks-motion.md",
86
+ "machinal-editing/references/styles.json",
87
+ "machinal-editing/references/styles.md",
88
+ "machinal-editing/references/transitions.md",
89
+ "machinal-editing/references/workflow.md",
90
+ "machinal-media/references/workflow.md",
91
+ "machinal-recipes/references/catalog.v1.json",
92
+ "machinal-recipes/references/commands.md",
93
+ "machinal-recipes/references/examples.md",
94
+ "machinal-recipes/references/examples/caption-audio.yaml",
95
+ "machinal-recipes/references/examples/cinematic-sequence.yaml",
96
+ "machinal-recipes/references/examples/client-scene.yaml",
97
+ "machinal-recipes/references/examples/generated-media.yaml",
98
+ "machinal-recipes/references/examples/modify-snapshot.yaml",
99
+ "machinal-recipes/references/examples/montage-v3.yaml",
100
+ "machinal-recipes/references/examples/narrated-documentary.yaml",
101
+ "machinal-recipes/references/examples/narration-timing.yaml",
102
+ "machinal-recipes/references/examples/scene-edit.yaml",
103
+ "machinal-recipes/references/examples/scene-generated-image.yaml",
104
+ "machinal-recipes/references/examples/scene-generation.yaml",
105
+ "machinal-recipes/references/examples/scene-image-insert.yaml",
106
+ "machinal-recipes/references/examples/scene-three-explainer.yaml",
107
+ "machinal-recipes/references/examples/social-hook.yaml",
108
+ "machinal-recipes/references/examples/tutorial-clean.yaml",
109
+ "machinal-recipes/references/jobs-scenes.md",
110
+ "machinal-recipes/references/text-audio.md",
111
+ "machinal-recipes/references/yaml.md",
112
+ "machinal-review/references/production.md",
113
+ "machinal-scenes/references/authoring.md",
114
+ "machinal-scenes/references/runtime.md",
115
+ "machinal-scenes/references/scene-templates.json",
116
+ "machinal-scenes/references/scene-templates.md",
117
+ "machinal-scenes/references/scene-templates/blueprint-mechanism.svelte",
118
+ "machinal-scenes/references/scene-templates/glitch-handoff.svelte",
119
+ "machinal-scenes/references/scene-templates/image-reveal.svelte",
120
+ "machinal-scenes/references/scene-templates/kinetic-type.svelte",
121
+ "machinal-scenes/references/scene-templates/layered-parallax.svelte",
122
+ "machinal-scenes/references/scene-templates/lens-assembly-3d.svelte",
123
+ "machinal-scenes/references/scene-templates/paper-stage-3d.svelte",
124
+ "machinal-scenes/references/scene-templates/signal-diagram.svelte",
125
+ "machinal-scenes/references/scene-templates/swiss-grid-motion.svelte",
126
+ "machinal-scenes/references/workflow.md"
127
+ ]
@@ -0,0 +1,51 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { VERSION } from './version.mjs';
7
+
8
+ const ROOT = fileURLToPath(new URL('../', import.meta.url));
9
+ const FILES = ['bin/machinal-stdio.mjs', 'src/bridge.mjs', 'src/connection.mjs', 'src/credential-store.mjs',
10
+ 'src/credits.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/version.mjs', 'package.json'];
11
+
12
+ export function stateDirectory({ home = homedir(), env = process.env } = {}) {
13
+ return join(env.XDG_CONFIG_HOME || join(home, '.config'), 'machinal');
14
+ }
15
+
16
+ export function endpointFiles(url, context) {
17
+ const id = createHash('sha256').update(url).digest('hex').slice(0, 24);
18
+ const root = stateDirectory(context);
19
+ return { catalogFile: join(root, 'catalogs', `${id}.json`), localConfig: join(root, 'local', id, 'providers.env') };
20
+ }
21
+
22
+ // A stable, private runtime avoids npm-cache eviction and Windows .cmd spawning bugs.
23
+ export async function installRuntime(context) {
24
+ const content = await Promise.all(FILES.map((file) => readFile(join(ROOT, file))));
25
+ const hash = createHash('sha256');
26
+ for (const data of content) hash.update(data);
27
+ const root = join(stateDirectory(context), 'runtime');
28
+ const destination = join(root, `${VERSION}-${process.platform}-${process.arch}-${hash.digest('hex').slice(0, 16)}`);
29
+ const script = join(destination, 'bin', 'machinal-stdio.mjs');
30
+ try { if ((await lstat(script)).isFile()) return script; } catch (error) { if (error.code !== 'ENOENT') throw error; }
31
+ await mkdir(root, { recursive: true, mode: 0o700 });
32
+ const staging = join(root, `.install-${randomUUID()}`);
33
+ await mkdir(staging, { mode: 0o700 });
34
+ try {
35
+ for (let index = 0; index < FILES.length; index++) {
36
+ const file = join(staging, FILES[index]);
37
+ await mkdir(join(file, '..'), { recursive: true, mode: 0o700 });
38
+ await writeFile(file, content[index], { mode: 0o600, flag: 'wx' });
39
+ }
40
+ try {
41
+ const scope = join(ROOT, 'node_modules', '@napi-rs');
42
+ for (const name of await readdir(scope)) {
43
+ if (/^keyring(?:-|$)/.test(name)) await cp(join(scope, name), join(staging, 'node_modules', '@napi-rs', name), { recursive: true, errorOnExist: true });
44
+ }
45
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
46
+ try { await rename(staging, destination); } catch (error) {
47
+ if (!['EEXIST', 'ENOTEMPTY', 'EPERM'].includes(error.code) || !(await lstat(script)).isFile()) throw error;
48
+ }
49
+ return script;
50
+ } finally { await rm(staging, { recursive: true, force: true }); }
51
+ }