diff --git a/changelog/2026-11-24-model-cycles-device-load.md b/changelog/2026-11-24-model-cycles-device-load.md new file mode 100644 index 0000000000..2139cffb61 --- /dev/null +++ b/changelog/2026-11-24-model-cycles-device-load.md @@ -0,0 +1 @@ +The developer MCP's `device_load` reads the audio load of a Model:Cycles running a Modwerk base over its link (`--elektron-midi`). diff --git a/changelog/2026-11-24-model-cycles-device-log.md b/changelog/2026-11-24-model-cycles-device-log.md new file mode 100644 index 0000000000..08110bd5f4 --- /dev/null +++ b/changelog/2026-11-24-model-cycles-device-log.md @@ -0,0 +1 @@ +The developer MCP's `device_log` reads the diagnostics log of a Model:Cycles running a Modwerk base through the link's `log` request (`--elektron-midi`), with the Octatrack's parser. diff --git a/changelog/2026-11-24-model-cycles-device-status.md b/changelog/2026-11-24-model-cycles-device-status.md new file mode 100644 index 0000000000..779fd63c8a --- /dev/null +++ b/changelog/2026-11-24-model-cycles-device-status.md @@ -0,0 +1 @@ +The developer MCP's `device_status` reads a Model:Cycles running a Modwerk base over its link (`--elektron-midi`) and names the build it runs from a folder of your own images. diff --git a/changelog/2026-11-24-model-cycles-device-trial.md b/changelog/2026-11-24-model-cycles-device-trial.md new file mode 100644 index 0000000000..5956b8a90c --- /dev/null +++ b/changelog/2026-11-24-model-cycles-device-trial.md @@ -0,0 +1 @@ +The developer MCP loads modules onto a Model:Cycles running a Modwerk base over its link: `device_review`, `device_trial`, `device_keep` and `device_undo`, one change a trial, and `device_status` lists the live modules. A Keep or Undo the unit refuses (while a pattern plays) leaves the trial on to try again, and `device_status` says when a trial was lost, or kept by a Keep whose answer went missing. diff --git a/changelog/2026-11-25-link-wire-shared.md b/changelog/2026-11-25-link-wire-shared.md new file mode 100644 index 0000000000..13f8dff64e --- /dev/null +++ b/changelog/2026-11-25-link-wire-shared.md @@ -0,0 +1 @@ +The Digitone II and the Model:Cycles share one client for the link's SysEx wire (`link-wire.ts`): header, requests, replies and the 7-bit numbers and blocks. Each keeps its own commands and status wording, and "no answer" names no machine. diff --git a/docs/FRONTEND_MCP.md b/docs/FRONTEND_MCP.md index c43fb65e23..710b28ca09 100644 --- a/docs/FRONTEND_MCP.md +++ b/docs/FRONTEND_MCP.md @@ -281,6 +281,55 @@ counterpart for; once a Zoom base loads modules over USB, that goes behind `device_review`, `device_trial`, Keep and Undo, as the [recipe](MACHINE_RECIPE.md) asks. Tests run against `fakeZoomPedal`. +### A Model:Cycles over its link + +```sh +node scripts/frontend-mcp.mjs --data-dir /private/path/modwerk-mcp --elektron-midi [--elektron-images DIR] [--allow-device-writes] +``` + +With `--elektron-midi` alone, `device_status` asks a Model:Cycles running a +Modwerk base (release or development) for its link identity over USB MIDI +([LINK.md](../sdk/machines/model-cycles/LINK.md)): link version, port, arm, +counters, the RAM boot's result and the set identity the base took at boot. +`build` names the `.syx` in `--elektron-images` (a private folder of your own +builds, never committed) whose set identity matches, or is `null`. +`device_load` reads the audio's share of the CPU from the base's load probe +(the link's `load`): `windowPercent` over the last half second (`null` until +the first one has ended), `windowPeakPercent` for its dearest codec block, +`peakPercent` since boot, and the windows and blocks counted. An older +development base without the probe reports unsupported. `device_log` reads the base's +diagnostics log (the link's `diag`, then `log`, which reads nothing outside +the log, in every base), which is the Octatrack's +layout and reads with the same parser: `boot`, `seq`, the five-minute +`loads` and the `incidents`, without the nonce. The Model:Cycles fills +`cpu` with the audio's share and leaves the DSP fields at 0 (LINK.md). An +older development base without the log or `log` reports unsupported. `device_status` also +gives `loader`: the module pool's free bytes, the last refusal and the live +modules, or `unsupported` from a base without the loader. + +The runtime loader takes one change a trial (LINK.md, "Loading modules"): +`device_review({"moduleIds":["NAME.mwrm"]})` names a runtime package in +`--elektron-images` (built with `sdk/runtime/loader/build.py`), or +`remove:NAME` the module built as NAME; it returns a 60-second plan with the +package's SHA-256 and changes nothing. `device_trial` (with +`--allow-device-writes`) loads it to RAM on trial, holds the unit's turn and +sends a request every three seconds, since the unit undoes a trial by itself +after ten quiet seconds; `device_keep` keeps it until the next power cycle, +`device_undo` puts the previous set back and checks it is the one reviewed. +While a pattern plays the unit refuses both (`unsafe`): the trial and its +pings stay, so stop playback and call the tool again. A ping that fails shows +as `state.trial.pingError` in `device_status`, and `state.status` turns +`trial-lost` once no ping has reached the unit for ten seconds. When the unit no +longer has the trial (its loader in the normal phase, or in the ready phase +after an ACCEPT or ROLLBACK whose answer was lost, which the MCP then leaves), +its active set tells what happened: the reviewed set means the trial was undone +(`trial-lost`), another set means a Keep went through (`trial-kept`). A later +`device_keep` or `device_undo` reports the same, as done when it matches. A remote session or a rebuilt site bundle waits for +the trial's end. Closing the MCP during a trial undoes it ten seconds later. Nothing is +saved: there are no saved sets. Close Elektron Transfer first. Tests run +against a fake unit (`scripts/mc-device.test.mjs`); the trial test runs the +base's own transport, controller and loader compiled for the computer. + ## A member's unit through a remote session An administrator can read a member's Octatrack through their browser, with diff --git a/docs/MACHINE_RECIPE.md b/docs/MACHINE_RECIPE.md index 2f3c75f8e0..24ce6e6b54 100644 --- a/docs/MACHINE_RECIPE.md +++ b/docs/MACHINE_RECIPE.md @@ -43,7 +43,7 @@ Read this before you plan a core, a base or the first modules for any machine ot | Digitakt II | preview | Modwerk base from core-dt2 1.1's source (elekloader#221 at `0df8409`), with sequencer and project hooks | started: the site builds the [pinned base](../sdk/machines/digitakt-ii/elekloader/README.md) `8650bb8a` (`e88273ed`, which passed on one unit on 17 November 2026, with kit data ended before the project archive); downloads off. The USB link is not started (SysEx over USB MIDI, from the Rytm's) | digikit (emulator only) | the exact build on a second unit, then the USB link ([goal](../sdk/machines/digitakt-ii/GOAL.md)) | | Syntakt | research | Modwerk boot probe | not started | digiemu's port (open upstream pull request; emulator only) | the core stage, planned as the base | | Digitone II | research | core-dn2 0.3, with the Digitakt II 1.1 additions, in toonst's elekloader fork: boots and its six UI events run on units (18 November 2026) | started: Modwerk's builder carries the device (`machine:base` and the site's kit, 19 November 2026) | digikit (the author's; emulator only) | the Modwerk base, reusing the Digitakt II's with its own recipe as the Rytm MKI does, then flashing from the site and the link ([goal](../sdk/machines/digitone-ii/GOAL.md)) | -| Model:Cycles | research | Modwerk base from core-mc 0.3's source (Elekloader v0.11.0) plus a key-LED hook ([events.json](../sdk/machines/model-cycles/events.json)) | started: built by `npm run machine:base`; runs on a unit with a test module on the LED hook; the USB link started over USB MIDI SysEx: in every base the identity, the audio load, a diagnostics log in the Octatrack's layout and the Octatrack's runtime loader (modules on trial, kept, undone, refused while playing), on a unit flashed with the release base (24 November 2026); development bases add memory reads, keys, encoder turns and a RAM boot ([LINK.md](../sdk/machines/model-cycles/LINK.md)); the site builds the pinned base from the owner's OS file as a local preview, downloads off (24 November 2026) | digiemu (emulator only) | the first module, Control All Config ([guide](../sdk/machines/model-cycles/README.md)) | +| Model:Cycles | research | Modwerk base from core-mc 0.3's source (Elekloader v0.11.0) plus a key-LED hook ([events.json](../sdk/machines/model-cycles/events.json)) | started: built by `npm run machine:base`; runs on a unit with a test module on the LED hook; the USB link started over USB MIDI SysEx: in every base the identity, the audio load, a diagnostics log in the Octatrack's layout and the Octatrack's runtime loader (modules on trial, kept, undone, refused while playing), on a unit flashed with the release base (24 November 2026); development bases add memory reads, keys, encoder turns and a RAM boot ([LINK.md](../sdk/machines/model-cycles/LINK.md)); the site builds the pinned base from the owner's OS file as a local preview, downloads off; the MCP's `device_status` reads its identity, `device_load` the audio load, `device_log` the log, and its trial tools load modules (24 November 2026) | digiemu (emulator only) | the first module, Control All Config ([guide](../sdk/machines/model-cycles/README.md)) | | Analog Keys | research | none | not started | none known | the machine steps first ([add a machine](ADD_A_MACHINE.md)) | | Zoom MultiStomp | preview (MS-70CDR); research (MS-50G, MS-60B, G1on) | MIDISTOMP on the MS-70CDR; the MS-50G and MS-60B need builds from their own OS | browser base build and flash over Web MIDI. Shared MCP status and load tools use the same link. Load needs the MIDISTOMP SysEx load reply. | Ziddle (emulator only) | Prove a RAM-only effect trial and rollback on the MS-70CDR before wiring review, trial, Keep and Undo. See the [plan](ZOOM_MULTISTOMP.md#plan). | | Zoom G1 FOUR | research | none: effects load on the stock OS | not started: zoom-zt2's file commands work over USB, the pedal page does not speak ZD2 yet | none known | [next steps](ZOOM_ZD2.md#next-steps) | diff --git a/scripts/frontend-mcp-bridge.ts b/scripts/frontend-mcp-bridge.ts index 1167998866..b0d95b0b18 100644 --- a/scripts/frontend-mcp-bridge.ts +++ b/scripts/frontend-mcp-bridge.ts @@ -18,3 +18,4 @@ export { buildBase } from '../src/engine/elekloader/octatrack-base' export { apiFetch, setAdminSession } from '../src/community/api' export { DSP_LOADER } from '../src/engine/protocol' export { ZoomLink } from '../src/engine/zoom/zoom-link' +export { readMcIdentity, readMcLoad, readMcLog, mcSetIdentity, withMc, mcModules, mcTry, mcFinish, mcUploadSession, mcRemovalPackage, mcUploadBase, McRefused } from '../src/engine/elektron/mc-link' diff --git a/scripts/frontend-mcp.mjs b/scripts/frontend-mcp.mjs index 09db1145f6..9665595354 100644 --- a/scripts/frontend-mcp.mjs +++ b/scripts/frontend-mcp.mjs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later import { existsSync } from 'node:fs' -import { readFile, writeFile, mkdir, rename, lstat, rm, stat } from 'node:fs/promises' +import { readFile, readdir, writeFile, mkdir, rename, lstat, rm, stat } from 'node:fs/promises' import { resolve, join, isAbsolute } from 'node:path' import { pathToFileURL, fileURLToPath } from 'node:url' import { randomUUID, createHash } from 'node:crypto' @@ -63,14 +63,14 @@ const TOOLS = [ tool('board_take', 'Take one wanted task. Its parent issue or claim and sibling tasks keep their own holders.', { id: string, pullRequest: { type: 'integer' } }, ['id'], true), tool('board_close', 'Close a question or finding this developer wrote, by id; with foldPullRequest, link the pull request that folds a finding into a guide instead (it ends when that merges). Needs --allow-api-writes.', { id: string, foldPullRequest: { type: 'number' } }, ['id'], true), tool('firmware_download', 'Build from exact deployed public inputs using local private stock, save files privately and return only a hash/identity receipt. Never sends firmware to MCP.', { request: { type: 'object' } }, ['request'], true), - tool('device_status', 'Read identity and inventory through the site’s device link. On Octatrack also read missing modules and diagnostic status. With --zoom-midi alone, read the pedal’s file inventory.'), - tool('device_load', 'Read one CPU/DSP meter snapshot through the site’s device link. Uses the Octatrack’s cached reading or the Zoom pedal’s MIDISTOMP load reply when available. Read-only.'), - tool('device_log', 'Read the unit’s own log (five-minute load records and incidents with what it was doing) through the real frontend client. Read-only; Zoom pedals and older Octatrack bases report unsupported.'), + tool('device_status', 'Read identity and inventory through the site’s device link. On Octatrack also read missing modules and diagnostic status. With --zoom-midi alone, read the pedal’s file inventory. With --elektron-midi alone, read the link identity of a Model:Cycles running a Modwerk base, the image in --elektron-images that matches its set, and its runtime loader’s live modules.'), + tool('device_load', 'Read one CPU/DSP meter snapshot through the site’s device link. Uses the Octatrack’s cached reading or the Zoom pedal’s MIDISTOMP load reply when available; with --elektron-midi alone, the audio load of a Model:Cycles running a Modwerk base, over its link. Read-only.'), + tool('device_log', 'Read the unit’s own log (five-minute load records and incidents with what it was doing) through the real frontend client; with --elektron-midi alone, the log of a Model:Cycles running a Modwerk base, over its link. Read-only; Zoom pedals and older Octatrack and Model:Cycles bases report unsupported.'), { ...tool('device_saved_backup', 'Read only /MODWERK0.SET and /MODWERK1.SET through the frontend client, save verified bytes in the startup-selected private workspace and return only a metadata receipt. No card writes, memory access, arbitrary paths or recovery qualification. Older bases report unsupported.'), annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true, idempotentHint: false } }, - tool('device_review', 'Review a requested set against exact connected base, active digest and verified packages. Returns a short-lived plan; no device changes.', { moduleIds: strings }, ['moduleIds']), + tool('device_review', 'Review a requested set against exact connected base, active digest and verified packages. Returns a short-lived plan; no device changes. With --elektron-midi alone (a Model:Cycles), moduleIds is one change: a runtime package file NAME.mwrm in --elektron-images, or remove:NAME to take out the module built as NAME.', { moduleIds: strings }, ['moduleIds']), tool('device_trial', 'Install a reviewed set through the real frontend link as a trial, with no self-test (as a site sync). Requires --allow-device-writes; never accepts automatically.', { review: string }, ['review'], true), - tool('device_keep', 'Explicitly accept the current trial and save it on the card. Requires --allow-device-writes.', { trial: string }, ['trial'], true), + tool('device_keep', 'Explicitly accept the current trial and save it on the card (a Model:Cycles keeps it in RAM until the next power cycle). Requires --allow-device-writes.', { trial: string }, ['trial'], true), tool('device_undo', 'Undo the current trial and restore its exact reviewed previous packages.', { trial: string }, ['trial'], true), tool('zoom_status', 'Connect to the Zoom MultiStomp over MIDI (startup --zoom-midi) through the site\u2019s own ZoomLink and read its model and firmware; on MIDISTOMP also its version, features and load. Read-only.'), tool('zoom_list', 'List every file on the Zoom pedal with the group, ID and version of each effect in the group added effects use, and the free space. Read-only.'), @@ -241,7 +241,10 @@ export async function createFrontendTools(options, injected, dependencies = {}) const clock = dependencies.now ?? Date.now const reviews = new Map() const zoomSelected = () => options.zoomMidi && !options.deviceSocket && !remote + // The Model:Cycles over its link, in every Modwerk base (startup --elektron-midi): identity, load, log and the runtime loader. + const cyclesSelected = () => options.elektronMidi && !options.deviceSocket && !remote async function connected() { + if (cyclesSelected()) throw new Error('The Model:Cycles has no saved sets: device_status, device_load, device_log, device_review, device_trial, device_keep and device_undo work over its link.') if (zoomSelected()) throw new Error('MIDISTOMP does not provide the runtime set loader or saved-set files. Use zoom_list or zoom_backup for the pedal’s files.') if (!options.deviceSocket && !remote) throw new Error('Device tools require an explicitly selected --device-socket or a connected remote session (remote_session_connect).') if (remote?.relay.state().ended) { remote = undefined; dropLink(); throw new Error('The remote session has ended.') } @@ -309,6 +312,163 @@ export async function createFrontendTools(options, injected, dependencies = {}) if (name && !options.zoomEffects) throw new Error('Choose the effect files at startup with --zoom-effects DIR.') return name ? join(options.zoomEffects, args.file) : args.file } + // The Model:Cycles: a fresh MIDI port list per read (RtMidi has no hot-plug here), its link's ident, and the built + // image in --elektron-images whose set identity matches the one the unit took at boot. + const noCycles = 'No Model:Cycles answered over USB MIDI. It needs a Modwerk base (sdk/machines/model-cycles/LINK.md), Elektron Transfer closed, and exactly one Model:Cycles connected.' + async function withCycles(what, read) { + const turn = dependencies.elektronAccess || trialTurn ? null : await unitTurn(what, 10000) + let access + try { + access = await (dependencies.elektronAccess ?? nodeMidiAccess)() + return await read(access) + } finally { try { access?.close?.() } finally { turn?.release() } } + } + const cyclesSnapshot = () => cyclesSerial(() => withCycles('read Model:Cycles', async access => { + const identity = await frontend.readMcIdentity(access) + if (!identity) throw new Error(noCycles) + const loader = await frontend.withMc(access, 2000, call => cyclesModules(call)) + let build = null + if (identity.set && options.elektronImages) { + for (const name of (await readdir(options.elektronImages)).filter(name => /\.syx$/i.test(name)).sort()) { + const bytes = new Uint8Array(await readFile(join(options.elektronImages, name))) + let set + try { set = frontend.mcSetIdentity(bytes, identity.set.bytes) } catch { continue } + if (set.crc === identity.set.crc) { build = { file: name, sha256: hash(bytes) }; break } + } + } + const trial = cyclesTrialState() + return { machine: 'model-cycles', state: { status: !trial ? 'ready' : trial.lost ? 'trial-lost' : trial.kept ? 'trial-kept' : 'trial', identity, ...(trial && { trial }) }, build, inventory: null, loader } + })) + // The audio's share of the CPU from the base's load probe (LINK.md `load`); an older development base refuses it. + const cyclesLoad = () => cyclesSerial(() => withCycles('read Model:Cycles load', async access => { + const reading = await frontend.readMcLoad(access) + if (!reading) throw new Error(noCycles) + return reading === 'unsupported' ? { machine: 'model-cycles', supported: false, reading: null } : { machine: 'model-cycles', supported: true, reading } + })) + // The base's diagnostics log (LINK.md `diag`), in the Octatrack's layout; an older development base refuses it. + const cyclesLog = () => cyclesSerial(() => withCycles('read Model:Cycles log', async access => { + const read = await frontend.readMcLog(access) + if (!read) throw new Error(noCycles) + if (read === 'unsupported') return { machine: 'model-cycles', supported: false, log: null } + if (!read.log) throw new Error('The Model:Cycles sent a log in no layout the site reads.') + // The nonce identifies the unit's log across connections; like the Octatrack's, it stays out. + const { boot, seq, loads, incidents } = read.log + return { machine: 'model-cycles', supported: true, log: { boot, seq, loads, incidents } } + })) + // The Model:Cycles' runtime loader (LINK.md "Loading modules"): one change a trial, read from --elektron-images. The + // unit undoes a trial by itself after ten seconds without a link request, so a trial pings every three seconds until + // its Keep or Undo. Every exchange goes in turn: a frame's parts from two requests must not interleave. + let cyclesChain = Promise.resolve() + const cyclesSerial = work => { const run = cyclesChain.then(work, work); cyclesChain = run.catch(() => {}); return run } + const cyclesLine = (what, work) => cyclesSerial(() => withCycles(what, async access => { + const out = await frontend.withMc(access, 10000, work) + if (out === null) throw new Error(noCycles) + return out + })) + const cyclesModules = call => frontend.mcModules(call).catch(error => { if (error instanceof frontend.McRefused && error.status === 2) return 'unsupported'; throw error }) + let cyclesTrial + // A trial's pings: the last one that reached the unit and the last failure. Once the unit's loader is in the ready + // phase (an ACCEPT or ROLLBACK whose answer was lost: upload mode is left here) or back in the normal one, the trial + // is over, and its active set tells how: the reviewed one means undone, another means a Keep + // went through though its answer was lost. More than ten seconds without a ping that reached it means it was + // probably undone. + const CYCLES_LAPSE = 10000 + // The unit's set, leaving upload mode when an ACCEPT or ROLLBACK left it in the ready phase. + const cyclesSettle = async call => { + const session = await frontend.mcUploadSession(call) + if (!session) return null + const phase = session.status.phase + if (phase === 'ready') await session.leaveUploadMode() + return { over: phase === 'ready' || phase === 'normal', phase: session.status.phase, generation: session.status.generation, active: session.status.active } + } + const cyclesEnding = (active, before) => active === before.active + ? { kept: false, text: 'The unit no longer has the trial and runs the reviewed set again: the trial was undone (ten seconds without a ping, a power cycle, or an Undo whose answer was lost).' } + : { kept: true, text: 'The unit no longer has the trial and runs a different set than the reviewed one: a Keep went through though its answer was lost.' } + function cyclesTrialState() { + if (!cyclesTrial) return null + const quiet = clock() - cyclesTrial.lastPing, ended = cyclesTrial.ended + const lost = ended ? (ended.kept ? null : ended.text) : quiet > CYCLES_LAPSE ? 'No ping reached the unit for ' + Math.round(quiet / 1000) + ' s; it undoes a trial after ten quiet seconds.' : null + return { lost, kept: ended?.kept ? ended.text : null, pingError: cyclesTrial.pingError } + } + async function cyclesPackage(change) { + const removal = /^remove:([A-Za-z0-9._-]{1,64})$/.exec(change) + if (removal) return { module: change, data: frontend.mcRemovalPackage(removal[1]) } + if (!options.elektronImages) throw new Error('Give the folder of your runtime packages at startup: --elektron-images DIR.') + if (!/^[A-Za-z0-9._-]{1,64}\.mwrm$/.test(change)) throw new Error('Name one runtime package NAME.mwrm in --elektron-images, or remove:NAME.') + const data = new Uint8Array(await readFile(join(options.elektronImages, change))) + if (data.length < 32 || String.fromCharCode(...data.subarray(0, 4)) !== 'MWRM') throw new Error(change + ' is not a runtime package.') + return { module: change, data } + } + async function cyclesReview(args) { + if (cyclesTrial) throw new Error('Finish the current trial first.') + if (args.moduleIds.length !== 1) throw new Error('The Model:Cycles takes one change a trial: one package or one remove:NAME.') + const change = await cyclesPackage(args.moduleIds[0]) + const before = await cyclesLine('review Model:Cycles', async call => { + const session = await frontend.mcUploadSession(call) + if (!session) return null + return { base: session.status.base, phase: session.status.phase, active: session.status.active, loader: await cyclesModules(call) } + }) + if (before.phase !== 'normal') throw new Error('The Model:Cycles loader is busy (phase ' + before.phase + '): wait ten seconds and review again.') + for (const [id, item] of reviews) if (item.expires < clock()) reviews.delete(id) + if (reviews.size >= 10) throw new Error('Finish or expire existing reviews first.') + const review = randomUUID() + reviews.set(review, { cycles: true, before, change, expires: clock() + 60000 }) + return { review, expiresInSeconds: 60, machine: 'model-cycles', base: before.base, active: before.active, loader: before.loader, + changes: [{ module: change.module, sha256: hash(change.data), bytes: change.data.length, undoAvailable: true }] } + } + async function cyclesStart(plan) { + trialTurn = dependencies.elektronAccess ? null : await unitTurn('device_trial', 10 * 60000) // held until Keep or Undo + try { + const status = await cyclesLine('trial Model:Cycles', async call => { + const session = await frontend.mcUploadSession(call) + if (!session) return null + if (session.status.base !== plan.before.base || session.status.active !== plan.before.active) throw new Error('The device changed after review; nothing was sent.') + return frontend.mcTry(call, plan.change.data) + }) + const trial = { id: randomUUID(), before: plan.before, lastPing: clock(), pingError: null, ended: null } + trial.ping = setInterval(() => { + cyclesLine('keep Model:Cycles trial', cyclesSettle).then(now => { + if (cyclesTrial !== trial) return + if (now.over) { clearInterval(trial.ping); trial.ended = cyclesEnding(now.active, trial.before); return } + trial.lastPing = clock(); trial.pingError = null + }, error => { if (cyclesTrial === trial) trial.pingError = error.message }) + }, 3000) + trial.ping.unref?.() + cyclesTrial = trial + const id = trial.id + return { trial: id, machine: 'model-cycles', state: { phase: status.phase, generation: status.generation, active: status.active } } + } finally { if (!cyclesTrial) endTrialTurn() } + } + async function cyclesFinish(args, keep) { + if (!options.allowDeviceWrites || !cyclesTrial || args.trial !== cyclesTrial.id) throw new Error('No matching authorized device trial.') + const completed = cyclesTrial + const done = () => { clearInterval(completed.ping); if (cyclesTrial === completed) cyclesTrial = undefined; endTrialTurn() } + // The trial and its pings stay until the unit has finished: a refusal (unsafe while a pattern plays) leaves both, + // so the agent can try again, as the Octatrack's finish() does. + let after + try { + after = await cyclesLine((keep ? 'keep' : 'undo') + ' Model:Cycles trial', async call => { + const status = await frontend.mcFinish(call, keep) + return status && { phase: status.phase, generation: status.generation, active: status.active, loader: await cyclesModules(call) } + }) + } catch (error) { + if (/Nothing is on trial/.test(error.message)) { + // The trial ended without an answer that said so: the unit's active set tells which way. + const now = await cyclesLine('read Model:Cycles set', async call => { + const settled = await cyclesSettle(call) + return settled && { phase: settled.phase, generation: settled.generation, active: settled.active, loader: await cyclesModules(call) } + }) + done() + const ending = cyclesEnding(now.active, completed.before) + if (ending.kept === keep) return { kept: keep, completed: true, machine: 'model-cycles', ...now, note: ending.text } + throw new Error(ending.text + (keep ? ' Nothing was kept.' : ' Undo changed nothing: remove the module with remove:NAME, or power-cycle the unit.'), { cause: error }) + } + throw new Error((keep ? 'Keep' : 'Undo') + ' did not finish: ' + error.message + ' The trial stays on and its pings go on: stop playback if a pattern plays, then call ' + (keep ? 'device_keep' : 'device_undo') + ' again.', { cause: error }) + } + done() + if (!keep && after.active !== completed.before.active) throw new Error('Undo did not restore the reviewed set.') + return { kept: keep, completed: true, machine: 'model-cycles', ...after } + } async function snapshot() { const unit = await connected(), kit = frontend.moduleSetKit(unit) if (unit.getState().status === 'trial') return { state: unit.getState(), before: trial?.before, trial: trial?.id } @@ -389,8 +549,9 @@ export async function createFrontendTools(options, injected, dependencies = {}) return { status: response.status, body } }, firmware_download: async args => { if (!options.stock) throw new Error('Choose private stock at startup with --stock.'); return buildAndSave(args.request, { stockPath: options.stock, outputDir: dataDir, site, root }) }, - device_status: async () => zoomSelected() ? zoomSnapshot(true) : snapshot(), + device_status: async () => cyclesSelected() ? cyclesSnapshot() : zoomSelected() ? zoomSnapshot(true) : snapshot(), device_load: async () => { + if (cyclesSelected()) return cyclesLoad() if (zoomSelected()) { const { machine, state, load } = await zoomSnapshot(false) return { machine, identity: state.identity, supported: load !== null, reading: load } @@ -402,6 +563,7 @@ export async function createFrontendTools(options, injected, dependencies = {}) return { base: after.identity.base, supported: reading !== undefined, reading: reading ?? null } }, device_log: async () => { + if (cyclesSelected()) return cyclesLog() if (zoomSelected()) return { supported: false, log: null } const unit = await connected(), before = unit.getState() if (before.status !== 'ready' || !/^[0-9a-f]{64}$/.test(before.identity?.base ?? '')) throw new Error('The Octatrack must be idle with a verified base identity.') @@ -421,6 +583,7 @@ export async function createFrontendTools(options, injected, dependencies = {}) return saveSavedBackup(dataDir, { base: after.state.identity.base, active: after.state.active }, snapshots, directory) }, device_review: async args => { + if (cyclesSelected()) return cyclesReview(args) if (trial) throw new Error('Finish the current trial first.') const before = await snapshot(), target = usbTarget('MCP reviewed set', ids(args.moduleIds), before.inventory) if (!before.diagnostics) throw new Error('The device does not provide the required self-test status.') @@ -438,9 +601,10 @@ export async function createFrontendTools(options, injected, dependencies = {}) device_trial: async args => { readOnlyRemote() if (!options.allowDeviceWrites) throw new Error('Device writes require --allow-device-writes.') - if (trial) throw new Error('Finish the current trial first.') + if (trial || cyclesTrial) throw new Error('Finish the current trial first.') const plan = reviews.get(args.review); reviews.delete(args.review) if (!plan || plan.expires < clock()) throw new Error('Review expired; review the connected device again.') + if (plan.cycles) return cyclesStart(plan) trialTurn = await unitTurn('device_trial', 10 * 60000) // held until Keep, Undo or close; given back if no trial starts try { const now = await snapshot() @@ -459,8 +623,8 @@ export async function createFrontendTools(options, injected, dependencies = {}) return { trial: trial.id, state: link.getState() } } finally { if (!trial) endTrialTurn() } }, - device_keep: async args => finish(args, true), - device_undo: async args => finish(args, false), + device_keep: async args => cyclesSelected() ? cyclesFinish(args, true) : finish(args, true), + device_undo: async args => cyclesSelected() ? cyclesFinish(args, false) : finish(args, false), zoom_status: async () => zoomRun('status'), zoom_list: async () => zoomRun('list'), zoom_backup: async () => zoomRun('backup'), @@ -511,7 +675,7 @@ export async function createFrontendTools(options, injected, dependencies = {}) remote_session_status: async args => ({ ...await adminApi('/admin/remote-sessions/' + sessionId(args.session)), relay: remote?.id === args.session ? remote.relay.state() : null }), remote_session_connect: async args => { const id = sessionId(args.session) - if (trial) throw new Error('Finish the current trial first.') + if (trial || cyclesTrial) throw new Error('Finish the current trial first.') const { ticket } = await adminApi('/admin/remote-sessions/' + id + '/ticket', 'POST', {}) const url = new URL(api.href + '/remote-sessions/' + id + '/socket') url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'; url.searchParams.set('ticket', ticket) @@ -551,10 +715,10 @@ export async function createFrontendTools(options, injected, dependencies = {}) if (!keep && !frontend.sameModules(result.inventory.moduleIds, completed.before.inventory.moduleIds)) throw new Error('Undo did not restore the reviewed inventory.') return { kept: keep, completed: true, ...result } } - // Before each tool call: rebuild the bundle when a file it was built from changed. An open trial keeps the bundle it - // started with until Keep or Undo; the link and reviews belong to the old bundle, so they are dropped. + // Before each tool call: rebuild the bundle when a file it was built from changed. An open trial (the Octatrack's or + // the Model:Cycles') keeps the bundle it started with until Keep or Undo; the link and reviews belong to the old bundle, so they are dropped. async function refreshFrontend() { - if (trial || await stamp(built.files) === built.stamp) return + if (trial || cyclesTrial || await stamp(built.files) === built.stamp) return dropLink(); closeZoom() try { await loadFrontend() } catch (error) { throw new Error('The checkout changed since this server bundled the site (a branch switch or base regeneration), and rebuilding failed: ' + error.message + ' Once the checkout builds again, call the tool again; nothing was sent.', { cause: error }) } @@ -579,7 +743,7 @@ export async function createFrontendTools(options, injected, dependencies = {}) }, // Every caller gets the same promise: on SIGTERM both the closed input and the signal handler close, and the handler // exits only after the lock is removed (an early return here once let the process exit with the lock still there). - close() { return closing ??= (async () => { closed = true; clearTimeout(idleTimer); try { if (trial) { try { await link.undo() } catch { /* Unaccepted trials also recover through device timeout. */ } } remote?.relay.end(); release?.(); bench?.socket.destroy(); closeZoom() } finally { endTrialTurn(); activeWorkspace = false; await rm(lease, { recursive: true, force: true }) } })() }, + close() { return closing ??= (async () => { closed = true; clearTimeout(idleTimer); if (cyclesTrial) clearInterval(cyclesTrial.ping) /* the unit undoes it after ten quiet seconds */; try { if (trial) { try { await link.undo() } catch { /* Unaccepted trials also recover through device timeout. */ } } remote?.relay.end(); release?.(); bench?.socket.destroy(); closeZoom() } finally { endTrialTurn(); activeWorkspace = false; await rm(lease, { recursive: true, force: true }) } })() }, } } catch (error) { activeWorkspace = false; await rm(lease, { recursive: true, force: true }); throw error } } @@ -605,8 +769,8 @@ export function createProtocol(service) { if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { for (const method of ['log', 'info', 'debug', 'warn', 'error']) console[method] = (...args) => process.stderr.write(formatMcpLog(...args) + '\n') try { - const { values } = parseArgs({ options: { 'data-dir': { type: 'string' }, 'frontend-root': { type: 'string' }, 'prepared-modules': { type: 'string' }, 'api': { type: 'string' }, site: { type: 'string' }, 'session-file': { type: 'string' }, stock: { type: 'string' }, 'device-socket': { type: 'string' }, 'zoom-midi': { type: 'boolean' }, 'zoom-effects': { type: 'string' }, 'allow-api-writes': { type: 'boolean' }, 'allow-device-writes': { type: 'boolean' } } }) - const service = await createFrontendTools({ root: values['frontend-root'] && resolve(values['frontend-root']), preparedModules: values['prepared-modules'] && resolve(values['prepared-modules']), dataDir: values['data-dir'] && resolve(values['data-dir']), apiBase: values.api, site: values.site, sessionFile: values['session-file'], stock: values.stock, deviceSocket: values['device-socket'], zoomMidi: values['zoom-midi'], zoomEffects: values['zoom-effects'] && resolve(values['zoom-effects']), allowApiWrites: values['allow-api-writes'], allowDeviceWrites: values['allow-device-writes'] }) + const { values } = parseArgs({ options: { 'data-dir': { type: 'string' }, 'frontend-root': { type: 'string' }, 'prepared-modules': { type: 'string' }, 'api': { type: 'string' }, site: { type: 'string' }, 'session-file': { type: 'string' }, stock: { type: 'string' }, 'device-socket': { type: 'string' }, 'zoom-midi': { type: 'boolean' }, 'zoom-effects': { type: 'string' }, 'elektron-midi': { type: 'boolean' }, 'elektron-images': { type: 'string' }, 'allow-api-writes': { type: 'boolean' }, 'allow-device-writes': { type: 'boolean' } } }) + const service = await createFrontendTools({ root: values['frontend-root'] && resolve(values['frontend-root']), preparedModules: values['prepared-modules'] && resolve(values['prepared-modules']), dataDir: values['data-dir'] && resolve(values['data-dir']), apiBase: values.api, site: values.site, sessionFile: values['session-file'], stock: values.stock, deviceSocket: values['device-socket'], zoomMidi: values['zoom-midi'], zoomEffects: values['zoom-effects'] && resolve(values['zoom-effects']), elektronMidi: values['elektron-midi'], elektronImages: values['elektron-images'] && resolve(values['elektron-images']), allowApiWrites: values['allow-api-writes'], allowDeviceWrites: values['allow-device-writes'] }) const protocol = createProtocol(service), input = createInterface({ input: process.stdin, crlfDelay: Infinity }) let queue = Promise.resolve() input.on('line', line => { queue = queue.then(async () => { let reply; try { if (Buffer.byteLength(line) > 64 * 1024) throw new Error('Message too large.'); reply = await protocol(JSON.parse(line)) } catch { reply = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid JSON-RPC message.' } } } if (reply) process.stdout.write(JSON.stringify(reply) + '\n') }) }) diff --git a/scripts/mc-device.test.mjs b/scripts/mc-device.test.mjs new file mode 100644 index 0000000000..bd95fd4386 --- /dev/null +++ b/scripts/mc-device.test.mjs @@ -0,0 +1,247 @@ +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { spawn, spawnSync } from 'node:child_process' +import { createInterface } from 'node:readline' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { build } from 'vite' +import { packSection } from '../src/engine/aplib' +import { contentChecksum, encodeSyx } from '../src/engine/elektron/sysex' +import { ELE3_DEVICES } from '../src/engine/elektron/ele3' +import { createFrontendTools } from './frontend-mcp.mjs' + +const root = fileURLToPath(new URL('../', import.meta.url)) +// A generated Model:Cycles container, no firmware bytes: its image's last bytes stand for the linked .run block. +function syx(seed) { + const image = Uint8Array.from({ length: 512 }, (_, i) => (i * seed) % 251), packed = packSection(image) + const container = new Uint8Array(64 + packed.length + (-packed.length & 15)), view = new DataView(container.buffer) + container.set([0x45, 0x4c, 0x45, 0x33]) + view.setUint32(0x1c, 1); view.setUint32(0x20, 3); view.setUint32(0x24, 64); view.setUint32(0x28, packed.length); view.setUint32(0x2c, 0x40000400) + container.set(packed, 64) + const stream = new Uint8Array(8 + container.length), streamView = new DataView(stream.buffer) + streamView.setUint32(0, container.length); streamView.setUint32(4, contentChecksum(container)); stream.set(container, 8) + const id = ELE3_DEVICES['model-cycles'].sysexId, framing = Uint8Array.from([0xf0, 0, 0x20, 0x3c, id, 0, 0x7d, 0, 0x10, 1, 2, 3, 0, 0, 0, 0xf7]) + return encodeSyx(stream, id, framing, framing) +} +const put32 = v => [0, 1, 2, 3, 4].map(i => v >>> 7 * i & 0x7f) +const get32 = (p, at) => (p[at] | p[at + 1] << 7 | p[at + 2] << 14 | p[at + 3] << 21 | (p[at + 4] & 0x0f) << 28) >>> 0 +const pack7 = data => { const out = []; for (let i = 0; i < data.length; i += 7) { const c = data.subarray(i, i + 7); out.push(c.reduce((t, b, k) => t | (b & 0x80 ? 0x40 >> k : 0), 0), ...Array.from(c, b => b & 0x7f)) } return out } +const LOG_AT = 0x47e02404 +// diag.h's log, big-endian: START and BASE, one load record (a made-up log, no unit's). +function logBytes() { + const bytes = new Uint8Array(6148), v = new DataView(bytes.buffer) + ;[0x4d574447, 2, 0xabcd, 1, 3, 1, 2].forEach((x, i) => v.setUint32(4 * i, x)) + const load = 40 + 92, incident = load + 32 * 96 + ;[3, 1, 5].forEach((x, i) => v.setUint32(load + 4 * i, x)); ;[738, 829, 0, 0, 0, 0, 600, 0, 714, 53].forEach((x, i) => v.setUint16(load + 12 + 2 * i, x)) + ;[[1, 1, 0], [2, 7, 0x4f182a66]].forEach(([seq, kind, a], n) => { const at = incident + 92 * n; v.setUint32(at, seq); v.setUint32(at + 4, 1); v.setUint32(at + 12, a); v.setUint16(at + 16, kind) }) + return bytes +} +// A unit with a Modwerk base: answers ident with the given set identity, load (0x23) with the given tenths of a +// percent and counts (link.c CMD_LOAD), and diag (0x22) and log (0x24) with a log; without them, as a base before the load +// probe or the log (status 2, bad request). +// With `loader`, the base's own upload transport, controller and runtime loader compiled for the host +// (base/test_modules.c): up_part (0x31) and up_run (0x32) go to it, mods (0x33) answers an empty pool. +function fakeCycles(set, name = 'Elektron Model:Cycles', load = null, log = null, loader = null) { + const input = { id: 'i', name, state: 'connected', onmidimessage: null }, requests = {} + // lose.cmd: the next frame with that wire command runs on the loader, but its answer is a refusal, as an answer lost + // on the way (without the wait for a timeout); frame is the command of the frame whose parts came last + const lose = { cmd: null } + let frame = null + const fields = [1, 1, 0, 146, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, ...(set ? [set.crc, set.bytes] : [])] + const answer = (data, status, reply) => input.onmidimessage?.({ data: Uint8Array.from([0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1, data[6], data[7] | 0x40, status, ...reply, 0xf7]) }) + const output = { id: 'o', name, state: 'connected', send(data) { + const body = data.slice(8, -1) + requests[data[7]] = (requests[data[7]] ?? 0) + 1 + if (data[7] >= 0x31 && data[7] <= 0x33) { + if (!loader) { queueMicrotask(() => answer(data, 2, [])); return } + if (data[7] === 0x31 && get32(body, 0) === 0) frame = body[5 + 9] // the wire header's command byte, packed + const line = data[7] === 0x31 ? 'P ' + get32(body, 0) + ' ' + Buffer.from(Uint8Array.from(body).subarray(5)).toString('hex') : data[7] === 0x32 ? 'R ' + get32(body, 0) : null + if (!line) { queueMicrotask(() => answer(data, 0, pack7(Uint8Array.from([0, 0, 0xfe, 0x60, 0, 0, 0xfe, 0x60, 0, 0, 0, 0, 0, 0, 0, 0, 0x4d, 0x57, 0x49, 0])))); return } + loader.ask(line).then(out => { + if (data[7] === 0x32 && lose.cmd !== null && lose.cmd === frame) { lose.cmd = null; answer(data, 4, []); return } + answer(data, data[7] === 0x31 ? (Number(out) ? 0 : 4) : out ? 0 : 4, data[7] === 0x31 || !out ? [] : pack7(Uint8Array.from(Buffer.from(out, 'hex')))) + }) + return + } + const [status, reply] = data[7] === 0x23 ? (load ? [0, load.flatMap(put32)] : [2, []]) + : data[7] === 0x22 ? (log ? [0, [LOG_AT, log.length].flatMap(put32)] : [2, []]) + : data[7] === 0x24 ? (!log ? [2, []] : (() => { const at = get32(body, 0), n = get32(body, 5); return at + n > log.length ? [4, []] : [0, [...put32(at), ...put32(n), ...pack7(log.subarray(at, at + n))]] })()) + : [0, fields.flatMap(put32)] + queueMicrotask(() => answer(data, status, reply)) + } } + const inputs = new Map([['i', input]]), outputs = new Map([['o', output]]) + // unplug() takes the ports away, plug() brings them back + return { inputs, outputs, requests, lose, onstatechange: null, close() {}, unplug() { inputs.clear(); outputs.clear() }, plug() { inputs.set('i', input); outputs.set('o', output) } } +} + +describe('the developer MCP’s Model:Cycles identity', () => { + let frontend, folder, images, service + beforeAll(async () => { + const bundled = await build({ root, configFile: false, logLevel: 'silent', define: { + 'import.meta.env.VITE_COMMUNITY_API_URL': JSON.stringify('http://127.0.0.1:8788/api'), 'import.meta.env.DEV': 'false', 'import.meta.env.BASE_URL': JSON.stringify('/'), + }, build: { ssr: join(root, 'scripts/frontend-mcp-bridge.ts'), write: false, minify: false, sourcemap: false } }) + frontend = await import('data:text/javascript;base64,' + Buffer.from(bundled.output.find(entry => entry.type === 'chunk' && entry.isEntry).code).toString('base64')) + }, 60000) + beforeEach(async () => { + folder = await mkdtemp(join(tmpdir(), 'modwerk-mcp-cycles-test-')); images = await mkdtemp(join(tmpdir(), 'modwerk-cycles-images-')) + await writeFile(join(images, 'a-other.syx'), syx(3)); await writeFile(join(images, 'b-built.syx'), syx(7)); await writeFile(join(images, 'notes.txt'), 'x') + }) + afterEach(async () => { await service?.close(); service = undefined; await rm(folder, { recursive: true, force: true }); await rm(images, { recursive: true, force: true }) }) + let now = 0 + const open = (access, options = {}) => createFrontendTools({ dataDir: folder, elektronMidi: true, elektronImages: images, ...options }, frontend, { elektronAccess: async () => access, now: () => now }) + + it('reads the link identity and names the image whose set the unit runs', async () => { + const set = frontend.mcSetIdentity(syx(7), 64) + service = await open(fakeCycles(set)) + const status = await service.call('device_status') + expect(status).toMatchObject({ machine: 'model-cycles', state: { status: 'ready', identity: { linkVersion: 1, port: 'USB', set } }, inventory: null }) + expect(status.build).toMatchObject({ file: 'b-built.syx' }) + expect(status.build.sha256).toMatch(/^[0-9a-f]{64}$/) + }) + it('names no build when none matches or the base is older, and says what a missing unit needs', async () => { + service = await open(fakeCycles({ crc: 1, bytes: 64 })) + expect((await service.call('device_status')).build).toBeNull() + await service.close(); service = await open(fakeCycles(null)) + expect(await service.call('device_status')).toMatchObject({ build: null, state: { identity: { set: null } } }) + await service.close(); service = await open(fakeCycles(null, 'IAC Driver Bus 1')) + await expect(service.call('device_status')).rejects.toThrow(/No Model:Cycles answered/) + }) + it('reads the audio load, and reports an older base without the probe as unsupported', async () => { + service = await open(fakeCycles(null, undefined, [738, 801, 849, 12, 9000])) + expect(await service.call('device_load')).toEqual({ machine: 'model-cycles', supported: true, + reading: { windowPercent: 73.8, windowPeakPercent: 80.1, peakPercent: 84.9, windows: 12, blocks: 9000 } }) + await service.close(); service = await open(fakeCycles(null, undefined, [0, 0, 812, 0, 400])) + expect((await service.call('device_load')).reading).toEqual({ windowPercent: null, windowPeakPercent: null, peakPercent: 81.2, windows: 0, blocks: 400 }) + await service.close(); service = await open(fakeCycles(null)) + expect(await service.call('device_load')).toEqual({ machine: 'model-cycles', supported: false, reading: null }) + await service.close(); service = await open(fakeCycles(null, 'IAC Driver Bus 1')) + await expect(service.call('device_load')).rejects.toThrow(/No Model:Cycles answered/) + }) + it('reads the diagnostics log through log, and reports an older base without it as unsupported', async () => { + service = await open(fakeCycles(null, undefined, null, logBytes())) + const { machine, supported, log } = await service.call('device_log') + expect({ machine, supported, boot: log.boot, seq: log.seq }).toEqual({ machine: 'model-cycles', supported: true, boot: 1, seq: 3 }) + expect(log.loads).toEqual([{ seq: 3, boot: 1, minute: 5, cpu: [738, 829], dsp1to4: [0, 0], dsp5to8: [0, 0], samples: 600, playing: 0, frameGap: 714, tickGap: 53 }]) + expect(log.incidents.map(i => [i.kind, i.a])).toEqual([['start', 0], ['base', 0x4f182a66]]) + expect(log).not.toHaveProperty('nonce') + await service.close(); service = await open(fakeCycles(null)) + expect(await service.call('device_log')).toEqual({ machine: 'model-cycles', supported: false, log: null }) + }) + it('reports an older base without the loader, and takes one change a trial', async () => { + service = await open(fakeCycles({ crc: 1, bytes: 64 }), { allowDeviceWrites: true }) + expect((await service.call('device_status')).loader).toBe('unsupported') + await expect(service.call('device_review', { moduleIds: [] })).rejects.toThrow(/one change a trial/) + await expect(service.call('device_review', { moduleIds: ['../x.mwrm'] })).rejects.toThrow(/NAME.mwrm/) + await expect(service.call('device_review', { moduleIds: ['notes.txt'] })).rejects.toThrow(/NAME.mwrm/) + }) + // The base's transport, controller and loader on the host (the harness sdk/tests/test_machine_base.py runs): its base + // identity is the SHA-256 of the set CRC 0x12345678. + const cc = spawnSync('cc', ['--version']).status === 0 + // The base's loader on the host, one request a line (test_modules.c), and a runtime package for it. + function hostLoader() { + const base = join(root, 'sdk/machines/model-cycles/elekloader/base'), rt = join(root, 'sdk/runtime') + const exe = join(folder, 'loader') + const built = spawnSync('cc', ['-std=c99', '-DMODWERK_HOST', '-DRUNTIME_MODULES=16u', '-DRUNTIME_POOL_BYTES=65536u', '-I', join(rt, 'loader'), '-I', join(rt, 'upload'), + join(base, 'test_modules.c'), join(base, 'modules.c'), join(base, 'runtime.c'), join(rt, 'loader/loader.c'), join(rt, 'upload/upload.c'), + join(rt, 'upload/wire.c'), join(rt, 'upload/sha256.c'), '-o', exe]) + expect(built.status, String(built.stderr)).toBe(0) + const child = spawn(exe), lines = createInterface({ input: child.stdout }), waiting = [] + lines.on('line', line => waiting.shift()?.(line)) + let chain = Promise.resolve() + const loader = { ask: line => (chain = chain.then(() => new Promise(resolve => { waiting.push(resolve); child.stdin.write(line + '\n') }))) } + // ABI 4: a tick hook that returns at once + const pkg = Buffer.concat([Buffer.from('MWRM'), Buffer.from([0, 4, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0x10, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0x59, 0x4c, 0xfd, 0x26]), + Buffer.alloc(4), Buffer.from([0x4e, 0x75, 0x4e, 0x71])]) + return { child, loader, pkg } + } + it.skipIf(!cc)('reviews a package, puts it on trial, undoes it and keeps it, through the base\'s own loader', async () => { + const { child, loader, pkg } = hostLoader() + try { + await writeFile(join(images, 'frames.mwrm'), pkg) + service = await open(fakeCycles({ crc: 0x12345678, bytes: 64 }, undefined, null, null, loader), { allowDeviceWrites: true }) + expect((await service.call('device_status')).loader).toMatchObject({ free: 65120, active: 0, modules: [] }) + const review = await service.call('device_review', { moduleIds: ['frames.mwrm'] }) + expect(review).toMatchObject({ machine: 'model-cycles', changes: [{ module: 'frames.mwrm', bytes: pkg.length, undoAvailable: true }] }) + expect(review.base).toBe(frontend.mcUploadBase(0x12345678)) + const trial = await service.call('device_trial', { review: review.review }) + expect(trial.state.phase).toBe('trial') + await expect(service.call('device_trial', { review: review.review })).rejects.toThrow(/current trial/) + const undone = await service.call('device_undo', { trial: trial.trial }) + expect(undone).toMatchObject({ kept: false, completed: true, phase: 'normal', active: review.active }) + const again = await service.call('device_trial', { review: (await service.call('device_review', { moduleIds: ['frames.mwrm'] })).review }) + const kept = await service.call('device_keep', { trial: again.trial }) + expect(kept).toMatchObject({ kept: true, completed: true, phase: 'normal' }) + expect(kept.active).not.toBe(review.active) + await expect(service.call('device_keep', { trial: again.trial })).rejects.toThrow(/No matching/) + } finally { child.stdin.end() } + }, 30000) + // Pings every three seconds (fake setInterval): a ping and a Keep go in turn; a Keep or Undo the unit refuses while a + // pattern plays leaves the trial and its pings; a failed ping and ten quiet seconds show in device_status. + it.skipIf(!cc)('keeps a refused trial, pings it in turn, and reports a lost one', async () => { + const { child, loader, pkg } = hostLoader() + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) + const pinged = async (access, before) => { vi.advanceTimersByTime(3000); while ((access.requests[1] ?? 0) <= before) await new Promise(resolve => setTimeout(resolve, 5)) } + try { + await writeFile(join(images, 'frames.mwrm'), pkg) + const access = fakeCycles({ crc: 0x12345678, bytes: 64 }, undefined, null, null, loader) + service = await open(access, { allowDeviceWrites: true }) + const review = await service.call('device_review', { moduleIds: ['frames.mwrm'] }) + const trial = await service.call('device_trial', { review: review.review }) + // a pattern plays: the unit answers unsafe, the trial stays and is still pinged + await loader.ask('S 0') + await expect(service.call('device_keep', { trial: trial.trial })).rejects.toThrow(/Keep did not finish: .*unsafe.*trial stays on/s) + await expect(service.call('device_undo', { trial: trial.trial })).rejects.toThrow(/Undo did not finish: .*unsafe.*trial stays on/s) + expect((await service.call('device_status')).state).toMatchObject({ status: 'trial', trial: { lost: null, kept: null, pingError: null } }) + const idents = access.requests[1] + await pinged(access, idents) + expect(access.requests[1]).toBeGreaterThan(idents) + // stopped: a ping fires and a Keep follows at once; they go in turn, so the Keep's frame arrives whole + await loader.ask('S 1') + vi.advanceTimersByTime(3000) + const kept = await service.call('device_keep', { trial: trial.trial }) + expect(kept).toMatchObject({ kept: true, completed: true, phase: 'normal' }) + expect((await service.call('device_status')).state.status).toBe('ready') + // a second trial loses its unit: the failed ping is reported, and after ten quiet seconds the trial is lost + const again = await service.call('device_trial', { review: (await service.call('device_review', { moduleIds: ['remove:frames'] })).review }) + access.unplug() + vi.advanceTimersByTime(3000) + await new Promise(resolve => setTimeout(resolve, 50)) + access.plug() + expect((await service.call('device_status')).state).toMatchObject({ status: 'trial', trial: { lost: null, pingError: expect.stringMatching(/No Model:Cycles answered/) } }) + now += 11000 + expect((await service.call('device_status')).state).toMatchObject({ status: 'trial-lost', trial: { lost: expect.stringMatching(/ten quiet seconds/) } }) + await service.call('device_undo', { trial: again.trial }) + } finally { vi.useRealTimers(); now = 0; child.stdin.end() } + }, 30000) + // The unit did the Keep (or the Undo) but its answer went missing: the trial stays, and once the unit no longer has + // it, its active set says which way it went. + it.skipIf(!cc)('tells a Keep or Undo whose answer was lost by the unit\'s active set', async () => { + const { child, loader, pkg } = hostLoader() + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) + const pinged = async (access, before) => { vi.advanceTimersByTime(3000); while ((access.requests[1] ?? 0) <= before) await new Promise(resolve => setTimeout(resolve, 5)) } + try { + await writeFile(join(images, 'frames.mwrm'), pkg) + const access = fakeCycles({ crc: 0x12345678, bytes: 64 }, undefined, null, null, loader) + service = await open(access, { allowDeviceWrites: true }) + // a Keep that went through: the ping finds the trial over on another set, and device_keep says it was kept + const review = await service.call('device_review', { moduleIds: ['frames.mwrm'] }) + const trial = await service.call('device_trial', { review: review.review }) + access.lose.cmd = 6 // ACCEPT + await expect(service.call('device_keep', { trial: trial.trial })).rejects.toThrow(/Keep did not finish.*trial stays on/s) + await pinged(access, access.requests[1]) + expect((await service.call('device_status')).state).toMatchObject({ status: 'trial-kept', trial: { lost: null, kept: expect.stringMatching(/a Keep went through/) } }) + const kept = await service.call('device_keep', { trial: trial.trial }) + expect(kept).toMatchObject({ kept: true, completed: true, note: expect.stringMatching(/a Keep went through/) }) + expect(kept.active).not.toBe(review.active) + expect((await service.call('device_status')).state.status).toBe('ready') + // an Undo that went through: device_undo again reports it undone + const before = await service.call('device_review', { moduleIds: ['remove:frames'] }) + const again = await service.call('device_trial', { review: before.review }) + access.lose.cmd = 7 // ROLLBACK + await expect(service.call('device_undo', { trial: again.trial })).rejects.toThrow(/Undo did not finish.*trial stays on/s) + const undone = await service.call('device_undo', { trial: again.trial }) + expect(undone).toMatchObject({ kept: false, completed: true, active: before.active, note: expect.stringMatching(/undone/) }) + } finally { vi.useRealTimers(); child.stdin.end() } + }, 30000) +}) diff --git a/sdk/machines/model-cycles/LINK.md b/sdk/machines/model-cycles/LINK.md index 705a178902..1a37abb0b6 100644 --- a/sdk/machines/model-cycles/LINK.md +++ b/sdk/machines/model-cycles/LINK.md @@ -65,7 +65,7 @@ Status: 0 ok, 1 not armed, 2 bad request, 3 busy, 4 out of range, 5 a person is | `up_run` | 0x32 | runs the frame's first N bytes as one wire request; the upload controller's 144-byte response, packed | | `mods` | 0x33 | the module pool's free bytes and largest run, the last refusal, the live count and up to three inventory entries from the n-th | -The set identity tells a host which build runs: `mc_link.py runid IMAGE.syx` computes the same two numbers from a built image and the patcher's `IMAGE.syx.json` (the `.run` block sits at the layout's `run_load` in the MAIN OS and is copied unchanged to DDR). The base cannot carry its own package hash; the build that made the image knows it. `mc_link.py rundiff IMAGE.syx` reads the running block and lists every word that differs from the image. +The set identity tells a host which build runs: `mc_link.py runid IMAGE.syx` computes the same two numbers from a built image and the patcher's `IMAGE.syx.json` (the `.run` block sits at the layout's `run_load` in the MAIN OS and is copied unchanged to DDR). The base cannot carry its own package hash; the build that made the image knows it. The developer MCP reads the same identity with `device_status` (`--elektron-midi`, [FRONTEND_MCP.md](../../../docs/FRONTEND_MCP.md#a-modelcycles-over-its-link)) and names the matching image in `--elektron-images`. `mc_link.py rundiff IMAGE.syx` reads the running block and lists every word that differs from the image. The screen needs no command: stock answers Elektron's own screenshot request over USB. @@ -88,6 +88,10 @@ mc_link.py keep | undo mc_link.py remove NAME --seconds 5 [--keep] # an empty package with NAME's id: that module out, on trial ``` +The developer MCP does the same with `device_review`, `device_trial`, `device_keep` and `device_undo` +([FRONTEND_MCP.md](../../../docs/FRONTEND_MCP.md#a-modelcycles-over-its-link)), through +[`mc-link.ts`](../../../src/engine/elektron/mc-link.ts)'s `mcUploadTransport` and the site's `UploadSession`. + A module patches stock code at declared sites: [`tools/build_sites.py`](tools/build_sites.py) `--sites SITES.json` (around the loader's `build.py`) takes them in base.json's format (a `jsr` or `jmp` to a function of the module, the stock bytes' SHA-256), and the base checks the running code before it patches and puts the stock bytes back at an undo or a removal. [`examples/frames.c`](elekloader/examples/frames.c) @@ -189,9 +193,9 @@ Left as stock has it: id `0x04`'s commands 1 and 3 (`0x40080822`, `0x4008084a`) first was not read (the scheduler's order of priorities); the link covers both orders. On a unit: not run yet on this build. -The audio load (`base/load.c`, `load.s`, every base): the base's probe replaces the audio interrupt's call of the audio function (OS 1.13 `0x40059382`, `jsr 0x4005979e`) and reads DMA timer 0 before and after it, 90,112 ticks a codec block. Over 750 blocks (half a second) the busy ticks give the share; about 25 instructions a block. On the Model:Cycles every voice runs whether a pattern plays or not, so the load hardly changes with the sequencer. +The audio load (`base/load.c`, `load.s`, every base): the base's probe replaces the audio interrupt's call of the audio function (OS 1.13 `0x40059382`, `jsr 0x4005979e`) and reads DMA timer 0 before and after it, 90,112 ticks a codec block. Over 750 blocks (half a second) the busy ticks give the share; about 25 instructions a block. On the Model:Cycles every voice runs whether a pattern plays or not, so the load hardly changes with the sequencer. The developer MCP's `device_load` reads it (`--elektron-midi`). -The diagnostics log (`base/diag.c`, `diag.h`, every base) is the Octatrack's, layout version 2, so the site's parser reads it unchanged (`sdk/tests/test_machine_base.py` checks the layout word for word). Every five minutes a load record: the mean of the half-second windows and the dearest block (per mille), the longest time between two codec blocks (µs) and the longest run of blocks without a UI tick. Incidents: START and BASE (the set identity) at a boot's first tick, HOT for a second at 90 % or more, FREEZE when the UI tick stands still for five seconds while audio runs, each with the six tracks' machines and the last 16 keys pressed. The DSP fields, the tempo, the screen and `playing` stay 0. It lives in the base's memory and starts again at every boot: a freeze that needs a power cycle is lost with it. The audio interrupt keeps the sums; the UI tick alone writes the records. `test_diag.c` runs it on the host. +The diagnostics log (`base/diag.c`, `diag.h`, every base) is the Octatrack's, layout version 2, so the site's parser reads it unchanged (`sdk/tests/test_machine_base.py` checks the layout word for word). Every five minutes a load record: the mean of the half-second windows and the dearest block (per mille), the longest time between two codec blocks (µs) and the longest run of blocks without a UI tick. Incidents: START and BASE (the set identity) at a boot's first tick, HOT for a second at 90 % or more, FREEZE when the UI tick stands still for five seconds while audio runs, each with the six tracks' machines and the last 16 keys pressed. The DSP fields, the tempo, the screen and `playing` stay 0. It lives in the base's memory and starts again at every boot: a freeze that needs a power cycle is lost with it. The audio interrupt keeps the sums; the UI tick alone writes the records. `test_diag.c` runs it on the host. The developer MCP's `device_log` reads it through `log` (`--elektron-midi`). ## Evidence @@ -223,6 +227,7 @@ On the submitter's Model:Cycles, OS 1.13, 23 November 2026, `mc_link.py` from a | the same | `try frames.mwrm --seconds 5 --keep`, then `try v2/frames.mwrm --seconds 20` | "F1 n", on trial "F2 n" counting on, after the undo "F1 n" again; 1 live (`594cfd26 frames`) | | the same | `try hello.mwrm --seconds 5 --keep` beside frames, then `remove frames --seconds 5 --keep`, `mem 0x40007678 6` | 2 live, "F1 n" and the square; after the removal 1 live (`2cf24dba`), "F1" gone, the square stays, 65200 bytes free; the site holds the stock bytes | | `7c794349…` (dev base `d1cc7df8`, the loader at 0x31-0x33), RAM-booted | `try frames.mwrm --seconds 10` | on trial, "F1 n" counting (the OS composes frames without a turn too); undone, 0 live | +| `7c794349…` RAM-booted again | the developer MCP: `device_review` and `device_trial` with `frames.mwrm` for 15 s, `device_undo`, a second trial and `device_keep`, `device_status` | "F1 n" all 15 s (the MCP's pings); undone to the base's set; kept: 1 live (`594cfd26 frames`) | | the same | `try hello.mwrm --seconds 30`, PLAY on trial; STOP 5 s after the tool ends | the pattern plays without dropouts (tester's report); at the end `enter: unsafe (phase trial)`, the square stays while playing and goes about 10 s after the tool ended; 0 live | | `7c794349…` RAM-booted from `520f99e7…` | `try big33.mwrm` (33,832 bytes, past the 32 KiB staging), `mods` 15 s later | `begin: limit (too large)`; nothing loaded, 65536 bytes free, no refusal counted (the controller refuses before the loader sees it) | | the same | `try --keep` two modules of 31,832 bytes each, then a third | both kept, 1504 bytes free; the third `verify: rejected`, last refusal `memory`, the two still live and drawing | diff --git a/sdk/machines/model-cycles/README.md b/sdk/machines/model-cycles/README.md index 9ce9f8c9ed..a93d59a4fe 100644 --- a/sdk/machines/model-cycles/README.md +++ b/sdk/machines/model-cycles/README.md @@ -6,7 +6,7 @@ The Model:Cycles is in research for stock OS 1.13. Its Modwerk base is in develo The Model:Cycles follows the Octatrack's stack ([recipe](../../../docs/MACHINE_RECIPE.md)). Its [Modwerk base](elekloader/README.md) starts from drumkilla's core-mc 0.3 at Elekloader v0.11.0, imported unchanged. Modwerk adds one hook, `ev_key_leds`, as the Digitakt II has it. The base owns the six sites below; a module subscribes to them and never patches them. What several modules will share (pages behind a stock key, menu rows, per-kit state) goes into the base before the first module that needs it ([choose how a module hooks in](../../../docs/module-guides/README.md#choose-how-a-module-hooks-in)). A site only one module needs stays that module's own declared site (`platform.claims`). -The Model:Cycles gets the whole stack before its base is released (owner, 23 November 2026). The USB link is started, after the Rytm's: every base answers its identity over USB MIDI SysEx, measures the audio's share of the CPU (`load`), keeps a diagnostics log in the Octatrack's layout that `log` reads, and carries the Octatrack's runtime loader, so `mc_link.py try` loads a module to RAM on trial, keeps it or undoes it without a reflash ([LINK.md](LINK.md)). Development bases add memory reads, panel keys and encoder turns, and a RAM boot of an uploaded image. Flashing from the site is started: the machine page builds the pinned base from the owner's own OS file in the browser (a local build preview, `CORE_BUILD_PREVIEWS`), byte for byte the image `machine:base` and Elekloader's patcher build; downloads stay off until review. The page can also send a build over USB as a stock OS update (`usb-upgrade.ts`, the unit asks UPGRADE OS NOW?); that button waits for the same approval as downloads. The sender ran on a unit (24 November 2026). The device tools are not started. The first module, Control All Config, waits for the base. +The Model:Cycles gets the whole stack before its base is released (owner, 23 November 2026). The USB link is started, after the Rytm's: every base answers its identity over USB MIDI SysEx, measures the audio's share of the CPU (`load`), keeps a diagnostics log in the Octatrack's layout that `log` reads, and carries the Octatrack's runtime loader, so `mc_link.py try` loads a module to RAM on trial, keeps it or undoes it without a reflash ([LINK.md](LINK.md)). Development bases add memory reads, panel keys and encoder turns, and a RAM boot of an uploaded image. The MCP's `device_status` reads the link's identity and names the build the unit runs, `device_load` reads the audio load, `device_log` the diagnostics log through `log`, and `device_review`, `device_trial`, `device_keep` and `device_undo` load a module through the runtime loader (`--elektron-midi`, [FRONTEND_MCP.md](../../../docs/FRONTEND_MCP.md#a-modelcycles-over-its-link)). Flashing from the site is started: the machine page builds the pinned base from the owner's own OS file in the browser (a local build preview, `CORE_BUILD_PREVIEWS`), byte for byte the image `machine:base` and Elekloader's patcher build; downloads stay off until review. The page can also send a build over USB as a stock OS update (`usb-upgrade.ts`, the unit asks UPGRADE OS NOW?); that button waits for the same approval as downloads. The sender ran on a unit (24 November 2026). The first module, Control All Config, waits for the base. ## Core hooks diff --git a/sdk/machines/model-cycles/elekloader/base/test_modules.c b/sdk/machines/model-cycles/elekloader/base/test_modules.c index 69fd3485e4..5590d7ddc3 100644 --- a/sdk/machines/model-cycles/elekloader/base/test_modules.c +++ b/sdk/machines/model-cycles/elekloader/base/test_modules.c @@ -4,6 +4,7 @@ // P offset hex an UP_PART's packed bytes -> the bytes taken // R length an UP_RUN -> the controller's response in hex, or an empty line // T n n UI ticks -> the lapses counted so far +// S 0 or 1 the transport playing (0) or stopped (1), as runtime.c reads it -> the same // cc -std=c99 -DMODWERK_HOST -I sdk/runtime/loader -I sdk/runtime/upload test_modules.c modules.c runtime.c // sdk/runtime/loader/loader.c sdk/runtime/upload/{upload,wire,sha256}.c #include @@ -15,6 +16,7 @@ unsigned mw_modules_run(uint32_t length, uint8_t *out); void mw_modules_identity(uint32_t crc); void mw_modules_tick(void); extern volatile uint32_t mw_modules_lapses; +extern int modwerk_test_stopped; int main(void) { @@ -34,6 +36,9 @@ int main(void) unsigned k = mw_modules_run(v, out); for (unsigned i = 0; i < k; i++) printf("%02x", out[i]); printf("\n"); + } else if (op == 'S') { + modwerk_test_stopped = (int)v; + printf("%u\n", v); } else { while (v--) mw_modules_tick(); printf("%u\n", (unsigned)mw_modules_lapses); diff --git a/sdk/machines/model-cycles/machine.json b/sdk/machines/model-cycles/machine.json index 0a93aaa299..76ffd33d33 100644 --- a/sdk/machines/model-cycles/machine.json +++ b/sdk/machines/model-cycles/machine.json @@ -32,7 +32,8 @@ "link": "started", "flash": "started", "loader": "started", - "diagnostics": "started" + "diagnostics": "started", + "tools": "started" }, "research": [ { diff --git a/src/devices/machines.generated.json b/src/devices/machines.generated.json index 73f6db97f9..1459d5ca98 100644 --- a/src/devices/machines.generated.json +++ b/src/devices/machines.generated.json @@ -1067,7 +1067,7 @@ "loader": "started", "status": "open", "diagnostics": "started", - "tools": "open" + "tools": "started" }, "art": { "body": "model", diff --git a/src/engine/elektron/dn2-link.ts b/src/engine/elektron/dn2-link.ts index e4aec640b1..f4b70f2c5b 100644 --- a/src/engine/elektron/dn2-link.ts +++ b/src/engine/elektron/dn2-link.ts @@ -4,15 +4,16 @@ // the reads the page and the diagnostics need: the link's identity, memory, the screen and the diagnostics log, which // is the Octatrack's layout and reads with parseDeviceLog. No keys, turns or RAM boot from here. The one command // that changes the unit is `upload`, which carries the runtime loader's upload controller (uploadTransport): modules -// load to RAM for a trial, and a power cycle ends them (sdk/machines/digitone-ii/LOADER.md). +// load to RAM for a trial, and a power cycle ends them (sdk/machines/digitone-ii/LOADER.md). The wire itself, shared +// with the Model:Cycles, is link-wire.ts; this file keeps the Digitone II's commands and status wording. // Transport-free (LinkLine): the page gives it Web MIDI, a test a simulated unit. import { sha } from '../../../vendor/elekloader/kit/src/bytes.ts' import { DEVICE_LOG_IMAGE_BYTES, parseDeviceLog, type DeviceLog } from '../elekloader/device-log.ts' import type { UploadTransport } from '../elekloader/upload-session.ts' import { UPLOAD_RESPONSE } from '../elekloader/upload-wire.ts' +import { askLink, get32, LinkError, linkFrame, pack7, u32, unpack7, type LinkLine } from './link-wire.ts' -/** F0 7D 'M' 'W' 'L' version: the link's header, a request's and a reply's. */ -export const LINK_HEADER = [0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1] as const +export { get32, LINK_HEADER, LinkError, pack7, parseLinkReply, u32, unpack7, type LinkLine } from './link-wire.ts' export const LINK_COMMANDS = { ident: 0x01, mem: 0x21, diag: 0x22, upload: 0x30 } as const export type LinkCommand = keyof typeof LINK_COMMANDS export const LINK_STATUS: Readonly> = { @@ -23,66 +24,13 @@ export const MEM_MAX = 128 /** Stock keeps two frame pointers side by side (OS 1.12): the frame on the screen is the second's. 128x64, 1 bit. */ export const FRAME_POINTERS = 0x402a10c8, FRAME_BYTES = 1024 -/** SysEx in and out: whole messages, F0 to F7. next() waits up to `ms` and gives null when none came. */ -export type LinkLine = { send(data: Uint8Array): void; next(ms: number): Promise } -export class LinkError extends Error { - readonly status?: number - constructor(message: string, status?: number) { super(message); this.status = status } -} - -/** A u32 as five 7-bit bytes, least significant first. */ -export function u32(value: number): number[] { - return Array.from({ length: 5 }, (_, i) => Math.floor(value / 2 ** (7 * i)) & 0x7f) -} -export function get32(bytes: Uint8Array, at: number): number { - return (bytes[at] | bytes[at + 1] << 7 | bytes[at + 2] << 14 | bytes[at + 3] << 21) + (bytes[at + 4] & 0x0f) * 2 ** 28 -} -/** The link's byte blocks: groups of up to seven, each led by a byte holding their top bits (the first's in bit 6). */ -export function unpack7(bytes: Uint8Array): Uint8Array { - const out: number[] = [] - for (let i = 0; i < bytes.length; i += 8) { - const top = bytes[i] - bytes.subarray(i + 1, i + 8).forEach((byte, k) => out.push(byte | (top & 0x40 >> k ? 0x80 : 0))) - } - return Uint8Array.from(out) -} - -/** link.c's byte blocks from bytes: groups of up to seven, each led by a byte holding their top bits. */ -export function pack7(data: Uint8Array): number[] { - const out: number[] = [] - for (let i = 0; i < data.length; i += 7) { - const chunk = data.subarray(i, i + 7) - out.push(chunk.reduce((top, b, k) => top | (b & 0x80 ? 0x40 >> k : 0), 0), ...Array.from(chunk, b => b & 0x7f)) - } - return out -} - export function linkRequest(seq: number, command: LinkCommand, ...values: number[]): Uint8Array { - return linkRequestWith(seq, command, values, []) -} -function linkRequestWith(seq: number, command: LinkCommand, values: number[], raw: number[]): Uint8Array { - return Uint8Array.from([...LINK_HEADER, seq & 0x7f, LINK_COMMANDS[command], ...values.flatMap(u32), ...raw, 0xf7]) + return linkFrame(seq, LINK_COMMANDS[command], values.flatMap(u32)) } -/** A reply's sequence, command, status and payload; null for anything that is not one. */ -export function parseLinkReply(message: Uint8Array): { seq: number; command: number; status: number; payload: Uint8Array } | null { - if (message.length < LINK_HEADER.length + 4 || message.at(-1) !== 0xf7 || LINK_HEADER.some((b, i) => message[i] !== b) || !(message[7] & 0x40)) return null - return { seq: message[6], command: message[7] & 0x3f, status: message[8], payload: message.subarray(9, -1) } -} - -let nextSeq = 0 -/** One request and its reply; throws a LinkError on a refusal or no answer. */ +/** One request and its reply (link-wire's askLink with the Digitone II's commands and status wording); throws a + * LinkError on a refusal or no answer. */ export async function ask(line: LinkLine, command: LinkCommand, values: number[] = [], timeoutMs = 2000, raw: number[] = []): Promise { - const seq = nextSeq = (nextSeq + 1) & 0x7f - line.send(linkRequestWith(seq, command, values, raw)) - for (const end = Date.now() + timeoutMs; Date.now() < end;) { - const message = await line.next(Math.max(1, end - Date.now())) - if (!message) break - const reply = parseLinkReply(message) - if (!reply || reply.seq !== seq || reply.command !== LINK_COMMANDS[command]) continue - if (reply.status) throw new LinkError(`${command}: ${LINK_STATUS[reply.status] ?? 'status ' + reply.status}`, reply.status) - return reply.payload - } - throw new LinkError(`${command}: no answer. Is a development base with the link on the unit?`) + return askLink(line, LINK_COMMANDS[command], [...values.flatMap(u32), ...raw], { timeoutMs, label: command, status: LINK_STATUS }) } export type LinkIdent = { version: number; received: number; dropped: number; ticks: number; armed?: boolean; person?: boolean; bootStatus?: number } diff --git a/src/engine/elektron/link-wire.test.ts b/src/engine/elektron/link-wire.test.ts new file mode 100644 index 0000000000..32e790e6d6 --- /dev/null +++ b/src/engine/elektron/link-wire.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { askLink, get32, LINK_HEADER, linkExchange, linkFrame, LinkError, pack7, parseLinkReply, u32, unpack7, type LinkLine } from './link-wire' + +/** A unit on the shared wire: answers every request with `status` and `payload` for the same sequence and command, + * after an unrelated message and an echo of the request. */ +function unit(status: number, payload: number[], answer = true): LinkLine & { sent: Uint8Array[] } { + const queue: Uint8Array[] = [], sent: Uint8Array[] = [] + return { + sent, + send(data) { + sent.push(data) + queue.push(Uint8Array.of(0xf0, 0x00, 0x20, 0x3c, 0x10, 0, 0xf7), data) + if (answer) queue.push(Uint8Array.from([...LINK_HEADER, data[6], data[7] | 0x40, status, ...payload, 0xf7])) + }, + async next() { return queue.shift() ?? null }, + } +} + +describe('the shared link wire', () => { + it('frames a request and parses its reply with a numeric command', () => { + expect([...linkFrame(0x85, 0x24, u32(300))]).toEqual([0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1, 0x05, 0x24, 44, 2, 0, 0, 0, 0xf7]) + expect(parseLinkReply(Uint8Array.from([...LINK_HEADER, 5, 0x64, 0, 1, 2, 0xf7]))).toEqual({ seq: 5, command: 0x24, status: 0, payload: Uint8Array.of(1, 2) }) + expect(parseLinkReply(linkFrame(5, 0x24))).toBeNull() // a request, not a reply + expect(get32(Uint8Array.from(u32(0xf2fe7324)), 0)).toBe(0xf2fe7324) + const bytes = Uint8Array.of(0x80, 1, 0xff, 3, 4, 5, 6, 0x87, 9) + expect(unpack7(Uint8Array.from(pack7(bytes)))).toEqual(bytes) + }) + it('passes over other messages and the echo, and gives null without a reply', async () => { + expect(await linkExchange(unit(0, [7]), 9, 0x23, [], 50)).toEqual({ seq: 9, command: 0x23, status: 0, payload: Uint8Array.of(7) }) + expect(await linkExchange(unit(0, [], false), 9, 0x23, [], 50)).toBeNull() + }) + it('asks with the caller\'s wording and names no machine', async () => { + expect(await askLink(unit(0, [1, 2]), 0x01)).toEqual(Uint8Array.of(1, 2)) + await expect(askLink(unit(2, []), 0x23, [], { label: 'load', status: { 2: 'bad request' } })).rejects.toThrow('load: bad request') + const quiet = askLink(unit(0, [], false), 0x23, [], { timeoutMs: 20 }) + await expect(quiet).rejects.toBeInstanceOf(LinkError) + await expect(quiet).rejects.toThrow('command 0x23: no answer. Is a Modwerk base with the link on the unit?') + }) +}) diff --git a/src/engine/elektron/link-wire.ts b/src/engine/elektron/link-wire.ts new file mode 100644 index 0000000000..c7ec638f60 --- /dev/null +++ b/src/engine/elektron/link-wire.ts @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Modwerk SysEx link's wire, shared by every machine that speaks it (the Analog Rytm MKII's format: the Digitone II +// in dn2-link.ts, the Model:Cycles in mc-link.ts): the header, a request, a reply, a request and its reply over a line, +// and the 7-bit numbers and byte blocks. A request is F0 7D 'M' 'W' 'L' version, a sequence byte, the command, its body +// and F7; the reply carries the same sequence, the command with 0x40 set, a status byte (0 = ok) and a payload. Each +// machine keeps its own command table and status wording; nothing here names a machine. + +/** F0 7D 'M' 'W' 'L' version: the link's header, a request's and a reply's. */ +export const LINK_HEADER = [0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1] as const + +/** SysEx in and out: whole messages, F0 to F7. next() waits up to `ms` and gives null when none came. */ +export type LinkLine = { send(data: Uint8Array): void; next(ms: number): Promise } +export class LinkError extends Error { + readonly status?: number + constructor(message: string, status?: number) { super(message); this.status = status } +} + +/** A u32 as five 7-bit bytes, least significant first. */ +export function u32(value: number): number[] { + return Array.from({ length: 5 }, (_, i) => Math.floor(value / 2 ** (7 * i)) & 0x7f) +} +export function get32(bytes: Uint8Array, at: number): number { + return (bytes[at] | bytes[at + 1] << 7 | bytes[at + 2] << 14 | bytes[at + 3] << 21) + (bytes[at + 4] & 0x0f) * 2 ** 28 +} +/** The link's byte blocks: groups of up to seven, each led by a byte holding their top bits (the first's in bit 6). */ +export function unpack7(bytes: Uint8Array): Uint8Array { + const out: number[] = [] + for (let i = 0; i < bytes.length; i += 8) { + const top = bytes[i] + bytes.subarray(i + 1, i + 8).forEach((byte, k) => out.push(byte | (top & 0x40 >> k ? 0x80 : 0))) + } + return Uint8Array.from(out) +} +/** link.c's byte blocks from bytes: groups of up to seven, each led by a byte holding their top bits. */ +export function pack7(data: Uint8Array): number[] { + const out: number[] = [] + for (let i = 0; i < data.length; i += 7) { + const chunk = data.subarray(i, i + 7) + out.push(chunk.reduce((top, b, k) => top | (b & 0x80 ? 0x40 >> k : 0), 0), ...Array.from(chunk, b => b & 0x7f)) + } + return out +} + +/** A request: header, sequence, command, body (already 7-bit), F7. */ +export function linkFrame(seq: number, command: number, body: readonly number[] = []): Uint8Array { + return Uint8Array.from([...LINK_HEADER, seq & 0x7f, command, ...body, 0xf7]) +} +/** A reply's sequence, command, status and payload; null for anything that is not one (a request echoed back included). */ +export function parseLinkReply(message: Uint8Array): { seq: number; command: number; status: number; payload: Uint8Array } | null { + if (message.length < LINK_HEADER.length + 4 || message.at(-1) !== 0xf7 || LINK_HEADER.some((b, i) => message[i] !== b) || !(message[7] & 0x40)) return null + return { seq: message[6], command: message[7] & 0x3f, status: message[8], payload: message.subarray(9, -1) } +} + +/** Send request `seq` and wait up to `timeoutMs` for its reply, passing over any other message: its status and + * payload, or null when none came. */ +export async function linkExchange(line: LinkLine, seq: number, command: number, body: readonly number[], timeoutMs: number): Promise<{ status: number; payload: Uint8Array } | null> { + line.send(linkFrame(seq, command, body)) + for (const end = Date.now() + timeoutMs; Date.now() < end;) { + const message = await line.next(Math.max(1, end - Date.now())) + if (!message) break + const reply = parseLinkReply(message) + if (reply && reply.seq === (seq & 0x7f) && reply.command === command) return reply + } + return null +} + +export type LinkAsk = { timeoutMs?: number; label?: string; status?: Readonly> } +let nextSeq = 0 +/** One request and its payload; throws a LinkError on a refusal (worded from `status`) or no answer. */ +export async function askLink(line: LinkLine, command: number, body: readonly number[] = [], { timeoutMs = 2000, label, status = {} }: LinkAsk = {}): Promise { + const name = label ?? 'command 0x' + command.toString(16).padStart(2, '0') + const reply = await linkExchange(line, nextSeq = (nextSeq + 1) & 0x7f, command, body, timeoutMs) + if (!reply) throw new LinkError(`${name}: no answer. Is a Modwerk base with the link on the unit?`) + if (reply.status) throw new LinkError(`${name}: ${status[reply.status] ?? 'status ' + reply.status}`, reply.status) + return reply.payload +} diff --git a/src/engine/elektron/mc-link.test.ts b/src/engine/elektron/mc-link.test.ts new file mode 100644 index 0000000000..a9ca45942b --- /dev/null +++ b/src/engine/elektron/mc-link.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, it } from 'vitest' +import { packSection } from '../aplib' +import { contentChecksum, encodeSyx } from './sysex' +import { ELE3_DEVICES } from './ele3' +import { MC_PART_BYTES, McRefused, mcModules, mcRemovalPackage, mcReply, mcRequest, mcSetIdentity, mcUploadBase, mcUploadTransport, parseMcIdent, parseMcLoad, readMcIdentity, readMcLoad, type McCall } from './mc-link' +import { pack7, unpack7 } from './dn2-link' +import type { MidiAccessLike, MidiIn, MidiOut } from './os-upgrade-midi' + +const put32 = (v: number) => [0, 1, 2, 3, 4].map(i => v >>> 7 * i & 0x7f) +const identPayload = (fields: number[]) => fields.flatMap(put32) +// link.c's ident order: version, received, dropped, ticks, port, sent, failures, armed, person, presses, posted, +// refused, mailbox, boot status, boot image CRC, set CRC, set bytes +const FIELDS = [1, 3, 0, 395, 2, 2, 0, 1, 0, 0, 0, 0, 0x4d574253, 1, 0x36fc4fa1, 0xf2fe7324, 5764] +// link.c's begin(): the reply carries the command with 0x40 set +const reply = (seq: number, body: number[], status = 0, cmd = 0x41) => Uint8Array.from([0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1, seq, cmd, status, ...body, 0xf7]) + +describe('the Model:Cycles link', () => { + it('asks for the identity in the Rytm link wire format', () => { + expect([...mcRequest(0x85, 1)]).toEqual([0xf0, 0x7d, 0x4d, 0x57, 0x4c, 1, 0x05, 1, 0xf7]) + }) + it('reads every ident field, the set identity included', () => { + const payload = mcReply(reply(9, identPayload(FIELDS)), 9, 1)! + expect(parseMcIdent(payload)).toEqual({ + linkVersion: 1, port: 'USB', armed: true, personAtUnit: false, + counts: { received: 3, dropped: 0, sent: 2, sendFailures: 0, posted: 0, refused: 0, ticks: 395 }, + ramBoot: { status: 'booted from RAM', imageCrc: 0x36fc4fa1 }, set: { crc: 0xf2fe7324, bytes: 5764 }, + }) + }) + it('reads an older base without the set identity, and refuses a short one', () => { + expect(parseMcIdent(Uint8Array.from(identPayload(FIELDS.slice(0, 15)))).set).toBeNull() + expect(() => parseMcIdent(Uint8Array.from(identPayload(FIELDS.slice(0, 14))))).toThrow('short identity') + }) + it('ignores other messages and reports a refusal', () => { + expect(mcReply(reply(8, []), 9, 1)).toBeNull() + expect(mcReply(reply(9, [], 0, 0x01), 9, 1)).toBeNull() // a request echoed back, not a reply + expect(mcReply(Uint8Array.from([0xf0, 0x00, 0x20, 0x3c, 0x10, 0, 0, 0, 0, 0xf7]), 9, 1)).toBeNull() + expect(() => mcReply(reply(9, [], 2), 9, 1)).toThrow('bad request') + }) + it('asks the unit whose port names a Model:Cycles, and gives up quietly without one', async () => { + const sent: number[][] = [] + const input: MidiIn = { id: 'i', name: 'Elektron Model:Cycles', onmidimessage: null } + const output: MidiOut = { id: 'o', name: 'Elektron Model:Cycles', send(data) { sent.push(data); queueMicrotask(() => input.onmidimessage?.({ data: reply(data[6], identPayload(FIELDS)) })) } } + const access: MidiAccessLike = { inputs: new Map([['i', input]]), outputs: new Map([['o', output]]) } + expect((await readMcIdentity(access))?.set).toEqual({ crc: 0xf2fe7324, bytes: 5764 }) + expect(sent).toHaveLength(1) + expect(input.onmidimessage).toBeNull() + expect(await readMcIdentity({ inputs: new Map(), outputs: new Map() })).toBeNull() + }) + it('reads the load in tenths of a percent, with no window share before the first window ends', () => { + expect(parseMcLoad(Uint8Array.from(identPayload([738, 801, 849, 12, 9000])))).toEqual({ windowPercent: 73.8, windowPeakPercent: 80.1, peakPercent: 84.9, windows: 12, blocks: 9000 }) + expect(parseMcLoad(Uint8Array.from(identPayload([0, 0, 812, 0, 400])))).toMatchObject({ windowPercent: null, windowPeakPercent: null, peakPercent: 81.2 }) + expect(() => parseMcLoad(Uint8Array.from(identPayload([1, 2, 3, 4])))).toThrow('short load') + }) + it('asks for the load with 0x23 and reads a refusal as an older base', async () => { + const unit = (status: number, body: number[]) => { + const sent: number[][] = [] + const input: MidiIn = { id: 'i', name: 'Elektron Model:Cycles', onmidimessage: null } + const output: MidiOut = { id: 'o', name: 'Elektron Model:Cycles', send(data) { sent.push(data); queueMicrotask(() => input.onmidimessage?.({ data: reply(data[6], body, status, data[7] | 0x40) })) } } + return { sent, access: { inputs: new Map([['i', input]]), outputs: new Map([['o', output]]) } as MidiAccessLike } + } + const ok = unit(0, identPayload([738, 801, 849, 12, 9000])) + expect(await readMcLoad(ok.access)).toMatchObject({ windowPercent: 73.8 }) + expect(ok.sent[0][7]).toBe(0x23) + expect(await readMcLoad(unit(2, []).access)).toBe('unsupported') + await expect(readMcLoad(unit(3, []).access)).rejects.toBeInstanceOf(McRefused) + }) + it('computes the set identity from the end of a built image', () => { + // a generated container, no firmware bytes: the last 64 bytes stand for the linked .run block + const image = Uint8Array.from({ length: 512 }, (_, i) => i * 7 % 251), packed = packSection(image) + const container = new Uint8Array(64 + packed.length + (-packed.length & 15)), view = new DataView(container.buffer) + container.set([0x45, 0x4c, 0x45, 0x33]) + view.setUint32(0x1c, 1); view.setUint32(0x20, 3); view.setUint32(0x24, 64); view.setUint32(0x28, packed.length); view.setUint32(0x2c, 0x40000400) + container.set(packed, 64) + const stream = new Uint8Array(8 + container.length), streamView = new DataView(stream.buffer) + streamView.setUint32(0, container.length); streamView.setUint32(4, contentChecksum(container)); stream.set(container, 8) + const id = ELE3_DEVICES['model-cycles'].sysexId, framing = Uint8Array.from([0xf0, 0, 0x20, 0x3c, id, 0, 0x7d, 0, 0x10, 1, 2, 3, 0, 0, 0, 0xf7]) + const syx = encodeSyx(stream, id, framing, framing) + // zlib's crc32 of the last 64 bytes, computed independently + let c = 0xffffffff + for (const b of image.subarray(448)) { c ^= b; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ c >>> 1 : c >>> 1 } + expect(mcSetIdentity(syx, 64)).toEqual({ crc: (c ^ 0xffffffff) >>> 0, bytes: 64 }) + expect(() => mcSetIdentity(syx, 513)).toThrow('larger than the image') + }) +}) + +describe('the Model:Cycles runtime loader over the link', () => { + it('binds uploads to the SHA-256 of the set CRC, big-endian (base/modules.c)', () => { + // python3: hashlib.sha256(bytes.fromhex('f8812876')).hexdigest() + expect(mcUploadBase(0xf8812876)).toBe('ce2bb2aa7f867fb9932446cac1eb45c726561979bb5f75ffe10f6efdbd31b5d9') + }) + it('sends a frame in parts under 128 bytes, then runs it and decodes the 144-byte response', async () => { + const frame = Uint8Array.from({ length: 2100 }, (_, i) => (i * 37 + (i >> 8)) & 0xff) + const got = new Uint8Array(2100), sizes: number[] = [], response = Uint8Array.from({ length: 144 }, (_, i) => 255 - i) + let ran = 0 + const call: McCall = async (cmd, body = []) => { + sizes.push(8 + body.length + 1) + const at = body[0] | body[1] << 7 | body[2] << 14 + if (cmd === 0x31) { got.set(unpack7(Uint8Array.from(body.slice(5))), at); return new Uint8Array() } + if (cmd === 0x32) { ran = at; return Uint8Array.from(pack7(response)) } + return null + } + const out = await mcUploadTransport(call).exchange(frame, new AbortController().signal) + expect([...got]).toEqual([...frame]) + expect(ran).toBe(2100) + expect(Math.max(...sizes)).toBeLessThanOrEqual(124) + expect(sizes.length).toBe(Math.ceil(2100 / MC_PART_BYTES) + 1) + expect([...out]).toEqual([...response]) + }) + it('stops at a part the unit does not take', async () => { + const call: McCall = async () => null + await expect(mcUploadTransport(call).exchange(new Uint8Array(48), new AbortController().signal)).rejects.toThrow('did not take') + }) + it('removes a module with an empty package under its id', () => { + // mc_link.py empty_package('hello'): python3 -c "import hashlib;print(hashlib.sha256(b'hello').hexdigest()[:8])" is 2cf24dba + expect(Buffer.from(mcRemovalPackage('hello')).toString('hex')).toBe('4d57524d0004000000000000000000000000000000000000000000002cf24dba') + }) + it('lists the pool and the live modules, three a reply', async () => { + const entry = (id: number, name: string) => [0xff, 0, 0, 1, id >>> 24, id >>> 16 & 0xff, id >>> 8 & 0xff, id & 0xff, ...[...name.padEnd(16, '\0')].map(c => c.charCodeAt(0))] + const head = (n: number) => [0, 0, 0xfe, 0x60, 0, 0, 0xfe, 0x60, 0, 0, 0, 0, 0, 0, 0, 4, 0x4d, 0x57, 0x49, n] + const pages = [[...head(3), ...entry(0x594cfd26, 'frames'), ...entry(0x2cf24dba, ''), ...entry(1, 'a')], [...head(1), ...entry(2, 'b')]] + const firsts: number[] = [] + const call: McCall = async (_cmd, body = []) => { firsts.push(body[0]); return Uint8Array.from(pack7(Uint8Array.from(pages[firsts.length - 1]))) } + const list = await mcModules(call) + expect(firsts).toEqual([0, 3]) + expect(list).toEqual({ free: 65120, largest: 65120, refusal: 'none', active: 4, + modules: [{ id: '594cfd26', name: 'frames' }, { id: '2cf24dba', name: '' }, { id: '00000001', name: 'a' }, { id: '00000002', name: 'b' }] }) + }) +}) diff --git a/src/engine/elektron/mc-link.ts b/src/engine/elektron/mc-link.ts new file mode 100644 index 0000000000..acb5bbe7e4 --- /dev/null +++ b/src/engine/elektron/mc-link.ts @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// The Model:Cycles link (sdk/machines/model-cycles/LINK.md): the identity every Modwerk base reports over +// USB MIDI SysEx, and the same set identity computed from a built image. The wire format is the Analog Rytm MKII +// link's; sdk/machines/model-cycles/tools/mc_link.py speaks it from the computer. Reads: `ident`, `load`, `diag`, `log` +// and `mods`, all of them in every base (`mem` is a development base's and is not used here). The diagnostics log is the Octatrack's layout and reads with its parser, as the Digitone II's. The one +// path that changes the unit is the runtime loader's upload controller (mcUploadTransport for UploadSession): its wire +// frames go in parts, as the link takes them (base/modules.c), where the Digitone II's link takes a whole frame. The +// wire (header, request, reply, 7-bit numbers and blocks) is link-wire.ts, shared with the Digitone II; this file keeps +// the Model:Cycles' commands, status wording and readings. +import { sha } from '../../../vendor/elekloader/kit/src/bytes.ts' +import { DEVICE_LOG_IMAGE_BYTES, parseDeviceLog, type DeviceLog } from '../elekloader/device-log' +import { UploadSession, type UploadTransport } from '../elekloader/upload-session' +import { UPLOAD_RESPONSE, type UploadStatus } from '../elekloader/upload-wire' +import { get32, linkExchange, linkFrame, pack7, parseLinkReply, u32 as put32, unpack7 } from './link-wire' +import { ELE3_DEVICES, mainImage, readEle3Syx } from './ele3' +import { findUnit, midiLine, type MidiAccessLike } from './os-upgrade-midi' + +const IDENT = 0x01, DIAG = 0x22, LOAD = 0x23, LOG = 0x24, UP_PART = 0x31, UP_RUN = 0x32, MODS = 0x33 +/** An upload frame's part: 8 + 5 + 110 packed + 1 = 124 bytes a message, under the 128 of stock's upgrade messages. */ +export const MC_PART_BYTES = 96 +/** Package bytes a CHUNK frame carries: 23 parts. */ +export const MC_UPLOAD_CHUNK = 2048 +const LOG_MAX = 128 +const BAD_REQUEST = 2 +const STATUS = ['ok', 'not armed', 'bad request', 'busy', 'out of range', 'a person is at the unit'] +const PORTS: Record = { 1: 'MIDI setting', 2: 'USB', 3: 'DIN', 4: 'USB and DIN' } +const BOOT: Record = { 0: 'none', 1: 'booted from RAM', 2: 'mailbox without a software reset', 3: 'check word', + 4: 'lengths', 5: 'container CRC', 6: 'no MAIN OS section', 8: 'failed after the unpack (reset)' } +// ident's fields in order (link.c, CMD_IDENT); a base before the set identity sends the first 15. +const FIELDS = ['linkVersion', 'received', 'dropped', 'ticks', 'port', 'sent', 'sendFailures', 'armed', 'personAtUnit', + 'personPresses', 'posted', 'refused', 'mailbox', 'bootStatus', 'bootImageCrc', 'setCrc', 'setBytes'] as const +type Field = typeof FIELDS[number] + +export type McIdentity = { + linkVersion: number; port: string; armed: boolean; personAtUnit: boolean + counts: { received: number; dropped: number; sent: number; sendFailures: number; posted: number; refused: number; ticks: number } + /** What the RAM boot gate saw at this boot; meaningful only after a RAM boot was asked for. */ + ramBoot: { status: string; imageCrc: number } + /** The CRC32 and length of the running set's .run block (the base and its modules), taken at boot; null on an older base. */ + set: { crc: number; bytes: number } | null +} + +/** The audio's share of the CPU in percent, one decimal (link.c CMD_LOAD, base/load.c). */ +export type McLoad = { + /** The last half second (750 codec blocks); null until the first window has ended. */ + windowPercent: number | null + /** The dearest block of that window. */ + windowPeakPercent: number | null + /** The dearest block since boot. */ + peakPercent: number + windows: number; blocks: number +} + +/** A refusal by the unit's link, with its status byte. */ +export class McRefused extends Error { + readonly status: number + constructor(status: number) { + super('The Model:Cycles link refused: ' + (STATUS[status] ?? 'status ' + status) + '.') + this.status = status + } +} + +/** A link request: header, sequence number, command, body (link-wire's linkFrame). */ +export const mcRequest = linkFrame + +/** The reply to request `seq` and `cmd` (link.c's begin(): the command with 0x40 set), or null for any other message. + * Throws on a refusal. */ +export function mcReply(message: Uint8Array, seq: number, cmd: number): Uint8Array | null { + const reply = parseLinkReply(message) + if (!reply || reply.seq !== seq || reply.command !== cmd) return null + if (reply.status) throw new McRefused(reply.status) + return reply.payload +} + +/** ident's payload as named fields. */ +export function parseMcIdent(payload: Uint8Array): McIdentity { + const n = Math.floor(payload.length / 5) + if (n < 15) throw new Error('The Model:Cycles link sent a short identity.') + const v = Object.fromEntries(FIELDS.slice(0, n).map((name, i) => [name, get32(payload, 5 * i)])) as Record + return { + linkVersion: v.linkVersion, port: PORTS[v.port] ?? 'port ' + v.port, armed: v.armed === 1, personAtUnit: v.personAtUnit === 1, + counts: { received: v.received, dropped: v.dropped, sent: v.sent, sendFailures: v.sendFailures, posted: v.posted, refused: v.refused, ticks: v.ticks }, + ramBoot: { status: BOOT[v.bootStatus] ?? 'none', imageCrc: v.bootImageCrc }, + set: n >= 17 ? { crc: v.setCrc, bytes: v.setBytes } : null, + } +} + +/** load's payload; tenths of a percent on the wire. */ +export function parseMcLoad(payload: Uint8Array): McLoad { + if (payload.length < 25) throw new Error('The Model:Cycles link sent a short load reading.') + const [avg, wmax, peak, windows, blocks] = [0, 1, 2, 3, 4].map(i => get32(payload, 5 * i)) + return { windowPercent: windows ? avg / 10 : null, windowPeakPercent: windows ? wmax / 10 : null, peakPercent: peak / 10, windows, blocks } +} + +export type McCall = (cmd: number, body?: number[]) => Promise +/** Requests to the connected Model:Cycles over one line: each gives its reply's payload, or null without a reply; the + * whole is null without a unit. */ +export async function withMc(access: MidiAccessLike, timeoutMs: number, work: (call: McCall) => Promise): Promise { + const unit = findUnit(access, 'Model:Cycles') + if (!unit) return null + const line = midiLine(unit.input, unit.output) + let seq = Date.now() / 100 & 0x7f + const call: McCall = async (cmd, body = []) => { + const reply = await linkExchange(line, seq = seq + 1 & 0x7f, cmd, body, timeoutMs) + if (reply?.status) throw new McRefused(reply.status) + return reply ? reply.payload : null + } + try { return await work(call) } finally { line.close() } +} +const mcCall = (access: MidiAccessLike, cmd: number, timeoutMs: number) => withMc(access, timeoutMs, call => call(cmd)) + +/** Ask the connected Model:Cycles for its identity. Needs a Modwerk base; null when no unit or no reply. */ +export async function readMcIdentity(access: MidiAccessLike, timeoutMs = 2000): Promise { + const payload = await mcCall(access, IDENT, timeoutMs) + return payload && parseMcIdent(payload) +} + +/** Ask the connected Model:Cycles for its audio load: null when no unit or no reply, 'unsupported' from a development + * base without the load probe (it refuses the command as a bad request). */ +export async function readMcLoad(access: MidiAccessLike, timeoutMs = 2000): Promise { + try { + const payload = await mcCall(access, LOAD, timeoutMs) + return payload && parseMcLoad(payload) + } catch (error) { + if (error instanceof McRefused && error.status === BAD_REQUEST) return 'unsupported' + throw error + } +} + +/** The diagnostics log (base/diag.c): `diag` names its size, `log` reads it 128 bytes at a time from an offset into it + * and nothing outside it. Its bytes and the log the Octatrack's parser reads from them; null when no unit or no reply, + * 'unsupported' from a base without the log or without `log` (it refuses either as a bad request). */ +export async function readMcLog(access: MidiAccessLike, timeoutMs = 2000): Promise<{ bytes: Uint8Array; log: DeviceLog | undefined } | 'unsupported' | null> { + try { + return await withMc(access, timeoutMs, async call => { + const place = await call(DIAG) + if (!place) return null + const size = get32(place, 5) + if (size < 8 || size > DEVICE_LOG_IMAGE_BYTES) throw new Error(`The Model:Cycles link named a ${size}-byte log.`) + const bytes = new Uint8Array(size) + for (let at = 0; at < size; at += LOG_MAX) { + const n = Math.min(LOG_MAX, size - at), p = await call(LOG, [...put32(at), ...put32(n)]) + if (!p) return null + if (p.length < 10 || get32(p, 0) !== at || get32(p, 5) !== n) throw new Error('The Model:Cycles link sent another block than asked for.') + const data = unpack7(p.subarray(10)) + if (data.length !== n) throw new Error('The Model:Cycles link sent a short block.') + bytes.set(data, at) + } + const image = new Uint8Array(DEVICE_LOG_IMAGE_BYTES) + image.set(bytes) // no crash or stall record: zeros, as an older Octatrack base answers + return { bytes, log: parseDeviceLog(image) } + }) + } catch (error) { + if (error instanceof McRefused && error.status === BAD_REQUEST) return 'unsupported' + throw error + } +} + +/** The base identity a base's upload controller binds a BEGIN to (base/modules.c): the SHA-256 of its set + * CRC, big-endian, as hex. */ +export function mcUploadBase(setCrc: number): string { + return sha(Uint8Array.of(setCrc >>> 24, setCrc >>> 16 & 0xff, setCrc >>> 8 & 0xff, setCrc & 0xff)) +} + +/** The upload controller over the link, for UploadSession: a frame's parts (`up_part`), then `up_run`, whose reply is + * the controller's 144-byte response. A missing reply or a refusal throws; the session then trusts the line no more. */ +export function mcUploadTransport(call: McCall): UploadTransport { + return { + async exchange(frame, signal) { + for (let at = 0; at < frame.length; at += MC_PART_BYTES) { + if (signal.aborted) throw new Error('The upload was cancelled.') + if (!await call(UP_PART, [...put32(at), ...pack7(frame.subarray(at, at + MC_PART_BYTES))])) throw new Error('The Model:Cycles did not take an upload part.') + } + const payload = await call(UP_RUN, put32(frame.length)) + if (!payload) throw new Error('The Model:Cycles did not answer an upload frame.') + const response = unpack7(payload) + if (response.length !== UPLOAD_RESPONSE) throw new Error(`The Model:Cycles sent a ${response.length}-byte upload response.`) + return response + }, + } +} + +export type McModules = { + free: number; largest: number; refusal: string; active: number + /** The live modules' ids (hex) and names (empty for a module without one). */ + modules: { id: string; name: string }[] +} +const REFUSALS = ['none', 'malformed', 'memory', 'conflict', 'full', 'busy', 'cycles', 'in use', 'stock bytes differ', 'event site', + 'feature', 'UI open', 'buffer'] +/** The runtime loader's pool and its live modules (`mods`, three entries a reply). */ +export async function mcModules(call: McCall): Promise { + const out: McModules = { free: 0, largest: 0, refusal: 'none', active: 0, modules: [] } + for (let first = 0; ; ) { + const p = await call(MODS, put32(first)) + if (!p) return null + const bytes = unpack7(p), view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) + if (bytes.length < 20 || String.fromCharCode(...bytes.subarray(16, 19)) !== 'MWI' || bytes.length < 20 + 24 * bytes[19]) + throw new Error('The Model:Cycles sent a malformed module list.') + const why = view.getUint32(8) + Object.assign(out, { free: view.getUint32(0), largest: view.getUint32(4), refusal: REFUSALS[why] ?? 'refusal ' + why, active: view.getUint32(12) }) + for (let i = 0; i < bytes[19]; i++) { + const e = bytes.subarray(20 + 24 * i, 44 + 24 * i), name = e.subarray(8, 24) + out.modules.push({ id: view.getUint32(24 + 24 * i).toString(16).padStart(8, '0'), + name: String.fromCharCode(...name.subarray(0, name.indexOf(0) < 0 ? 16 : name.indexOf(0))) }) + } + first += bytes[19] + if (bytes[19] < 3 || out.modules.length >= out.active) return out + } +} + +/** The upload controller's session with the connected unit: identity first, so BEGIN names the running base. */ +export async function mcUploadSession(call: McCall, timeoutMs = 20000): Promise { + const payload = await call(IDENT) + if (!payload) return null + const set = parseMcIdent(payload).set + if (!set) throw new Error('This base reports no set identity: build a newer one.') + return UploadSession.connect(mcUploadTransport(call), mcUploadBase(set.crc), { timeoutMs }) +} + +/** A package that removes the module built as `name` (build.py: its id is the first four bytes of the SHA-256 of the + * name): no image, hooks or sites under that id. */ +export function mcRemovalPackage(name: string): Uint8Array { + const out = new Uint8Array(32), view = new DataView(out.buffer) + out.set([0x4d, 0x57, 0x52, 0x4d]); view.setUint16(4, 4) + view.setUint32(28, parseInt(sha(new TextEncoder().encode(name)).slice(0, 8), 16)) + return out +} + +/** Put a package on trial: staged, published and running, the previous set kept for an undo. The unit undoes it by + * itself after ten seconds without a link request (mcUploadSession's hello is one). */ +export async function mcTry(call: McCall, data: Uint8Array): Promise { + const session = await mcUploadSession(call) + if (!session) return null + await session.stage({ base: session.status.base, data, sha256: sha(data) }, { chunk: MC_UPLOAD_CHUNK }) + await session.activate() + return session.startTrial() +} + +/** End a trial: keep its set, or put the previous one back; then leave upload mode. */ +export async function mcFinish(call: McCall, keep: boolean): Promise { + const session = await mcUploadSession(call) + if (!session) return null + if (!session.adopt() || !['trial', 'pending'].includes(session.status.phase)) throw new Error('Nothing is on trial.') + if (keep) { if (session.status.phase === 'trial') await session.holdTrial(); await session.accept() } + else await session.rollback() + return session.leaveUploadMode() +} + +const TABLE = Uint32Array.from({ length: 256 }, (_, n) => { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ c >>> 1 : c >>> 1 + return c +}) +function crc32(data: Uint8Array) { + let c = 0xffffffff + for (const b of data) c = TABLE[(c ^ b) & 0xff] ^ c >>> 8 + return (c ^ 0xffffffff) >>> 0 +} + +/** The set identity a unit running this built image reports for `bytes` of .run: the linker appends the mods' blob to + * the MAIN OS with .run last, so it is the image's last `bytes` bytes (mc_link.py runid computes the same from the + * layout). */ +export function mcSetIdentity(syx: Uint8Array, bytes: number): { crc: number; bytes: number } { + const image = mainImage(readEle3Syx(syx), ELE3_DEVICES['model-cycles']) + if (bytes <= 0 || bytes > image.length) throw new Error('The set is larger than the image.') + return { crc: crc32(image.subarray(image.length - bytes)), bytes } +}