@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
package/src/docker.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { lstat } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
import { DEFAULT_LOCAL_URL } from './setup-options.mjs';
|
|
7
|
+
import { DOCKER_URL } from './presentation.mjs';
|
|
8
|
+
|
|
9
|
+
const exec = promisify(execFile);
|
|
10
|
+
const COMPOSE_FILE = 'compose.editengine.yaml';
|
|
11
|
+
const SERVICES = ['api', 'scene-renderer'];
|
|
12
|
+
|
|
13
|
+
function runQuietly(args, options) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const child = spawn('docker', args, { ...options, stdio: 'ignore' });
|
|
16
|
+
child.once('error', reject);
|
|
17
|
+
child.once('close', (code) => code === 0 ? resolve('') : reject(new Error('Docker did not complete successfully')));
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function runDocker(args, { cwd, env, timeout = 15_000, discardOutput = false } = {}) {
|
|
22
|
+
const { MACHINAL_API_KEY: _machinalKey, DIRECTION_API_KEY: _legacyKey, ...childEnv } = env ?? process.env;
|
|
23
|
+
try {
|
|
24
|
+
const options = { cwd, env: childEnv, timeout, windowsHide: true };
|
|
25
|
+
if (discardOutput) return await runQuietly(args, options);
|
|
26
|
+
return (await exec('docker', args, { ...options, maxBuffer: 2 * 1024 * 1024 })).stdout.trim();
|
|
27
|
+
} catch (error) {
|
|
28
|
+
const missing = error.code === 'ENOENT';
|
|
29
|
+
throw new InstallerError(missing
|
|
30
|
+
? `Docker was not found. Install Docker Desktop/Engine: ${DOCKER_URL}. Start it, then rerun setup. Your client settings were not changed.`
|
|
31
|
+
: 'Docker could not complete the operation. Check that Docker Desktop/Engine is running, the selected context is local, ports are free, and disk space/network access are available. Check Docker locally for details; container output is not printed because it may contain secrets.', { code: missing ? 'docker-missing' : 'docker-failed' });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function regularFile(file) {
|
|
36
|
+
try { return (await lstat(file)).isFile(); } catch (error) {
|
|
37
|
+
if (error.code === 'ENOENT') return false;
|
|
38
|
+
throw new InstallerError('Could not inspect the local checkout. Check folder permissions or use --docker-dir with a readable checkout.');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function findCheckout(start, explicit) {
|
|
43
|
+
let root = resolve(start, explicit ?? '.');
|
|
44
|
+
while (true) {
|
|
45
|
+
if ((await Promise.all([COMPOSE_FILE, 'api/Dockerfile', 'services/scene-renderer/Dockerfile'].map((file) => regularFile(join(root, file))))).every(Boolean)) return root;
|
|
46
|
+
if (explicit || dirname(root) === root) return null;
|
|
47
|
+
root = dirname(root);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function localDaemon(host) {
|
|
52
|
+
if (host.startsWith('unix://') || host.startsWith('npipe://')) return true;
|
|
53
|
+
try {
|
|
54
|
+
const url = new URL(host);
|
|
55
|
+
return url.protocol === 'tcp:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
56
|
+
} catch { return false; }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function prepareLocalDocker(values, url, context) {
|
|
60
|
+
const { cwd, env, interactive, ui, log } = context;
|
|
61
|
+
if (new URL(url).port !== new URL(DEFAULT_LOCAL_URL).port) {
|
|
62
|
+
throw new InstallerError('No API is listening at this local URL. The bundled Docker checkout exposes port 8080. Start your custom deployment yourself, or rerun with --mode local --url http://127.0.0.1:8080/mcp. No Docker changes were made.');
|
|
63
|
+
}
|
|
64
|
+
const root = await findCheckout(cwd, values['docker-dir']);
|
|
65
|
+
if (!root) throw new InstallerError('No running local API or machinal checkout was found. Use --docker-dir PATH to a checkout containing compose.editengine.yaml, api/ and services/scene-renderer/. Configure api/.env first. To use an existing deployment instead, choose --mode server --url YOUR-API. No image is downloaded from an unverified registry.');
|
|
66
|
+
const docker = context.docker ?? ((args, options = {}) => runDocker(args, { cwd: root, env, ...options }));
|
|
67
|
+
const compose = ['compose', '--project-directory', root, '-f', join(root, COMPOSE_FILE)];
|
|
68
|
+
log(`Local Docker checkout: ${root}. Checking Docker, containers, and images (no changes yet)...`);
|
|
69
|
+
await docker(['info', '--format', '{{.ServerVersion}}']);
|
|
70
|
+
const host = !env.DOCKER_CONTEXT && env.DOCKER_HOST
|
|
71
|
+
? env.DOCKER_HOST
|
|
72
|
+
: await docker(['context', 'inspect', ...(env.DOCKER_CONTEXT ? [env.DOCKER_CONTEXT] : []), '--format', '{{.Endpoints.docker.Host}}']);
|
|
73
|
+
if (!localDaemon(host)) throw new InstallerError('Local mode requires a local Docker daemon; the current Docker context points elsewhere. Switch to a local context yourself, or choose Server. No Docker changes were made.');
|
|
74
|
+
await docker(['compose', 'version', '--short']);
|
|
75
|
+
if (!await regularFile(join(root, 'api', '.env'))) throw new InstallerError(`Docker needs ${join(root, 'api', '.env')}. Configure the backend authentication, billing, and providers using the checkout documentation, then rerun setup. No secrets or placeholder credentials were created.`);
|
|
76
|
+
const containers = await docker([...compose, 'ps', '--all', '--format', '{{.Service}}: {{.State}}', ...SERVICES]);
|
|
77
|
+
log(containers ? `Docker containers: ${containers.replace(/[\r\n]+/g, '; ')}` : 'Docker containers: not created yet.');
|
|
78
|
+
const images = (await docker([...compose, 'config', '--images'])).split(/\r?\n/).filter(Boolean);
|
|
79
|
+
let build = images.length === 0;
|
|
80
|
+
for (const image of images) {
|
|
81
|
+
try { await docker(['image', 'inspect', '--format', '{{.Id}}', image]); } catch (error) {
|
|
82
|
+
if (error.code !== 'docker-failed') throw error;
|
|
83
|
+
build = true;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
log(build ? 'Docker images: missing; a local build is needed (first build may take several minutes).' : 'Docker images: already available; existing images can be reused.');
|
|
87
|
+
const message = `${build ? 'Build missing images and start' : 'Start'} api + scene-renderer from ${root}? This may download base images, use disk/CPU, create persistent volumes, and expose API port 8080. Existing volumes will not be deleted.`;
|
|
88
|
+
const approved = values['start-docker'] || (interactive && await ui.confirm({ message, default: false }));
|
|
89
|
+
if (!approved) throw new InstallerError('Docker was not started. Start the checkout yourself or explicitly use --start-docker with --mode local. --yes alone never authorizes starting/building containers. Existing client settings and Docker volumes were preserved.');
|
|
90
|
+
log(`Docker: ${build ? 'building and starting' : 'starting'} services. Please wait; detailed output stays private.`);
|
|
91
|
+
await docker([...compose, 'up', '-d', ...(build ? ['--build'] : []), '--wait', '--wait-timeout', '120', ...SERVICES], { timeout: 15 * 60_000, discardOutput: true });
|
|
92
|
+
log(`Docker ready: API at ${url}. Verifying MCP next; Docker readiness does not prove account/provider access. Containers keep running after setup; manage them from ${root}.`);
|
|
93
|
+
}
|
package/src/download.mjs
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { createWriteStream } from 'node:fs';
|
|
3
|
+
import { link, mkdir, realpath, stat, unlink } from 'node:fs/promises';
|
|
4
|
+
import { dirname, isAbsolute, join, parse, resolve } from 'node:path';
|
|
5
|
+
import { Transform } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
7
|
+
import { downloadResponse, TransferError } from './transfer-http.mjs';
|
|
8
|
+
|
|
9
|
+
export const MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
export function downloadFilename(value) {
|
|
12
|
+
if (typeof value !== 'string' || !value || Buffer.byteLength(value) > 255 || /^[.]/.test(value)
|
|
13
|
+
|| /[<>:"/\\|?*\x00-\x1f\x7f]/.test(value) || /[. ]$/.test(value)
|
|
14
|
+
|| /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(value)) {
|
|
15
|
+
throw new TransferError('Choose a plain filename without paths, reserved names or control characters.');
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function downloadDirectory(value) {
|
|
21
|
+
if (typeof value !== 'string' || !isAbsolute(value) || /[\x00-\x1f]/.test(value)) {
|
|
22
|
+
throw new TransferError('Choose an absolute client-local download directory. Ask the user if it is unset.');
|
|
23
|
+
}
|
|
24
|
+
const missing = [];
|
|
25
|
+
let existing = resolve(value);
|
|
26
|
+
for (;;) {
|
|
27
|
+
try { return join(await realpath(existing), ...missing.reverse()); } catch (error) {
|
|
28
|
+
if (error.code !== 'ENOENT') throw error;
|
|
29
|
+
const parent = dirname(existing);
|
|
30
|
+
if (parent === existing) throw error;
|
|
31
|
+
missing.push(parse(existing).base);
|
|
32
|
+
existing = parent;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function assertNewDownload(path) {
|
|
38
|
+
try { await stat(path); } catch (error) {
|
|
39
|
+
if (error.code === 'ENOENT') return;
|
|
40
|
+
throw error;
|
|
41
|
+
}
|
|
42
|
+
throw new TransferError('The destination already exists. Choose another filename; existing files are never overwritten.');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function saveDownload({ url, directory, filename, signal, progress = async () => {}, request,
|
|
46
|
+
maxBytes = MAX_DOWNLOAD_BYTES }) {
|
|
47
|
+
const path = join(directory, downloadFilename(filename));
|
|
48
|
+
await assertNewDownload(path);
|
|
49
|
+
const response = await downloadResponse(url, { ...request, signal });
|
|
50
|
+
const length = response.headers['content-length'];
|
|
51
|
+
const total = length === undefined ? null : Number(length);
|
|
52
|
+
let temporary;
|
|
53
|
+
let owned = false;
|
|
54
|
+
try {
|
|
55
|
+
if (total !== null && (!Number.isSafeInteger(total) || total < 1 || total > maxBytes)) {
|
|
56
|
+
throw new TransferError('The download is empty or exceeds the 2 GiB size limit.');
|
|
57
|
+
}
|
|
58
|
+
if (response.headers['content-encoding'] && response.headers['content-encoding'] !== 'identity') {
|
|
59
|
+
throw new TransferError('The download server ignored the identity encoding request. No file was saved.');
|
|
60
|
+
}
|
|
61
|
+
await mkdir(directory, { recursive: true });
|
|
62
|
+
temporary = join(directory, `.machinal-${randomUUID()}.part`);
|
|
63
|
+
const hash = createHash('sha256');
|
|
64
|
+
let bytes = 0;
|
|
65
|
+
let lastProgress = Date.now();
|
|
66
|
+
const meter = new Transform({
|
|
67
|
+
transform(chunk, _encoding, done) {
|
|
68
|
+
bytes += chunk.length;
|
|
69
|
+
if (bytes > maxBytes) return done(new TransferError('The download exceeded the 2 GiB size limit.'));
|
|
70
|
+
hash.update(chunk);
|
|
71
|
+
const now = Date.now();
|
|
72
|
+
const update = now - lastProgress >= 1000;
|
|
73
|
+
if (update) lastProgress = now;
|
|
74
|
+
Promise.resolve(update ? progress({ status: 'Downloading', bytes, ...(total === null ? {} : { totalBytes: total }) }) : undefined)
|
|
75
|
+
.then(() => done(null, chunk), done);
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
const writer = createWriteStream(temporary, { flags: 'wx', mode: 0o600 });
|
|
79
|
+
writer.once('open', () => { owned = true; });
|
|
80
|
+
await pipeline(response, meter, writer, { signal });
|
|
81
|
+
if (!bytes || (total !== null && bytes !== total)) throw new TransferError('The download was incomplete. No final file was saved.');
|
|
82
|
+
signal?.throwIfAborted();
|
|
83
|
+
// Linking publishes the complete file atomically and refuses a concurrent destination.
|
|
84
|
+
await link(temporary, path);
|
|
85
|
+
return { path, bytes, sha256: hash.digest('hex') };
|
|
86
|
+
} finally {
|
|
87
|
+
response.destroy();
|
|
88
|
+
if (owned) await unlink(temporary).catch(() => {});
|
|
89
|
+
}
|
|
90
|
+
}
|
package/src/errors.mjs
ADDED
package/src/formats.mjs
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { applyEdits, findNodeAtLocation, getNodeValue, modify, parseTree } from 'jsonc-parser';
|
|
3
|
+
import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
|
|
4
|
+
import { InstallerError } from './errors.mjs';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
|
|
7
|
+
export function bridgeEntry(client, { url, localConfig, catalogFile, command = process.execPath, script = fileURLToPath(new URL('../bin/machinal-stdio.mjs', import.meta.url)) }) {
|
|
8
|
+
const args = [script, 'serve', '--url', url,
|
|
9
|
+
...(localConfig ? ['--local-config', localConfig] : []), ...(catalogFile ? ['--catalog-file', catalogFile] : [])];
|
|
10
|
+
if (client === 'opencode') return { type: 'local', command: [command, ...args] };
|
|
11
|
+
if (client === 'claude') return { type: 'stdio', command, args };
|
|
12
|
+
if (client === 'codex') return { command, args, env_vars: ['MACHINAL_API_KEY', 'DIRECTION_API_KEY'], startup_timeout_sec: 30, tool_timeout_sec: 180 };
|
|
13
|
+
throw new InstallerError('Choose opencode, claude, or codex.');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function serverEntry(client, url) {
|
|
17
|
+
switch (client) {
|
|
18
|
+
case 'opencode':
|
|
19
|
+
return { type: 'remote', url, oauth: false, headers: { Authorization: 'Bearer {env:MACHINAL_API_KEY}' } };
|
|
20
|
+
case 'claude':
|
|
21
|
+
return { type: 'http', url, headers: { Authorization: 'Bearer ${MACHINAL_API_KEY}' } };
|
|
22
|
+
case 'codex':
|
|
23
|
+
return { url, bearer_token_env_var: 'MACHINAL_API_KEY' };
|
|
24
|
+
default:
|
|
25
|
+
throw new InstallerError('Choose opencode, claude, or codex.');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function assertUniqueKeys(node) {
|
|
30
|
+
if (node.type === 'object') {
|
|
31
|
+
const keys = node.children.map((property) => property.children[0].value);
|
|
32
|
+
if (new Set(keys).size !== keys.length) {
|
|
33
|
+
throw new InstallerError('The configuration has duplicate JSON keys. Resolve them before running setup.');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
for (const child of node.children ?? []) assertUniqueKeys(child);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function updateJSON(original, client, name, entry) {
|
|
40
|
+
const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';
|
|
41
|
+
const source = original.slice(bom.length) || '{}\n';
|
|
42
|
+
const errors = [];
|
|
43
|
+
const tree = parseTree(source, errors, { allowTrailingComma: client === 'opencode', disallowComments: client !== 'opencode' });
|
|
44
|
+
if (errors.length || tree?.type !== 'object') {
|
|
45
|
+
throw new InstallerError('The existing configuration is not a valid JSON object. It was left unchanged.');
|
|
46
|
+
}
|
|
47
|
+
assertUniqueKeys(tree);
|
|
48
|
+
|
|
49
|
+
const path = client === 'opencode' ? ['mcp', 'servers', name] : ['mcpServers', name];
|
|
50
|
+
for (let depth = 1; depth < path.length; depth++) {
|
|
51
|
+
const node = findNodeAtLocation(tree, path.slice(0, depth));
|
|
52
|
+
if (node && node.type !== 'object') {
|
|
53
|
+
throw new InstallerError('The existing MCP settings must be objects. The configuration was left unchanged.');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (client === 'opencode') {
|
|
58
|
+
const mcpNode = findNodeAtLocation(tree, ['mcp']);
|
|
59
|
+
const mcp = mcpNode && getNodeValue(mcpNode);
|
|
60
|
+
if (mcp && Object.values(mcp).some((value) => value?.type === 'local' || value?.type === 'remote')) {
|
|
61
|
+
throw new InstallerError('This file uses OpenCode V1 MCP settings. Migrate its MCP section to V2 before running setup.');
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const currentNode = findNodeAtLocation(tree, path);
|
|
66
|
+
const current = currentNode ? structuredClone(getNodeValue(currentNode)) : undefined;
|
|
67
|
+
const conflict = currentNode !== undefined && !isDeepStrictEqual(current, entry);
|
|
68
|
+
const indent = source.match(/^[ \t]+(?=")/m)?.[0] ?? ' ';
|
|
69
|
+
const options = { formattingOptions: { insertSpaces: !indent.includes('\t'), tabSize: indent.length, eol: source.includes('\r\n') ? '\r\n' : '\n' } };
|
|
70
|
+
let content = source;
|
|
71
|
+
if (!isDeepStrictEqual(current, entry)) content = applyEdits(content, modify(content, path, entry, options));
|
|
72
|
+
if (client === 'opencode' && name === 'machinal') {
|
|
73
|
+
const legacy = findNodeAtLocation(tree, ['mcp', 'servers', 'directional']);
|
|
74
|
+
if (legacy && getNodeValue(legacy)?.url === entry.url) {
|
|
75
|
+
content = applyEdits(content, modify(content, ['mcp', 'servers', 'directional'], undefined, options));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (client === 'opencode' && !findNodeAtLocation(tree, ['$schema'])) {
|
|
79
|
+
content = applyEdits(content, modify(content, ['$schema'], 'https://opencode.ai/config.json', options));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return { content: bom + content, conflict };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function parseConfigTOML(source) {
|
|
86
|
+
try {
|
|
87
|
+
const ast = parseTOML(source, { tomlVersion: '1.0.0' });
|
|
88
|
+
return { ast, value: getStaticTOMLValue(ast) };
|
|
89
|
+
} catch {
|
|
90
|
+
throw new InstallerError('The Codex configuration is not valid TOML. It was left unchanged.');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function withoutServer(value, name) {
|
|
95
|
+
const copy = structuredClone(value);
|
|
96
|
+
if (copy.mcp_servers) {
|
|
97
|
+
delete copy.mcp_servers[name];
|
|
98
|
+
if (!Object.keys(copy.mcp_servers).length) delete copy.mcp_servers;
|
|
99
|
+
}
|
|
100
|
+
return copy;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function updateTOML(original, name, entry) {
|
|
104
|
+
const bom = original.startsWith('\uFEFF') ? '\uFEFF' : '';
|
|
105
|
+
const source = original.slice(bom.length);
|
|
106
|
+
const { ast, value } = parseConfigTOML(source);
|
|
107
|
+
const servers = value.mcp_servers;
|
|
108
|
+
if (servers !== undefined && (!servers || typeof servers !== 'object' || Array.isArray(servers))) {
|
|
109
|
+
throw new InstallerError('Codex mcp_servers must be a table. The configuration was left unchanged.');
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const current = servers && Object.hasOwn(servers, name) ? servers[name] : undefined;
|
|
113
|
+
if (isDeepStrictEqual(current, entry)) return { content: original, conflict: false };
|
|
114
|
+
|
|
115
|
+
const tables = ast.body[0].body.filter((node) => node.type === 'TOMLTable'
|
|
116
|
+
&& node.resolvedKey[0] === 'mcp_servers' && node.resolvedKey[1] === name);
|
|
117
|
+
if (current !== undefined && !tables.some((node) => node.resolvedKey.length === 2 && node.kind === 'standard')) {
|
|
118
|
+
throw new InstallerError('Use a standard [mcp_servers.NAME] table for this server, or choose a new --name. No settings were changed.');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
let content = source;
|
|
122
|
+
for (const table of tables.toSorted((left, right) => right.range[0] - left.range[0])) {
|
|
123
|
+
content = content.slice(0, table.range[0]) + content.slice(table.range[1]);
|
|
124
|
+
}
|
|
125
|
+
const eol = source.includes('\r\n') ? '\r\n' : '\n';
|
|
126
|
+
const section = [`[mcp_servers.${name}]`, ...Object.entries(entry).map(([key, value]) => `${key} = ${JSON.stringify(value)}`), ''].join(eol);
|
|
127
|
+
content += (content ? `${eol}${eol}` : '') + section;
|
|
128
|
+
|
|
129
|
+
let updated;
|
|
130
|
+
try {
|
|
131
|
+
updated = parseConfigTOML(content).value;
|
|
132
|
+
} catch {
|
|
133
|
+
throw new InstallerError('Cannot safely edit inline or dotted MCP tables. Use standard [mcp_servers.NAME] tables, or a new configuration. No settings were changed.');
|
|
134
|
+
}
|
|
135
|
+
if (!isDeepStrictEqual(withoutServer(value, name), withoutServer(updated, name))) {
|
|
136
|
+
throw new InstallerError('Could not preserve unrelated Codex settings. The configuration was left unchanged.');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return { content: bom + content, conflict: current !== undefined };
|
|
140
|
+
}
|
package/src/keys.mjs
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { checkConnection, normalizeEndpoint, validateAPIKey } from './connection.mjs';
|
|
2
|
+
import { InstallerError } from './errors.mjs';
|
|
3
|
+
import { API_KEYS_URL } from './presentation.mjs';
|
|
4
|
+
|
|
5
|
+
async function promptKey({ interactive, ui, log, verbose }) {
|
|
6
|
+
if (!interactive) throw new InstallerError(`No API key is available. Create one at ${API_KEYS_URL}, then supply MACHINAL_API_KEY securely, save a key with key set on Windows, or rerun in an interactive terminal for hidden entry. Nothing was saved.`);
|
|
7
|
+
log(verbose ? `To create a new application key, open ${API_KEYS_URL} (use your own website's /api-keys page for a self-hosted account), then return here for hidden entry. Active Premium/API access is required. Never paste the key into chat.`
|
|
8
|
+
: `Create a key: open ${API_KEYS_URL} (or your self-hosted /api-keys page). Premium/API access required. Enter it only in the hidden prompt, never in chat.`);
|
|
9
|
+
return validateAPIKey(await ui.password({ message: 'machinal API key (Ctrl+C to cancel):', mask: '*', validate: (value) => {
|
|
10
|
+
try { validateAPIKey(value); return true; } catch { return `Enter the complete mach_ application key from ${API_KEYS_URL}.`; }
|
|
11
|
+
} }));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function chooseAvailableKey(value, source, context) {
|
|
15
|
+
const { interactive, ui, log } = context;
|
|
16
|
+
const location = source === 'saved' ? 'Windows Credential Manager' : 'MACHINAL_API_KEY';
|
|
17
|
+
let key;
|
|
18
|
+
try { key = validateAPIKey(value); } catch {
|
|
19
|
+
if (!interactive) throw new InstallerError(`The API key from ${location} is invalid. Use key set to replace it, key delete to remove a saved key, or --session-key to bypass saved credentials. Check MACHINAL_API_KEY if set. Create a key at ${API_KEYS_URL}. Nothing was changed.`);
|
|
20
|
+
log(`Warning: the API key from ${location} has an invalid format. You can enter a replacement without deleting the current key first.`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
if (interactive) {
|
|
24
|
+
const action = await ui.select({
|
|
25
|
+
message: `API key from ${location}`,
|
|
26
|
+
default: key ? 'reuse' : 'key',
|
|
27
|
+
choices: [
|
|
28
|
+
...(key ? [{ name: 'Use the current API key', value: 'reuse' }] : []),
|
|
29
|
+
{ name: 'Enter a different key', value: 'key', description: 'Hidden entry. The saved key is kept until you approve replacement.' },
|
|
30
|
+
{ name: 'Create a new key', value: 'create', description: API_KEYS_URL },
|
|
31
|
+
{ name: 'Cancel', value: 'cancel', description: 'Keep the current key and settings.' },
|
|
32
|
+
],
|
|
33
|
+
});
|
|
34
|
+
if (action === 'key' || action === 'create') return { key: await promptKey(context), source: 'prompt' };
|
|
35
|
+
if (action !== 'reuse' || !key) throw new InstallerError('Cancelled. The current API key and settings were not changed.');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!interactive) log(`Using the API key from ${location}.`);
|
|
39
|
+
return { key, source };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function readKey(context, { sessionOnly = false } = {}) {
|
|
43
|
+
const { env, credentialStore, log } = context;
|
|
44
|
+
const environmentKey = env.MACHINAL_API_KEY || env.DIRECTION_API_KEY;
|
|
45
|
+
if (environmentKey) return chooseAvailableKey(environmentKey, 'environment', context);
|
|
46
|
+
|
|
47
|
+
if (credentialStore && !sessionOnly) {
|
|
48
|
+
let saved;
|
|
49
|
+
try { saved = await credentialStore.read(); } catch (error) {
|
|
50
|
+
if (!context.interactive) throw error;
|
|
51
|
+
log('Warning: Windows Credential Manager is unavailable. Continue with hidden entry for this session; no saved credential will be changed unless you approve saving after verification.');
|
|
52
|
+
return { key: await promptKey(context), source: 'prompt' };
|
|
53
|
+
}
|
|
54
|
+
if (saved !== null) return chooseAvailableKey(saved, 'saved', context);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return { key: await promptKey(context), source: 'prompt' };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function offerKeyStorage(credentials, context, { sessionOnly = false } = {}) {
|
|
61
|
+
const { credentialStore, interactive, ui, log } = context;
|
|
62
|
+
if (!credentialStore || !interactive || sessionOnly || credentials.source === 'saved') return;
|
|
63
|
+
|
|
64
|
+
let previous;
|
|
65
|
+
try {
|
|
66
|
+
previous = await credentialStore.read();
|
|
67
|
+
} catch {
|
|
68
|
+
log('Warning: Windows Credential Manager is unavailable. The key has not been saved; it is available for this session only.');
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (previous === credentials.key) return;
|
|
72
|
+
|
|
73
|
+
const message = previous === null
|
|
74
|
+
? 'Remember this API key in Windows Credential Manager on this device?'
|
|
75
|
+
: 'Replace the API key saved in Windows Credential Manager with this key?';
|
|
76
|
+
if (!await ui.confirm({ message, default: false })) return;
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
await credentialStore.write(credentials.key);
|
|
80
|
+
log(context.verbose ? 'API key saved in Windows Credential Manager. The automatic OpenCode MCP integration will load it and reconnect; legacy launcher sessions also read it.'
|
|
81
|
+
: 'API key saved in Windows Credential Manager. OpenCode will load it automatically.');
|
|
82
|
+
const environmentKey = context.env.MACHINAL_API_KEY || context.env.DIRECTION_API_KEY;
|
|
83
|
+
if (environmentKey && environmentKey.trim() !== credentials.key) {
|
|
84
|
+
log('Warning: an API-key environment variable still contains a different key and takes precedence next time. Unset it before launching to use the saved replacement. Running clients were not changed.');
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
log('Warning: the API key could not be saved in Windows Credential Manager. Use it for this session or retry with key set. No plaintext fallback is used.');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function manageKey(action, values, context) {
|
|
92
|
+
if (!['set', 'delete'].includes(action)) throw new InstallerError('Use key set or key delete.');
|
|
93
|
+
const { credentialStore, interactive, ui, log, env } = context;
|
|
94
|
+
if (!credentialStore) throw new InstallerError('Saved-key management is currently supported only on Windows. Use MACHINAL_API_KEY or hidden entry on this platform.');
|
|
95
|
+
|
|
96
|
+
if (action === 'set') {
|
|
97
|
+
if (!interactive) throw new InstallerError('Run key set in an interactive terminal. The new key must be entered through the hidden prompt, never command arguments.');
|
|
98
|
+
const endpoint = values.url === undefined ? null : normalizeEndpoint(values.url);
|
|
99
|
+
const key = await promptKey(context);
|
|
100
|
+
if (endpoint) {
|
|
101
|
+
log('Checking the replacement key against MCP before changing Windows Credential Manager (no paid operations)...');
|
|
102
|
+
await (context.checkConnection ?? checkConnection)(endpoint, key);
|
|
103
|
+
log('MCP verified: the replacement API key was accepted. The saved key has not been changed yet.');
|
|
104
|
+
}
|
|
105
|
+
if (!await ui.confirm({ message: 'Save this key in Windows Credential Manager, replacing any previously saved key?', default: false })) {
|
|
106
|
+
log('Saved API key was not changed.');
|
|
107
|
+
return 0;
|
|
108
|
+
}
|
|
109
|
+
await credentialStore.write(key);
|
|
110
|
+
log(endpoint
|
|
111
|
+
? 'API key saved in Windows Credential Manager after successful MCP verification.'
|
|
112
|
+
: 'API key saved in Windows Credential Manager. Its format was checked; run setup to verify API access.');
|
|
113
|
+
log('The automatic OpenCode MCP integration picks up saved-key changes without restarting OpenCode. Existing clients without that integration still use their previous key; use launch opencode / launch claude / launch codex for legacy environment-based connections.');
|
|
114
|
+
} else {
|
|
115
|
+
if (!values.yes && !interactive) throw new InstallerError('Run key delete interactively, or use key delete --yes to explicitly confirm removal.');
|
|
116
|
+
if (!values.yes && !await ui.confirm({ message: 'Delete the API key saved in Windows Credential Manager?', default: false })) {
|
|
117
|
+
log('Saved API key was not changed.');
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
const deleted = await credentialStore.delete();
|
|
121
|
+
log(deleted ? 'Saved API key deleted from Windows Credential Manager.' : 'No API key was saved in Windows Credential Manager.');
|
|
122
|
+
log('This does not revoke the key in your account or remove it from running clients or environment variables.');
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (env.MACHINAL_API_KEY || env.DIRECTION_API_KEY) log('An API-key environment variable is set and still takes precedence over the saved key. Unset it before launching if you want to use saved credentials.');
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
package/src/launch.mjs
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import crossSpawn from 'cross-spawn';
|
|
2
|
+
import { InstallerError } from './errors.mjs';
|
|
3
|
+
import { validateAPIKey } from './connection.mjs';
|
|
4
|
+
|
|
5
|
+
export async function launchClient(client, key, { args = [], cwd = process.cwd(), env = process.env, spawn = crossSpawn, unkeyed = false } = {}) {
|
|
6
|
+
if (!['opencode', 'claude', 'codex'].includes(client)) throw new InstallerError('Choose opencode, claude, or codex.');
|
|
7
|
+
if (client === 'opencode' && args.some((arg) => arg === '--server' || arg.startsWith('--server='))) {
|
|
8
|
+
throw new InstallerError('Launch uses a private OpenCode server so it can inherit the key. --server is not supported.');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const commandArgs = client === 'opencode' ? ['--standalone', ...args] : args;
|
|
12
|
+
const apiKey = unkeyed ? undefined : validateAPIKey(key);
|
|
13
|
+
const child = spawn(client, commandArgs, {
|
|
14
|
+
cwd,
|
|
15
|
+
env: {
|
|
16
|
+
...env,
|
|
17
|
+
...(unkeyed ? {} : { MACHINAL_API_KEY: apiKey,
|
|
18
|
+
DIRECTION_API_KEY: apiKey,
|
|
19
|
+
MACHINAL_MCP_USE_ENV_KEY: '1',
|
|
20
|
+
DIRECTION_MCP_USE_ENV_KEY: '1' }),
|
|
21
|
+
},
|
|
22
|
+
stdio: 'inherit',
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
child.once('error', () => reject(new InstallerError('Could not start the client. Install its CLI and make sure it is on PATH. MCP configuration has not been removed.')));
|
|
27
|
+
child.once('exit', (code, signal) => resolve(code ?? (signal === 'SIGINT' ? 130 : 1)));
|
|
28
|
+
});
|
|
29
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, readFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { parseEnv } from 'node:util';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
import { findCheckout, runDocker } from './docker.mjs';
|
|
7
|
+
import { localCredentials } from './bridge.mjs';
|
|
8
|
+
import { planTextFile, saveConfiguration } from './configuration.mjs';
|
|
9
|
+
|
|
10
|
+
const MODELS = ['OPENROUTER_MODEL', 'OPENROUTER_SCENE_MODEL', 'OPENROUTER_STT_MODEL'];
|
|
11
|
+
|
|
12
|
+
async function fileExists(file) {
|
|
13
|
+
try { const info = await lstat(file); if (!info.isFile() || info.isSymbolicLink()) throw new Error(); return true; } catch (error) {
|
|
14
|
+
if (error.code === 'ENOENT') return false;
|
|
15
|
+
throw new InstallerError('The local profile is not a readable regular file. No provider settings were replaced.');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function providerKey(value) {
|
|
20
|
+
const key = value?.trim();
|
|
21
|
+
if (!/^sk-or-v1-[a-f\d]{64}$/i.test(key ?? '')) throw new InstallerError('Enter a complete OpenRouter key (sk-or-v1-…) through hidden entry or OPENROUTER_API_KEY, never command arguments.');
|
|
22
|
+
return key;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function providers(context) {
|
|
26
|
+
const { env, interactive, ui } = context;
|
|
27
|
+
let key = env.OPENROUTER_API_KEY;
|
|
28
|
+
if (!key && interactive) key = await ui.password({ message: 'Your OpenRouter API key (hidden; charged directly by OpenRouter)', mask: '*',
|
|
29
|
+
validate: (value) => { try { providerKey(value); return true; } catch (error) { return error.message; } } });
|
|
30
|
+
const values = { OPENROUTER_API_KEY: providerKey(key) };
|
|
31
|
+
for (const name of MODELS) {
|
|
32
|
+
const fallback = name === 'OPENROUTER_SCENE_MODEL' ? values.OPENROUTER_MODEL : '';
|
|
33
|
+
const hint = name === 'OPENROUTER_MODEL' ? 'required' : name === 'OPENROUTER_SCENE_MODEL' ? 'optional; falls back to OPENROUTER_MODEL' : 'optional; empty disables transcription';
|
|
34
|
+
const value = interactive ? await ui.input({ message: `${name} (${hint})`,
|
|
35
|
+
default: env[name] || fallback || '', required: name === 'OPENROUTER_MODEL' }) : env[name] || fallback || '';
|
|
36
|
+
if ((name === 'OPENROUTER_MODEL' && !value) || (value && !/^[\w~./:@+-]{1,200}$/.test(value))) {
|
|
37
|
+
throw new InstallerError(`Set ${name} to a provider/model identifier, not a URL or credential.`);
|
|
38
|
+
}
|
|
39
|
+
values[name] = value;
|
|
40
|
+
}
|
|
41
|
+
return values;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function prepareIndependentLocal(values, endpoint, localConfig, context) {
|
|
45
|
+
const { cwd, interactive, ui, log } = context;
|
|
46
|
+
if (new URL(endpoint).protocol !== 'http:') throw new InstallerError('The generated independent Docker profile uses HTTP on loopback only. Use --mode server for an existing TLS deployment.');
|
|
47
|
+
const directory = dirname(localConfig);
|
|
48
|
+
const composeFile = join(directory, 'compose.json');
|
|
49
|
+
let existing;
|
|
50
|
+
if (await fileExists(localConfig)) {
|
|
51
|
+
const key = await localCredentials(localConfig, endpoint);
|
|
52
|
+
existing = { key, values: parseEnv(await readFile(localConfig, 'utf8')) };
|
|
53
|
+
if (!values['configure-local']) return { key, localConfig, start: () => startLocal(composeFile, context, values) };
|
|
54
|
+
}
|
|
55
|
+
let checkout = await findCheckout(cwd, values['docker-dir']);
|
|
56
|
+
if (!checkout && interactive) {
|
|
57
|
+
const path = await ui.input({ message: 'Machinal source checkout folder (Docker builds locally)', required: true });
|
|
58
|
+
checkout = await findCheckout(cwd, path);
|
|
59
|
+
}
|
|
60
|
+
if (!checkout) throw new InstallerError('Independent local mode needs Docker/Compose and a Machinal source checkout. Use --docker-dir PATH. No public image is assumed and no Machinal account/API key is needed.');
|
|
61
|
+
const configuration = await providers(context);
|
|
62
|
+
const approved = values['start-docker'] || (interactive && await ui.confirm({
|
|
63
|
+
message: `Save provider secrets outside the project (${directory}) and build/start the independent local API + renderer? This uses disk/CPU and may download build dependencies. OpenRouter charges your own key. No Machinal credits, account or PocketBase.`, default: false,
|
|
64
|
+
}));
|
|
65
|
+
if (!approved) throw new InstallerError('Local setup cancelled. No provider files or containers were changed. --yes alone does not authorize Docker startup; use --start-docker.');
|
|
66
|
+
const key = existing?.key ?? `local_${randomBytes(32).toString('hex')}`;
|
|
67
|
+
const sceneToken = existing?.values.SCENE_SERVICE_TOKEN ?? randomBytes(32).toString('hex');
|
|
68
|
+
const settings = { ...configuration, MACHINAL_LOCAL_URL: endpoint, MACHINAL_MODE: 'local', MACHINAL_LOCAL_CONTAINER: '1',
|
|
69
|
+
MACHINAL_LOCAL_TOKEN: key, SCENE_SERVICE_TOKEN: sceneToken, SCENE_SERVICE_URL: 'http://scene-renderer:8091', DATA_DIR: '/data' };
|
|
70
|
+
const port = new URL(endpoint).port || '80';
|
|
71
|
+
const host = new URL(endpoint).hostname === '[::1]' ? '[::1]' : '127.0.0.1';
|
|
72
|
+
const compose = {
|
|
73
|
+
name: `machinal-local-${directory.split(/[\\/]/).at(-1)}`,
|
|
74
|
+
services: {
|
|
75
|
+
api: { build: { context: join(checkout, 'api'), target: 'runtime' }, ports: [`${host}:${port}:8080`],
|
|
76
|
+
env_file: [localConfig], volumes: ['local-data:/data'], depends_on: ['scene-renderer'], restart: 'unless-stopped', stop_grace_period: '45s' },
|
|
77
|
+
'scene-renderer': { init: true, build: { context: join(checkout, 'services', 'scene-renderer'), target: 'service',
|
|
78
|
+
additional_contexts: { 'client-source': join(checkout, 'client') } },
|
|
79
|
+
environment: { SCENE_SERVICE_TOKEN: sceneToken, SCENE_CACHE_DIR: '/var/cache/scene', SCENE_WORKERS: 'auto' },
|
|
80
|
+
volumes: ['scene-cache:/var/cache/scene', 'scene-work:/tmp'], shm_size: '1gb', mem_limit: '3g', cpus: 4, pids_limit: 256,
|
|
81
|
+
read_only: true, tmpfs: ['/home/scene:rw,nosuid,size=64m,uid=10001,gid=10001'], cap_drop: ['ALL'], security_opt: ['no-new-privileges:true'], restart: 'unless-stopped' },
|
|
82
|
+
},
|
|
83
|
+
volumes: { 'local-data': {}, 'scene-cache': {}, 'scene-work': {} },
|
|
84
|
+
};
|
|
85
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
86
|
+
const profilePlan = await planTextFile(localConfig, Object.entries(settings).map(([name, value]) => `${name}='${value}'`).join('\n') + '\n');
|
|
87
|
+
const composePlan = await planTextFile(composeFile, JSON.stringify(compose, null, 2));
|
|
88
|
+
await saveConfiguration({ ...profilePlan, mode: 0o600 });
|
|
89
|
+
await saveConfiguration({ ...composePlan, mode: 0o600 });
|
|
90
|
+
log(`Local provider settings saved privately: ${localConfig}. Keep this file and its backups out of version control.`);
|
|
91
|
+
await startLocal(composeFile, context, { ...values, 'start-docker': true });
|
|
92
|
+
return { key, localConfig, start: () => startLocal(composeFile, context, values) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function startLocal(composeFile, context, values) {
|
|
96
|
+
const { interactive, ui, log, env } = context;
|
|
97
|
+
if (!await fileExists(composeFile)) throw new InstallerError('The local Compose profile is missing. Rerun setup --mode local --configure-local --docker-dir PATH.');
|
|
98
|
+
const docker = context.docker ?? ((args, options = {}) => runDocker(args, { env, cwd: dirname(composeFile), ...options }));
|
|
99
|
+
await docker(['info', '--format', '{{.ServerVersion}}']);
|
|
100
|
+
const host = !env.DOCKER_CONTEXT && env.DOCKER_HOST ? env.DOCKER_HOST
|
|
101
|
+
: await docker(['context', 'inspect', ...(env.DOCKER_CONTEXT ? [env.DOCKER_CONTEXT] : []), '--format', '{{.Endpoints.docker.Host}}']);
|
|
102
|
+
if (!/^(unix:|npipe:|tcp:\/\/(localhost|127\.0\.0\.1|\[::1\])(?::|\/|$))/.test(host)) throw new InstallerError('Local mode requires a local Docker daemon. No remote daemon was changed.');
|
|
103
|
+
await docker(['compose', 'version', '--short']);
|
|
104
|
+
if (!values['start-docker'] && !(interactive && await ui.confirm({ message: 'Start the saved independent local Docker profile? Existing data volumes are preserved.', default: false }))) {
|
|
105
|
+
throw new InstallerError('Local API is unavailable. Start its saved Docker profile or rerun with --start-docker. The MCP adapter can still report the connection problem.');
|
|
106
|
+
}
|
|
107
|
+
log('Building/starting the independent local API and renderer. Detailed output stays private; first build may take several minutes.');
|
|
108
|
+
await docker(['compose', '-f', resolve(composeFile), 'up', '-d', '--build', '--wait', '--wait-timeout', '180'], { timeout: 20 * 60_000, discardOutput: true });
|
|
109
|
+
}
|