Skip to content

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Plainsong Worker

A Cloudflare Worker that compiles TapScript notation to MIDI on the edge — no server, no cold start, no dependencies.

Write music in plain text. Get MIDI back. In 50ms. From anywhere on Earth.

The worker pipeline — brass pipework carrying the song to the edge


Table of Contents


Vision

TapScript Studio proved that plain-text music notation works. But it's a local Python tool — you need Python installed, you need to run it on your machine, and the output stays local.

Plainsong Worker brings TapScript to the edge. Write TapScript notation, POST it to a Cloudflare Worker, and get back a standard MIDI file. The compilation runs on Cloudflare's edge network — meaning it's fast (~50ms), it's always available, and it's free under the Workers free tier.

The worker includes a built-in HTML playground (no setup required) and a JSON API for programmatic access. It compiles both TapScript v1 (Roman numeral) and v2 (absolute pitch) notation.

Why a Worker?

Local Python Script Cloudflare Worker
Requires Python + pretty_midi installed Zero dependencies — just a URL
Output stays on your machine Accessible from any browser or API client
Cold start: ~2s (Python) Cold start: ~5ms (V8 isolate)
No rate limiting Built-in per-IP rate limiting (30 req/min)
Only works locally Works from anywhere via HTTP

Design Principles

  1. Zero runtime dependencies — the MIDI binary writer, the TapScript parser, and the HTML playground are all in three files. No npm packages at runtime.
  2. Edge-first — runs on Cloudflare's V8 isolates, not containers. Sub-50ms cold starts.
  3. Standard MIDI output — the output is a binary .mid file readable by any DAW, player, or library.
  4. Rate-limited by design — 30 requests per minute per IP, in-memory. Prevents abuse without needing external state.

Architecture

┌──────────────────────────────────────────────────────────┐
│                  Cloudflare Edge Network                   │
│                                                            │
│  Browser ──► Worker (V8 isolate)                          │
│             ┌──────────────────────────────────┐           │
│             │  src/index.ts                     │           │
│             │  ├─ Rate limiter (in-memory)      │           │
│             │  ├─ Route handler                 │           │
│             │  ├─ HTML playground server        │           │
│             │  └─ CORS handler                  │           │
│             │                                   │           │
│             │  src/tapscript.ts                 │           │
│             │  ├─ Tokenizer (v1 + v2)           │           │
│             │  ├─ Chord parser                  │           │
│             │  ├─ Roman numeral parser          │           │
│             │  ├─ Scale degree parser           │           │
│             │  └─ MIDI compiler                 │           │
│             │                                   │           │
│             │  src/midi.ts                      │           │
│             │  ├─ SMF binary writer             │           │
│             │  ├─ VLQ encoder                   │           │
│             │  ├─ Track chunk builder           │           │
│             │  └─ Note event serializer         │           │
│             └──────────────┬───────────────────┘           │
│                            │                                │
│  Browser ◄─── audio/midi ◄─┘                               │
└──────────────────────────────────────────────────────────┘

Module Map

Module Lines Responsibility
index.ts ~280 Worker entry point: routing, rate limiting, HTML playground, CORS, handlers
tapscript.ts ~600 TapScript parser + MIDI composition compiler (v1 + v2 notation)
midi.ts ~170 Standard MIDI File (SMF) binary writer — format-1 multi-track

Data Flow

1. Client POSTs to /compile with { tapscript: "...", format: "base64" }
2. Rate limiter checks per-IP bucket (30 req/min)
3. Parser detects notation version (v1 Roman numeral vs v2 absolute pitch)
4. Parse sections → bars → chords, melody, player lines
5. Compile to MidiComposition: tracks with notes, programs, channels
6. Generate SMF binary: header chunk + tempo track + note tracks
7. Return as binary MIDI (audio/midi) or base64 JSON

Quick Start

Try the Playground

Open the worker URL in a browser. You'll get a live TapScript editor with:

  • Syntax-highlighted editor
  • Compile and Parse buttons
  • Example compositions (Neon Shadows, Harbor Dawn, The Room Is Safe, Creatures of Interval)
  • Download MIDI and audio playback

API Usage

# Compile to MIDI binary
curl -X POST https://plainsong-worker.your-subdomain.workers.dev/compile \
  -H "Content-Type: application/json" \
  -d '{
    "tapscript": "**TRACK: Test**\n[MetaData]\nkey: C | tempo: 120\n\n[V1]\nChords: | C . | G . |\nMelody: | C4 . | G4 . |",
    "format": "midi"
  }' \
  --output output.mid

# Compile to base64 JSON
curl -X POST https://plainsong-worker.your-subdomain.workers.dev/compile \
  -H "Content-Type: application/json" \
  -d '{
    "tapscript": "**TRACK: Test**\n[MetaData]\nkey: C | tempo: 120\n\n[V1]\nChords: | C . | G . |",
    "format": "base64"
  }'

Response (base64 format):

{
  "success": true,
  "midi": "TVRoZAAAAAYAAA...",
  "bytes": 420,
  "tracks": 3,
  "ticks": 768,
  "tempo": 120,
  "key": "C",
  "notation": "v2"
}

Parse Without Compiling

curl -X POST https://plainsong-worker.your-subdomain.workers.dev/parse \
  -H "Content-Type: application/json" \
  -d '{"tapscript": "**TRACK: Neon Shadows**\n..."}'

Returns structured metadata: title, key, tempo, swing, section count, bar count, player names.


Key Concepts

Standard MIDI File (SMF) Format

The worker generates Standard MIDI Files — the universal format readable by every DAW, sequencer, and MIDI player. Specifically, it produces Format 1 multi-track files:

  • Track 0 (Tempo Track): Contains the tempo meta-event (SET_TEMPO) and track name
  • Track 1+ (Note Tracks): One per instrument, each with a PROGRAM_CHANGE event followed by NOTE_ON/NOTE_OFF events

The binary format uses:

V8 Isolates

Cloudflare Workers run on V8 isolates — the same JavaScript engine that powers Chrome, but sandboxed. Unlike containers or VMs, isolates start in ~5ms and share a single process, making them ideal for stateless compilation tasks.

The in-memory rate limiter works because each isolate has its own Map — but note that Cloudflare may route different requests from the same IP to different isolates, so the rate limit is approximate (an upper bound, not exact).

Seeded RNG for Reproducible Humanization

The compiler applies velocity humanization — small random variations in note velocity to make the MIDI sound less mechanical. It uses a deterministic seeded RNG (seed: 42, Linear Congruential Generator) so that the same input always produces the same output. This is critical for reproducibility in version control and testing.


API Reference

GET /

Returns the HTML playground — a live TapScript editor in the browser.

GET /health

{
  "status": "ok",
  "service": "plainsong-worker",
  "version": "1.0.0",
  "timestamp": "2026-08-13T15:26:00.000Z"
}

POST /parse

Parses TapScript notation and returns metadata (no MIDI generation).

Request:

{ "tapscript": "**TRACK: Title**\n..." }

Or raw text with Content-Type: text/plain.

Response:

{
  "title": "Neon Shadows",
  "notation": "v2",
  "key": "Am",
  "tempo": 75,
  "swing": 10,
  "subdivision": "16th",
  "sections": 2,
  "bars": 8,
  "players": ["flash", "hermes", "wesley"]
}

POST /compile

Compiles TapScript notation to MIDI.

Request:

{
  "tapscript": "**TRACK: Title**\n...",
  "format": "midi" | "base64"
}

Response (format=midi): Binary MIDI file (Content-Type: audio/midi)

Response (format=base64):

{
  "success": true,
  "midi": "<base64-encoded MIDI>",
  "bytes": 420,
  "tracks": 3,
  "ticks": 768,
  "tempo": 120,
  "key": "C"
}

Rate Limiting

Setting Value
Limit 30 requests per minute
Window 60 seconds
Scope Per IP (CF-Connecting-IP header)
Storage In-memory (per isolate)
Response 429 with error message

Configuration

wrangler.jsonc

{
  "name": "plainsong-worker",
  "main": "src/index.ts",
  "compatibility_date": "2026-07-01",
  "compatibility_flags": ["nodejs_compat"],
  "observability": {
    "enabled": true,
    "head_sampling_rate": 1
  }
}

No external bindings needed — no KV, D1, R2, or AI. The worker is completely stateless.

Dependencies

None at runtime. Dev dependencies only:

Package Purpose
@cloudflare/vitest-pool-workers Workers-aware test runner
TypeScript Type checking
Vitest Test framework
Wrangler CF Workers CLI

Testing

npm test          # Run Vitest with Workers pool
npx wrangler dev  # Local development server

Tests verify:

  • v2 notation parsing (absolute pitch, chords, players, velocity)
  • v1 notation parsing (Roman numerals, scale degrees)
  • MIDI binary generation (correct header, track chunks, VLQ encoding)
  • Edge cases (empty input, malformed notation, unknown chords)
  • Rate limiting behavior

Deployment

# Deploy to Cloudflare Workers
npx wrangler deploy

# The worker will be available at:
# https://plainsong-worker.<your-subdomain>.workers.dev

That's it. No server, no container, no VM. One command.

Custom Domain

Add a custom domain in the Cloudflare dashboard or via wrangler:

// wrangler.jsonc
{
  "routes": ["tapscript.yourdomain.com/*"]
}

Further Reading

For Developers

For Musicians

For Engineers


Relation to the Fleet

Component Relationship
tapscript-studio The local Python version. This Worker is a TypeScript port of the parser + MIDI writer.
fleet-jepa-midi Uses TapScript notation for musical input; JEPA perceives the feel
fleet-ensemble Renders TapScript scores as agentic performances
fleet-gateway Not directly used — this Worker is stateless and needs no gateway
plainsong The canonical compiler — this Worker is its TypeScript port; the Python original lives there
fleet-radio The airwaves — where fleet music (Plainsong-family notation underneath) gets broadcast nightly
superinstance-ai The front door — the Plainsong Playground is its featured demo

License

MIT — part of the SuperInstance fleet.

About

No description, website, or topics provided.

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages