{
  "schema_version": "1.0",
  "name": "Synth&I Agent API",
  "description": "Browser-based retro synth PWA. All tools are exposed at runtime under window.SynthAndI in a loaded page; this document is the machine-readable manual.",
  "binding": {
    "type": "javascript-window",
    "global": "window.SynthAndI",
    "note": "All async tools return Promises. Most state-changing tools also emit events via SynthAndI.on(fn)."
  },
  "tools": [
    {
      "name": "start",
      "description": "Initialize the Web Audio context. MUST be invoked from a user gesture (click) by the page before any noteOn/playSequence call.",
      "parameters": { "type": "object", "properties": {}, "additionalProperties": false },
      "returns": { "type": "object", "properties": { "started": { "type": "boolean" }, "sampleRate": { "type": "number" } } }
    },
    {
      "name": "isStarted",
      "description": "Whether the Web Audio context has been initialized via start(). Useful for headless drivers that need to gate calls on engine readiness.",
      "parameters": { "type": "object", "properties": {} },
      "returns": { "type": "boolean" }
    },
    {
      "name": "noteOn",
      "description": "Trigger a MIDI note on the active engine.",
      "parameters": {
        "type": "object",
        "properties": {
          "midi": { "type": "integer", "minimum": 0, "maximum": 127 },
          "velocity": { "type": "number", "minimum": 0, "maximum": 1, "default": 0.85 }
        },
        "required": ["midi"]
      }
    },
    {
      "name": "noteOff",
      "description": "Release a previously triggered MIDI note.",
      "parameters": { "type": "object", "properties": { "midi": { "type": "integer" } }, "required": ["midi"] }
    },
    {
      "name": "allNotesOff",
      "description": "Force-release every active note (panic).",
      "parameters": { "type": "object", "properties": {} }
    },
    {
      "name": "setWaveform",
      "description": "Pick what the keys (and any noteOn) trigger. 'ensemble' uses the active preset's per-key-range voice mapping (low keys = bass, mid = counter, high = lead, top range = noise drums) — applyPreset auto-flips to this when the preset declares a `voices` array. The other values flatten the keyboard to a single voice across all keys: 'square'/'pulse25'/'pulse12'/'triangle'/'sawtooth'/'sine' synth oscillators, 'fm' for 2-op Yamaha-style FM, 'noise' for LFSR noise, or 'sample' for the captured mic buffer (only valid after sampleRecord() or setSampleBuffer()).",
      "parameters": {
        "type": "object",
        "properties": { "waveform": { "type": "string", "enum": ["ensemble", "square", "pulse25", "pulse12", "triangle", "sawtooth", "sine", "fm", "noise", "sample"] } },
        "required": ["waveform"]
      }
    },
    {
      "name": "setADSR",
      "description": "Update ADSR envelope (any subset of attack/decay/sustain/release).",
      "parameters": {
        "type": "object",
        "properties": {
          "attack": { "type": "number", "minimum": 0, "maximum": 5 },
          "decay": { "type": "number", "minimum": 0, "maximum": 5 },
          "sustain": { "type": "number", "minimum": 0, "maximum": 1 },
          "release": { "type": "number", "minimum": 0, "maximum": 10 }
        }
      }
    },
    {
      "name": "setVolume",
      "description": "Master volume in decibels.",
      "parameters": { "type": "object", "properties": { "db": { "type": "number", "minimum": -60, "maximum": 6 } }, "required": ["db"] }
    },
    {
      "name": "setOctaveShift",
      "description": "Shift incoming MIDI notes by N octaves.",
      "parameters": { "type": "object", "properties": { "n": { "type": "integer", "minimum": -3, "maximum": 3 } }, "required": ["n"] }
    },
    {
      "name": "setBitDepth",
      "description": "Apply a global bit-crusher. 0 disables.",
      "parameters": { "type": "object", "properties": { "bits": { "type": "integer", "minimum": 0, "maximum": 16 } }, "required": ["bits"] }
    },
    {
      "name": "setCompressor",
      "description": "Adjust the master hardware-style compressor.",
      "parameters": {
        "type": "object",
        "properties": {
          "threshold": { "type": "number" },
          "ratio": { "type": "number" },
          "attack": { "type": "number" },
          "release": { "type": "number" }
        }
      }
    },
    {
      "name": "setMaxPolyphony",
      "description": "Cap simultaneous tonal voices to mimic the original chip's channel count. NES = 2, GameBoy = 2, Arcade SN76489 = 3, Genesis YM2612 = 6, SNES SPC700 = 8.",
      "parameters": { "type": "object", "properties": { "n": { "type": "integer", "minimum": 1, "maximum": 16 } }, "required": ["n"] }
    },
    {
      "name": "setSampleRateCrush",
      "description": "Sample-and-hold downsampling factor — mimics low chip DAC rates and their aliasing artifacts. 0 or 1 disables; 3-6 is typical chip range (NES ~3, GameBoy ~6).",
      "parameters": { "type": "object", "properties": { "factor": { "type": "integer", "minimum": 0, "maximum": 32 } }, "required": ["factor"] }
    },
    {
      "name": "setAmpSteps",
      "description": "Quantize post-mix amplitude to a fixed number of discrete levels — emulates chip DACs whose volume registers had only a few bits (e.g. NES had a 4-bit volume register = 16 levels). 0 or 1 disables; 16 mimics NES, 8 is harsher.",
      "parameters": { "type": "object", "properties": { "steps": { "type": "integer", "minimum": 0, "maximum": 256 } }, "required": ["steps"] }
    },
    {
      "name": "setVibrato",
      "description": "Pitch vibrato that ramps from zero to `depth` over `delay` seconds after each note attack — chiptune leads bloom rather than wobbling at attack. Pass null to disable. Typical chip values: rate 4-7 Hz, depth 0.03-0.06, delay 0.2-0.5 s.",
      "parameters": {
        "type": "object",
        "properties": {
          "opts": {
            "oneOf": [
              { "type": "null" },
              {
                "type": "object",
                "properties": {
                  "rate": { "type": "number", "minimum": 0.1, "maximum": 20 },
                  "depth": { "type": "number", "minimum": 0, "maximum": 1 },
                  "delay": { "type": "number", "minimum": 0, "maximum": 5 }
                }
              }
            ]
          }
        },
        "required": ["opts"]
      }
    },
    {
      "name": "setPwm",
      "description": "Pulse-width modulation. Sweeps the duty cycle of pulse waveforms (pulse25, pulse12) at a low LFO rate, mimicking the software-driven width changes vintage chip music used to add motion to a pulse lead. Only affects pulse waveforms; ignored on square/triangle/saw/sine. Pass null to disable. Typical chip values: rate 1-5 Hz, depth 0.04-0.10.",
      "parameters": {
        "type": "object",
        "properties": {
          "opts": {
            "oneOf": [
              { "type": "null" },
              {
                "type": "object",
                "properties": {
                  "rate": { "type": "number", "minimum": 0.1, "maximum": 20 },
                  "depth": { "type": "number", "minimum": 0, "maximum": 0.5 }
                }
              }
            ]
          }
        },
        "required": ["opts"]
      }
    },
    {
      "name": "setNoiseMode",
      "description": "NES-APU-style noise feedback mode for the noise voice (only used when waveform is 'noise'). 'long' = 15-bit LFSR with hihat-like white noise; 'short' = 7-bit LFSR with buzzy, melodic-tonal character.",
      "parameters": { "type": "object", "properties": { "mode": { "type": "string", "enum": ["long", "short"] } }, "required": ["mode"] }
    },
    {
      "name": "recordSongStart",
      "description": "Begin capturing live note-on/off events. Each captured event records absolute time (seconds from start), midi pitch, velocity, and held duration.",
      "parameters": { "type": "object", "properties": {} }
    },
    {
      "name": "recordSongStop",
      "description": "Stop the current recording and return the captured event list. Pass the result to serializeSong to ship it as a file or to playSong to replay.",
      "parameters": { "type": "object", "properties": {} }
    },
    {
      "name": "serializeSong",
      "description": "Return a Synth&I song JSON string (format v2) for the given event list. Each event may carry a `state` field with the full engine snapshot at trigger time so live mid-song knob tweaks (ADSR, vibrato, pwm, sample-rate crush, preset, …) replay exactly.",
      "parameters": {
        "type": "object",
        "properties": {
          "events": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "t": { "type": "number" },
                "midi": { "type": "integer" },
                "vel": { "type": "number" },
                "dur": { "type": "number" },
                "state": { "type": "object" }
              }
            }
          }
        },
        "required": ["events"]
      }
    },
    {
      "name": "parseSong",
      "description": "Parse a Synth&I song JSON string into {preset, events}. Throws on unsupported version or malformed structure.",
      "parameters": { "type": "object", "properties": { "text": { "type": "string" } }, "required": ["text"] }
    },
    {
      "name": "playSong",
      "description": "Schedule playback of a parsed song through the active synth voice. Resolves when the song finishes naturally OR is cancelled via stopSong. Calling playSong while a song is already playing cancels the previous one.",
      "parameters": { "type": "object", "properties": { "song": { "type": "object" } }, "required": ["song"] }
    },
    {
      "name": "stopSong",
      "description": "Cancel the in-flight song playback (if any). The playSong promise resolves immediately. No-op if nothing is playing.",
      "parameters": { "type": "object", "properties": {} }
    },
    {
      "name": "loadSongFromUrl",
      "description": "Fetch a Synth&I song JSON from a URL and parse it. The URL must be CORS-accessible. Returns the parsed song.",
      "parameters": { "type": "object", "properties": { "url": { "type": "string" } }, "required": ["url"] }
    },
    { "name": "listPresets", "description": "List built-in console-flavored presets.", "parameters": { "type": "object", "properties": {} } },
    { "name": "applyPreset", "description": "Activate a preset by id.", "parameters": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] } },
    { "name": "getActivePreset", "description": "Return the currently active preset.", "parameters": { "type": "object", "properties": {} } },
    {
      "name": "playSequence",
      "description": "Play an arbitrary note list at a given BPM. Each entry: {n: midi|null, d: duration in beats}.",
      "parameters": {
        "type": "object",
        "properties": {
          "notes": { "type": "array", "items": { "type": "object", "properties": { "n": { "type": ["integer", "null"] }, "d": { "type": "number" } } } },
          "bpm": { "type": "number", "default": 120 }
        },
        "required": ["notes"]
      }
    },
    { "name": "stopSequence", "description": "Stop any running sequence.", "parameters": { "type": "object", "properties": {} } },
    {
      "name": "sampleRecord",
      "description": "Record a short mic sample. The captured buffer is automatically pushed into the engine's sample voice and WAVE flips to 'sample' so subsequent noteOn calls play the sampled buffer pitched per key, through the full ADSR + master FX chain. To play the sample programmatically without re-recording, call setWaveform('sample') then noteOn.",
      "parameters": { "type": "object", "properties": { "durationMs": { "type": "integer", "default": 3000 } } }
    },
    { "name": "sampleStop", "description": "Stop in-progress sample recording.", "parameters": { "type": "object", "properties": {} } },
    { "name": "sampleSetLofi", "description": "Enable/disable 4-bit + downsample lo-fi processing on the sample. Re-pushes the processed buffer to the engine if a sample is loaded.", "parameters": { "type": "object", "properties": { "on": { "type": "boolean" } }, "required": ["on"] } },
    { "name": "sampleHasBuffer", "description": "Whether a sample is currently loaded into the engine's sample voice.", "parameters": { "type": "object", "properties": {} } },
    { "name": "samplePreview", "description": "Trigger the loaded sample once at C4 through the engine's master FX chain — useful to confirm a recording without flipping WAVE or hunting for a key.", "parameters": { "type": "object", "properties": {} } },
    { "name": "setSampleBuffer", "description": "Push an AudioBuffer (e.g. from a different source than the mic) into the engine's sample voice. Pass null to clear. After setting, setWaveform('sample') routes noteOn through the buffer.", "parameters": { "type": "object", "properties": { "buf": {} }, "required": ["buf"] } },
    { "name": "getState", "description": "Token-efficient JSON snapshot of the synth state.", "parameters": { "type": "object", "properties": {} } },
    {
      "name": "restoreState",
      "description": "Restore a previously exported state snapshot. Pass the snapshot object directly (the same shape getState() returns).",
      "parameters": {
        "type": "object",
        "properties": {
          "preset": { "type": "string" },
          "waveform": { "type": "string" },
          "adsr": { "type": "object" },
          "volume": { "type": "number" },
          "octaveShift": { "type": "integer" },
          "compressor": { "type": "object" },
          "bitDepth": { "type": "integer" }
        }
      }
    },
    { "name": "shareUrl", "description": "Return a deep link encoding the current state in the URL hash.", "parameters": { "type": "object", "properties": {} } },
    { "name": "exportPrompt", "description": "Export the state as JSON or YAML for LLM prompts.", "parameters": { "type": "object", "properties": { "format": { "type": "string", "enum": ["json", "yaml"] } } } },
    { "name": "startRecordWav", "description": "Begin recording the engine output. Stop with stopRecordWav to obtain a WAV Blob.", "parameters": { "type": "object", "properties": {} } },
    { "name": "stopRecordWav", "description": "Stop and download the live recording as WAV.", "parameters": { "type": "object", "properties": {} } }
  ],
  "events": {
    "subscribe": "window.SynthAndI.on((ev) => {...})",
    "types": [
      "engine-started",
      "state",
      "preset-applied",
      "note-on",
      "note-off",
      "all-notes-off"
    ]
  },
  "dom": {
    "note": "Every interactive element exposes both aria-label (for accessibility) and data-testid (for headless automation). Use the data-testid attributes for stable selectors in Playwright/Puppeteer.",
    "examples": [
      "[data-testid=\"audio-start\"]",
      "[data-testid=\"preset-select\"]",
      "[data-testid=\"ctl-waveform\"]",
      "[data-testid=\"help-tab\"]",
      "[data-testid=\"keyboard\"] [data-testid=\"key-60\"]",
      "[data-testid=\"sampler-record\"]",
      "[data-testid=\"sampler-preview\"]",
      "[data-testid=\"sampler-lofi\"]",
      "[data-testid=\"transfer-mic\"]",
      "[data-testid=\"transfer-file\"]",
      "[data-testid=\"action-share\"]",
      "[data-testid=\"action-rec-song\"]",
      "[data-testid=\"action-save-song\"]",
      "[data-testid=\"action-load-song\"]",
      "[data-testid=\"action-play-song\"]"
    ]
  }
}
