# JamRoom Agent Skill (NOMCP authenticated pairing)

You were given a link like `https://<app>.berrry.app/SKILL.md?room=jam-6idn2&host=<userId>`.
There are no secrets in the URL and no expiry. Your identity is your Berrry NOMCP account plus a persistent Ed25519 key.

## Flow
1. **The human** writes an Offer to the public key `jr-agent-offer-<room>`: `{v:2, room, nonce, sdp, host:{userId,username}}`.
2. **Sign in** through NOMCP: `POST /api/nomcp/register/challenge` → `/register/solve` → `/auth/sign-in` → `brry_rw_…` (or set `BERRRY_TOKEN`). Read the Offer with `GET /api/public-data/<host>/jr-agent-offer-<room>`.
3. **Answer** the offer. Sign `nomcp1|room|nonce|sha256hex(offerSdp)|sha256hex(answerSdp)|fingerprint|handle` with your Ed25519 key, where `handle` is your Berrry username.
   Write `{v:2, room, nonce, sdp, fp, handle, name, pub (raw b64url), sig (b64url)}` to `POST /api/data/jr-agent-answer-<room>?visibility=public`.
4. **The human's browser** verifies the signature and fingerprint. It shows `@handle` as **verified** when the handle matches the Berrry user who wrote the record.
5. **After Allow**, the DataChannel opens. Your key is saved as a band member, so next time you are let in without a prompt. The bridge deletes its answer record.

If the human's door isn't open yet (no Offer, or the nonce has already been answered), wait and retry. The bridge polls.

## Run
```
npm i werift
node jamroom-bridge.mjs "<room link>"
```

## Drive JamRoom over localhost
```
POST http://127.0.0.1:7878/cmd   Authorization: Bearer <local key>
{"cmd":"screenshot"} {"cmd":"state"} {"cmd":"click","x":40,"y":22} {"cmd":"key","key":" "}
{"cmd":"op","op":{"type":"set_step","track":0,"clip":0,"row":2,"step":4,"vel":0.8}}
{"cmd":"chat","text":"added ghost hats"} {"cmd":"ping"}
GET  http://127.0.0.1:7878/events
```
Screen layout (800×520): PLAY button at x10-100, y8-36. Tracks at x=10+98·i (92 wide). Headers at y46-70. Clip slots at y=76+30·c (26 tall). The step editor starts at y208. Cells are at x=60+45.6·step, with row heights of 34 (drums) or 23 (synth).

**Telemetry:** programmatic agents should use `{"cmd":"state"}` (compact JSON, exact). `screenshot` returns a compressed JPEG and is meant for vision bots only.

If the link drops, the human's browser reposts a fresh offer automatically; restart the bridge and it rejoins as a band member.

Ops: `del_track {track}`, `set_step` (optional `len` in 16ths), `set_note {track,clip,step,midi,len,vel}`, `set_clip_len {track,clip,bars:1|2|4|8}`, `set_clip_chrom {track,clip,value}`, `set_clip`, `new_clip`, `clear_clip`, `set_param`, `launch_clip`, `scene`, `set_bpm`, `set_song`, `set_arr`, `transport`.
Device params for `set_param`: `duck`, `crush`, `fm` (0–1), `fmr`, `chord` (off|maj|min|7th|sus4|power), `arp` (off|up|down|updown|random).

Song commands: `{"cmd":"play_song","bar":9,"loop":false}` `{"cmd":"stop_song"}` `{"cmd":"seek_bar","section":3}`.

## Rules
- The human sets the mode: drive, watch or paused. Grants and toggles are enforced.
- At most 20 commands per second. Read `state` (or screenshot if you're a vision bot) before you click. Tempo/transport are allowed by default. Say in chat what you changed. Don't delete the human's bassline without asking.

## jamroom-bridge.mjs
```js
import { RTCPeerConnection } from 'werift';
import http from 'node:http';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
const link = new URL(process.argv[2] || '');
const ROOM = link.searchParams.get('room'), HOST = link.searchParams.get('host');
if (!ROOM || !HOST) { console.error('link needs ?room=…&host=…'); process.exit(1); }
const API = (process.env.BERRRY_ORIGIN || link.origin).replace(/\/$/, '');
const OKEY = 'jr-agent-offer-' + ROOM, AKEY = 'jr-agent-answer-' + ROOM;
const b64u = b => Buffer.from(b).toString('base64url');
const shaHex = s => crypto.createHash('sha256').update(s).digest('hex');
const pick = (o, ...ks) => { for (const k of ks) if (o && o[k] != null) return o[k]; };
async function api(method, p, body, tok) {
  const r = await fetch(API + p, { method, headers: { 'Content-Type': 'application/json', ...(tok ? { Authorization: 'Bearer ' + tok } : {}) }, body: body ? JSON.stringify(body) : undefined });
  const t = await r.text(); let d; try { d = t ? JSON.parse(t) : {}; } catch { throw new Error(`${method} ${p}: non-JSON ${r.status}`); }
  if (!r.ok) throw new Error(`${method} ${p} → ${r.status}: ${d.error || t.slice(0, 160)}`);
  return d;
}

// ---- 1. persistent identity: NOMCP creds + Ed25519 key ----
const credFile = path.resolve('.jamroom-agent.json');
let creds = fs.existsSync(credFile) ? JSON.parse(fs.readFileSync(credFile, 'utf8')) : {};
const want = process.env.AGENT_NAME || 'chiptunebot';
if (!creds.ed) { const { privateKey } = crypto.generateKeyPairSync('ed25519'); creds.ed = privateKey.export({ format: 'jwk' }); }
const priv = crypto.createPrivateKey({ key: creds.ed, format: 'jwk' });
const pubRaw = creds.ed.x;
async function signIn() {
  if (process.env.BERRRY_TOKEN) return process.env.BERRRY_TOKEN;
  if (!creds.username && !creds.token) {
    const c = await api('POST', '/api/nomcp/register/challenge', { name: want });
    const cid = pick(c, 'challengeId', 'challenge_id', 'id'), chal = pick(c, 'challenge', 'prefix', 'nonce');
    const diff = +pick(c, 'difficulty', 'bits') || 0; let sol = '';
    if (diff) { for (let n = 0; ; n++) { const hh = shaHex(chal + n); if (BigInt('0x' + hh) >> BigInt(256 - diff) === 0n) { sol = String(n); break; } } }
    else sol = shaHex(String(chal));
    const s = await api('POST', '/api/nomcp/register/solve', { challengeId: cid, solution: sol, nonce: sol, name: want });
    Object.assign(creds, { username: pick(s, 'username', 'handle', 'login'), password: pick(s, 'password', 'secret'), token: pick(s, 'token', 'apiKey', 'access_token') });
  }
  fs.writeFileSync(credFile, JSON.stringify(creds), { mode: 0o600 });
  if (creds.username && creds.password) {
    const si = await api('POST', '/api/nomcp/auth/sign-in', { username: creds.username, password: creds.password });
    return pick(si, 'token', 'apiKey', 'access_token') || (si.tokens && pick(si.tokens, 'rw', 'readWrite'));
  }
  return creds.token;
}
const BTOK = await signIn();
fs.writeFileSync(credFile, JSON.stringify(creds), { mode: 0o600 });
let handle = creds.username;
try { const me = await api('GET', '/api/auth/user', null, BTOK); handle = me.username || handle; } catch {}
handle = String(handle || want).replace(/^@/, '');
console.log('[bridge] signed in as @' + handle);

// ---- 2. read offer (poll until the door is open) ----
let offer;
for (;;) {
  try { let v = await api('GET', `/api/public-data/${HOST}/${encodeURIComponent(OKEY)}`); if (v && v.value && !v.sdp) v = v.value; if (v && v.sdp && v.nonce) { offer = v; break; } } catch {}
  console.log('[bridge] door closed, retrying in 3s…'); await new Promise(r => setTimeout(r, 3000));
}

// ---- 3. answer, sign, post ----
const pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] });
let ch = null, seq = 0; const waiting = new Map(), events = [];
const cleanup = async () => { try { await api('DELETE', '/api/data/' + encodeURIComponent(AKEY), null, BTOK); } catch {} };
pc.onDataChannel.subscribe(c => { ch = c; console.log('[bridge] connected as @' + handle); cleanup();
  const onMsg = raw => { let m; try { m = JSON.parse((raw && raw.data != null ? raw.data : raw).toString()); } catch { return; }
    if (m.id != null && waiting.has(m.id)) { waiting.get(m.id)(m); waiting.delete(m.id); } else { events.push(m); if (events.length > 200) events.shift(); } };
  if (c.onMessage?.subscribe) c.onMessage.subscribe(onMsg); else c.onmessage = onMsg; });
await pc.setRemoteDescription({ type: 'offer', sdp: offer.sdp });
await pc.setLocalDescription(await pc.createAnswer());
for (let i = 0; i < 50 && pc.iceGatheringState !== 'complete'; i++) await new Promise(r => setTimeout(r, 100));
const sdp = pc.localDescription.sdp, fp = sdp.match(/a=fingerprint:([^\r\n]+)/)[1].trim();
const msg = `nomcp1|${ROOM}|${offer.nonce}|${shaHex(offer.sdp)}|${shaHex(sdp)}|${fp}|${handle}`;
const sig = b64u(crypto.sign(null, Buffer.from(msg), priv));
const rec = { v: 2, room: ROOM, nonce: offer.nonce, sdp, fp, handle, name: want, pub: pubRaw, sig };
try { await api('POST', '/api/data/' + encodeURIComponent(AKEY) + '?visibility=public', rec, BTOK); console.log('[bridge] answer posted, waiting for the human…'); }
catch (e) { console.error('[bridge] post failed:', e.message); }
console.log('[bridge] fallback token:\nnomcp1.' + b64u(JSON.stringify(rec)) + '\n');
process.on('SIGINT', async () => { await cleanup(); process.exit(0); });

// ---- 4. localhost control API ----
const BEARER = crypto.randomBytes(18).toString('base64url'), PORT = +process.env.PORT || 7878;
http.createServer(async (req, res) => {
  const out = (c, o) => { res.writeHead(c, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(o)); };
  if (req.headers.authorization !== 'Bearer ' + BEARER) return out(401, { error: 'bad bearer key' });
  if (req.method === 'GET' && req.url === '/events') return out(200, events.splice(0));
  if (req.method !== 'POST' || req.url !== '/cmd') return out(404, { error: 'use POST /cmd or GET /events' });
  let body = ''; for await (const c of req) body += c;
  if (!ch) return out(503, { error: 'not connected yet (waiting for Allow)' });
  let m; try { m = JSON.parse(body || '{}'); } catch { return out(400, { error: 'bad json' }); }
  m.id = ++seq;
  const p = new Promise(ok => { waiting.set(m.id, ok); setTimeout(() => { if (waiting.delete(m.id)) ok({ id: m.id, ok: false, error: 'timeout' }); }, 15000); });
  ch.send(JSON.stringify(m)); const r2 = await p;
  if (r2.jpg) { const f = path.resolve(`shot-${m.id}.jpg`); fs.writeFileSync(f, Buffer.from(r2.jpg, 'base64')); r2.file = f; delete r2.jpg; }
  out(200, r2);
}).listen(PORT, '127.0.0.1', () => console.log(`[bridge] http://127.0.0.1:${PORT}  bearer: ${BEARER}`));
```