@machinal/mcp 0.4.2 → 0.4.4
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 +62 -23
- package/package.json +3 -2
- package/skills/machinal-cinema/SKILL.md +1 -1
- package/skills/machinal-media/SKILL.md +3 -1
- package/skills/machinal-media/references/workflow.md +8 -0
- package/skills/machinal-recipes/SKILL.md +1 -1
- package/skills/machinal-recipes/references/yaml.md +2 -0
- package/skills/machinal-support/SKILL.md +6 -2
- package/src/bridge.mjs +7 -2
- package/src/cli.mjs +49 -18
- package/src/commands.mjs +89 -0
- package/src/configuration.mjs +15 -5
- package/src/credential-store.mjs +22 -0
- package/src/formats.mjs +6 -1
- package/src/keys.mjs +27 -20
- package/src/local-setup.mjs +13 -4
- package/src/opencode-auth.mjs +39 -15
- package/src/opencode-configuration.mjs +83 -20
- package/src/opencode-media.mjs +5 -3
- package/src/opencode-tools.mjs +1 -0
- package/src/opencode-upgrade.mjs +40 -0
- package/src/opencode-uploads.mjs +59 -0
- package/src/opencode-workflow.mjs +54 -13
- package/src/paths.mjs +8 -0
- package/src/presentation.mjs +1 -1
- package/src/private-json.mjs +86 -0
- package/src/prompts.mjs +3 -5
- package/src/runtime.mjs +11 -5
- package/src/settings.mjs +26 -0
- package/src/setup-stdio.mjs +27 -9
- package/src/transfer-http.mjs +20 -4
- package/src/upload.mjs +96 -0
|
@@ -1,13 +1,69 @@
|
|
|
1
1
|
import { applyEdits, modify, parse } from 'jsonc-parser';
|
|
2
2
|
import { InstallerError } from './errors.mjs';
|
|
3
3
|
import { VERSION } from './version.mjs';
|
|
4
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
+
import { isManagedRuntimeCommand } from './runtime.mjs';
|
|
6
|
+
import { parseJSONConfiguration } from './formats.mjs';
|
|
4
7
|
|
|
5
8
|
const installedPackage = /\/node_modules\//.test(import.meta.url);
|
|
6
9
|
export const OPENCODE_AUTH_PLUGIN = installedPackage ? `@machinal/mcp@${VERSION}` : new URL('./opencode-plugin', import.meta.url).href;
|
|
7
10
|
|
|
8
11
|
function ownPlugin(entry) {
|
|
9
12
|
const name = typeof entry === 'string' ? entry : entry?.package;
|
|
10
|
-
return name === OPENCODE_AUTH_PLUGIN || /^@machinal\/mcp(?:@[\w.+-]+)?$/.test(name ?? '')
|
|
13
|
+
return name === OPENCODE_AUTH_PLUGIN || /^@machinal\/mcp(?:@[\w.+-]+)?$/.test(name ?? '')
|
|
14
|
+
|| /^file:\/\/\/.*\/(?:mcp-installer|node_modules\/@machinal\/mcp)\/src\/opencode-plugin\/?$/.test(name ?? '');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function companion(config, context = {}) {
|
|
18
|
+
const plugins = config.plugins ?? [];
|
|
19
|
+
if (!Array.isArray(plugins)) throw new InstallerError('OpenCode plugins must be an array. No configuration was changed.');
|
|
20
|
+
const indexes = plugins.flatMap((entry, index) => ownPlugin(entry) ? [index] : []);
|
|
21
|
+
const options = {};
|
|
22
|
+
for (const index of indexes) {
|
|
23
|
+
const entry = typeof plugins[index] === 'string' ? {} : plugins[index].options ?? {};
|
|
24
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw new InstallerError('The machinal authentication plugin options are invalid. No configuration was changed.');
|
|
25
|
+
for (const [key, value] of Object.entries(entry)) {
|
|
26
|
+
if (['servers', 'commands'].includes(key)) {
|
|
27
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new InstallerError('The machinal authentication plugin options are invalid. No configuration was changed.');
|
|
28
|
+
options[key] ??= {};
|
|
29
|
+
for (const [name, setting] of Object.entries(value)) {
|
|
30
|
+
if (Object.hasOwn(options[key], name) && !isDeepStrictEqual(options[key][name], setting)) {
|
|
31
|
+
const previous = options[key][name];
|
|
32
|
+
if (key === 'commands' && isManagedRuntimeCommand(previous, context) && isManagedRuntimeCommand(setting, context)
|
|
33
|
+
&& isDeepStrictEqual([previous[0], ...previous.slice(2)], [setting[0], ...setting.slice(2)])) {
|
|
34
|
+
const server = config.mcp?.servers?.[name];
|
|
35
|
+
if (server && (server.type !== 'local' || !isManagedRuntimeCommand(server.command, context)
|
|
36
|
+
|| !isDeepStrictEqual([server.command[0], ...server.command.slice(2)], [setting[0], ...setting.slice(2)]))) {
|
|
37
|
+
throw new InstallerError('A Machinal MCP command differs from its approved companion command. No configuration was changed; inspect this override before upgrading.');
|
|
38
|
+
}
|
|
39
|
+
options[key] = { ...options[key], [name]: server?.command ?? setting };
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
throw new InstallerError('Duplicate Machinal plugins have conflicting server/options settings. Resolve the conflict before upgrading; no configuration was changed.');
|
|
43
|
+
}
|
|
44
|
+
options[key] = { ...options[key], [name]: setting };
|
|
45
|
+
}
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (Object.hasOwn(options, key) && !isDeepStrictEqual(options[key], value)) throw new InstallerError('Duplicate Machinal plugins have conflicting options. No configuration was changed.');
|
|
49
|
+
Object.defineProperty(options, key, { value, enumerable: true, writable: true, configurable: true });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { plugins, indexes, options };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function writeCompanion(content, { plugins, indexes }, options) {
|
|
56
|
+
const entry = { package: OPENCODE_AUTH_PLUGIN, options };
|
|
57
|
+
const index = indexes[0] ?? -1;
|
|
58
|
+
if (indexes.length === 1 && isDeepStrictEqual(plugins[index], entry)) return content;
|
|
59
|
+
const indent = content.match(/^[ \t]+(?=")/m)?.[0] ?? ' ';
|
|
60
|
+
const formattingOptions = { insertSpaces: !indent.includes('\t'), tabSize: indent.length, eol: content.includes('\r\n') ? '\r\n' : '\n' };
|
|
61
|
+
if (indexes.length > 1) {
|
|
62
|
+
const consolidated = plugins.flatMap((plugin, position) => position === index ? [entry] : indexes.includes(position) ? [] : [plugin]);
|
|
63
|
+
// Deleting individual nested array entries can corrupt compact JSON in jsonc-parser.
|
|
64
|
+
return applyEdits(content, modify(content, ['plugins'], consolidated, { formattingOptions }));
|
|
65
|
+
}
|
|
66
|
+
return applyEdits(content, modify(content, plugins.length ? ['plugins', index < 0 ? -1 : index] : ['plugins'], plugins.length ? entry : [entry], { formattingOptions }));
|
|
11
67
|
}
|
|
12
68
|
|
|
13
69
|
export function removeOpenCodeAuthServer(content, name) {
|
|
@@ -25,29 +81,36 @@ export function removeOpenCodeAuthServer(content, name) {
|
|
|
25
81
|
return applyEdits(content, modify(content, ['plugins'], plugins, { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
|
|
26
82
|
}
|
|
27
83
|
|
|
28
|
-
export function configureOpenCodeAuth(content, name, url, command) {
|
|
84
|
+
export function configureOpenCodeAuth(content, name, url, command, context = {}) {
|
|
29
85
|
const config = parse(content);
|
|
30
|
-
const
|
|
31
|
-
|
|
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
|
-
}
|
|
86
|
+
const current = companion(config, context);
|
|
87
|
+
const existing = current.options;
|
|
40
88
|
const servers = { ...existing.servers, [name]: url };
|
|
41
89
|
if (name === 'machinal' && servers.directional === url) delete servers.directional;
|
|
42
90
|
const commands = { ...existing.commands };
|
|
43
91
|
if (command) commands[name] = command;
|
|
44
92
|
else delete commands[name];
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
93
|
+
return writeCompanion(content, current, { ...existing, servers, ...(Object.keys(commands).length ? { commands } : {}) });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function upgradeOpenCodeAuth(content, { script, home, env }) {
|
|
97
|
+
parseJSONConfiguration(content, 'opencode');
|
|
98
|
+
const config = parse(content);
|
|
99
|
+
const current = companion(config, { home, env });
|
|
100
|
+
if (!current.indexes.length) return content;
|
|
101
|
+
const commands = { ...current.options.commands };
|
|
102
|
+
for (const [name, command] of Object.entries(commands)) {
|
|
103
|
+
if (!isManagedRuntimeCommand(command, { home, env })) continue;
|
|
104
|
+
const server = config.mcp?.servers?.[name];
|
|
105
|
+
if (server && (server.type !== 'local' || !isDeepStrictEqual(server.command, command))) {
|
|
106
|
+
throw new InstallerError('A Machinal MCP command differs from its approved companion command. No configuration was changed; inspect this override before upgrading.');
|
|
107
|
+
}
|
|
108
|
+
commands[name] = [command[0], script, ...command.slice(2)];
|
|
109
|
+
if (server && !isDeepStrictEqual(command, commands[name])) {
|
|
110
|
+
content = applyEdits(content, modify(content, ['mcp', 'servers', name, 'command'], commands[name], { formattingOptions: { insertSpaces: true, tabSize: 2 } }));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const upgraded = writeCompanion(content, current, { ...current.options, ...(current.options.commands ? { commands } : {}) });
|
|
114
|
+
parseJSONConfiguration(upgraded, 'opencode');
|
|
115
|
+
return upgraded;
|
|
53
116
|
}
|
package/src/opencode-media.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { assertNewDownload, downloadDirectory, downloadFilename, saveDownload } from './download.mjs';
|
|
3
3
|
import { readTransferJSON, requestTransfer, transferURL, TransferError } from './transfer-http.mjs';
|
|
4
|
+
import { readSettings } from './settings.mjs';
|
|
4
5
|
|
|
5
6
|
const projectPattern = /^[a-z\d_-]{1,64}$/i;
|
|
6
7
|
const jobPattern = /^[a-f\d]{32}$/;
|
|
@@ -47,7 +48,7 @@ export function projectAPI(connection, signal, request = requestTransfer) {
|
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
50
|
|
|
50
|
-
async function projectSource(input, connection, signal, request) {
|
|
51
|
+
async function projectSource(input, connection, signal, request, getSettings) {
|
|
51
52
|
const api = projectAPI(connection, signal, request);
|
|
52
53
|
const root = projectPath(input);
|
|
53
54
|
let filename = input.file;
|
|
@@ -59,6 +60,7 @@ async function projectSource(input, connection, signal, request) {
|
|
|
59
60
|
filename = downloadFilename(job.filename);
|
|
60
61
|
}
|
|
61
62
|
let directory = input.directory;
|
|
63
|
+
if (!directory) directory = (await getSettings()).downloadDirectory;
|
|
62
64
|
if (!directory) directory = (await api('/v1/preferences/downloads')).directory;
|
|
63
65
|
if (!directory) throw new TransferError('No client-local download directory is set. Ask the user where to save the file.');
|
|
64
66
|
return {
|
|
@@ -83,7 +85,7 @@ function permission(ctx, context, action, resources) {
|
|
|
83
85
|
});
|
|
84
86
|
}
|
|
85
87
|
|
|
86
|
-
export async function installOpenCodeMedia(ctx, { getConnection, signal: lifetime, request = requestTransfer } = {}) {
|
|
88
|
+
export async function installOpenCodeMedia(ctx, { getConnection, signal: lifetime, request = requestTransfer, getSettings = () => readSettings() } = {}) {
|
|
87
89
|
await ctx.tool.transform((editor) => {
|
|
88
90
|
editor.add({
|
|
89
91
|
name: 'machinal_download',
|
|
@@ -110,7 +112,7 @@ export async function installOpenCodeMedia(ctx, { getConnection, signal: lifetim
|
|
|
110
112
|
try {
|
|
111
113
|
source = input.url ? { directory: input.directory, filename: input.filename,
|
|
112
114
|
delivery: async () => ({ url: input.url }) }
|
|
113
|
-
: await projectSource(input, await getConnection(input.server), signal, request);
|
|
115
|
+
: await projectSource(input, await getConnection(input.server), signal, request, getSettings);
|
|
114
116
|
directory = await downloadDirectory(source.directory);
|
|
115
117
|
path = join(directory, downloadFilename(source.filename));
|
|
116
118
|
await assertNewDownload(path);
|
package/src/opencode-tools.mjs
CHANGED
|
@@ -19,6 +19,7 @@ export async function installDirectTools(ctx, servers) {
|
|
|
19
19
|
});
|
|
20
20
|
await ctx.session.hook('context', (event) => {
|
|
21
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
|
+
event.system.push({ type: 'text', text: 'machinal source uploads: for approved named files on the CLIENT computer, call the native machinal_upload with projectId, files (exact absolute paths) and userApproved:true. It streams to the configured server using the existing in-memory key; no shell scripts, credential extraction or separate login. Use its actual returned project filenames. list_local_media/inspect_local_media/import_local_media access SERVER-mounted roots only; they do not browse the client disk or select local rendering. A local stdio adapter can still use Machinal Server; inspect connection_status.mode/endpoint rather than inferring processing location from type:local. Do not call list_local_media as an upload prerequisite, or ask for mounts/local Docker when approved client upload is intended. Respect no-upload choices. If a transfer is uncertain, retain returned successful files and pending.file, inspect/recover that exact remote filename with existing source-use approval, and never automatically upload duplicates or submit paid jobs.' });
|
|
22
23
|
});
|
|
23
24
|
await ctx.session.hook('context', (event) => {
|
|
24
25
|
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.` });
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { dirname, join, resolve } from 'node:path';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { chooseJSONFile, configurationPath, planTextFile, saveConfiguration } from './configuration.mjs';
|
|
4
|
+
import { upgradeOpenCodeAuth } from './opencode-configuration.mjs';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
// OpenCode combines plugin arrays from global and ancestor configs, not just the setup target.
|
|
8
|
+
export async function planOpenCodeUpgrade(plan, options) {
|
|
9
|
+
const files = new Set([await configurationPath({ ...options, scope: 'global' })]);
|
|
10
|
+
for (let directory = resolve(options.cwd); ; directory = dirname(directory)) {
|
|
11
|
+
for (const root of [directory, join(directory, '.opencode')]) {
|
|
12
|
+
files.add(await chooseJSONFile(root));
|
|
13
|
+
}
|
|
14
|
+
if (dirname(directory) === directory) break;
|
|
15
|
+
}
|
|
16
|
+
const plans = [];
|
|
17
|
+
for (const file of files) {
|
|
18
|
+
if (resolve(file) === resolve(plan.file)) continue;
|
|
19
|
+
const previous = await planTextFile(file, '');
|
|
20
|
+
if (previous.original === null) continue;
|
|
21
|
+
const content = upgradeOpenCodeAuth(previous.original, { ...options, home: options.home ?? homedir() });
|
|
22
|
+
if (content !== previous.original) plans.push({ ...previous, content });
|
|
23
|
+
}
|
|
24
|
+
return plans;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function saveOpenCodeUpgrade(plan, related) {
|
|
28
|
+
const plans = [...related, plan];
|
|
29
|
+
for (const current of plans) {
|
|
30
|
+
if ((await planTextFile(current.file, '')).original !== current.original) throw new InstallerError('An OpenCode configuration changed during setup. Run setup again; no settings were overwritten.');
|
|
31
|
+
}
|
|
32
|
+
const saved = [];
|
|
33
|
+
try {
|
|
34
|
+
for (const current of plans) saved.push({ file: current.file, ...await saveConfiguration(current) });
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (saved.some(entry => entry.changed)) throw new InstallerError('OpenCode upgrade stopped while saving multiple configurations. Some files were upgraded and backed up; rerun setup to finish synchronization. No API key was changed.');
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
return saved;
|
|
40
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { filePermission } from './opencode-recipes.mjs';
|
|
2
|
+
import { projectAPI } from './opencode-media.mjs';
|
|
3
|
+
import { inspectUpload, MAX_UPLOAD_BYTES, uploadFile, validateUpload } from './upload.mjs';
|
|
4
|
+
import { requestTransfer, TransferError } from './transfer-http.mjs';
|
|
5
|
+
|
|
6
|
+
function failure(error, files, pending, signal) {
|
|
7
|
+
const message = error instanceof TransferError ? error.message : signal?.aborted
|
|
8
|
+
? 'Upload cancelled or timed out. Do not automatically retry; recover any attempted remote filename first.'
|
|
9
|
+
: 'Upload failed. Check file access, server storage limits and network. Do not automatically retry; recover any attempted remote filename first.';
|
|
10
|
+
return { content: JSON.stringify({ status: files.length ? 'partial' : 'failed', files, ...(pending ? { pending } : {}), error: message }) };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function installOpenCodeUploads(ctx, { getConnection, signal: lifetime, request = requestTransfer } = {}) {
|
|
14
|
+
await ctx.tool.transform(editor => {
|
|
15
|
+
editor.add({
|
|
16
|
+
name: 'machinal_upload',
|
|
17
|
+
description: 'Upload 1–100 explicitly approved client-local media files into an owned project on the configured machinal server. Uses in-memory authentication and native streaming, not PowerShell/curl or S3. Originals remain read-only. Pass exact absolute file paths, projectId and userApproved; never pass a key or URL. Uses host upload/read permissions, refuses redirects and never retries uncertain transfers. Returns actual project filenames, bytes and transmitted SHA-256; no generation/render spending. For a Windows folder on your computer use this tool, not list_local_media (which accesses server-mounted roots).',
|
|
18
|
+
input: { type: 'object', additionalProperties: false, required: ['projectId', 'files', 'userApproved'], properties: {
|
|
19
|
+
projectId: { type: 'string' },
|
|
20
|
+
files: { type: 'array', minItems: 1, maxItems: 100, items: { type: 'string' }, description: 'Exact approved absolute client-local media paths; no recursive folders or globs.' },
|
|
21
|
+
server: { type: 'string', description: 'Approved MCP registration; required when multiple servers are configured.' },
|
|
22
|
+
userApproved: { type: 'boolean', description: 'True only after explicit permission to read/upload these named sources to this project. Does not authorize generation or rendering.' },
|
|
23
|
+
} },
|
|
24
|
+
options: { codemode: false },
|
|
25
|
+
async execute(input, context) {
|
|
26
|
+
try { validateUpload(input); } catch (error) { return failure(error, []); }
|
|
27
|
+
await ctx.permission.assert({ sessionID: context.sessionID, agent: context.agent,
|
|
28
|
+
source: { type: 'tool', messageID: context.messageID, id: context.id },
|
|
29
|
+
action: 'machinal_upload', resources: [`${input.server ?? 'machinal'}/${input.projectId}`], save: [],
|
|
30
|
+
});
|
|
31
|
+
for (const path of input.files) await filePermission(ctx, context, 'read', path);
|
|
32
|
+
const signal = AbortSignal.any([context.signal, lifetime, AbortSignal.timeout(10 * 60 * 1000)].filter(Boolean));
|
|
33
|
+
const files = [];
|
|
34
|
+
let pending;
|
|
35
|
+
try {
|
|
36
|
+
signal.throwIfAborted();
|
|
37
|
+
const sources = [];
|
|
38
|
+
let total = 0;
|
|
39
|
+
for (const path of input.files) {
|
|
40
|
+
const source = await inspectUpload(path);
|
|
41
|
+
total += source.info.size;
|
|
42
|
+
if (total > MAX_UPLOAD_BYTES) throw new TransferError('The selected upload batch exceeds 2 GiB. Select a smaller explicitly approved batch.');
|
|
43
|
+
sources.push(source);
|
|
44
|
+
}
|
|
45
|
+
const connection = await getConnection(input.server);
|
|
46
|
+
await projectAPI(connection, signal, request)(`/v1/projects/${input.projectId}`);
|
|
47
|
+
for (const source of sources) {
|
|
48
|
+
signal.throwIfAborted();
|
|
49
|
+
pending = { path: source.path, file: source.file, storage: 'volume', status: 'unknown' };
|
|
50
|
+
await context.progress({ status: 'Uploading', filename: source.file, completedFiles: files.length, totalFiles: sources.length });
|
|
51
|
+
files.push(await uploadFile(source, { connection, projectId: input.projectId, signal, progress: context.progress, request }));
|
|
52
|
+
pending = undefined;
|
|
53
|
+
}
|
|
54
|
+
return { content: JSON.stringify({ status: 'completed', projectId: input.projectId, files, storage: 'volume', uploadsToS3: false, originalsReadOnly: true }) };
|
|
55
|
+
} catch (error) { return failure(error, files, pending, signal); }
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
});
|
|
59
|
+
}
|
|
@@ -1,21 +1,19 @@
|
|
|
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;
|
|
1
|
+
export const productionSkills = ['machinal-editing', 'machinal-recipes', 'machinal-scenes', 'machinal-cinema', 'machinal-review', 'machinal-credits'];
|
|
5
2
|
|
|
6
|
-
async function
|
|
3
|
+
async function installedSkills(ctx) {
|
|
7
4
|
try {
|
|
8
5
|
const result = await ctx.skill.list();
|
|
9
6
|
const skills = Array.isArray(result) ? result : result?.data;
|
|
10
7
|
if (!Array.isArray(skills)) throw new TypeError('Unsupported skill list response');
|
|
11
|
-
return new
|
|
8
|
+
return new Map(skills.filter(skill => typeof skill?.id === 'string').map(skill => [skill.id, skill]));
|
|
12
9
|
} catch {
|
|
13
|
-
|
|
14
|
-
return new Set();
|
|
10
|
+
return new Map();
|
|
15
11
|
}
|
|
16
12
|
}
|
|
17
13
|
|
|
18
|
-
export async function installWorkflowStartup(ctx) {
|
|
14
|
+
export async function installWorkflowStartup(ctx, servers = []) {
|
|
15
|
+
const names = [...servers];
|
|
16
|
+
const prepared = new Map();
|
|
19
17
|
if (ctx.skill?.transform) {
|
|
20
18
|
await ctx.skill.transform(editor => {
|
|
21
19
|
for (const id of [...productionSkills, 'machinal-media', 'machinal-support']) {
|
|
@@ -29,16 +27,59 @@ export async function installWorkflowStartup(ctx) {
|
|
|
29
27
|
if (!prompt) return;
|
|
30
28
|
const selected = new Set((prompt.skills ?? []).map(skill => skill.id));
|
|
31
29
|
const explicit = productionSkills.some(id => selected.has(id));
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const available = await availableProductionSkills(ctx);
|
|
30
|
+
if (!explicit) return;
|
|
31
|
+
const available = await installedSkills(ctx);
|
|
35
32
|
for (const id of productionSkills) {
|
|
36
33
|
if (available.has(id) && !selected.has(id)) {
|
|
37
34
|
(prompt.skills ??= []).push({ id });
|
|
38
35
|
}
|
|
39
36
|
}
|
|
40
37
|
});
|
|
38
|
+
await ctx.tool.transform(editor => {
|
|
39
|
+
editor.add({
|
|
40
|
+
name: 'machinal_prepare_video',
|
|
41
|
+
description: 'Start or resume video creation/editing in ANY language. Call before the video brief, media work or production, based on the meaning of the user request, not keywords. Loads the installed production skills INCLUDING machinal-cinema into this session. Required before compile_scene/render_video; those tools refuse unprepared sessions. No model/router/provider calls, media access, uploads, job submission or spending. Do not use for MCP/code debugging or standalone image searches. This initializes guidance, not permission to produce a video.',
|
|
42
|
+
input: { type: 'object', additionalProperties: false, required: ['purpose'], properties: {
|
|
43
|
+
purpose: { type: 'string', enum: ['create', 'edit'], description: 'The video task understood by the current agent, independent of the user’s language.' },
|
|
44
|
+
} },
|
|
45
|
+
options: { codemode: false },
|
|
46
|
+
async execute(input, context) {
|
|
47
|
+
if (!['create', 'edit'].includes(input.purpose) || !context.sessionID) return { content: JSON.stringify({ status: 'blocked', error: 'Use create/edit in a session.' }) };
|
|
48
|
+
prepared.delete(context.sessionID);
|
|
49
|
+
const installed = await installedSkills(ctx);
|
|
50
|
+
const missing = productionSkills.filter(id => !installed.get(id)?.content?.trim());
|
|
51
|
+
if (missing.length) return { content: JSON.stringify({ status: 'blocked', missingSkills: missing, error: 'Install/restore these production skills before video production. No production action was executed.' }) };
|
|
52
|
+
await ctx.permission.assert({ sessionID: context.sessionID, agent: context.agent,
|
|
53
|
+
source: { type: 'tool', messageID: context.messageID, id: context.id },
|
|
54
|
+
action: 'skill', resources: productionSkills, save: productionSkills,
|
|
55
|
+
});
|
|
56
|
+
const skills = productionSkills.map(id => installed.get(id));
|
|
57
|
+
prepared.delete(context.sessionID);
|
|
58
|
+
prepared.set(context.sessionID, { skills, contextLoaded: false });
|
|
59
|
+
if (prepared.size > 128) prepared.delete(prepared.keys().next().value);
|
|
60
|
+
return { content: JSON.stringify({ status: 'ready', purpose: input.purpose, loadedSkills: productionSkills,
|
|
61
|
+
next: 'Follow the loaded brief/production/cinema guidance. Existing source/spending approvals remain separate; resume existing jobs/assets rather than submitting duplicates.' }) };
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
for (const server of names) {
|
|
65
|
+
for (const name of ['compile_scene', 'render_video']) {
|
|
66
|
+
editor.update(`${server}_${name}`.replace(/[^a-z\d_-]/gi, '_'), tool => {
|
|
67
|
+
const execute = tool.execute;
|
|
68
|
+
tool.description += ' Requires machinal_prepare_video in this session to load production guidance including cinema. Missing preparation executes no scene/render action.';
|
|
69
|
+
tool.execute = async (input, context) => {
|
|
70
|
+
if (!prepared.get(context.sessionID)?.contextLoaded) return { content: JSON.stringify({ status: 'blocked', nextTool: 'machinal_prepare_video', error: 'Load video production guidance, including cinema, into the next model context before this action. Do not batch preparation and production in one model turn. No action was executed; no paid job was submitted.' }) };
|
|
71
|
+
return execute(input, context);
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
});
|
|
41
77
|
await ctx.session.hook('context', event => {
|
|
42
|
-
event.system.push({ type: 'text', text: 'machinal production startup:
|
|
78
|
+
event.system.push({ type: 'text', text: 'machinal production startup: understand the user’s intent in their language using the CURRENT agent. For any request to create/edit a video, call the native machinal_prepare_video tool before the brief/media/production stages. Do not match keywords, maintain language lists or invoke a second classifier/router model. The tool loads installed production skills INCLUDING machinal-cinema; compile_scene/render_video refuse an unprepared session. Preparation is free and grants no source-use/spending permission. Debugging MCP/code is not video production. 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. Save production state, sources, resolved recipeFile and job IDs; resume existing jobs/assets after interruption, not new paid submissions.' });
|
|
79
|
+
const state = prepared.get(event.sessionID);
|
|
80
|
+
for (const skill of state?.skills ?? []) {
|
|
81
|
+
event.system.push({ type: 'text', text: `<skill_content name="${skill.id}">\n${skill.content}\n\nSkill source: ${skill.path ?? 'installed skill registry'}\n</skill_content>` });
|
|
82
|
+
}
|
|
83
|
+
if (state) state.contextLoaded = true;
|
|
43
84
|
});
|
|
44
85
|
}
|
package/src/paths.mjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export function stateDirectory({ home, env = process.env, platform = process.platform } = {}) {
|
|
5
|
+
const base = home ?? (platform !== 'win32' && env.HOME && isAbsolute(env.HOME) ? env.HOME : homedir());
|
|
6
|
+
const config = env.XDG_CONFIG_HOME;
|
|
7
|
+
return join(config && isAbsolute(config) ? config : join(base, '.config'), 'machinal');
|
|
8
|
+
}
|
package/src/presentation.mjs
CHANGED
|
@@ -14,7 +14,7 @@ export function createLogger({ write = console.log, stream = process.stdout, env
|
|
|
14
14
|
const style = terminalStyle({ stream, env });
|
|
15
15
|
return (message, kind) => {
|
|
16
16
|
if (!message) return;
|
|
17
|
-
if (kind === 'heading') return write(`\n${style('bold', message)}`);
|
|
17
|
+
if (kind === 'heading') return write(`\n${style(['bold', 'magenta'], message)}`);
|
|
18
18
|
if (kind === 'error') return write(`${style('red', 'Error:')} ${message}`);
|
|
19
19
|
const label = message.match(/^(Warning:|Low balance:|Usage awaiting payment:|[^:]*unavailable:)/)?.[0];
|
|
20
20
|
if (label) return write(style('yellow', label) + message.slice(label.length));
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { chmod, lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const MAX_BYTES = 64 * 1024;
|
|
8
|
+
|
|
9
|
+
function owned(info) {
|
|
10
|
+
return !process.getuid || info.uid === process.getuid();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
async function directory(file, create) {
|
|
14
|
+
const path = dirname(file);
|
|
15
|
+
if (create) await mkdir(path, { recursive: true, mode: 0o700 });
|
|
16
|
+
const info = await lstat(path);
|
|
17
|
+
if (!info.isDirectory() || info.isSymbolicLink() || !owned(info)) throw new Error('Unsafe directory');
|
|
18
|
+
if (process.platform !== 'win32' && (info.mode & 0o077)) {
|
|
19
|
+
if (!create) throw new Error('Directory permissions');
|
|
20
|
+
await chmod(path, 0o700);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function inspect(file) {
|
|
25
|
+
const info = await lstat(file);
|
|
26
|
+
if (!info.isFile() || info.isSymbolicLink() || !owned(info) || info.size > MAX_BYTES
|
|
27
|
+
|| (process.platform !== 'win32' && (info.mode & 0o077))) throw new Error('Unsafe file');
|
|
28
|
+
return info;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function readPrivateJSON(file) {
|
|
32
|
+
let handle;
|
|
33
|
+
try {
|
|
34
|
+
await directory(file, false);
|
|
35
|
+
const before = await inspect(file);
|
|
36
|
+
handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
37
|
+
const info = await handle.stat();
|
|
38
|
+
if (info.ino !== before.ino || info.dev !== before.dev || info.size > MAX_BYTES) throw new Error('File changed');
|
|
39
|
+
const buffer = Buffer.alloc(MAX_BYTES + 1);
|
|
40
|
+
let size = 0;
|
|
41
|
+
while (size < buffer.length) {
|
|
42
|
+
const { bytesRead } = await handle.read(buffer, size, buffer.length - size, null);
|
|
43
|
+
if (!bytesRead) break;
|
|
44
|
+
size += bytesRead;
|
|
45
|
+
}
|
|
46
|
+
if (size > MAX_BYTES) throw new Error('File too large');
|
|
47
|
+
return JSON.parse(buffer.subarray(0, size).toString('utf8'));
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error.code === 'ENOENT') return null;
|
|
50
|
+
throw new InstallerError('Could not read the private Machinal file. Check ownership, directory mode 0700 and file mode 0600; symlinks are not supported. Nothing was deleted.');
|
|
51
|
+
} finally { await handle?.close(); }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function writePrivateJSON(file, value) {
|
|
55
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
56
|
+
let handle;
|
|
57
|
+
try {
|
|
58
|
+
await directory(file, true);
|
|
59
|
+
try { await inspect(file); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
60
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
61
|
+
if (Buffer.byteLength(text) > MAX_BYTES) throw new Error('File too large');
|
|
62
|
+
handle = await open(temporary, 'wx', 0o600);
|
|
63
|
+
await handle.writeFile(text, 'utf8');
|
|
64
|
+
await handle.sync();
|
|
65
|
+
await handle.close();
|
|
66
|
+
handle = null;
|
|
67
|
+
await rename(temporary, file);
|
|
68
|
+
} catch {
|
|
69
|
+
throw new InstallerError('Could not save the private Machinal file. Check ownership, permissions and free disk space. No plaintext backup or alternate location was created.');
|
|
70
|
+
} finally {
|
|
71
|
+
await handle?.close();
|
|
72
|
+
await unlink(temporary).catch(() => {});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function deletePrivateJSON(file) {
|
|
77
|
+
try {
|
|
78
|
+
await directory(file, false);
|
|
79
|
+
await inspect(file);
|
|
80
|
+
await unlink(file);
|
|
81
|
+
return true;
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error.code === 'ENOENT') return false;
|
|
84
|
+
throw new InstallerError('Could not delete the private Machinal file. Check ownership and permissions; nothing else was removed.');
|
|
85
|
+
}
|
|
86
|
+
}
|
package/src/prompts.mjs
CHANGED
|
@@ -4,13 +4,13 @@ export function createPromptUI(prompts, options = {}) {
|
|
|
4
4
|
const style = terminalStyle(options);
|
|
5
5
|
const stream = options.stream ?? process.stdout;
|
|
6
6
|
const theme = {
|
|
7
|
-
prefix: { idle: '?', done: '-' },
|
|
7
|
+
prefix: { idle: style('magenta', '?'), done: style('magenta', '-') },
|
|
8
8
|
spinner: { interval: 120, frames: ['-', '\\', '|', '/'] },
|
|
9
9
|
icon: { cursor: '>' },
|
|
10
10
|
style: {
|
|
11
11
|
message: (text, status) => status === 'done' ? text : style('bold', text),
|
|
12
12
|
answer: (text) => text,
|
|
13
|
-
highlight: (text) => style('
|
|
13
|
+
highlight: (text) => style('magenta', text),
|
|
14
14
|
description: (text) => text,
|
|
15
15
|
help: (text) => text,
|
|
16
16
|
disabled: (text) => text,
|
|
@@ -18,9 +18,7 @@ export function createPromptUI(prompts, options = {}) {
|
|
|
18
18
|
confirmDefault: (text) => text.toUpperCase(),
|
|
19
19
|
key: (text) => `<${text}>`,
|
|
20
20
|
error: (text) => `${style('red', 'Error:')} ${text}`,
|
|
21
|
-
keysHelpTip: () =>
|
|
22
|
-
? ' Up/down · Enter · Ctrl+C cancels'
|
|
23
|
-
: ' Up/down to move · Enter to select · Ctrl+C to cancel',
|
|
21
|
+
keysHelpTip: () => ' Up/down · Enter · Ctrl+C cancels',
|
|
24
22
|
},
|
|
25
23
|
};
|
|
26
24
|
return Object.fromEntries(Object.entries(prompts).map(([name, prompt]) => [name, (config, context) => prompt({
|
package/src/runtime.mjs
CHANGED
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import { cp, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
-
import {
|
|
4
|
-
import { join } from 'node:path';
|
|
3
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
5
4
|
import { fileURLToPath } from 'node:url';
|
|
6
5
|
import { VERSION } from './version.mjs';
|
|
6
|
+
import { stateDirectory } from './paths.mjs';
|
|
7
|
+
|
|
8
|
+
export { stateDirectory } from './paths.mjs';
|
|
7
9
|
|
|
8
10
|
const ROOT = fileURLToPath(new URL('../', import.meta.url));
|
|
9
11
|
const FILES = ['bin/machinal-stdio.mjs', 'src/bridge.mjs', 'src/connection.mjs', 'src/credential-store.mjs',
|
|
10
|
-
'src/credits.mjs', 'src/endpoints.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/
|
|
12
|
+
'src/credits.mjs', 'src/endpoints.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/paths.mjs',
|
|
13
|
+
'src/private-json.mjs', 'src/version.mjs', 'package.json'];
|
|
11
14
|
|
|
12
|
-
export function
|
|
13
|
-
|
|
15
|
+
export function isManagedRuntimeCommand(command, context = {}) {
|
|
16
|
+
if (!Array.isArray(command) || !isAbsolute(command[1] ?? '')) return false;
|
|
17
|
+
const parts = relative(join(stateDirectory(context), 'runtime'), command[1]).split(sep);
|
|
18
|
+
return parts.length === 3 && /^\d+\.\d+\.\d+(?:-[\w.-]+)?-(?:win32|linux|darwin)-[\w]+-[a-f\d]{16}$/.test(parts[0])
|
|
19
|
+
&& parts[1] === 'bin' && parts[2] === 'machinal-stdio.mjs' && command[2] === 'serve';
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
export function endpointFiles(url, context) {
|
package/src/settings.mjs
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { normalizeEndpoint } from './connection.mjs';
|
|
3
|
+
import { InstallerError } from './errors.mjs';
|
|
4
|
+
import { stateDirectory } from './paths.mjs';
|
|
5
|
+
import { readPrivateJSON, writePrivateJSON } from './private-json.mjs';
|
|
6
|
+
|
|
7
|
+
export function settingsFile(context) {
|
|
8
|
+
return join(stateDirectory(context), 'config.json');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function readSettings(context) {
|
|
12
|
+
const value = await readPrivateJSON(settingsFile(context));
|
|
13
|
+
if (value === null) return { version: 1 };
|
|
14
|
+
if (value.version !== 1 || (value.connection && (!['server', 'custom', 'local'].includes(value.connection.mode)
|
|
15
|
+
|| normalizeEndpoint(value.connection.url) !== value.connection.url))) {
|
|
16
|
+
throw new InstallerError('The Machinal settings file is invalid. Check machinal place; existing settings were not replaced.');
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function saveSettings(patch, context) {
|
|
22
|
+
const current = await readSettings(context);
|
|
23
|
+
const next = { ...current, ...patch, version: 1 };
|
|
24
|
+
if (JSON.stringify(current) !== JSON.stringify(next)) await writePrivateJSON(settingsFile(context), next);
|
|
25
|
+
return next;
|
|
26
|
+
}
|