@machinal/mcp 0.5.0 → 0.5.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 +12 -8
- package/package.json +1 -1
- package/skills/machinal-editing/references/brief.md +2 -0
- package/skills/machinal-editing/references/workflow.md +2 -0
- package/skills/machinal-recipes/SKILL.md +2 -0
- package/skills/machinal-recipes/references/yaml.md +3 -0
- package/skills/machinal-review/SKILL.md +2 -0
- package/skills/machinal-review/references/production.md +8 -0
- package/src/bridge.mjs +22 -5
- package/src/opencode-checkpoints.mjs +23 -5
- package/src/opencode-recipes.mjs +14 -1
- package/src/opencode-tools.mjs +1 -0
- package/src/request-scheduler.mjs +45 -0
- package/src/runtime.mjs +1 -1
package/README.md
CHANGED
|
@@ -4,6 +4,10 @@ Set up **Codex, Claude Code or OpenCode V2** with a resilient stdio adapter. Cho
|
|
|
4
4
|
|
|
5
5
|
See the repository's [testing guide](../../docs/TESTING.md) for source-package and pre-publish checks.
|
|
6
6
|
|
|
7
|
+
### Version 0.5.1: bounded concurrency and recipe diagnostics
|
|
8
|
+
|
|
9
|
+
Version 0.5.1 adds separate adapter lanes for 8 reads, 8 job waits, 4 other tool calls and 2 control calls, with bounded queues and cancellation rather than a shared eight-request rejection cap. No submitted paid call is retried. Backend independent media jobs default to 4 per process (`MACHINAL_MEDIA_CONCURRENCY=1..16`); this is separate from MCP requests and render workers. Updated APIs report parse failures before caption guards, add a bounded narration/caption text-difference report and return compact `get_project` summaries (`fullResult:true` for editing). The OpenCode companion reuses project IDs and original beat contracts from approved checkpoints. See [scope, limits and activation](../../docs/MCP.md#recipe-diagnostics-and-concurrency-hardening-source-changes). npm publication does not deploy the API backend.
|
|
10
|
+
|
|
7
11
|
### Version 0.5.0: animation crafts and sound library
|
|
8
12
|
|
|
9
13
|
Version 0.5.0 bundles five additional on-demand skills: `machinal-motion`, `machinal-choreography`, `machinal-spatial`, `machinal-visual-review` and `machinal-sound`. Their source of truth is the API's `reference/animation-skills`; `npm run sync:reference` synchronizes identical native skills for all supported clients. Updated APIs expose the same content through `get_editing_reference(topic: animation-skills)` and MCP resources. Startup still loads editing/cinema only, not every craft.
|
|
@@ -41,7 +45,7 @@ Local mode detects a saved profile and reuses a running backend. With permission
|
|
|
41
45
|
|
|
42
46
|
**Migration compatibility:** existing `dal_…` keys, `DIRECTION_API_KEY` / `DIRECTION_API_ORIGIN` environment variables, and the previous Windows Credential Manager entry continue to work. New setups use `mach_…`, `MACHINAL_API_KEY` / `MACHINAL_API_ORIGIN`, and `Machinal/mcp.MACHINAL_API_KEY`; when both environment names are set, `MACHINAL_API_KEY` takes precedence. New keys are issued with the `mach_` prefix.
|
|
43
47
|
|
|
44
|
-
**Version 0.5.
|
|
48
|
+
**Version 0.5.1:** use the pinned commands below to install this release from the `@machinal` scope:
|
|
45
49
|
|
|
46
50
|
This release adds focused animation/sound skills and richer scene review guidance/templates, retaining native approved client-file uploads and language-independent video preparation. `machinal_prepare_video` loads editing/cinema startup skills; other crafts stay on demand, and scene compilation/final rendering are guarded until startup context is loaded. No keyword classifier, extra model call or automatic spending is introduced.
|
|
47
51
|
|
|
@@ -50,14 +54,14 @@ OpenCode compatibility: production startup accepts the V2 skill-list response (`
|
|
|
50
54
|
```sh
|
|
51
55
|
npx @machinal/mcp setup
|
|
52
56
|
# Machinal Server: no URL entry, only your Machinal key:
|
|
53
|
-
npx --yes @machinal/mcp@0.5.
|
|
54
|
-
npx --yes @machinal/mcp@0.5.
|
|
55
|
-
npx --yes @machinal/mcp@0.5.
|
|
57
|
+
npx --yes @machinal/mcp@0.5.1 setup --client opencode --mode server
|
|
58
|
+
npx --yes @machinal/mcp@0.5.1 setup --client codex --mode server
|
|
59
|
+
npx --yes @machinal/mcp@0.5.1 setup --client claude --scope global --mode server
|
|
56
60
|
# Independent local; the wizard asks for OpenRouter and model IDs:
|
|
57
|
-
npx --yes @machinal/mcp@0.5.
|
|
58
|
-
npx --yes @machinal/mcp@0.5.
|
|
61
|
+
npx --yes @machinal/mcp@0.5.1 setup --client codex --mode local --docker-dir /path/to/machinal
|
|
62
|
+
npx --yes @machinal/mcp@0.5.1 setup --client claude --mode local --docker-dir /path/to/machinal
|
|
59
63
|
# Your own deployment, explicitly selected:
|
|
60
|
-
npx --yes @machinal/mcp@0.5.
|
|
64
|
+
npx --yes @machinal/mcp@0.5.1 setup --client opencode --mode custom --url https://YOUR-API/mcp
|
|
61
65
|
```
|
|
62
66
|
|
|
63
67
|
The wizard asks for:
|
|
@@ -393,7 +397,7 @@ Test the npm executable/tarball path without publishing:
|
|
|
393
397
|
```sh
|
|
394
398
|
npm pack --dry-run
|
|
395
399
|
npm pack
|
|
396
|
-
npx --yes --package ./machinal-mcp-0.5.
|
|
400
|
+
npx --yes --package ./machinal-mcp-0.5.1.tgz machinal-mcp --help
|
|
397
401
|
```
|
|
398
402
|
|
|
399
403
|
The publish allowlist includes only selected `bin/*.mjs`, runtime/plugin source, portable skills, package metadata and this README. Package smoke tests reject project configs, nested agent installs, `.env`, media and old archives. No tests, local preferences or credentials are packaged.
|
package/package.json
CHANGED
|
@@ -95,4 +95,6 @@ Be honest about how media was made when asked; never pass generated material off
|
|
|
95
95
|
|
|
96
96
|
## Creative choices are not consent to access or spend
|
|
97
97
|
|
|
98
|
+
When animated scenes are proposed, explain **scene-frame rendering and final-video encoding as separate billed components** at the live configured tariffs before the initial spending approval. Include image/speech/caption provider usage separately, with uncertain amounts marked approximate/pending. Do not quote only the final encoding tariff and discover the scene-render component after assets have already been generated. A model choice or scene-style choice does not itself approve either rendering charge.
|
|
99
|
+
|
|
98
100
|
Choosing a type, duration, resolution, style, image or scene is not media-access or spending authorization. Include known permissions as separate explicit questions in the same form, rather than a second generic “approve the plan?” round. Keep listing, named-file use/download and spending scopes distinct, with a clear refusal option; approving one does not approve the others. Ask only about files and actions whose scope can already be explained, and check live credits before requesting paid-work authorization. Explain the proposed generation/render actions and approximate costs only when supported; do not promise an exact advance AI quote. If named sources or paid scope are not yet known, continue the already-authorized/free work and ask only for the missing permission once it is known. Do not repeat authorization for stages already approved within the same workflow, and never treat a cancelled form as consent. Do not run providers while collecting the brief. Keep host tool-approval controls enabled.
|
|
@@ -8,6 +8,8 @@ For cinematic direction, prettier/cinematic animation or a specific visual langu
|
|
|
8
8
|
|
|
9
9
|
Prefer directly exposed native tools when available. Discover only unknown MCP tools once, reuse their exact signatures, and read independent guides concurrently. Cache schema/capabilities and already-read references for this workflow until their deployed version/schemaHash changes; use exact preset IDs instead of repeatedly searching the full catalog. Do not use web search for MCP tool names or call suggest_tools before every operation. OpenCode's companion integration exposes the common discovery/reference/wait/result tools directly and provides native machinal_download; other clients may expose a different tool surface. These paths reduce discovery round trips, not the host web-search provider's latency.
|
|
10
10
|
|
|
11
|
+
Parallelize independent reads, not dependent recipe writes/preflights or duplicate waits for one job. The stdio adapter separates read, wait, work and control capacity; this is not an MCP-wide two-call limit. Independent provider jobs have their own configured limit in `generation.mediaConcurrency`. Respect overload/Retry-After without reconnecting for queue pressure or replaying ambiguous paid work. `get_project` defaults to compact save evidence; use `fullResult:true` before editing/saving complete state. Reuse unexpired delivery URLs instead of requesting another immediately. Parse failures precede caption comparisons; inspect `captionContentReview` separately for transcription review, not as audio evidence.
|
|
12
|
+
|
|
11
13
|
MCP scenes use `topic=scene-authoring`: the current client AI writes Svelte, `compile_scene` validates/saves source without a server-model generation fee, and example `client-scene` places the pinned asset in video tracks. `get_scene_source` supports edits. Pending scene.generate/scene.edit examples are legacy site references, not new MCP submissions. Server scene rendering AND final video rendering are billed at the configured render tariff, separately from image/TTS/caption provider charges. Source compilation and client-authored code are not server frame rendering.
|
|
12
14
|
|
|
13
15
|
## Required authoring workflow
|
|
@@ -5,6 +5,8 @@ description: Author, edit, validate and compile machinal YAML video recipes usin
|
|
|
5
5
|
|
|
6
6
|
# Schema-grounded video recipes
|
|
7
7
|
|
|
8
|
+
**Diagnose before changing data.** Invalid YAML means caption comparison was `not_checked`, not that captions changed. Fix only the actual parse diagnostic, keep the original baseline, and rerun free preflight. Never treat two empty regex matches as evidence; compare parsed complete entries and require real text/result IDs. Read `captionContentReview` after timing: verify names and omissions against approved narration/sources and ask before exact spelling corrections. Preservation hashes do not prove transcription accuracy. Reuse checkpoint project IDs rather than retyping them. `get_project` is compact by default; request `fullResult:true` before editing/saving full state. Batch independent reads, respect reported provider concurrency, and reuse the first unexpired delivery link.
|
|
9
|
+
|
|
8
10
|
**TikTok caption font.** When the brief targets TikTok or requests TikTok-style captions, NEW captions explicitly use `fontFamily: montserrat` and `fontWeight: 700`, unless the user explicitly chooses another font. Verify the deployed `fonts` entry; Montserrat is the supported TikTok-style choice, not official TikTok Sans. Set both fields in `captions.generate.style` before the timing-first pass, or flattened on newly authored manual captions; a `tiktok-pop`/`tiktok-box`/`tiktok-glow` preset name alone is not enough. Preserve existing caption fonts/configuration unless a font change is explicitly requested. Generic portrait/social output does not imply TikTok or authorize adding captions. Read `references/text-audio.md`.
|
|
9
11
|
|
|
10
12
|
**Existing captions are read-only.** Unless the user explicitly requests a caption change, preserve complete caption entries: exact `texts[].text`/`words[].text` (spaces, line breaks, punctuation, diacritics), grouping/order, IDs/`resultTextIds`, source anchors, timings, positions/fonts and all style, animation/highlighting/effects. Do not reword, trim, split/merge/reflow, reposition or restyle them while adding visuals or repairing unrelated fields. Existing caption configuration overrides style/profile/`captionMaxWords` defaults; four-word/two-line defaults apply only to NEW caption generation. The renderer handles fitting/wrapping/collision avoidance: adapt scene labels around captions, not captions around scenes; never bake/duplicate them into Svelte. Patch resolved `recipeYaml`, use `sourceJobId` for unchanged continuation, and compare complete caption entries against that baseline before submission; undo unintended changes. Validation alone does not prove preservation. Read `references/text-audio.md` for encoding-only repair exceptions; report genuine blockers and ask before other caption changes. This is not a new YAML lock flag.
|
|
@@ -58,6 +58,9 @@ To place a clip for timeline duration `D`, set `outPoint = inPoint + D * playbac
|
|
|
58
58
|
|
|
59
59
|
## Pre-submit checks
|
|
60
60
|
|
|
61
|
+
- Parse the exact edited file before interpreting caption/contract diagnostics. A parse failure means caption comparison was not performed; retain the original baseline and fix indentation/syntax rather than reordering tracks or dropping guards. Preserve UTF-8 and use a structural YAML editor/serializer for generated edits, or a narrowly scoped patch followed immediately by free validation.
|
|
62
|
+
- Review `captionContentReview` after timing and before final rendering. It checks narration text against caption tokens, not audio, and never changes the protected entries. Verify names/omissions against approved sources, ask for exact corrections, and use the original baseline with approved text edits. Preservation and transcription accuracy are separate checks.
|
|
63
|
+
|
|
61
64
|
- Edit the existing resolved `.edit.yaml` with normal workspace tools. Preserve successful assets, speech/caption results and unrelated fields; do not reconstruct the whole document to repair one field.
|
|
62
65
|
- Compare complete caption entries and `resultTextIds` against the resolved baseline before submission; undo unintended caption changes. Preserve YAML string values, including spaces and line breaks, when choosing scalar quoting/block syntax. A successful validation/compile does not prove that captions were preserved.
|
|
63
66
|
- Write valid YAML directly or use an existing YAML serializer. Do not write an ad-hoc JSON-to-YAML emitter. `tracks`, each track's `clips`, `transitions`, `texts`, caption `words` and `assets` are lists: use `- ` entries or `[...]`, not repeated mapping keys. Keep numeric `version` distinct from quoted string compatibility pins.
|
|
@@ -5,6 +5,8 @@ description: Critique a machinal production contract before scene authoring and
|
|
|
5
5
|
|
|
6
6
|
# Video production critic
|
|
7
7
|
|
|
8
|
+
Retain the original measured beat IDs through final review, even for one long scene. Do not collapse six specific beats into a generic whole-video declaration. Where deployed, use `productionBaseline` or OpenCode's `productionContractFile`/`productionBaselineFile` and contract-bearing checkpoints to expose omissions. Compare each promised action and cut/dissolve with actual source and consent-bound sampled frames, not only compiler success. Check separate `captionContentReview` findings for names/omissions; surface real errors and ask for exact approved text corrections without changing timing/style or regenerating speech. These checks do not certify pixels, motion or audio.
|
|
9
|
+
|
|
8
10
|
Read `get_editing_reference(topic: production)` (offline: `references/production.md`) after the brief. Keep the existing scene-engine. Do not repeat the brief, request a separate plan confirmation, change media scope or regenerate successful narration/captions/images. A small edit needs only a targeted review of the changed beat/junction.
|
|
9
11
|
|
|
10
12
|
1. **Before code:** the director writes a compact production contract using actual measured cues/supplied copy: subject-specific action, medium/assets, composition/light, independent objects, local reveal/action/hold/exit, adjacent-shot handoff and exact treatment targets or a justified cut. Critique the contract before implementation. For expressive work, reject interchangeable title cards, repeated portrait zooms and the unchanged runtime demo primitive; don't confuse rich direction with decorative clutter. Respect deliberately minimal/no-generation briefs.
|
|
@@ -72,6 +72,10 @@ Validate the exact final YAML, then use `compile_recipe` once for its normalized
|
|
|
72
72
|
|
|
73
73
|
The default response is compact: diagnostics, requirements, `planSummary`, exact `compositionVersion`, conservative `captionVersion` and the reviews below. Request `fullResult:true` only for the full normalized document/plan/recovery. `expectedCaptionVersion` on preflight/generation/render rejects changes to any existing text entry or caption result ID before submission; it includes all recipe text, so authorized title/text changes require an updated baseline. OpenCode can save new `checkpointFile` artifacts alongside the resolved `recipeFile`, use `captionBaselineFile` for subsequent visual-only edits and read a preflight `checkpointFile` on paid calls to apply the reviewed hash automatically. No hand-copied hash, repeated generation or caption reconstruction is necessary. Checkpoints do not grant permission or aesthetic approval.
|
|
74
74
|
|
|
75
|
+
Parsing precedes caption/contract comparisons. A malformed recipe returns its actual parse diagnostic and `captionReview.status=not_checked`; it is not evidence of caption mutation. Repair the syntax only, keep the original caption guard and rerun free preflight. An empty baseline/current text comparison returns `not_applicable`, never successful preservation evidence. Prefer structured parsed comparisons, not regex checks that can accidentally compare two empty strings.
|
|
76
|
+
|
|
77
|
+
`captionContentReview` is a separate, bounded comparison of one resolved narration's text with its materialized same-language captions. It flags spelling/name substitutions and omitted/extra tokens with caption IDs. `review_required` is not an audio finding: punctuation/case are normalized for comparison only, never changed in the recipe. Empty/ambiguous/over-limit inputs are `not_checked`. Review names against approved factual sources and surface real errors before final rendering. Ask permission for exact text replacements and use the intact caption baseline plus `captionTextEdits`/`captionEditsApproved`; never regenerate successful speech or change caption timings/grouping/styles. A preservation hash alone cannot certify transcription accuracy.
|
|
78
|
+
|
|
75
79
|
- `status: not_ready`: no complete normalized plan, pending requirements or compile errors. Do not accept a draft as final.
|
|
76
80
|
- `status: review_required`: the plan is available for the current client's critic. This does **not** mean approved or aesthetically successful.
|
|
77
81
|
- `junctions`: each same-track cut, gap, declared transition or implicit cross-dissolve, with actual clip IDs and seconds. Other tracks may cover a per-track gap; it is not automatically a blank output.
|
|
@@ -91,6 +95,10 @@ Close the critic's major findings using evidence or report the blocker; do not s
|
|
|
91
95
|
|
|
92
96
|
`compile_recipe` optionally accepts `productionContract` as a TOOL argument, never as a recipe YAML field. With or without a contract it adds `productionReview`, unless the authoritative response leaves insufficient room. Missing/truncated review is never approval. `compositionVersion` is SHA-256 of the exact UTF-8 YAML bytes, including whitespace. Obtain it from an initial compile or compute that hash in the current client; do not change the recipe just to create a review. After any edit reconcile the contract and use the new version. The original compiler document/captions remain untouched.
|
|
93
97
|
|
|
98
|
+
Keep the original beat IDs and each promised action/handoff through final review, even when all beats share one long scene clip. Do not replace a multi-beat contract with one generic whole-video declaration. Optional `productionBaseline` compares the original structured contract with the reconciled contract and reports `missing_original_beat`/`revision_required` for omissions. In OpenCode, `productionContractFile` reads an approved local JSON contract, `checkpointFile` retains it, and `productionBaselineFile` reuses that original contract-bearing checkpoint. These are tool inputs, not recipe fields. A baseline proves identity coverage only, not that an action string corresponds to visible pixels; compare each beat with exact source and consent-bound sampled frames. If a crossfade was promised but source uses a hard cut/flash, repair it or explicitly reconcile the treatment with the brief; compiler success does not close that finding.
|
|
99
|
+
|
|
100
|
+
For composition tools, `projectId` may be omitted only when an approved baseline/preflight checkpoint supplies it. Conflicting project IDs fail before execution. Prefer that recorded ID over manual transcription. `get_project` returns compact save-verification evidence by default; use `fullResult=true` before editing/saving the complete state. Never submit its summary to `save_project`.
|
|
101
|
+
|
|
94
102
|
Contract shape (replace placeholders with real clip IDs and pinned source versions):
|
|
95
103
|
|
|
96
104
|
```json
|
package/src/bridge.mjs
CHANGED
|
@@ -6,9 +6,11 @@ import { normalizeEndpoint, validateAPIKey, isLoopbackEndpoint } from './connect
|
|
|
6
6
|
import { createCredentialStore } from './credential-store.mjs';
|
|
7
7
|
import { VERSION } from './version.mjs';
|
|
8
8
|
import { MACHINAL_SERVER_URL } from './endpoints.mjs';
|
|
9
|
+
import { RequestScheduler, requestClass, requestLimits } from './request-scheduler.mjs';
|
|
9
10
|
|
|
10
11
|
const MAX_REQUEST = 4 * 1024 * 1024;
|
|
11
12
|
const MAX_RESPONSE = 2 * 1024 * 1024;
|
|
13
|
+
const MAX_PENDING_REQUESTS = 64;
|
|
12
14
|
const PROTOCOL = '2025-11-25';
|
|
13
15
|
const VERSIONS = ['2025-03-26', '2025-06-18', PROTOCOL];
|
|
14
16
|
const CLIENT_VERSIONS = ['2024-11-05', ...VERSIONS];
|
|
@@ -82,6 +84,7 @@ export class MCPBridge {
|
|
|
82
84
|
|
|
83
85
|
status() {
|
|
84
86
|
return { ...this.state, transport: 'connected', mode: this.localConfig ? 'local' : 'server', endpoint: this.url,
|
|
87
|
+
requestConcurrency: requestLimits,
|
|
85
88
|
credentialSource: this.credentialSource ?? 'unchecked',
|
|
86
89
|
...(this.localConfig ? {} : { credentialStore: this.credentialStore?.description ?? { supported: false } }),
|
|
87
90
|
service: this.localConfig ? 'Local' : this.url === MACHINAL_SERVER_URL ? 'Machinal Server' : 'Custom server',
|
|
@@ -125,8 +128,11 @@ export class MCPBridge {
|
|
|
125
128
|
body: JSON.stringify({ jsonrpc: '2.0', ...(id !== undefined ? { id } : {}), method, ...(params ? { params } : {}) }),
|
|
126
129
|
});
|
|
127
130
|
if (!response.ok) {
|
|
131
|
+
const retryAfter = response.headers.get('retry-after');
|
|
128
132
|
await response.body?.cancel();
|
|
129
|
-
throw Object.assign(new Error('Service unavailable'), { status: response.status
|
|
133
|
+
throw Object.assign(new Error('Service unavailable'), { status: response.status,
|
|
134
|
+
...(/^\d{1,5}$/.test(retryAfter ?? '') ? { retryAfter: Math.min(86400, Number(retryAfter)) } : {}),
|
|
135
|
+
});
|
|
130
136
|
}
|
|
131
137
|
if (notification) { await response.body?.cancel(); return; }
|
|
132
138
|
const reply = await jsonResponse(response);
|
|
@@ -145,7 +151,9 @@ export class MCPBridge {
|
|
|
145
151
|
service_error: 'The endpoint did not provide a compatible Machinal MCP service. Check its URL/version.',
|
|
146
152
|
connection_unavailable: 'Connection unavailable: check the API/container, URL, TLS and network. The MCP adapter is still running.',
|
|
147
153
|
};
|
|
148
|
-
this.state = { status, message: messages[status], ...(error.status ? { httpStatus: error.status } : {})
|
|
154
|
+
this.state = { status, message: messages[status], ...(error.status ? { httpStatus: error.status } : {}),
|
|
155
|
+
...(Number.isInteger(error.retryAfter) && error.retryAfter >= 0 ? { retryAfter: error.retryAfter } : {}),
|
|
156
|
+
};
|
|
149
157
|
if (this.localConfig && error.status === 401) this.state = { status: 'local_configuration_required', message: 'The local device token was rejected. Rerun independent local setup; do not create a Machinal account key.' };
|
|
150
158
|
}
|
|
151
159
|
|
|
@@ -248,6 +256,7 @@ export async function serveBridge(options, { input = process.stdin, output = pro
|
|
|
248
256
|
const bridge = new MCPBridge({ ...options, ...runtime, signal: lifetime.signal, notify: send });
|
|
249
257
|
await bridge.loadCatalog();
|
|
250
258
|
const calls = new Map();
|
|
259
|
+
const scheduler = new RequestScheduler();
|
|
251
260
|
let buffer = Buffer.alloc(0);
|
|
252
261
|
const refresh = setInterval(() => {
|
|
253
262
|
void (async () => {
|
|
@@ -261,11 +270,19 @@ export async function serveBridge(options, { input = process.stdin, output = pro
|
|
|
261
270
|
if (message.jsonrpc !== '2.0' || typeof message.method !== 'string' || !['string', 'number'].includes(typeof id)) {
|
|
262
271
|
send({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } }); return;
|
|
263
272
|
}
|
|
264
|
-
if (calls.
|
|
273
|
+
if (calls.has(id)) { send({ jsonrpc: '2.0', id, error: { code: -32600, message: 'Duplicate active request ID' } }); return; }
|
|
274
|
+
if (calls.size >= MAX_PENDING_REQUESTS) { send({ jsonrpc: '2.0', id, error: { code: -32000, message: 'Request capacity reached; no operation was submitted', data: { retryAfter: 1, submissionState: 'not-submitted' } } }); return; }
|
|
265
275
|
const controller = new AbortController();
|
|
266
276
|
calls.set(id, controller);
|
|
267
|
-
try {
|
|
268
|
-
|
|
277
|
+
try {
|
|
278
|
+
const result = await scheduler.run(requestClass(message.method, message.params, bridge.tools),
|
|
279
|
+
() => bridge.handle(message.method, message.params, controller.signal), controller.signal);
|
|
280
|
+
send({ jsonrpc: '2.0', id, result });
|
|
281
|
+
} catch (error) {
|
|
282
|
+
send({ jsonrpc: '2.0', id, error: { code: error.rpcCode ?? -32603,
|
|
283
|
+
message: error.submissionState === 'not-submitted' ? 'Request queue is full; no operation was submitted' : controller.signal.aborted ? 'Request cancelled' : error.rpcCode === -32601 ? 'Method not found' : 'Could not process the request. Use connection_status.',
|
|
284
|
+
...(error.submissionState ? { data: { retryAfter: error.retryAfter, submissionState: error.submissionState } } : {}),
|
|
285
|
+
} });
|
|
269
286
|
} finally { calls.delete(id); }
|
|
270
287
|
};
|
|
271
288
|
try {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { lstat, realpath } from 'node:fs/promises';
|
|
2
2
|
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
3
|
-
import { filePermission, readBoundedUTF8, resultJSON, saveUTF8 } from './opencode-recipes.mjs';
|
|
3
|
+
import { filePermission, readBoundedUTF8, readProductionContract, resultJSON, saveUTF8 } from './opencode-recipes.mjs';
|
|
4
4
|
|
|
5
5
|
const preflightTools = ['validate_recipe', 'compile_recipe'];
|
|
6
6
|
const freeTools = [...preflightTools, 'get_job_result'];
|
|
@@ -19,14 +19,14 @@ async function checkpointPath(ctx, context, path, action) {
|
|
|
19
19
|
async function readCheckpoint(ctx, context, path, projectId) {
|
|
20
20
|
const canonical = await checkpointPath(ctx, context, path, 'read');
|
|
21
21
|
const checkpoint = JSON.parse(await readBoundedUTF8(canonical, context.signal));
|
|
22
|
-
if (checkpoint.version !== 1 || checkpoint.projectId !== projectId || !versionPattern.test(checkpoint.compositionVersion)) throw new Error('Checkpoint is invalid or belongs to another project.');
|
|
22
|
+
if (checkpoint.version !== 1 || !/^[a-z\d_-]{1,64}$/i.test(checkpoint.projectId ?? '') || projectId !== undefined && checkpoint.projectId !== projectId || !versionPattern.test(checkpoint.compositionVersion)) throw new Error('Checkpoint is invalid or belongs to another project.');
|
|
23
23
|
return checkpoint;
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
function checkpointData(output, input, operation) {
|
|
27
27
|
const data = output?.data;
|
|
28
28
|
if (output?.statusCode !== 200 || !versionPattern.test(data?.compositionVersion)) return;
|
|
29
|
-
const { compositionVersion, captionVersion, diagnostics = [], requirements = [], productionReview, editorialReview, captionReview } = data;
|
|
29
|
+
const { compositionVersion, captionVersion, diagnostics = [], requirements = [], productionReview, editorialReview, captionReview, captionContentReview } = data;
|
|
30
30
|
if (!Array.isArray(diagnostics) || !Array.isArray(requirements)) return;
|
|
31
31
|
const valid = diagnostics.every(item => item?.severity !== 'error');
|
|
32
32
|
return { version: 1, operation, projectId: input.projectId, ...(input.jobId ? { jobId: input.jobId } : {}),
|
|
@@ -34,6 +34,8 @@ function checkpointData(output, input, operation) {
|
|
|
34
34
|
valid, ready: valid && requirements.length === 0,
|
|
35
35
|
diagnostics, requirements, ...(productionReview ? { productionReview } : {}), ...(editorialReview ? { editorialReview } : {}),
|
|
36
36
|
...(captionReview ? { captionReview } : {}),
|
|
37
|
+
...(captionContentReview ? { captionContentReview } : {}),
|
|
38
|
+
...(input.productionContract ? { productionContract: input.productionContract } : {}),
|
|
37
39
|
visualInspection: false,
|
|
38
40
|
};
|
|
39
41
|
}
|
|
@@ -46,16 +48,30 @@ export async function installCheckpoints(ctx, servers) {
|
|
|
46
48
|
editor.update(`${server}_${name}`.replace(/[^a-z\d_-]/gi, '_'), tool => {
|
|
47
49
|
const original = tool.execute;
|
|
48
50
|
const paid = paidTools.includes(name);
|
|
49
|
-
tool.input = { ...tool.input, properties: { ...tool.input.properties,
|
|
51
|
+
tool.input = { ...tool.input, required: name === 'get_job_result' ? tool.input.required : (tool.input.required ?? []).filter(key => key !== 'projectId'), properties: { ...tool.input.properties,
|
|
52
|
+
projectId: { type: 'string', description: 'Owned project ID. May be omitted only when supplied by an approved checkpointFile/captionBaselineFile; conflicting project IDs are rejected before execution.' },
|
|
50
53
|
checkpointFile: { type: 'string', description: paid
|
|
51
54
|
? 'Optional saved .checkpoint.json from free preflight. Read with host permission and apply its exact compositionVersion as the server stale-review guard; never creates spending consent.'
|
|
52
55
|
: 'Optional absolute new .checkpoint.json. Save compact versions, project/job IDs and diagnostics for deterministic recovery; never overwrite.' },
|
|
53
56
|
...(name === 'get_job_result' ? {} : { captionBaselineFile: { type: 'string', description: 'Optional .checkpoint.json from the resolved baseline. Apply its captionVersion before submission to detect any changed text entry or caption resultTextIds. Omit only for authorized text edits.' } }),
|
|
57
|
+
...(name === 'compile_recipe' ? { productionBaselineFile: { type: 'string', description: 'Original contract-bearing .checkpoint.json. Verifies original beat IDs survive the final review; cannot replace caption or spending approval.' } } : {}),
|
|
54
58
|
} };
|
|
55
59
|
tool.execute = async (input, context) => {
|
|
56
|
-
const { checkpointFile, captionBaselineFile, ...args } = input;
|
|
60
|
+
const { checkpointFile, captionBaselineFile, productionBaselineFile, productionContractFile, ...args } = input;
|
|
61
|
+
if (productionContractFile !== undefined) {
|
|
62
|
+
if (name !== 'compile_recipe' || args.productionContract !== undefined) throw new Error('Use one production contract on compile_recipe only.');
|
|
63
|
+
args.productionContract = await readProductionContract(ctx, context, productionContractFile);
|
|
64
|
+
}
|
|
65
|
+
if (productionBaselineFile !== undefined) {
|
|
66
|
+
if (name !== 'compile_recipe' || args.productionBaseline !== undefined) throw new Error('Use one production baseline on compile_recipe only.');
|
|
67
|
+
const baseline = await readCheckpoint(ctx, context, productionBaselineFile, args.projectId);
|
|
68
|
+
args.projectId = baseline.projectId;
|
|
69
|
+
if (!baseline.productionContract) throw new Error('Production baseline has no original structured contract. Keep the original beat-level contract; do not substitute a generic summary.');
|
|
70
|
+
args.productionBaseline = baseline.productionContract;
|
|
71
|
+
}
|
|
57
72
|
if (captionBaselineFile !== undefined) {
|
|
58
73
|
const baseline = await readCheckpoint(ctx, context, captionBaselineFile, args.projectId);
|
|
74
|
+
args.projectId = baseline.projectId;
|
|
59
75
|
if (!versionPattern.test(baseline.captionVersion)) throw new Error('Baseline has no text/caption fingerprint. Retrieve the existing resolved result; never regenerate it.');
|
|
60
76
|
if (args.expectedCaptionVersion !== undefined && args.expectedCaptionVersion !== baseline.captionVersion) throw new Error('Conflicting caption baseline versions.');
|
|
61
77
|
args.expectedCaptionVersion = baseline.captionVersion;
|
|
@@ -64,12 +80,14 @@ export async function installCheckpoints(ctx, servers) {
|
|
|
64
80
|
if (checkpointFile !== undefined) {
|
|
65
81
|
if (paid) {
|
|
66
82
|
const checkpoint = await readCheckpoint(ctx, context, checkpointFile, args.projectId);
|
|
83
|
+
args.projectId = checkpoint.projectId;
|
|
67
84
|
const render = name === 'render_video';
|
|
68
85
|
if (!(render ? checkpoint.ready : checkpoint.valid) || !preflightTools.includes(checkpoint.operation) || render && ['revision_required', 'not_ready'].includes(checkpoint.productionReview?.status)) throw new Error('Checkpoint has unresolved preflight/review findings. Repair and save a new free preflight; no paid action was submitted.');
|
|
69
86
|
if (args.expectedCompositionVersion !== undefined && args.expectedCompositionVersion !== checkpoint.compositionVersion) throw new Error('Conflicting composition checkpoint versions.');
|
|
70
87
|
args.expectedCompositionVersion = checkpoint.compositionVersion;
|
|
71
88
|
} else destination = await checkpointPath(ctx, context, checkpointFile, 'edit');
|
|
72
89
|
}
|
|
90
|
+
if (!/^[a-z\d_-]{1,64}$/i.test(args.projectId ?? '')) throw new Error('Use an owned projectId or a matching baseline/preflight checkpoint. No project was guessed.');
|
|
73
91
|
const result = await original(args, context);
|
|
74
92
|
if (!destination) return result;
|
|
75
93
|
const output = resultJSON(result);
|
package/src/opencode-recipes.mjs
CHANGED
|
@@ -58,6 +58,14 @@ export async function saveUTF8(path, recipe, signal) {
|
|
|
58
58
|
return { path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
+
export async function readProductionContract(ctx, context, path) {
|
|
62
|
+
if (typeof path !== 'string' || !isAbsolute(path) || !path.endsWith('.json')) throw new Error('Use an absolute client-local production contract .json path.');
|
|
63
|
+
await filePermission(ctx, context, 'read', path);
|
|
64
|
+
const canonical = await realpath(path);
|
|
65
|
+
if (canonical !== path) await filePermission(ctx, context, 'read', canonical);
|
|
66
|
+
return JSON.parse(await readBoundedUTF8(path, context.signal));
|
|
67
|
+
}
|
|
68
|
+
|
|
61
69
|
export async function installRecipeFiles(ctx, servers) {
|
|
62
70
|
const names = [...servers];
|
|
63
71
|
await ctx.tool.transform(editor => {
|
|
@@ -72,11 +80,16 @@ export async function installRecipeFiles(ctx, servers) {
|
|
|
72
80
|
...(['validate_recipe', 'compile_recipe'].includes(name) ? {
|
|
73
81
|
captionBaselineRecipeFile: { type: 'string', description: 'Intact resolved baseline .edit.yaml for complete caption comparison. With authorized captionTextEdits, verifies only those exact text replacements and preserves every timing, ID, cue and style.' },
|
|
74
82
|
} : {}),
|
|
83
|
+
...(name === 'compile_recipe' ? { productionContractFile: { type: 'string', description: 'Absolute client-local .json containing the structured production contract. Read verbatim with host permission; keep original beat IDs and use productionBaselineFile for continuity.' } } : {}),
|
|
75
84
|
},
|
|
76
85
|
};
|
|
77
86
|
tool.description += ' OpenCode: use compositionFile to submit a local recipe without copying/retyping it into tool arguments. Existing consent, validation, idempotency and spending rules still apply.';
|
|
78
87
|
tool.execute = async (input, context) => {
|
|
79
|
-
const { compositionFile, captionBaselineRecipeFile, ...args } = input;
|
|
88
|
+
const { compositionFile, captionBaselineRecipeFile, productionContractFile, ...args } = input;
|
|
89
|
+
if (productionContractFile !== undefined) {
|
|
90
|
+
if (name !== 'compile_recipe' || args.productionContract !== undefined) throw new Error('Use one productionContractFile on compile_recipe only.');
|
|
91
|
+
args.productionContract = await readProductionContract(ctx, context, productionContractFile);
|
|
92
|
+
}
|
|
80
93
|
if (captionBaselineRecipeFile !== undefined) {
|
|
81
94
|
if (!['validate_recipe', 'compile_recipe'].includes(name) || args.captionBaseline !== undefined) throw new Error('Use one caption baseline source on free recipe preflight only.');
|
|
82
95
|
args.captionBaseline = await readRecipe(ctx, context, captionBaselineRecipeFile);
|
package/src/opencode-tools.mjs
CHANGED
|
@@ -19,6 +19,7 @@ export async function installDirectTools(ctx, servers) {
|
|
|
19
19
|
});
|
|
20
20
|
await ctx.session.hook('context', (event) => {
|
|
21
21
|
event.system.push({ type: 'text', text: 'machinal quick path: common project/preferences/credits/schema/reference/job-wait/result tools are exposed directly, so call their registered native tools without a Code Mode search. Discover only unknown tools and reuse their exact paths/signatures for this session; do not rediscover per step or use web search for MCP tool names. Read independent guides concurrently, and reuse unchanged schema/reference knowledge until schemaHash changes. For explicitly approved client-local downloads prefer machinal_download with projectId + jobId/file, or a public HTTPS url + directory + filename. It streams natively, with no PowerShell/curl/shell scripts, no key in arguments and no overwrite. A requested link stays a link; do not download unasked. Public internet downloads authorize neither project import nor media use/spending. Web search latency itself is controlled by the host search provider, not machinal.' });
|
|
22
|
+
event.system.push({ type: 'text', text: 'machinal orchestration: batch independent metadata/reference reads, not dependent recipe writes/preflights or duplicate waits for the same job. Adapter read and long-wait capacity is separate; provider concurrency is reported by get_capabilities, not a two-call MCP protocol limit. Respect Retry-After and never automatically replay ambiguous paid submissions. Reuse the first unexpired delivery URL. get_project defaults to compact save evidence; fullResult=true is required before editing/saving complete state. Retain baseline/preflight checkpoints to reuse project IDs and exact versions rather than retyping them. Check captionContentReview for names/omissions before rendering; preserving a hash is not transcription accuracy. Keep original production beat IDs and compare them through productionBaselineFile.' });
|
|
22
23
|
event.system.push({ type: 'text', text: 'machinal source uploads: for approved named files on the CLIENT computer, call the native machinal_upload with projectId, files (exact absolute paths) and userApproved:true. It streams to the configured server using the existing in-memory key; no shell scripts, credential extraction or separate login. Use its actual returned project filenames. list_local_media/inspect_local_media/import_local_media access SERVER-mounted roots only; they do not browse the client disk or select local rendering. A local stdio adapter can still use Machinal Server; inspect connection_status.mode/endpoint rather than inferring processing location from type:local. Do not call list_local_media as an upload prerequisite, or ask for mounts/local Docker when approved client upload is intended. Respect no-upload choices. If a transfer is uncertain, retain returned successful files and pending.file, inspect/recover that exact remote filename with existing source-use approval, and never automatically upload duplicates or submit paid jobs.' });
|
|
23
24
|
});
|
|
24
25
|
await ctx.session.hook('context', (event) => {
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export const requestLimits = Object.freeze({ read: 8, wait: 8, work: 4, control: 2 });
|
|
2
|
+
const maxQueuedPerClass = 16;
|
|
3
|
+
|
|
4
|
+
export function requestClass(method, params, tools = []) {
|
|
5
|
+
if (['tools/list', 'resources/list', 'resources/templates/list', 'resources/read', 'prompts/list', 'prompts/get'].includes(method)) return 'read';
|
|
6
|
+
if (method !== 'tools/call' || params?.name === 'connection_status') return 'control';
|
|
7
|
+
if (params?.name === 'wait_for_job' || params?.name === 'get_job' && params.arguments?.waitSeconds > 0) return 'wait';
|
|
8
|
+
return tools.find(tool => tool.name === params?.name)?.annotations?.readOnlyHint === true ? 'read' : 'work';
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Waiting for a slot never resubmits an operation; cancellation removes queued work.
|
|
12
|
+
export class RequestScheduler {
|
|
13
|
+
constructor(limits = requestLimits) {
|
|
14
|
+
this.lanes = new Map(Object.entries(limits).map(([name, limit]) => [name, { limit, active: 0, queue: [] }]));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async run(kind, operation, signal) {
|
|
18
|
+
const lane = this.lanes.get(kind);
|
|
19
|
+
if (!lane) throw new Error('Unknown request class');
|
|
20
|
+
signal?.throwIfAborted();
|
|
21
|
+
if (lane.active >= lane.limit) {
|
|
22
|
+
if (lane.queue.length >= maxQueuedPerClass) {
|
|
23
|
+
throw Object.assign(new Error('Request queue is full'), { rpcCode: -32000, retryAfter: 1, submissionState: 'not-submitted' });
|
|
24
|
+
}
|
|
25
|
+
await new Promise((resolve, reject) => {
|
|
26
|
+
const entry = { resolve: () => { signal?.removeEventListener('abort', abort); resolve(); } };
|
|
27
|
+
const abort = () => {
|
|
28
|
+
const index = lane.queue.indexOf(entry);
|
|
29
|
+
if (index >= 0) lane.queue.splice(index, 1);
|
|
30
|
+
reject(signal.reason);
|
|
31
|
+
};
|
|
32
|
+
lane.queue.push(entry);
|
|
33
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
34
|
+
});
|
|
35
|
+
} else lane.active++;
|
|
36
|
+
try {
|
|
37
|
+
signal?.throwIfAborted();
|
|
38
|
+
return await operation();
|
|
39
|
+
} finally {
|
|
40
|
+
const next = lane.queue.shift();
|
|
41
|
+
if (next) next.resolve();
|
|
42
|
+
else lane.active--;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/runtime.mjs
CHANGED
|
@@ -10,7 +10,7 @@ export { stateDirectory } from './paths.mjs';
|
|
|
10
10
|
const ROOT = fileURLToPath(new URL('../', import.meta.url));
|
|
11
11
|
const FILES = ['bin/machinal-stdio.mjs', 'src/bridge.mjs', 'src/connection.mjs', 'src/credential-store.mjs',
|
|
12
12
|
'src/credits.mjs', 'src/endpoints.mjs', 'src/errors.mjs', 'src/presentation.mjs', 'src/paths.mjs',
|
|
13
|
-
'src/private-json.mjs', 'src/version.mjs', 'package.json'];
|
|
13
|
+
'src/private-json.mjs', 'src/request-scheduler.mjs', 'src/version.mjs', 'package.json'];
|
|
14
14
|
|
|
15
15
|
export function isManagedRuntimeCommand(command, context = {}) {
|
|
16
16
|
if (!Array.isArray(command) || !isAbsolute(command[1] ?? '')) return false;
|