@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.
- package/README.md +361 -2
- package/bin/machinal-mcp.mjs +19 -0
- package/bin/machinal-stdio.mjs +14 -0
- package/package.json +47 -4
- package/skills/machinal-cinema/SKILL.md +18 -0
- package/skills/machinal-cinema/references/film-library/DIRECTOR.md +149 -0
- package/skills/machinal-cinema/references/film-library/LICENSE +21 -0
- package/skills/machinal-cinema/references/film-library/MY-STYLES.md +139 -0
- package/skills/machinal-cinema/references/film-library/README.md +13 -0
- package/skills/machinal-cinema/references/film-library/TECHNIQUE.md +162 -0
- package/skills/machinal-cinema/references/film-library/core/lib.js +44 -0
- package/skills/machinal-cinema/references/film-library/core/post/crt.js +144 -0
- package/skills/machinal-cinema/references/film-library/core/three/post.js +102 -0
- package/skills/machinal-cinema/references/film-library/manifest.json +394 -0
- package/skills/machinal-cinema/references/film-library/styleboard/catalog.json +1128 -0
- package/skills/machinal-cinema/references/film-library/styles/README.md +126 -0
- package/skills/machinal-cinema/references/film-library/styles/archive-lighttable/STYLE.md +107 -0
- package/skills/machinal-cinema/references/film-library/styles/art-deco/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/ascii-crt/STYLE.md +113 -0
- package/skills/machinal-cinema/references/film-library/styles/backrooms/STYLE.md +123 -0
- package/skills/machinal-cinema/references/film-library/styles/blueprint/STYLE.md +118 -0
- package/skills/machinal-cinema/references/film-library/styles/brick-toy/STYLE.md +112 -0
- package/skills/machinal-cinema/references/film-library/styles/briefing-board/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/caption-news/STYLE.md +135 -0
- package/skills/machinal-cinema/references/film-library/styles/cel-anime-80s/STYLE.md +117 -0
- package/skills/machinal-cinema/references/film-library/styles/chalkboard/STYLE.md +153 -0
- package/skills/machinal-cinema/references/film-library/styles/circuit-board/STYLE.md +149 -0
- package/skills/machinal-cinema/references/film-library/styles/city-symphony/STYLE.md +140 -0
- package/skills/machinal-cinema/references/film-library/styles/countdown/STYLE.md +130 -0
- package/skills/machinal-cinema/references/film-library/styles/crayon-book/STYLE.md +107 -0
- package/skills/machinal-cinema/references/film-library/styles/dark-keynote/STYLE.md +115 -0
- package/skills/machinal-cinema/references/film-library/styles/data-physical/STYLE.md +117 -0
- package/skills/machinal-cinema/references/film-library/styles/dataviz/STYLE.md +121 -0
- package/skills/machinal-cinema/references/film-library/styles/desktop-flythrough/STYLE.md +145 -0
- package/skills/machinal-cinema/references/film-library/styles/engraving/STYLE.md +121 -0
- package/skills/machinal-cinema/references/film-library/styles/game-show/STYLE.md +116 -0
- package/skills/machinal-cinema/references/film-library/styles/glass-product/STYLE.md +108 -0
- package/skills/machinal-cinema/references/film-library/styles/halftone-dossier/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/hd-2d/STYLE.md +109 -0
- package/skills/machinal-cinema/references/film-library/styles/hologram-hud/STYLE.md +127 -0
- package/skills/machinal-cinema/references/film-library/styles/impasto/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/ink-wash/STYLE.md +118 -0
- package/skills/machinal-cinema/references/film-library/styles/iso-infographic/STYLE.md +115 -0
- package/skills/machinal-cinema/references/film-library/styles/isometric-picture-book/STYLE.md +130 -0
- package/skills/machinal-cinema/references/film-library/styles/kino-montage/STYLE.md +149 -0
- package/skills/machinal-cinema/references/film-library/styles/lidar-survey/STYLE.md +116 -0
- package/skills/machinal-cinema/references/film-library/styles/living-screencast/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/lowpoly-island/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/memphis-diorama/STYLE.md +142 -0
- package/skills/machinal-cinema/references/film-library/styles/microgame/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/microscope/STYLE.md +106 -0
- package/skills/machinal-cinema/references/film-library/styles/midcentury-toon/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/news-package/STYLE.md +156 -0
- package/skills/machinal-cinema/references/film-library/styles/newsreel/STYLE.md +134 -0
- package/skills/machinal-cinema/references/film-library/styles/one-line/STYLE.md +112 -0
- package/skills/machinal-cinema/references/film-library/styles/paper-lantern/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/styles/paper-popup/STYLE.md +117 -0
- package/skills/machinal-cinema/references/film-library/styles/papercut-red/STYLE.md +108 -0
- package/skills/machinal-cinema/references/film-library/styles/pictogram-motion/STYLE.md +119 -0
- package/skills/machinal-cinema/references/film-library/styles/pixel-rpg/STYLE.md +115 -0
- package/skills/machinal-cinema/references/film-library/styles/printed-long-take/STYLE.md +141 -0
- package/skills/machinal-cinema/references/film-library/styles/risograph/STYLE.md +123 -0
- package/skills/machinal-cinema/references/film-library/styles/rubber-hose/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/satellite-briefing/STYLE.md +114 -0
- package/skills/machinal-cinema/references/film-library/styles/scifi-toon/STYLE.md +119 -0
- package/skills/machinal-cinema/references/film-library/styles/shadow-puppet/STYLE.md +122 -0
- package/skills/machinal-cinema/references/film-library/styles/silent-film/STYLE.md +107 -0
- package/skills/machinal-cinema/references/film-library/styles/silkscreen-poster/STYLE.md +138 -0
- package/skills/machinal-cinema/references/film-library/styles/spy-titles/STYLE.md +114 -0
- package/skills/machinal-cinema/references/film-library/styles/stained-glass/STYLE.md +121 -0
- package/skills/machinal-cinema/references/film-library/styles/swiss-motion/STYLE.md +113 -0
- package/skills/machinal-cinema/references/film-library/styles/teardown/STYLE.md +125 -0
- package/skills/machinal-cinema/references/film-library/styles/telestrator/STYLE.md +135 -0
- package/skills/machinal-cinema/references/film-library/styles/tilt-shift/STYLE.md +105 -0
- package/skills/machinal-cinema/references/film-library/styles/transit-map/STYLE.md +194 -0
- package/skills/machinal-cinema/references/film-library/styles/ukiyoe/STYLE.md +110 -0
- package/skills/machinal-cinema/references/film-library/styles/urban-sketch/STYLE.md +124 -0
- package/skills/machinal-cinema/references/film-library/styles/visual-investigation/STYLE.md +138 -0
- package/skills/machinal-cinema/references/film-library/styles/watercolor/STYLE.md +111 -0
- package/skills/machinal-cinema/references/film-library/styles/white-model/STYLE.md +113 -0
- package/skills/machinal-cinema/references/film-library/styles/whiteboard/STYLE.md +116 -0
- package/skills/machinal-cinema/references/film-library/styles/woodcut/STYLE.md +120 -0
- package/skills/machinal-cinema/references/film-library/upstream-skill.md +13 -0
- package/skills/machinal-cinema/references/film-styles.json +1322 -0
- package/skills/machinal-cinema/references/film-techniques.json +107 -0
- package/skills/machinal-cinema/references/workflow.md +58 -0
- package/skills/machinal-credits/SKILL.md +24 -0
- package/skills/machinal-editing/SKILL.md +43 -0
- package/skills/machinal-editing/references/brief.md +98 -0
- package/skills/machinal-editing/references/effects.md +58 -0
- package/skills/machinal-editing/references/looks-motion.md +37 -0
- package/skills/machinal-editing/references/styles.json +15 -0
- package/skills/machinal-editing/references/styles.md +16 -0
- package/skills/machinal-editing/references/transitions.md +46 -0
- package/skills/machinal-editing/references/workflow.md +43 -0
- package/skills/machinal-media/SKILL.md +23 -0
- package/skills/machinal-media/references/workflow.md +160 -0
- package/skills/machinal-recipes/SKILL.md +32 -0
- package/skills/machinal-recipes/references/catalog.v1.json +10445 -0
- package/skills/machinal-recipes/references/commands.md +45 -0
- package/skills/machinal-recipes/references/example.edit.yaml +26 -0
- package/skills/machinal-recipes/references/examples/caption-audio.yaml +28 -0
- package/skills/machinal-recipes/references/examples/cinematic-sequence.yaml +21 -0
- package/skills/machinal-recipes/references/examples/client-scene.yaml +26 -0
- package/skills/machinal-recipes/references/examples/generated-media.yaml +25 -0
- package/skills/machinal-recipes/references/examples/modify-snapshot.yaml +22 -0
- package/skills/machinal-recipes/references/examples/montage-v3.yaml +28 -0
- package/skills/machinal-recipes/references/examples/narrated-documentary.yaml +112 -0
- package/skills/machinal-recipes/references/examples/narration-timing.yaml +43 -0
- package/skills/machinal-recipes/references/examples/scene-edit.yaml +19 -0
- package/skills/machinal-recipes/references/examples/scene-generated-image.yaml +36 -0
- package/skills/machinal-recipes/references/examples/scene-generation.yaml +35 -0
- package/skills/machinal-recipes/references/examples/scene-image-insert.yaml +41 -0
- package/skills/machinal-recipes/references/examples/scene-three-explainer.yaml +38 -0
- package/skills/machinal-recipes/references/examples/social-hook.yaml +26 -0
- package/skills/machinal-recipes/references/examples/tutorial-clean.yaml +19 -0
- package/skills/machinal-recipes/references/examples.md +28 -0
- package/skills/machinal-recipes/references/jobs-scenes.md +206 -0
- package/skills/machinal-recipes/references/text-audio.md +118 -0
- package/skills/machinal-recipes/references/yaml.md +72 -0
- package/skills/machinal-review/SKILL.md +18 -0
- package/skills/machinal-review/references/production.md +146 -0
- package/skills/machinal-scenes/SKILL.md +44 -0
- package/skills/machinal-scenes/references/authoring.md +97 -0
- package/skills/machinal-scenes/references/runtime.md +136 -0
- package/skills/machinal-scenes/references/scene-templates/blueprint-mechanism.svelte +62 -0
- package/skills/machinal-scenes/references/scene-templates/glitch-handoff.svelte +30 -0
- package/skills/machinal-scenes/references/scene-templates/image-reveal.svelte +33 -0
- package/skills/machinal-scenes/references/scene-templates/kinetic-type.svelte +38 -0
- package/skills/machinal-scenes/references/scene-templates/layered-parallax.svelte +31 -0
- package/skills/machinal-scenes/references/scene-templates/lens-assembly-3d.svelte +57 -0
- package/skills/machinal-scenes/references/scene-templates/paper-stage-3d.svelte +83 -0
- package/skills/machinal-scenes/references/scene-templates/signal-diagram.svelte +43 -0
- package/skills/machinal-scenes/references/scene-templates/swiss-grid-motion.svelte +54 -0
- package/skills/machinal-scenes/references/scene-templates.json +178 -0
- package/skills/machinal-scenes/references/scene-templates.md +50 -0
- package/skills/machinal-scenes/references/workflow.md +206 -0
- package/skills/machinal-support/SKILL.md +42 -0
- package/src/bridge.mjs +285 -0
- package/src/cli.mjs +155 -0
- package/src/configuration.mjs +148 -0
- package/src/connection.mjs +187 -0
- package/src/credential-store.mjs +61 -0
- package/src/credits.mjs +86 -0
- package/src/docker.mjs +93 -0
- package/src/download.mjs +90 -0
- package/src/errors.mjs +9 -0
- package/src/formats.mjs +140 -0
- package/src/keys.mjs +127 -0
- package/src/launch.mjs +29 -0
- package/src/local-setup.mjs +109 -0
- package/src/opencode-auth.mjs +246 -0
- package/src/opencode-checkpoints.mjs +90 -0
- package/src/opencode-configuration.mjs +53 -0
- package/src/opencode-media.mjs +139 -0
- package/src/opencode-plugin/index.mjs +7 -0
- package/src/opencode-plugin/package.json +5 -0
- package/src/opencode-recipes.mjs +130 -0
- package/src/opencode-routing.mjs +154 -0
- package/src/opencode-tools.mjs +30 -0
- package/src/opencode-workflow.mjs +32 -0
- package/src/presentation.mjs +30 -0
- package/src/prompts.mjs +32 -0
- package/src/reference-files.json +127 -0
- package/src/runtime.mjs +51 -0
- package/src/setup-options.mjs +64 -0
- package/src/setup-stdio.mjs +114 -0
- package/src/setup.mjs +173 -0
- package/src/skills.mjs +68 -0
- package/src/transfer-http.mjs +109 -0
- package/src/version.mjs +3 -0
- package/src/windows-key-prompt.mjs +37 -0
- package/src/windows-key-prompt.ps1 +77 -0
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { createCredentialStore, WINDOWS_CREDENTIAL } from './credential-store.mjs';
|
|
2
|
+
import { checkConnection, normalizeEndpoint, validateAPIKey } from './connection.mjs';
|
|
3
|
+
import { API_KEYS_URL, MEMBERSHIP_URL } from './presentation.mjs';
|
|
4
|
+
import { promptWindowsKey } from './windows-key-prompt.mjs';
|
|
5
|
+
import { installOpenCodeMedia } from './opencode-media.mjs';
|
|
6
|
+
import { installDirectTools } from './opencode-tools.mjs';
|
|
7
|
+
import { installRecipeFiles } from './opencode-recipes.mjs';
|
|
8
|
+
import { installOpenCodeRouting } from './opencode-routing.mjs';
|
|
9
|
+
import { installWorkflowStartup } from './opencode-workflow.mjs';
|
|
10
|
+
import { installCheckpoints } from './opencode-checkpoints.mjs';
|
|
11
|
+
import { TransferError } from './transfer-http.mjs';
|
|
12
|
+
|
|
13
|
+
function trustedServers(options) {
|
|
14
|
+
const servers = new Map();
|
|
15
|
+
for (const [name, url] of Object.entries(options.servers ?? {})) {
|
|
16
|
+
if (!/^[a-z\d][a-z\d_-]{0,63}$/i.test(name)) continue;
|
|
17
|
+
try { servers.set(name, normalizeEndpoint(url)); } catch {}
|
|
18
|
+
}
|
|
19
|
+
return servers;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function matches(server, endpoint, approvedCommand) {
|
|
23
|
+
if (server?.type === 'local') {
|
|
24
|
+
const args = server.command ?? [];
|
|
25
|
+
const index = args.indexOf('--url');
|
|
26
|
+
return Array.isArray(approvedCommand) && JSON.stringify(args) === JSON.stringify(approvedCommand)
|
|
27
|
+
&& Object.keys(server.environment ?? {}).every((name) => ['MACHINAL_API_KEY', 'DIRECTION_API_KEY'].includes(name))
|
|
28
|
+
&& args.includes('serve') && args.some((arg) => /(?:^|[/\\])machinal-(?:mcp|stdio)\.mjs$/.test(arg))
|
|
29
|
+
&& index >= 0 && args[index + 1] === endpoint && !args.includes('--local-config');
|
|
30
|
+
}
|
|
31
|
+
if (server?.type !== 'remote' || server.oauth !== false) return false;
|
|
32
|
+
try { return normalizeEndpoint(server.url) === endpoint; } catch { return false; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function connectionFailure(error) {
|
|
36
|
+
if (error.status === 401) return {
|
|
37
|
+
code: 'key-rejected', nextAction: 'replace',
|
|
38
|
+
error: 'The machinal key was rejected. Offer replace for secure entry; do not repeatedly reconnect with the same rejected key. The previous saved key was not deleted.',
|
|
39
|
+
};
|
|
40
|
+
if ([402, 403].includes(error.status)) return {
|
|
41
|
+
code: 'account-access', nextAction: 'check-account',
|
|
42
|
+
error: `Account access is unavailable. Check ${MEMBERSHIP_URL}; do not generate more API keys to fix subscription or access restrictions.`,
|
|
43
|
+
};
|
|
44
|
+
if (error.status === 429) return {
|
|
45
|
+
code: 'rate-limited', nextAction: 'retry-later',
|
|
46
|
+
error: 'The MCP endpoint is rate limited. Wait before reconnecting; the saved key was not changed.',
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
code: 'connection-failed', nextAction: 'check-endpoint',
|
|
50
|
+
error: 'Could not complete the machinal connection. The current saved key was not deleted. Check the configured API/container, URL and network; retry for network failures, not by creating another key.',
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function installOpenCodeAuth(ctx, {
|
|
55
|
+
credentialStore = createCredentialStore(), env = process.env,
|
|
56
|
+
verify = checkConnection, prompt = promptWindowsKey, intervalMs = 2000,
|
|
57
|
+
} = {}) {
|
|
58
|
+
const servers = trustedServers(ctx.options ?? {});
|
|
59
|
+
const registrations = new Map();
|
|
60
|
+
const credential = {
|
|
61
|
+
name: 'Windows Credential Manager', ...WINDOWS_CREDENTIAL,
|
|
62
|
+
supported: Boolean(credentialStore), status: credentialStore ? 'unchecked' : 'unsupported',
|
|
63
|
+
};
|
|
64
|
+
const state = { key: null, source: 'none', warning: null, paused: null, sessionOnly: false };
|
|
65
|
+
const lifetime = new AbortController();
|
|
66
|
+
let queue = Promise.resolve();
|
|
67
|
+
const serial = (operation) => {
|
|
68
|
+
const result = queue.then(operation);
|
|
69
|
+
queue = result.catch(() => {});
|
|
70
|
+
return result;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
async function loadKey() {
|
|
74
|
+
if (state.sessionOnly) return;
|
|
75
|
+
let candidate;
|
|
76
|
+
let source = 'none';
|
|
77
|
+
state.warning = null;
|
|
78
|
+
if (credentialStore && env.MACHINAL_MCP_USE_ENV_KEY !== '1' && env.DIRECTION_MCP_USE_ENV_KEY !== '1') {
|
|
79
|
+
try {
|
|
80
|
+
candidate = await credentialStore.read();
|
|
81
|
+
credential.status = candidate == null ? 'missing' : 'found';
|
|
82
|
+
} catch {
|
|
83
|
+
credential.status = 'unavailable';
|
|
84
|
+
state.warning = 'Windows Credential Manager is unavailable. The current in-memory key was not removed.';
|
|
85
|
+
if (state.key) return;
|
|
86
|
+
}
|
|
87
|
+
if (candidate !== null && candidate !== undefined) source = 'saved';
|
|
88
|
+
} else if (credentialStore) credential.status = 'bypassed';
|
|
89
|
+
const environmentKey = env.MACHINAL_API_KEY || env.DIRECTION_API_KEY;
|
|
90
|
+
if (source === 'none' && environmentKey) { candidate = environmentKey; source = 'environment'; }
|
|
91
|
+
try { state.key = candidate ? validateAPIKey(candidate) : null; state.source = source; } catch {
|
|
92
|
+
state.key = null;
|
|
93
|
+
state.source = source;
|
|
94
|
+
state.warning = 'The saved machinal key has an invalid format. Use replace for secure entry; the saved value has not been deleted.';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
await loadKey();
|
|
99
|
+
await ctx.mcp.transform((editor) => {
|
|
100
|
+
const canonical = servers.get('machinal');
|
|
101
|
+
if (canonical && matches(editor.get('machinal'), canonical, ctx.options?.commands?.machinal) && matches(editor.get('directional'), canonical, ctx.options?.commands?.directional)) {
|
|
102
|
+
editor.remove('directional');
|
|
103
|
+
}
|
|
104
|
+
for (const [name, endpoint] of servers) {
|
|
105
|
+
const config = editor.get(name);
|
|
106
|
+
registrations.set(name, { name, endpoint, configuration: !config ? 'missing' : matches(config, endpoint, ctx.options?.commands?.[name]) ? 'matched' : 'mismatch' });
|
|
107
|
+
if (!matches(config, endpoint, ctx.options?.commands?.[name])) continue;
|
|
108
|
+
editor.update(name, (server) => {
|
|
109
|
+
if (server.type === 'local') {
|
|
110
|
+
server.environment = { ...server.environment, MACHINAL_API_KEY: state.key ?? '' };
|
|
111
|
+
if (state.paused === name) server.disabled = true;
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const headers = Object.fromEntries(Object.entries(server.headers ?? {}).filter(([key]) => key.toLowerCase() !== 'authorization'));
|
|
115
|
+
server.headers = { ...headers, Authorization: state.key ? `Bearer ${state.key}` : 'Bearer ' };
|
|
116
|
+
if (state.paused === name) server.disabled = true;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
async function status() {
|
|
122
|
+
let listed;
|
|
123
|
+
let connectionWarning;
|
|
124
|
+
try { listed = await ctx.mcp.list(); } catch {
|
|
125
|
+
connectionWarning = 'OpenCode could not list current MCP connection states. No connection success was assumed; inspect the MCP panel or run opencode mcp list.';
|
|
126
|
+
}
|
|
127
|
+
return {
|
|
128
|
+
source: state.source, hasKey: Boolean(state.key), warning: state.warning,
|
|
129
|
+
credentialStore: { ...credential }, registrations: [...registrations.values()],
|
|
130
|
+
servers: (listed?.data ?? []).filter((server) => servers.has(server.name)).map((server) => ({ name: server.name, status: server.status.status })),
|
|
131
|
+
...(connectionWarning ? { connectionWarning } : {}),
|
|
132
|
+
apiKeysURL: API_KEYS_URL,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function reconnect(name) {
|
|
137
|
+
state.paused = name;
|
|
138
|
+
try { await ctx.mcp.reload(); } finally { state.paused = null; }
|
|
139
|
+
await ctx.mcp.reload();
|
|
140
|
+
return status();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function connection(input, context) {
|
|
144
|
+
if (input.action === 'status') return status();
|
|
145
|
+
if (!input.server && servers.size > 1) return {
|
|
146
|
+
...await status(), code: 'server-required', nextAction: 'select-server',
|
|
147
|
+
error: 'Multiple machinal MCP servers are registered. Use the intended name from registrations as server; do not guess an endpoint or send the saved key to another server.',
|
|
148
|
+
};
|
|
149
|
+
const name = input.server ?? servers.keys().next().value;
|
|
150
|
+
const endpoint = servers.get(name);
|
|
151
|
+
if (!endpoint) return {
|
|
152
|
+
...await status(), code: 'server-not-registered', nextAction: 'check-setup',
|
|
153
|
+
error: 'This machinal server is not configured for automatic authentication. Inspect the existing MCP configuration and run the machinal setup if needed; never guess a URL or expose the saved key.',
|
|
154
|
+
};
|
|
155
|
+
await ctx.mcp.list();
|
|
156
|
+
if (registrations.get(name)?.configuration !== 'matched') return {
|
|
157
|
+
...await status(), code: 'server-configuration', nextAction: 'check-setup',
|
|
158
|
+
error: 'The registered MCP is missing or its configuration does not match the approved remote endpoint and API-key authentication. No key was sent. Restore the approved setup; never automatically trust a redirected endpoint.',
|
|
159
|
+
};
|
|
160
|
+
if (input.action === 'replace') {
|
|
161
|
+
await context.progress({ status: 'Use the secure machinal key window. The key never enters chat.' });
|
|
162
|
+
const answer = await prompt({ endpoint, apiKeysURL: API_KEYS_URL, signal: AbortSignal.any([lifetime.signal, context.signal]) });
|
|
163
|
+
if (!answer) return { cancelled: true, ...await status() };
|
|
164
|
+
if (answer.action === 'replace') {
|
|
165
|
+
const key = validateAPIKey(answer.key);
|
|
166
|
+
await verify(endpoint, key);
|
|
167
|
+
if (answer.remember) {
|
|
168
|
+
if (!credentialStore) return { error: 'Secure key storage is unavailable. The saved key was not changed.' };
|
|
169
|
+
await credentialStore.write(key);
|
|
170
|
+
credential.status = 'found';
|
|
171
|
+
}
|
|
172
|
+
state.key = key;
|
|
173
|
+
state.source = answer.remember ? 'saved' : 'session';
|
|
174
|
+
state.sessionOnly = !answer.remember;
|
|
175
|
+
state.warning = answer.remember ? null : 'This replacement is connected for the current session only. The saved key was not changed.';
|
|
176
|
+
return reconnect(name);
|
|
177
|
+
}
|
|
178
|
+
if (answer.action !== 'reuse') return { cancelled: true, ...await status() };
|
|
179
|
+
state.sessionOnly = false;
|
|
180
|
+
}
|
|
181
|
+
await loadKey();
|
|
182
|
+
if (!state.key) return {
|
|
183
|
+
...await status(),
|
|
184
|
+
code: credential.status === 'unavailable' ? 'credential-store-unavailable' : 'no-usable-key',
|
|
185
|
+
nextAction: credential.status === 'unavailable' ? 'retry-credential-store' : 'replace',
|
|
186
|
+
error: credential.status === 'unavailable'
|
|
187
|
+
? 'Windows Credential Manager could not be read. Retry under the same Windows user; do not assume the saved key is absent or dump credentials through shell commands.'
|
|
188
|
+
: 'No usable machinal key is available after checking the credential source. Use replace for secure entry. Only one machinal key is needed.',
|
|
189
|
+
};
|
|
190
|
+
await verify(endpoint, state.key);
|
|
191
|
+
return reconnect(name);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
await ctx.tool.transform((editor) => {
|
|
195
|
+
editor.add({
|
|
196
|
+
name: 'machinal_connection',
|
|
197
|
+
description: `Discover and recover machinal MCP even when remote tools are unavailable. status lists registered MCP names, actual connection states and credential diagnostics without secrets. On connection/authentication failure, immediately use reconnect to reread Windows Credential Manager target ${WINDOWS_CREDENTIAL.target}, verify and reconnect without restarting OpenCode. Only offer replace after the saved key is missing/invalid/rejected; it opens secure native entry. Network/account errors do not need new keys. Never put API keys in tool inputs or chat.`,
|
|
198
|
+
input: { type: 'object', properties: { action: { type: 'string', enum: ['status', 'reconnect', 'replace'] }, server: { type: 'string' } }, required: ['action'], additionalProperties: false },
|
|
199
|
+
options: { codemode: false },
|
|
200
|
+
async execute(input, context) {
|
|
201
|
+
const result = await serial(async () => {
|
|
202
|
+
try { return await connection(input, context); } catch (error) {
|
|
203
|
+
return { ...await status(), ...connectionFailure(error) };
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
return { content: JSON.stringify(result) };
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
await ctx.session.hook('context', (event) => {
|
|
212
|
+
event.system.push({ type: 'text', text: [
|
|
213
|
+
'For machinal work, proactively discover the existing MCP before claiming tools or authentication are missing. Use directly exposed tools first; otherwise search the tool catalog in Code Mode once for the missing machinal tool. Tools omitted from the initial list are not proof of disconnection. Reuse actual discovered namespaces/signatures, never invented tool names or repeated discovery per step.',
|
|
214
|
+
`The local machinal_connection tool remains available when the remote MCP is down. Use status to discover approved MCP names, actual connection states and credential diagnostics. Approved registrations: ${JSON.stringify([...servers].map(([name, endpoint]) => ({ name, endpoint })))}. Do not assume a server name or trust other endpoints. If discovery fails or a connection/authentication call fails, immediately call machinal_connection(action:reconnect,server:<registered name>) once, without asking the user to find or paste a key. Reconnect rereads the saved credential and refreshes MCP in the current OpenCode service; then rediscover tools and retry only safe read-only calls. Do not automatically repeat ambiguous paid submissions; recover their jobs/idempotency first.`,
|
|
215
|
+
`machinal uses ONE application API key, automatically loaded into memory from Windows Credential Manager: service ${WINDOWS_CREDENTIAL.service}, account ${WINDOWS_CREDENTIAL.account}, Windows target ${WINDOWS_CREDENTIAL.target}. The local integration, not the model or shell, reads its secret. Do not search credential files, dump the vault, run cmdkey to extract secrets, or print environment values. No separate OpenCode/AI-provider keys or launcher/restart are needed with this integration. Respect an explicitly selected session/environment key.`,
|
|
216
|
+
`After this one recovery attempt, follow the tool's code/nextAction. Only offer replace when the key is missing, invalid or rejected; secure entry links to ${API_KEYS_URL}, verifies before optional saving and reconnects. An unreadable vault is not an absent key. Network, rate-limit or subscription/access errors do not require a new key. Never request a key in chat, disable host approvals, change a trusted endpoint automatically or delete the old key before verification.`,
|
|
217
|
+
].join('\n\n') });
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
const getConnection = async (name) => {
|
|
221
|
+
if (!name && servers.size > 1) throw new TransferError('Multiple machinal servers are registered. Select the intended approved server explicitly.');
|
|
222
|
+
name ??= servers.keys().next().value;
|
|
223
|
+
const endpoint = servers.get(name);
|
|
224
|
+
if (!endpoint) throw new TransferError('Choose a machinal server approved in the integration settings.');
|
|
225
|
+
await ctx.mcp.list();
|
|
226
|
+
if (registrations.get(name)?.configuration !== 'matched') throw new TransferError('The current MCP configuration does not match the approved endpoint. No credentials were sent.');
|
|
227
|
+
if (!state.key) throw new TransferError('No usable machinal key is loaded. Use machinal_connection reconnect; never put a key in download arguments.');
|
|
228
|
+
return { endpoint, key: state.key };
|
|
229
|
+
};
|
|
230
|
+
await installOpenCodeMedia(ctx, { signal: lifetime.signal, getConnection });
|
|
231
|
+
await installDirectTools(ctx, servers.keys());
|
|
232
|
+
await installWorkflowStartup(ctx);
|
|
233
|
+
await installRecipeFiles(ctx, servers.keys());
|
|
234
|
+
await installCheckpoints(ctx, servers.keys());
|
|
235
|
+
await installOpenCodeRouting(ctx, { servers: [...servers.keys()], signal: lifetime.signal, getConnection });
|
|
236
|
+
|
|
237
|
+
const timer = setInterval(() => {
|
|
238
|
+
void serial(async () => {
|
|
239
|
+
const previous = state.key;
|
|
240
|
+
await loadKey();
|
|
241
|
+
if (state.key !== previous) await ctx.mcp.reload();
|
|
242
|
+
}).catch(() => {});
|
|
243
|
+
}, intervalMs);
|
|
244
|
+
timer.unref?.();
|
|
245
|
+
return () => { lifetime.abort(); clearInterval(timer); };
|
|
246
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { lstat, realpath } from 'node:fs/promises';
|
|
2
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
3
|
+
import { filePermission, readBoundedUTF8, resultJSON, saveUTF8 } from './opencode-recipes.mjs';
|
|
4
|
+
|
|
5
|
+
const preflightTools = ['validate_recipe', 'compile_recipe'];
|
|
6
|
+
const freeTools = [...preflightTools, 'get_job_result'];
|
|
7
|
+
const paidTools = ['render_video', 'generate_assets'];
|
|
8
|
+
const versionPattern = /^sha256:[a-f0-9]{64}$/;
|
|
9
|
+
|
|
10
|
+
async function checkpointPath(ctx, context, path, action) {
|
|
11
|
+
if (typeof path !== 'string' || !isAbsolute(path) || !path.endsWith('.checkpoint.json')) throw new Error('Use an absolute client-local .checkpoint.json path.');
|
|
12
|
+
await filePermission(ctx, context, action, path);
|
|
13
|
+
if (action === 'read' && (await lstat(path)).isSymbolicLink()) throw new Error('Checkpoint must be a regular file, not a symbolic link.');
|
|
14
|
+
const canonical = action === 'read' ? await realpath(path) : join(await realpath(dirname(path)), basename(path));
|
|
15
|
+
if (canonical !== path) await filePermission(ctx, context, action, canonical);
|
|
16
|
+
return canonical;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function readCheckpoint(ctx, context, path, projectId) {
|
|
20
|
+
const canonical = await checkpointPath(ctx, context, path, 'read');
|
|
21
|
+
const checkpoint = JSON.parse(await readBoundedUTF8(canonical, context.signal));
|
|
22
|
+
if (checkpoint.version !== 1 || checkpoint.projectId !== projectId || !versionPattern.test(checkpoint.compositionVersion)) throw new Error('Checkpoint is invalid or belongs to another project.');
|
|
23
|
+
return checkpoint;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function checkpointData(output, input, operation) {
|
|
27
|
+
const data = output?.data;
|
|
28
|
+
if (output?.statusCode !== 200 || !versionPattern.test(data?.compositionVersion)) return;
|
|
29
|
+
const { compositionVersion, captionVersion, diagnostics = [], requirements = [], productionReview, editorialReview, captionReview } = data;
|
|
30
|
+
if (!Array.isArray(diagnostics) || !Array.isArray(requirements)) return;
|
|
31
|
+
const valid = diagnostics.every(item => item?.severity !== 'error');
|
|
32
|
+
return { version: 1, operation, projectId: input.projectId, ...(input.jobId ? { jobId: input.jobId } : {}),
|
|
33
|
+
compositionVersion, ...(versionPattern.test(captionVersion) ? { captionVersion } : {}),
|
|
34
|
+
valid, ready: valid && requirements.length === 0,
|
|
35
|
+
diagnostics, requirements, ...(productionReview ? { productionReview } : {}), ...(editorialReview ? { editorialReview } : {}),
|
|
36
|
+
...(captionReview ? { captionReview } : {}),
|
|
37
|
+
visualInspection: false,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function installCheckpoints(ctx, servers) {
|
|
42
|
+
const names = [...servers];
|
|
43
|
+
await ctx.tool.transform(editor => {
|
|
44
|
+
for (const server of names) {
|
|
45
|
+
for (const name of [...freeTools, ...paidTools]) {
|
|
46
|
+
editor.update(`${server}_${name}`.replace(/[^a-z\d_-]/gi, '_'), tool => {
|
|
47
|
+
const original = tool.execute;
|
|
48
|
+
const paid = paidTools.includes(name);
|
|
49
|
+
tool.input = { ...tool.input, properties: { ...tool.input.properties,
|
|
50
|
+
checkpointFile: { type: 'string', description: paid
|
|
51
|
+
? 'Optional saved .checkpoint.json from free preflight. Read with host permission and apply its exact compositionVersion as the server stale-review guard; never creates spending consent.'
|
|
52
|
+
: 'Optional absolute new .checkpoint.json. Save compact versions, project/job IDs and diagnostics for deterministic recovery; never overwrite.' },
|
|
53
|
+
...(name === 'get_job_result' ? {} : { captionBaselineFile: { type: 'string', description: 'Optional .checkpoint.json from the resolved baseline. Apply its captionVersion before submission to detect any changed text entry or caption resultTextIds. Omit only for authorized text edits.' } }),
|
|
54
|
+
} };
|
|
55
|
+
tool.execute = async (input, context) => {
|
|
56
|
+
const { checkpointFile, captionBaselineFile, ...args } = input;
|
|
57
|
+
if (captionBaselineFile !== undefined) {
|
|
58
|
+
const baseline = await readCheckpoint(ctx, context, captionBaselineFile, args.projectId);
|
|
59
|
+
if (!versionPattern.test(baseline.captionVersion)) throw new Error('Baseline has no text/caption fingerprint. Retrieve the existing resolved result; never regenerate it.');
|
|
60
|
+
if (args.expectedCaptionVersion !== undefined && args.expectedCaptionVersion !== baseline.captionVersion) throw new Error('Conflicting caption baseline versions.');
|
|
61
|
+
args.expectedCaptionVersion = baseline.captionVersion;
|
|
62
|
+
}
|
|
63
|
+
let destination;
|
|
64
|
+
if (checkpointFile !== undefined) {
|
|
65
|
+
if (paid) {
|
|
66
|
+
const checkpoint = await readCheckpoint(ctx, context, checkpointFile, args.projectId);
|
|
67
|
+
const render = name === 'render_video';
|
|
68
|
+
if (!(render ? checkpoint.ready : checkpoint.valid) || !preflightTools.includes(checkpoint.operation) || render && ['revision_required', 'not_ready'].includes(checkpoint.productionReview?.status)) throw new Error('Checkpoint has unresolved preflight/review findings. Repair and save a new free preflight; no paid action was submitted.');
|
|
69
|
+
if (args.expectedCompositionVersion !== undefined && args.expectedCompositionVersion !== checkpoint.compositionVersion) throw new Error('Conflicting composition checkpoint versions.');
|
|
70
|
+
args.expectedCompositionVersion = checkpoint.compositionVersion;
|
|
71
|
+
} else destination = await checkpointPath(ctx, context, checkpointFile, 'edit');
|
|
72
|
+
}
|
|
73
|
+
const result = await original(args, context);
|
|
74
|
+
if (!destination) return result;
|
|
75
|
+
const output = resultJSON(result);
|
|
76
|
+
const checkpoint = checkpointData(output, args, name);
|
|
77
|
+
if (!checkpoint) return result;
|
|
78
|
+
try {
|
|
79
|
+
const receipt = await saveUTF8(destination, JSON.stringify(checkpoint, null, 2) + '\n', context.signal);
|
|
80
|
+
const saved = { ...output, data: { ...output.data, checkpointFile: receipt } };
|
|
81
|
+
return { ...result, ...(result.output === undefined ? {} : { output: saved }), content: JSON.stringify(saved) };
|
|
82
|
+
} catch (error) {
|
|
83
|
+
return { ...result, metadata: { ...result.metadata, checkpointFileError: error.code === 'EEXIST' ? 'Checkpoint exists; no overwrite. Keep this result or choose a new checkpoint filename.' : 'Checkpoint saving failed; retain this intact result. No operation was repeated.' } };
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { applyEdits, modify, parse } from 'jsonc-parser';
|
|
2
|
+
import { InstallerError } from './errors.mjs';
|
|
3
|
+
import { VERSION } from './version.mjs';
|
|
4
|
+
|
|
5
|
+
const installedPackage = /\/node_modules\//.test(import.meta.url);
|
|
6
|
+
export const OPENCODE_AUTH_PLUGIN = installedPackage ? `@machinal/mcp@${VERSION}` : new URL('./opencode-plugin', import.meta.url).href;
|
|
7
|
+
|
|
8
|
+
function ownPlugin(entry) {
|
|
9
|
+
const name = typeof entry === 'string' ? entry : entry?.package;
|
|
10
|
+
return name === OPENCODE_AUTH_PLUGIN || /^@machinal\/mcp(?:@[\w.+-]+)?$/.test(name ?? '');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function removeOpenCodeAuthServer(content, name) {
|
|
14
|
+
const config = parse(content);
|
|
15
|
+
if (!Array.isArray(config.plugins)) return content;
|
|
16
|
+
const plugins = config.plugins.flatMap((entry) => {
|
|
17
|
+
if (!ownPlugin(entry) || !entry.options?.servers?.[name]) return [entry];
|
|
18
|
+
const servers = { ...entry.options.servers };
|
|
19
|
+
const commands = { ...entry.options.commands };
|
|
20
|
+
delete servers[name];
|
|
21
|
+
delete commands[name];
|
|
22
|
+
return Object.keys(servers).length ? [{ ...entry, options: { ...entry.options, servers, commands } }] : [];
|
|
23
|
+
});
|
|
24
|
+
if (JSON.stringify(plugins) === JSON.stringify(config.plugins)) return content;
|
|
25
|
+
return applyEdits(content, modify(content, ['plugins'], plugins, { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function configureOpenCodeAuth(content, name, url, command) {
|
|
29
|
+
const config = parse(content);
|
|
30
|
+
const plugins = config.plugins ?? [];
|
|
31
|
+
if (!Array.isArray(plugins)) throw new InstallerError('OpenCode plugins must be an array. No configuration was changed.');
|
|
32
|
+
const indexes = plugins.map((entry, index) => ownPlugin(entry) ? index : -1).filter((index) => index >= 0);
|
|
33
|
+
if (indexes.length > 1) throw new InstallerError('Multiple Machinal companion plugin versions are configured. Consolidate them before setup; no settings were changed.');
|
|
34
|
+
const index = indexes[0] ?? -1;
|
|
35
|
+
const existing = index < 0 || typeof plugins[index] === 'string' ? {} : plugins[index].options ?? {};
|
|
36
|
+
if (!existing || typeof existing !== 'object' || Array.isArray(existing)
|
|
37
|
+
|| (existing.servers !== undefined && (!existing.servers || typeof existing.servers !== 'object' || Array.isArray(existing.servers)))) {
|
|
38
|
+
throw new InstallerError('The machinal authentication plugin options are invalid. No configuration was changed.');
|
|
39
|
+
}
|
|
40
|
+
const servers = { ...existing.servers, [name]: url };
|
|
41
|
+
if (name === 'machinal' && servers.directional === url) delete servers.directional;
|
|
42
|
+
const commands = { ...existing.commands };
|
|
43
|
+
if (command) commands[name] = command;
|
|
44
|
+
else delete commands[name];
|
|
45
|
+
const entry = { package: OPENCODE_AUTH_PLUGIN, options: { ...existing, servers, ...(Object.keys(commands).length ? { commands } : {}) } };
|
|
46
|
+
if (index >= 0 && JSON.stringify(plugins[index]) === JSON.stringify(entry)) return content;
|
|
47
|
+
const indent = content.match(/^[ \t]+(?=")/m)?.[0] ?? ' ';
|
|
48
|
+
const path = config.plugins ? ['plugins', index < 0 ? -1 : index] : ['plugins'];
|
|
49
|
+
const value = config.plugins ? entry : [entry];
|
|
50
|
+
return applyEdits(content, modify(content, path, value, {
|
|
51
|
+
formattingOptions: { insertSpaces: !indent.includes('\t'), tabSize: indent.length, eol: content.includes('\r\n') ? '\r\n' : '\n' },
|
|
52
|
+
}));
|
|
53
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { assertNewDownload, downloadDirectory, downloadFilename, saveDownload } from './download.mjs';
|
|
3
|
+
import { readTransferJSON, requestTransfer, transferURL, TransferError } from './transfer-http.mjs';
|
|
4
|
+
|
|
5
|
+
const projectPattern = /^[a-z\d_-]{1,64}$/i;
|
|
6
|
+
const jobPattern = /^[a-f\d]{32}$/;
|
|
7
|
+
const renderKinds = new Set(['automation-render', 'render', 'editor-render']);
|
|
8
|
+
|
|
9
|
+
function projectPath(input) {
|
|
10
|
+
if (!projectPattern.test(input.projectId ?? '')) throw new TransferError('Use a projectId returned by list_projects or create_project.');
|
|
11
|
+
return `/v1/projects/${input.projectId}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function validateDownload(input) {
|
|
15
|
+
if (input.userApproved !== true) throw new TransferError('Ask for approval to download the named file to the chosen client directory first.');
|
|
16
|
+
if (input.filename !== undefined) downloadFilename(input.filename);
|
|
17
|
+
if (input.url) {
|
|
18
|
+
if (input.projectId || input.jobId || input.file || input.storage || input.server) {
|
|
19
|
+
throw new TransferError('Choose either a public internet URL or an owned project file/job, not both.');
|
|
20
|
+
}
|
|
21
|
+
transferURL(input.url);
|
|
22
|
+
if (!input.directory || !input.filename) throw new TransferError('Internet downloads require an approved directory and filename.');
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
projectPath(input);
|
|
26
|
+
if (Boolean(input.jobId) === Boolean(input.file)) throw new TransferError('Choose one completed jobId or one exact project filename.');
|
|
27
|
+
if (input.jobId && (!jobPattern.test(input.jobId) || input.storage)) throw new TransferError('Use a returned jobId; storage applies only to existing media files.');
|
|
28
|
+
if (input.file) downloadFilename(input.file);
|
|
29
|
+
if (input.storage && !['s3', 'volume'].includes(input.storage)) throw new TransferError('Copy storage=s3 or volume from the approved media listing.');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function projectAPI(connection, signal, request = requestTransfer) {
|
|
33
|
+
const origin = new URL(connection.endpoint).origin;
|
|
34
|
+
return async (path, body) => {
|
|
35
|
+
const response = await request(new URL(path, origin), {
|
|
36
|
+
trustedOrigin: origin, signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)].filter(Boolean)),
|
|
37
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
38
|
+
headers: { Authorization: `Bearer ${connection.key}`, Accept: 'application/json',
|
|
39
|
+
...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
|
40
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
41
|
+
});
|
|
42
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
43
|
+
response.destroy();
|
|
44
|
+
throw new TransferError(`The machinal API request failed (HTTP ${response.statusCode}). Redirects are refused; no credentials were forwarded.`);
|
|
45
|
+
}
|
|
46
|
+
return readTransferJSON(response);
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function projectSource(input, connection, signal, request) {
|
|
51
|
+
const api = projectAPI(connection, signal, request);
|
|
52
|
+
const root = projectPath(input);
|
|
53
|
+
let filename = input.file;
|
|
54
|
+
if (input.jobId) {
|
|
55
|
+
const job = await api(`${root}/jobs/${input.jobId}?view=summary`);
|
|
56
|
+
if (job.status !== 'completed' || !renderKinds.has(job.kind)) {
|
|
57
|
+
throw new TransferError('This job is not a completed video/audio render. Wait for completion of the same job; do not render again.');
|
|
58
|
+
}
|
|
59
|
+
filename = downloadFilename(job.filename);
|
|
60
|
+
}
|
|
61
|
+
let directory = input.directory;
|
|
62
|
+
if (!directory) directory = (await api('/v1/preferences/downloads')).directory;
|
|
63
|
+
if (!directory) throw new TransferError('No client-local download directory is set. Ask the user where to save the file.');
|
|
64
|
+
return {
|
|
65
|
+
directory, filename: input.filename ?? filename,
|
|
66
|
+
async delivery() {
|
|
67
|
+
const descriptor = await api(`${root}/media/delivery-links`, { file: filename, storage: input.storage ?? 's3' });
|
|
68
|
+
const origin = new URL(connection.endpoint).origin;
|
|
69
|
+
const url = transferURL(descriptor.url, origin);
|
|
70
|
+
if (url.origin !== origin || !/^\/deliveries\/[a-z\d_-]{32,}$/i.test(url.pathname) || url.search) {
|
|
71
|
+
throw new TransferError('The API returned an invalid delivery descriptor. No file was downloaded.');
|
|
72
|
+
}
|
|
73
|
+
return { url, trustedOrigin: origin };
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function permission(ctx, context, action, resources) {
|
|
79
|
+
return ctx.permission.assert({
|
|
80
|
+
sessionID: context.sessionID, agent: context.agent,
|
|
81
|
+
source: { type: 'tool', messageID: context.messageID, id: context.id },
|
|
82
|
+
action, resources, save: resources,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function installOpenCodeMedia(ctx, { getConnection, signal: lifetime, request = requestTransfer } = {}) {
|
|
87
|
+
await ctx.tool.transform((editor) => {
|
|
88
|
+
editor.add({
|
|
89
|
+
name: 'machinal_download',
|
|
90
|
+
description: 'Download an approved completed machinal job, named project media, or public HTTPS internet file to the client computer. Native streaming with compact progress, no PowerShell/curl/scripts. Provide projectId + jobId/file, or url + directory + filename. Reuses saved authentication in memory; never pass keys or signed project URLs. Local delivery only when requested. Never overwrites; checks byte count and reports SHA-256. Internet downloads do not upload/import files or execute them.',
|
|
91
|
+
input: { type: 'object', additionalProperties: false, required: ['userApproved'], properties: {
|
|
92
|
+
projectId: { type: 'string' }, jobId: { type: 'string' }, file: { type: 'string' },
|
|
93
|
+
storage: { type: 'string', enum: ['s3', 'volume'], description: 'From the approved media listing; s3 even when cached. Default s3.' },
|
|
94
|
+
server: { type: 'string', description: 'Approved machinal MCP registration; omit for the first configured server.' },
|
|
95
|
+
url: { type: 'string', description: 'Public HTTPS source only; for machinal output use projectId and jobId/file instead.' },
|
|
96
|
+
directory: { type: 'string', description: 'Approved absolute client-local directory; project downloads can reuse the saved preference.' },
|
|
97
|
+
filename: { type: 'string', description: 'Plain new filename, required for internet downloads.' },
|
|
98
|
+
userApproved: { type: 'boolean', description: 'True only after explicit approval for this source and local delivery. Listing consent is insufficient.' },
|
|
99
|
+
} },
|
|
100
|
+
options: { codemode: false },
|
|
101
|
+
async execute(input, context) {
|
|
102
|
+
try { validateDownload(input); } catch (error) { return failure(error); }
|
|
103
|
+
const resource = input.url ? new URL(input.url).origin : `${input.server ?? 'machinal'}/${input.projectId}/${input.jobId ?? input.file}`;
|
|
104
|
+
// Permission rejections must propagate to the host, not become successful tool output.
|
|
105
|
+
await permission(ctx, context, 'machinal_download', [resource]);
|
|
106
|
+
const signal = AbortSignal.any([context.signal, lifetime, AbortSignal.timeout(10 * 60 * 1000)].filter(Boolean));
|
|
107
|
+
let source;
|
|
108
|
+
let directory;
|
|
109
|
+
let path;
|
|
110
|
+
try {
|
|
111
|
+
source = input.url ? { directory: input.directory, filename: input.filename,
|
|
112
|
+
delivery: async () => ({ url: input.url }) }
|
|
113
|
+
: await projectSource(input, await getConnection(input.server), signal, request);
|
|
114
|
+
directory = await downloadDirectory(source.directory);
|
|
115
|
+
path = join(directory, downloadFilename(source.filename));
|
|
116
|
+
await assertNewDownload(path);
|
|
117
|
+
} catch (error) { return failure(error, signal); }
|
|
118
|
+
await permission(ctx, context, 'edit', [path]);
|
|
119
|
+
try {
|
|
120
|
+
await context.progress({ status: 'Downloading', filename: source.filename });
|
|
121
|
+
const delivery = await source.delivery();
|
|
122
|
+
const result = await saveDownload({
|
|
123
|
+
...delivery, directory, filename: source.filename, signal, progress: context.progress,
|
|
124
|
+
request: { trustedOrigin: delivery.trustedOrigin, request },
|
|
125
|
+
});
|
|
126
|
+
return { content: JSON.stringify({ status: 'completed', ...result }) };
|
|
127
|
+
} catch (error) { return failure(error, signal); }
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function failure(error, signal) {
|
|
134
|
+
let message = 'Download failed. Check the network, directory permissions and free disk space. No existing file was overwritten.';
|
|
135
|
+
if (error instanceof TransferError) message = error.message;
|
|
136
|
+
else if (signal?.aborted) message = 'Download cancelled or timed out. Partial files were removed; no final file was published.';
|
|
137
|
+
else if (error.code === 'EEXIST') message = 'The destination already exists. Choose another filename; it was not overwritten.';
|
|
138
|
+
return { content: JSON.stringify({ status: 'failed', error: message }) };
|
|
139
|
+
}
|