@machinal/mcp 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +366 -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 +287 -0
- package/src/cli.mjs +157 -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/endpoints.mjs +3 -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 +31 -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 +69 -0
- package/src/setup-stdio.mjs +116 -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/cli.mjs
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { parseArgs } from 'node:util';
|
|
2
|
+
import { confirm, input, password, select } from '@inquirer/prompts';
|
|
3
|
+
import { InstallerError } from './errors.mjs';
|
|
4
|
+
import { createCredentialStore } from './credential-store.mjs';
|
|
5
|
+
import { manageKey, offerKeyStorage, readKey } from './keys.mjs';
|
|
6
|
+
import { launchClient } from './launch.mjs';
|
|
7
|
+
import { chooseClient, EDITING_STYLES } from './setup-options.mjs';
|
|
8
|
+
import { setup } from './setup.mjs';
|
|
9
|
+
import { setupStdio } from './setup-stdio.mjs';
|
|
10
|
+
import { serveBridge, MCPBridge } from './bridge.mjs';
|
|
11
|
+
import { VERSION } from './version.mjs';
|
|
12
|
+
import { createLogger } from './presentation.mjs';
|
|
13
|
+
import { createPromptUI } from './prompts.mjs';
|
|
14
|
+
|
|
15
|
+
const HELP = `machinal MCP setup (Node.js 22.13+ or 24+)
|
|
16
|
+
|
|
17
|
+
npx @machinal/mcp setup
|
|
18
|
+
npx @machinal/mcp setup --client opencode --mode server
|
|
19
|
+
npx @machinal/mcp setup --client codex --mode custom --url https://YOUR-API/mcp
|
|
20
|
+
npx @machinal/mcp setup --client claude --mode local --docker-dir PATH
|
|
21
|
+
npx @machinal/mcp doctor --url https://YOUR-API/mcp
|
|
22
|
+
npx @machinal/mcp launch opencode
|
|
23
|
+
npx @machinal/mcp launch codex -- --help
|
|
24
|
+
npx @machinal/mcp key set Save or replace the key (Windows)
|
|
25
|
+
npx @machinal/mcp key set --url https://YOUR-API/mcp
|
|
26
|
+
npx @machinal/mcp key delete Remove the saved key (Windows)
|
|
27
|
+
|
|
28
|
+
Options for setup:
|
|
29
|
+
--client opencode|claude|codex
|
|
30
|
+
--scope project|global Default: global for Codex, project otherwise
|
|
31
|
+
--mode server|local|custom Machinal Server | independent Local | custom API
|
|
32
|
+
--mode hosted Compatibility alias for server
|
|
33
|
+
--url URL Custom server URL or optional local URL override
|
|
34
|
+
--docker-dir PATH Local: machinal source checkout
|
|
35
|
+
--start-docker Local: explicitly allow build/start if needed
|
|
36
|
+
--configure-local Explicitly replace saved local provider settings
|
|
37
|
+
--defer-login Server: install now with Login required
|
|
38
|
+
--transport stdio|http Default: resilient stdio; http is advanced compatibility
|
|
39
|
+
--name NAME Default: machinal
|
|
40
|
+
--replace Replace this named server only
|
|
41
|
+
--style STYLE Named editorial profile (see below)
|
|
42
|
+
--no-skills Do not install the bundled agent skills
|
|
43
|
+
--replace-skills Back up and replace changed bundled files
|
|
44
|
+
--yes No confirmations; requires --client
|
|
45
|
+
--no-launch Configure without launching the agent client
|
|
46
|
+
--verbose Show full setup, credit and authentication details
|
|
47
|
+
--help, -h Show help
|
|
48
|
+
--version, -v Show version
|
|
49
|
+
|
|
50
|
+
Options for setup/launch:
|
|
51
|
+
--session-key Ignore saved keys; do not offer to save
|
|
52
|
+
|
|
53
|
+
Options for key delete:
|
|
54
|
+
--yes Explicitly confirm removal without a prompt
|
|
55
|
+
|
|
56
|
+
Options for key set:
|
|
57
|
+
--url URL Verify MCP access before replacing the saved key
|
|
58
|
+
|
|
59
|
+
Machinal Server uses https://api.machinal.app/mcp automatically; no URL prompt.
|
|
60
|
+
It reads MACHINAL_API_KEY, Windows Credential Manager, or hidden entry.
|
|
61
|
+
Custom server asks for your own API URL; --url also selects custom mode for legacy scripts.
|
|
62
|
+
Opt-in Windows saving uses Credential Manager, not plaintext client config.
|
|
63
|
+
Local mode asks for OPENROUTER_API_KEY and model settings, builds the source
|
|
64
|
+
checkout with Docker, and keeps private provider settings outside the project.
|
|
65
|
+
Local requires no Machinal account, subscription, credits or PocketBase.
|
|
66
|
+
OpenRouter usage is charged directly to your own key; local rendering uses your CPU.
|
|
67
|
+
--yes alone never authorizes Docker startup; use --start-docker explicitly.
|
|
68
|
+
The stdio adapter starts even without login or a reachable backend. Its free
|
|
69
|
+
connection_status tool reports Login required / Connection unavailable / Connected
|
|
70
|
+
and reconnects discovery without retrying jobs. Host MCP badges belong to the client;
|
|
71
|
+
native Needs authentication labels require OAuth, not application API keys.
|
|
72
|
+
Codex defaults to global config; project settings require a trusted project.
|
|
73
|
+
No key is accepted in arguments or chat. Setup never generates media or spends AI credits.
|
|
74
|
+
Server keys: https://machinal.app/api-keys (your own website for self-hosting).
|
|
75
|
+
|
|
76
|
+
Styles: ${EDITING_STYLES.join(', ')}.
|
|
77
|
+
`;
|
|
78
|
+
|
|
79
|
+
function parseOptions(argv) {
|
|
80
|
+
const separator = argv.indexOf('--');
|
|
81
|
+
const forwarded = separator < 0 ? [] : argv.slice(separator + 1);
|
|
82
|
+
let parsed;
|
|
83
|
+
try {
|
|
84
|
+
parsed = parseArgs({
|
|
85
|
+
args: separator < 0 ? argv : argv.slice(0, separator),
|
|
86
|
+
allowPositionals: true,
|
|
87
|
+
options: {
|
|
88
|
+
client: { type: 'string' }, scope: { type: 'string' }, mode: { type: 'string' }, url: { type: 'string' }, name: { type: 'string' },
|
|
89
|
+
replace: { type: 'boolean' }, yes: { type: 'boolean' }, 'no-launch': { type: 'boolean' }, verbose: { type: 'boolean' },
|
|
90
|
+
style: { type: 'string' }, 'no-skills': { type: 'boolean' }, 'replace-skills': { type: 'boolean' },
|
|
91
|
+
'session-key': { type: 'boolean' },
|
|
92
|
+
'docker-dir': { type: 'string' }, 'start-docker': { type: 'boolean' },
|
|
93
|
+
transport: { type: 'string' }, 'defer-login': { type: 'boolean' }, 'configure-local': { type: 'boolean' },
|
|
94
|
+
'local-config': { type: 'string' }, 'catalog-file': { type: 'string' },
|
|
95
|
+
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean', short: 'v' },
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
} catch {
|
|
99
|
+
throw new InstallerError('Invalid options. Run --help. API keys must use MACHINAL_API_KEY or the hidden prompt, never command arguments.');
|
|
100
|
+
}
|
|
101
|
+
return { ...parsed, forwarded };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function run(argv = process.argv.slice(2), runtime = {}) {
|
|
105
|
+
const { values, positionals, forwarded } = parseOptions(argv);
|
|
106
|
+
if (values.help) { console.log(HELP); return 0; }
|
|
107
|
+
if (values.version) { console.log(VERSION); return 0; }
|
|
108
|
+
const command = positionals[0] ?? 'setup';
|
|
109
|
+
if (command === 'serve' || command === 'doctor') {
|
|
110
|
+
const allowed = ['url', 'local-config', 'catalog-file'];
|
|
111
|
+
if (positionals.length !== 1 || forwarded.length || !values.url || Object.keys(values).some((key) => !allowed.includes(key))) throw new InstallerError('serve/doctor require --url and accept only --local-config and --catalog-file.');
|
|
112
|
+
const options = { url: values.url, localConfig: values['local-config'], catalogFile: values['catalog-file'] };
|
|
113
|
+
if (command === 'serve') return serveBridge(options, runtime);
|
|
114
|
+
const bridge = new MCPBridge({ ...options, env: runtime.env ?? process.env, credentialStore: runtime.credentialStore ?? createCredentialStore() });
|
|
115
|
+
console.log(JSON.stringify(await bridge.connect(), null, 2));
|
|
116
|
+
return bridge.state.status === 'connected' ? 0 : 1;
|
|
117
|
+
}
|
|
118
|
+
const context = {
|
|
119
|
+
env: process.env, cwd: process.cwd(), launch: launchClient,
|
|
120
|
+
credentialStore: createCredentialStore(),
|
|
121
|
+
...runtime,
|
|
122
|
+
interactive: !values.yes && (runtime.interactive ?? (process.stdin.isTTY && process.stdout.isTTY)),
|
|
123
|
+
};
|
|
124
|
+
context.ui ??= createPromptUI({ confirm, input, password, select }, { env: context.env });
|
|
125
|
+
context.verbose = values.verbose || !context.interactive;
|
|
126
|
+
context.log ??= createLogger({ env: context.env });
|
|
127
|
+
if (command === 'key' && positionals.length === 2 && ['set', 'delete'].includes(positionals[1]) && !forwarded.length) {
|
|
128
|
+
const allowed = positionals[1] === 'set' ? ['url'] : ['yes'];
|
|
129
|
+
if (Object.keys(values).some((option) => !allowed.includes(option))) {
|
|
130
|
+
throw new InstallerError('key set accepts only --url; key delete accepts only --yes. Run --help.');
|
|
131
|
+
}
|
|
132
|
+
return manageKey(positionals[1], values, context);
|
|
133
|
+
}
|
|
134
|
+
if (command === 'setup' && positionals.length <= 1 && !forwarded.length) {
|
|
135
|
+
if (values.transport && !['stdio', 'http'].includes(values.transport)) throw new InstallerError('Choose --transport stdio (default) or http (advanced).');
|
|
136
|
+
if (values['local-config'] || values['catalog-file']) throw new InstallerError('Local profile/catalog paths are managed by setup, not provided as setup arguments.');
|
|
137
|
+
if (values.transport === 'http') {
|
|
138
|
+
if (values['defer-login'] || values['configure-local']) throw new InstallerError('--defer-login and --configure-local require the default stdio adapter.');
|
|
139
|
+
if (values.mode === 'local') context.log('Advanced HTTP compatibility mode uses the existing authenticated self-hosted API. Omit --transport http for independent local mode.');
|
|
140
|
+
return setup(values, context);
|
|
141
|
+
}
|
|
142
|
+
return setupStdio(values, context);
|
|
143
|
+
}
|
|
144
|
+
if (command === 'launch' && positionals.length <= 2) {
|
|
145
|
+
if (['scope', 'mode', 'url', 'name', 'replace', 'no-launch', 'style', 'no-skills', 'replace-skills', 'start-docker', 'docker-dir', 'verbose', 'transport', 'defer-login', 'configure-local', 'local-config', 'catalog-file'].some((option) => values[option] !== undefined)) {
|
|
146
|
+
throw new InstallerError('Setup-only options cannot be used with launch. Run --help.');
|
|
147
|
+
}
|
|
148
|
+
if (values.client && positionals[1]) throw new InstallerError('Specify the launch client only once.');
|
|
149
|
+
const client = await chooseClient(positionals[1] || values.client, context);
|
|
150
|
+
const keyOptions = { sessionOnly: values['session-key'] };
|
|
151
|
+
const credentials = await readKey(context, keyOptions);
|
|
152
|
+
await offerKeyStorage(credentials, context, keyOptions);
|
|
153
|
+
const { key } = credentials;
|
|
154
|
+
return context.launch(client, key, { args: forwarded, cwd: context.cwd, env: context.env });
|
|
155
|
+
}
|
|
156
|
+
throw new InstallerError('Use setup, launch, key set, or key delete. Run --help for examples.');
|
|
157
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { InstallerError } from './errors.mjs';
|
|
6
|
+
import { bridgeEntry, serverEntry, updateJSON, updateTOML } from './formats.mjs';
|
|
7
|
+
import { configureOpenCodeAuth, removeOpenCodeAuthServer } from './opencode-configuration.mjs';
|
|
8
|
+
|
|
9
|
+
const MAX_CONFIG_BYTES = 2 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
async function exists(file) {
|
|
12
|
+
try {
|
|
13
|
+
await lstat(file);
|
|
14
|
+
return true;
|
|
15
|
+
} catch (error) {
|
|
16
|
+
if (error.code === 'ENOENT') return false;
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function chooseJSONFile(directory) {
|
|
22
|
+
const json = join(directory, 'opencode.json');
|
|
23
|
+
const jsonc = join(directory, 'opencode.jsonc');
|
|
24
|
+
const [hasJSON, hasJSONC] = await Promise.all([exists(json), exists(jsonc)]);
|
|
25
|
+
if (hasJSON && hasJSONC) {
|
|
26
|
+
throw new InstallerError('Both opencode.json and opencode.jsonc exist in the target directory. Consolidate them before setup.');
|
|
27
|
+
}
|
|
28
|
+
return hasJSON ? json : jsonc;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function configurationPath({ client, scope, cwd = process.cwd(), home = homedir(), env = process.env }) {
|
|
32
|
+
if (!['project', 'global'].includes(scope)) throw new InstallerError('Choose project or global scope.');
|
|
33
|
+
if (client === 'opencode') {
|
|
34
|
+
if (scope === 'global') return chooseJSONFile(join(env.XDG_CONFIG_HOME || join(home, '.config'), 'opencode'));
|
|
35
|
+
const nested = join(cwd, '.opencode');
|
|
36
|
+
if (await exists(join(nested, 'opencode.json')) || await exists(join(nested, 'opencode.jsonc'))) {
|
|
37
|
+
return chooseJSONFile(nested);
|
|
38
|
+
}
|
|
39
|
+
return chooseJSONFile(cwd);
|
|
40
|
+
}
|
|
41
|
+
if (client === 'claude') {
|
|
42
|
+
if (scope === 'global' && env.CLAUDE_CONFIG_DIR) {
|
|
43
|
+
throw new InstallerError('Custom CLAUDE_CONFIG_DIR is not supported for global setup. Use project scope or the Claude CLI.');
|
|
44
|
+
}
|
|
45
|
+
return scope === 'global' ? join(home, '.claude.json') : join(cwd, '.mcp.json');
|
|
46
|
+
}
|
|
47
|
+
if (client === 'codex') return join(scope === 'global' ? env.CODEX_HOME || join(home, '.codex') : join(cwd, '.codex'), 'config.toml');
|
|
48
|
+
throw new InstallerError('Choose opencode, claude, or codex.');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function snapshot(file) {
|
|
52
|
+
try {
|
|
53
|
+
const stat = await lstat(file);
|
|
54
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
55
|
+
throw new InstallerError('The target configuration must be a regular file, not a symlink.');
|
|
56
|
+
}
|
|
57
|
+
if (stat.size > MAX_CONFIG_BYTES) throw new InstallerError('The configuration exceeds the 2 MiB safety limit.');
|
|
58
|
+
return { original: await readFile(file, 'utf8'), mode: stat.mode & 0o777 };
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error.code === 'ENOENT') return { original: null, mode: 0o600 };
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function planConfiguration(options) {
|
|
66
|
+
if (!/^[a-z\d][a-z\d_-]{0,63}$/i.test(options.name)) {
|
|
67
|
+
throw new InstallerError('Server names must start with a letter or number and contain at most 64 letters, numbers, hyphens, or underscores.');
|
|
68
|
+
}
|
|
69
|
+
const file = await configurationPath(options);
|
|
70
|
+
const previous = await snapshot(file);
|
|
71
|
+
const entry = options.transport === 'stdio' ? bridgeEntry(options.client, options) : serverEntry(options.client, options.url);
|
|
72
|
+
const updated = options.client === 'codex'
|
|
73
|
+
? updateTOML(previous.original ?? '', options.name, entry)
|
|
74
|
+
: updateJSON(previous.original ?? '', options.client, options.name, entry);
|
|
75
|
+
const automaticAuth = options.client === 'opencode' && !options.localConfig && (options.platform ?? process.platform) === 'win32';
|
|
76
|
+
if (automaticAuth) updated.content = configureOpenCodeAuth(updated.content, options.name, options.url, options.transport === 'stdio' ? entry.command : undefined);
|
|
77
|
+
if (options.client === 'opencode' && options.localConfig) updated.content = removeOpenCodeAuthServer(updated.content, options.name);
|
|
78
|
+
return { file, ...previous, ...updated, automaticAuth };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function planTextFile(file, content) {
|
|
82
|
+
return { file, ...await snapshot(file), content };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function writeExclusive(file, content, mode) {
|
|
86
|
+
const handle = await open(file, 'wx', mode);
|
|
87
|
+
try {
|
|
88
|
+
await handle.writeFile(content, 'utf8');
|
|
89
|
+
await handle.sync();
|
|
90
|
+
} finally {
|
|
91
|
+
await handle.close();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function ensureParentDirectory(file, { mkdirImpl = mkdir } = {}) {
|
|
96
|
+
const directory = dirname(file);
|
|
97
|
+
if (dirname(directory) !== directory) await mkdirImpl(directory, { recursive: true });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function saveConfiguration(plan) {
|
|
101
|
+
try {
|
|
102
|
+
return await writeConfiguration(plan);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
if (error instanceof InstallerError) throw error;
|
|
105
|
+
if (['EACCES', 'EPERM'].includes(error.code)) {
|
|
106
|
+
throw new InstallerError(`Could not save the client configuration: access denied (${error.code}). Run setup from a writable project folder or choose global scope. Check filesystem permissions and read-only/locked files.`);
|
|
107
|
+
}
|
|
108
|
+
if (['ENOSPC', 'EDQUOT'].includes(error.code)) {
|
|
109
|
+
throw new InstallerError('Could not save the client configuration: disk space or quota exhausted. Free some space and retry.');
|
|
110
|
+
}
|
|
111
|
+
throw new InstallerError('Could not save the client configuration. Check the target directory, write permissions, available disk space, and locked files.');
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function writeConfiguration(plan) {
|
|
116
|
+
if (plan.original === plan.content) return { changed: false };
|
|
117
|
+
await ensureParentDirectory(plan.file);
|
|
118
|
+
const lock = `${plan.file}.machinal-lock`;
|
|
119
|
+
let handle;
|
|
120
|
+
try {
|
|
121
|
+
handle = await open(lock, 'wx', 0o600);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error.code === 'EEXIST') throw new InstallerError('Another setup may be editing this configuration. Retry after it finishes; inspect any stale .machinal-lock file.');
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const temporary = `${plan.file}.machinal-${randomUUID()}.tmp`;
|
|
128
|
+
try {
|
|
129
|
+
if ((await snapshot(plan.file)).original !== plan.original) {
|
|
130
|
+
throw new InstallerError('The configuration changed during setup. Run setup again; no settings were overwritten.');
|
|
131
|
+
}
|
|
132
|
+
let backup;
|
|
133
|
+
if (plan.original !== null) {
|
|
134
|
+
backup = `${plan.file}.machinal-backup-${Date.now()}-${randomUUID()}`;
|
|
135
|
+
await writeExclusive(backup, plan.original, 0o600);
|
|
136
|
+
}
|
|
137
|
+
await writeExclusive(temporary, plan.content, plan.mode);
|
|
138
|
+
if ((await snapshot(plan.file)).original !== plan.original) {
|
|
139
|
+
throw new InstallerError('The configuration changed during setup. Run setup again; no settings were overwritten.');
|
|
140
|
+
}
|
|
141
|
+
await rename(temporary, plan.file);
|
|
142
|
+
return { changed: true, backup };
|
|
143
|
+
} finally {
|
|
144
|
+
await unlink(temporary).catch((error) => { if (error.code !== 'ENOENT') throw error; });
|
|
145
|
+
await handle.close();
|
|
146
|
+
await unlink(lock);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { InstallerError } from './errors.mjs';
|
|
2
|
+
import { VERSION } from './version.mjs';
|
|
3
|
+
import { parseCreditSummary } from './credits.mjs';
|
|
4
|
+
import { API_KEYS_URL, MEMBERSHIP_URL } from './presentation.mjs';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
|
|
7
|
+
const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
8
|
+
const PROTOCOL_VERSION = '2025-11-25';
|
|
9
|
+
const SUPPORTED_VERSIONS = new Set(['2025-03-26', '2025-06-18', PROTOCOL_VERSION]);
|
|
10
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
11
|
+
const MEDIA_WORKFLOW_TOOLS = ['request_media_access', 'list_media', 'get_asset_metadata', 'get_upload_target', 'get_media_download', 'get_video_result', 'get_download_preferences', 'set_download_preferences', 'wait_for_job', 'revoke_delivery_link'];
|
|
12
|
+
|
|
13
|
+
export function isLoopbackEndpoint(endpoint) {
|
|
14
|
+
return LOOPBACK_HOSTS.has(new URL(endpoint).hostname);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function normalizeEndpoint(value) {
|
|
18
|
+
let url;
|
|
19
|
+
try {
|
|
20
|
+
url = new URL(value);
|
|
21
|
+
} catch {
|
|
22
|
+
throw new InstallerError('Enter an absolute API URL, such as https://your-api.example/mcp.');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
26
|
+
throw new InstallerError('The API URL must not contain credentials, a query, or a fragment.');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname))) {
|
|
30
|
+
throw new InstallerError('HTTPS is required, except for localhost, 127.0.0.1, or [::1] development.');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!['/', '/mcp', '/mcp/'].includes(url.pathname)) {
|
|
34
|
+
throw new InstallerError('Enter the API origin or its /mcp endpoint, not a frontend page or /v1 route.');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
url.pathname = '/mcp';
|
|
38
|
+
return url.href;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function validateAPIKey(value) {
|
|
42
|
+
const key = value?.trim();
|
|
43
|
+
if (!/^(?:mach_|dal_)[a-fA-F\d]{64}$/.test(key ?? '')) {
|
|
44
|
+
throw new InstallerError(`Use a complete machinal application key (mach_… or a legacy dal_… key) from ${API_KEYS_URL}, not a login or provider token. For self-hosting, use the /api-keys page of your own website.`);
|
|
45
|
+
}
|
|
46
|
+
return key;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function readJSON(response) {
|
|
50
|
+
if (!response.headers.get('content-type')?.toLowerCase().startsWith('application/json')) {
|
|
51
|
+
await response.body?.cancel();
|
|
52
|
+
throw new InstallerError('The endpoint did not return MCP JSON. Check the API URL and proxy configuration.');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const reader = response.body?.getReader();
|
|
56
|
+
if (!reader) throw new InstallerError('The MCP response was empty.');
|
|
57
|
+
|
|
58
|
+
const chunks = [];
|
|
59
|
+
let size = 0;
|
|
60
|
+
try {
|
|
61
|
+
while (true) {
|
|
62
|
+
const { done, value } = await reader.read();
|
|
63
|
+
if (done) break;
|
|
64
|
+
size += value.byteLength;
|
|
65
|
+
if (size > MAX_RESPONSE_BYTES) {
|
|
66
|
+
await reader.cancel();
|
|
67
|
+
throw new InstallerError('The MCP response exceeded the 2 MiB safety limit.');
|
|
68
|
+
}
|
|
69
|
+
chunks.push(value);
|
|
70
|
+
}
|
|
71
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error instanceof InstallerError) throw error;
|
|
74
|
+
throw new InstallerError('The endpoint returned an invalid or interrupted MCP response.');
|
|
75
|
+
} finally {
|
|
76
|
+
reader.releaseLock();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function httpError(status) {
|
|
81
|
+
if (status === 401) return `Authentication failed (401). Create or replace your application key at ${API_KEYS_URL} (your own website's /api-keys for self-hosting). Check active Premium/API access. Use key set to replace a saved key, or --session-key for hidden entry.`;
|
|
82
|
+
if (status === 402) return `Active Premium/API access is required (402). Check ${MEMBERSHIP_URL} or your self-hosted account subscription before connecting.`;
|
|
83
|
+
if (status === 403) return `Access denied (403). Check Premium/API access at ${MEMBERSHIP_URL} and the server origin policy.`;
|
|
84
|
+
if (status === 429) return 'The API is rate limited (429). Wait before trying setup again.';
|
|
85
|
+
return `MCP connection failed (HTTP ${status}). Check the API URL and backend availability.`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function checkConnection(endpoint, apiKey, { fetchImpl = fetch, timeout = 15_000, attempts = 3, sleep = delay, local = false } = {}) {
|
|
89
|
+
const url = normalizeEndpoint(endpoint);
|
|
90
|
+
const key = local && isLoopbackEndpoint(url) && /^local_[a-f\d]{64}$/.test(apiKey ?? '') ? apiKey : validateAPIKey(apiKey);
|
|
91
|
+
const describeHTTPError = (status) => local && [401, 402, 403].includes(status)
|
|
92
|
+
? `The endpoint rejected the independent local device token (HTTP ${status}). Check the saved local profile and ensure this is the independent local backend, not an authenticated Server deployment. No Machinal login is required for independent local mode.`
|
|
93
|
+
: httpError(status);
|
|
94
|
+
const signal = AbortSignal.timeout(timeout);
|
|
95
|
+
const maxAttempts = Number.isInteger(attempts) ? Math.max(1, Math.min(attempts, 3)) : 3;
|
|
96
|
+
|
|
97
|
+
async function requestOnce(message, version) {
|
|
98
|
+
let response;
|
|
99
|
+
try {
|
|
100
|
+
response = await fetchImpl(url, {
|
|
101
|
+
method: 'POST',
|
|
102
|
+
redirect: 'error',
|
|
103
|
+
signal,
|
|
104
|
+
headers: {
|
|
105
|
+
Authorization: `Bearer ${key}`,
|
|
106
|
+
Accept: 'application/json, text/event-stream',
|
|
107
|
+
'Content-Type': 'application/json',
|
|
108
|
+
...(version ? { 'MCP-Protocol-Version': version } : {}),
|
|
109
|
+
},
|
|
110
|
+
body: JSON.stringify({ jsonrpc: '2.0', ...message }),
|
|
111
|
+
});
|
|
112
|
+
} catch (error) {
|
|
113
|
+
const transient = signal.aborted || ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'UND_ERR_SOCKET', 'UND_ERR_CONNECT_TIMEOUT'].includes(error.cause?.code);
|
|
114
|
+
throw new InstallerError(`Could not reach the MCP endpoint. ${isLoopbackEndpoint(url) ? 'Make sure the local API/container is running and the port is correct; Local mode can help start Docker.' : 'Check the server URL, TLS, and network.'} Redirects are not followed.`, { code: 'network', retryable: transient });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!response.ok) {
|
|
118
|
+
await response.body?.cancel();
|
|
119
|
+
throw new InstallerError(describeHTTPError(response.status), { status: response.status, retryable: [502, 503, 504].includes(response.status) });
|
|
120
|
+
}
|
|
121
|
+
if (message.id === undefined) {
|
|
122
|
+
await response.body?.cancel();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const reply = await readJSON(response);
|
|
127
|
+
if (reply?.jsonrpc !== '2.0' || reply.id !== message.id || reply.error || !reply.result) {
|
|
128
|
+
throw new InstallerError('The endpoint rejected the MCP handshake or discovery request.');
|
|
129
|
+
}
|
|
130
|
+
return reply.result;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function request(message, version) {
|
|
134
|
+
for (let attempt = 1; ; attempt++) {
|
|
135
|
+
try { return await requestOnce(message, version); } catch (error) {
|
|
136
|
+
if (!error.retryable || signal.aborted || attempt >= maxAttempts) throw error;
|
|
137
|
+
await sleep(250 * attempt);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const initialized = await request({
|
|
143
|
+
id: 1,
|
|
144
|
+
method: 'initialize',
|
|
145
|
+
params: {
|
|
146
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
147
|
+
capabilities: {},
|
|
148
|
+
clientInfo: { name: 'machinal-mcp-setup', version: VERSION },
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
const serverName = initialized.serverInfo?.name;
|
|
153
|
+
if (typeof serverName !== 'string' || serverName.toLowerCase() !== 'machinal' || !SUPPORTED_VERSIONS.has(initialized.protocolVersion)) {
|
|
154
|
+
throw new InstallerError('This is not a supported machinal MCP endpoint. No configuration was saved.');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
await request({ method: 'notifications/initialized' }, initialized.protocolVersion);
|
|
158
|
+
const catalog = await request({ id: 2, method: 'tools/list', params: {} }, initialized.protocolVersion);
|
|
159
|
+
const names = new Set(Array.isArray(catalog.tools) ? catalog.tools.map((tool) => tool?.name) : []);
|
|
160
|
+
if (!names.has('list_projects') || !names.has('get_recipe_schema')) {
|
|
161
|
+
throw new InstallerError('The endpoint is missing the expected machinal tools. Update the API before connecting.');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const result = { toolCount: catalog.tools.length, tools: catalog.tools, instructions: initialized.instructions, credits: null };
|
|
165
|
+
if (MEDIA_WORKFLOW_TOOLS.some((name) => !names.has(name))) {
|
|
166
|
+
result.mediaWarning = 'Full media workflow unavailable: update the API for consent tools, volume uploads, bounded job waits, opaque revocable download links and optional client-local delivery. Installed instructions do not add missing server capabilities.';
|
|
167
|
+
}
|
|
168
|
+
if (!names.has('get_editing_reference')) {
|
|
169
|
+
result.referenceWarning = 'Live editing reference unavailable: update the API for get_editing_reference. Installed guides are offline snapshots; verify the deployed schema/catalog.';
|
|
170
|
+
}
|
|
171
|
+
if (!names.has('get_credits')) {
|
|
172
|
+
return { ...result, creditsWarning: 'Live credits unavailable: this API does not expose get_credits. Update the API; no balance was assumed.' };
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
const wallet = await request({ id: 3, method: 'tools/call', params: { name: 'get_credits', arguments: {} } }, initialized.protocolVersion);
|
|
176
|
+
const output = wallet.structuredContent;
|
|
177
|
+
if (local && !wallet.isError && output?.statusCode === 200 && output.data?.mode === 'local' && output.data?.machinalCreditsRequired === false) {
|
|
178
|
+
return { ...result, local: true, creditsWarning: 'Local mode: no Machinal credits or subscription. Provider usage is billed directly to your own API key.' };
|
|
179
|
+
}
|
|
180
|
+
if ([401, 402, 403].includes(output?.statusCode)) throw new InstallerError(describeHTTPError(output.statusCode), { status: output.statusCode });
|
|
181
|
+
if (!wallet.isError && output?.statusCode === 200) result.credits = parseCreditSummary(output.data);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if ([401, 402, 403].includes(error.status)) throw error;
|
|
184
|
+
}
|
|
185
|
+
if (!result.credits) result.creditsWarning = 'Live credits unavailable: the API could not return a verified balance. No balance was assumed; check billing before paid work.';
|
|
186
|
+
return result;
|
|
187
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { InstallerError } from './errors.mjs';
|
|
2
|
+
|
|
3
|
+
export const WINDOWS_CREDENTIAL = Object.freeze({
|
|
4
|
+
service: 'Machinal/mcp',
|
|
5
|
+
account: 'MACHINAL_API_KEY',
|
|
6
|
+
target: 'Machinal/mcp.MACHINAL_API_KEY',
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
const LEGACY_WINDOWS_CREDENTIAL = Object.freeze({
|
|
10
|
+
service: 'direction.al/mcp',
|
|
11
|
+
account: 'DIRECTION_API_KEY',
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export function createCredentialStore({
|
|
15
|
+
platform = process.platform,
|
|
16
|
+
load = () => import('@napi-rs/keyring'),
|
|
17
|
+
service = WINDOWS_CREDENTIAL.service,
|
|
18
|
+
account = WINDOWS_CREDENTIAL.account,
|
|
19
|
+
} = {}) {
|
|
20
|
+
if (platform !== 'win32') return null;
|
|
21
|
+
|
|
22
|
+
let modulePromise;
|
|
23
|
+
let entry;
|
|
24
|
+
let legacyEntry;
|
|
25
|
+
const getModule = () => modulePromise ??= load();
|
|
26
|
+
const getEntry = () => entry ??= getModule().then(({ AsyncEntry }) => new AsyncEntry(service, account));
|
|
27
|
+
const canReadLegacy = service === WINDOWS_CREDENTIAL.service && account === WINDOWS_CREDENTIAL.account;
|
|
28
|
+
const getLegacyEntry = () => legacyEntry ??= getModule().then(({ AsyncEntry }) => new AsyncEntry(
|
|
29
|
+
LEGACY_WINDOWS_CREDENTIAL.service, LEGACY_WINDOWS_CREDENTIAL.account,
|
|
30
|
+
));
|
|
31
|
+
|
|
32
|
+
return {
|
|
33
|
+
async read() {
|
|
34
|
+
try {
|
|
35
|
+
const current = await (await getEntry()).getPassword();
|
|
36
|
+
if (current != null || !canReadLegacy) return current;
|
|
37
|
+
return await (await getLegacyEntry()).getPassword();
|
|
38
|
+
} catch {
|
|
39
|
+
throw new InstallerError('Could not read Windows Credential Manager. Retry, or use --session-key to bypass saved credentials.');
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
async write(key) {
|
|
43
|
+
try {
|
|
44
|
+
await (await getEntry()).setPassword(key);
|
|
45
|
+
} catch {
|
|
46
|
+
throw new InstallerError('Could not save the API key in Windows Credential Manager. No plaintext fallback is used.');
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
async delete() {
|
|
50
|
+
try {
|
|
51
|
+
const deleted = await (await getEntry()).deleteCredential();
|
|
52
|
+
if (canReadLegacy) {
|
|
53
|
+
try { return Boolean(await (await getLegacyEntry()).deleteCredential()) || Boolean(deleted); } catch {}
|
|
54
|
+
}
|
|
55
|
+
return Boolean(deleted);
|
|
56
|
+
} catch {
|
|
57
|
+
throw new InstallerError('Could not delete the API key from Windows Credential Manager. Retry or remove its Machinal/mcp entry manually.');
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/credits.mjs
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
const BALANCE_FIELDS = ['remaining', 'monthlyRemaining', 'purchasedRemaining', 'reserved', 'debt'];
|
|
2
|
+
const numberFormat = new Intl.NumberFormat('en', { maximumFractionDigits: 2 });
|
|
3
|
+
|
|
4
|
+
function decimal(value) {
|
|
5
|
+
return typeof value === 'string' && value.length <= 48 && /^\d+(?:\.\d+)?$/.test(value) && Number.isFinite(Number(value)) && Number(value) > 0
|
|
6
|
+
? value : null;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function minimumCredits(value) {
|
|
10
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function parseCreditSummary(data) {
|
|
14
|
+
const balance = data?.balance;
|
|
15
|
+
if (!balance || BALANCE_FIELDS.some((field) => typeof balance[field] !== 'number' || !Number.isFinite(balance[field]) || balance[field] < 0)
|
|
16
|
+
|| typeof balance.usagePending !== 'boolean') return null;
|
|
17
|
+
|
|
18
|
+
const reset = typeof balance.nextReset === 'string' ? Date.parse(balance.nextReset) : NaN;
|
|
19
|
+
return {
|
|
20
|
+
balance: {
|
|
21
|
+
...Object.fromEntries(BALANCE_FIELDS.map((field) => [field, balance[field]])),
|
|
22
|
+
usagePending: balance.usagePending,
|
|
23
|
+
nextReset: Number.isFinite(reset) ? new Date(reset).toISOString() : null,
|
|
24
|
+
},
|
|
25
|
+
pricing: {
|
|
26
|
+
configured: data.pricing?.configured === true,
|
|
27
|
+
usdPerCredit: decimal(data.pricing?.usdPerCredit),
|
|
28
|
+
renderPerMinute: decimal(data.pricing?.renderPerMinute),
|
|
29
|
+
},
|
|
30
|
+
mcpPricing: data.mcpPricing?.sceneAuthoringCredits === 0 && data.mcpPricing?.serverRenderingBilled === true
|
|
31
|
+
&& data.mcpPricing?.sceneCompilationCredits === 0
|
|
32
|
+
&& data.mcpPricing?.toolSelectionCredits === 0 && typeof data.mcpPricing?.providerPricingConfigured === 'boolean'
|
|
33
|
+
? { providerPricingConfigured: data.mcpPricing.providerPricingConfigured,
|
|
34
|
+
renderPricingConfigured: data.mcpPricing.renderPricingConfigured === true,
|
|
35
|
+
renderPerMinute: decimal(data.mcpPricing.renderPerMinute),
|
|
36
|
+
sceneRenderPerMinute: decimal(data.mcpPricing.sceneRenderPerMinute),
|
|
37
|
+
speechMinimumCredits: minimumCredits(data.mcpPricing.speechMinimumCredits),
|
|
38
|
+
transcriptionMinimumCredits: minimumCredits(data.mcpPricing.transcriptionMinimumCredits) } : null,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function creditSummaryLines(summary) {
|
|
43
|
+
const { balance, pricing, mcpPricing } = summary;
|
|
44
|
+
const n = (value) => numberFormat.format(value);
|
|
45
|
+
const lines = [
|
|
46
|
+
`API credits: ${n(balance.remaining)} available (monthly ${n(balance.monthlyRemaining)}; purchased ${n(balance.purchasedRemaining)}).`,
|
|
47
|
+
'Credits are charged from actual usage after completion, not reserved for current work.',
|
|
48
|
+
];
|
|
49
|
+
if (balance.debt > 0) lines.push(`Usage awaiting payment: ${n(balance.debt)} credits.`);
|
|
50
|
+
if (balance.usagePending) lines.push('Some provider costs are still being finalized; this does not reserve the balance.');
|
|
51
|
+
if (balance.remaining < 30) lines.push(mcpPricing
|
|
52
|
+
? 'Low balance: server video/scene rendering and image, speech and caption charges follow actual usage.'
|
|
53
|
+
: 'Low balance: rendering and scene cost estimates are approximate; final charges follow actual usage.');
|
|
54
|
+
if (balance.nextReset) lines.push(`Next monthly reset (UTC): ${balance.nextReset.slice(0, 10)}.`);
|
|
55
|
+
if (mcpPricing) {
|
|
56
|
+
lines.push('MCP: the current client writes scene code without a server AI generation fee. Server video rendering AND server scene rendering are billed; compiling live source is not an encoded scene export.');
|
|
57
|
+
if (!mcpPricing.renderPricingConfigured) lines.push('Server rendering pricing is not configured. Video and scene rendering cannot start; source authoring/compilation remains available.');
|
|
58
|
+
else if (mcpPricing.renderPerMinute && mcpPricing.sceneRenderPerMinute) lines.push(`Server render pricing: video ${mcpPricing.renderPerMinute} and scenes ${mcpPricing.sceneRenderPerMinute} credits/output minute, recorded separately.`);
|
|
59
|
+
if (!mcpPricing.providerPricingConfigured) lines.push('Paid image, speech and caption pricing is not configured.');
|
|
60
|
+
else lines.push(pricing.usdPerCredit
|
|
61
|
+
? `Pricing: USD ${pricing.usdPerCredit}/credit. AI charges are known after usage.`
|
|
62
|
+
: 'Paid media charges are known after usage; no exact advance AI quote is available.');
|
|
63
|
+
if (mcpPricing.providerPricingConfigured && mcpPricing.speechMinimumCredits > 0 && mcpPricing.transcriptionMinimumCredits > 0) {
|
|
64
|
+
lines.push(`Audio minimums: speech ${n(mcpPricing.speechMinimumCredits)} and captions/transcription ${n(mcpPricing.transcriptionMinimumCredits)} credits per new provider request with verified positive usage; higher usage costs more.`);
|
|
65
|
+
}
|
|
66
|
+
return lines;
|
|
67
|
+
}
|
|
68
|
+
if (!pricing.configured) {
|
|
69
|
+
lines.push('Paid API pricing is not configured. Recipe preparation/validation is still possible.');
|
|
70
|
+
} else if (pricing.renderPerMinute && pricing.usdPerCredit) {
|
|
71
|
+
lines.push(`Pricing: ${pricing.renderPerMinute} credits/output minute; USD ${pricing.usdPerCredit}/credit. AI charges are known after usage.`);
|
|
72
|
+
} else {
|
|
73
|
+
lines.push('Exact pricing could not be displayed. Do not assume a free render or an exact AI cost.');
|
|
74
|
+
}
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function compactCreditSummaryLines(summary) {
|
|
79
|
+
const lines = creditSummaryLines(summary);
|
|
80
|
+
const important = /^(Usage awaiting payment:|Some provider costs|Low balance:|Server rendering pricing|Audio minimums:|Paid image, speech and caption pricing|Paid API pricing|Exact pricing)/;
|
|
81
|
+
return [
|
|
82
|
+
`API credits: ${numberFormat.format(summary.balance.remaining)} available.`,
|
|
83
|
+
'Server rendering and generated media are billed after usage; credits are not reserved.',
|
|
84
|
+
...lines.filter((line) => important.test(line)),
|
|
85
|
+
];
|
|
86
|
+
}
|