@vibechain/os 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/AGENTS.md +22 -9
  2. package/README.md +53 -17
  3. package/SECURITY.md +6 -2
  4. package/dist/app-client.js +29 -5
  5. package/dist/app-host.d.ts +27 -4
  6. package/dist/app-host.js +76 -9
  7. package/dist/app-protocol.d.ts +36 -1
  8. package/dist/app-protocol.js +21 -0
  9. package/dist/app-wire.d.ts +24 -3
  10. package/dist/app-wire.js +19 -4
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +2 -0
  17. package/dist/capture.d.ts +22 -0
  18. package/dist/capture.js +99 -0
  19. package/dist/cli.js +3 -1
  20. package/dist/commands.d.ts +6 -0
  21. package/dist/commands.js +17 -0
  22. package/dist/index.d.ts +5 -2
  23. package/dist/index.js +1 -0
  24. package/dist/links.d.ts +21 -0
  25. package/dist/links.js +43 -0
  26. package/dist/os.d.ts +33 -8
  27. package/dist/os.js +68 -14
  28. package/dist/preview-parent.d.ts +8 -2
  29. package/dist/preview-parent.js +35 -10
  30. package/dist/preview-ui.js +1 -1
  31. package/dist/preview.js +1 -1
  32. package/dist/templates/plain/game.js +3 -1
  33. package/dist/testing.d.ts +15 -2
  34. package/dist/testing.js +64 -19
  35. package/dist/transport.d.ts +2 -0
  36. package/dist/transport.js +1 -1
  37. package/dist/vibemarket-os.js +1 -1
  38. package/examples/paw-beat/README.md +28 -9
  39. package/examples/paw-beat/game.ts +280 -123
  40. package/examples/paw-beat/index.html +18 -4
  41. package/examples/paw-beat/main.ts +101 -44
  42. package/examples/paw-beat/music.ts +72 -337
  43. package/examples/paw-beat/stage.ts +23 -9
  44. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  45. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  46. package/examples/paw-beat/synth.ts +477 -0
  47. package/examples/paw-beat/tracks.ts +286 -0
  48. package/examples/paw-beat/vibemarket.json +2 -2
  49. package/examples/vibexp-app/plain/game.ts +6 -2
  50. package/package.json +7 -1
  51. package/skill.md +399 -0
@@ -1,14 +1,17 @@
1
1
  import * as THREE from "three";
2
- import { connectVibeMarketApp, type AppValue, type VibeMarketAppSdk } from "@vibechain/os";
2
+ import { connectVibeMarketApp, type VibeMarketAppSdk } from "@vibechain/os";
3
+ import { createAudio, type AppAudio } from "@vibechain/os/audio";
3
4
  import { createLoop } from "@vibechain/os/loop";
4
5
  import { fitCanvas } from "@vibechain/os/canvas";
5
6
  import { createCat } from "./cat";
6
7
  import {
7
- BEAT_SECONDS, COMBO_MILESTONES, comboMultiplier, COUNT_IN_BEATS, createGame, gradeRound, sectionAt, SONG_SECONDS,
8
- type DanceGame, type Judgement, type Lane, type SectionName,
8
+ beatSeconds, COMBO_MILESTONES, comboMultiplier, countInBeats, createGame, gradeRound, pickTrack, readProgress, recordRound, sectionAt,
9
+ sectionsOf, songSeconds, type DanceGame, type Judgement, type Lane, type Progress, type SectionRole,
9
10
  } from "./game";
10
- import { createMusic } from "./music";
11
+ import { createMusic, soundLabel } from "./music";
11
12
  import { createStage, HIT_Z, type StageFrame } from "./stage";
13
+ import type { PlayableTrack } from "./synth";
14
+ import { TRACKS } from "./tracks";
12
15
 
13
16
  function element<T extends HTMLElement>(id: string): T {
14
17
  const node = document.getElementById(id);
@@ -20,29 +23,44 @@ const callout = element("callout"), call = element("call"), combo = element("com
20
23
  const intro = element("intro"), done = element("done"), bestLine = element("best"), lost = element("lost"), lostText = element("lost-text");
21
24
  const startButton = element<HTMLButtonElement>("start"), againButton = element<HTMLButtonElement>("again"), resumeButton = element<HTMLButtonElement>("resume");
22
25
  const soundButton = element<HTMLButtonElement>("sound"), scoreText = element("score"), multiplierText = element("multiplier");
23
- const progress = element("progress"), played = element("played");
26
+ const progress = element("progress"), played = element("played"), nowPlaying = element("now-playing");
27
+ const trackName = element("track-name"), trackMood = element("track-mood"), nextTrackButton = element<HTMLButtonElement>("next-track"), upNext = element("up-next");
24
28
 
25
29
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: "low-power" });
26
30
  renderer.setPixelRatio(1); // fitCanvas already sizes the backing store in device pixels.
27
31
  const stage = createStage(), cat = createCat();
28
32
  stage.scene.add(cat.root);
29
- const music = createMusic();
33
+ /**
34
+ * Sound is the desktop's: the helper's master follows the vmOS taskbar speaker and volume, the window and the browser's
35
+ * gesture rule, and recovers a context the browser stopped. The game's own button is only an extra mute on top.
36
+ */
37
+ let audio: AppAudio | null = null;
38
+ const music = createMusic(() => {
39
+ if (!app) return null;
40
+ try { audio = createAudio(app); } catch { return null; } // no Web Audio: the game keeps its own clock, silent
41
+ audio.muted = saved.muted;
42
+ audio.onChange(drawSound);
43
+ return audio;
44
+ });
30
45
  const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
31
46
 
32
47
  /** How hard the cat grooves and the stage pulses in each part of the song. */
33
- const ENERGY: Readonly<Record<SectionName, number>> = { "count-in": 0.4, intro: 0.55, build: 0.75, drop: 1, breakdown: 0.45, finale: 1, outro: 0.8 };
48
+ const ENERGY: Readonly<Record<SectionRole, number>> = { "count-in": 0.4, intro: 0.55, build: 0.75, drop: 1, break: 0.45, finale: 1, outro: 0.8 };
34
49
 
35
50
  // ---- Round state ----
36
- interface Saved { best: number; rounds: number; muted: boolean }
37
- function parseSaved(value: AppValue): Saved {
38
- if (!value || typeof value !== "object" || Array.isArray(value)) return { best: 0, rounds: 0, muted: false };
39
- const count = (input: AppValue | undefined) => (typeof input === "number" && Number.isFinite(input) && input >= 0 ? Math.floor(input) : 0);
40
- return { best: count(value.best), rounds: count(value.rounds), muted: value.muted === true };
41
- }
42
-
51
+ const TRACK_IDS = TRACKS.map(item => item.id);
43
52
  let app: VibeMarketAppSdk | undefined;
44
- let game: DanceGame = createGame();
45
- let saved: Saved = { best: 0, rounds: 0, muted: false };
53
+ /** The track that plays when the player next presses Start or Dance again. */
54
+ let chosen = 0;
55
+ let track: PlayableTrack = TRACKS[0]!;
56
+ let game: DanceGame = createGame(track);
57
+ let saved: Progress = readProgress(null, TRACK_IDS);
58
+ /**
59
+ * Tracks are picked by the game's seeded rule (pickTrack), from a seed that starts somewhere new
60
+ * in each window, so a fresh window starts on a random track and the same track never plays twice
61
+ * in a row. The steps themselves use the round number as their seed.
62
+ */
63
+ const shuffle = Math.floor(Math.random() * 0x7fffffff);
46
64
  type Phase = "title" | "playing" | "results";
47
65
  let phase: Phase = "title", paused = false, contextLost = false;
48
66
  let songTime = 0, idleClock = 0, lastMilestone = 0, reported = false, reportTimer: number | undefined;
@@ -54,7 +72,7 @@ let pendingScore = 0, viewWidth = 0, viewHeight = 0;
54
72
 
55
73
  function save() {
56
74
  // A failed write only loses the personal best and the sound setting; the game goes on.
57
- void app?.checkpoint.write({ best: saved.best, rounds: saved.rounds, muted: saved.muted }).catch(() => {});
75
+ void app?.checkpoint.write({ best: saved.best, bests: { ...saved.bests }, rounds: saved.rounds, muted: saved.muted, last: saved.last }).catch(() => {});
58
76
  }
59
77
 
60
78
  // ---- Feedback ----
@@ -125,23 +143,55 @@ function release(lane: Lane) {
125
143
  pads.querySelector(`[data-lane="${lane}"]`)?.classList.remove("down");
126
144
  }
127
145
 
146
+ /** The desktop's sound: from the helper once it exists, else from the host (audible on a host that does not say). */
147
+ function desktopSound() { return audio?.desktop ?? app?.sound?.current() ?? { muted: false, volume: 1 }; }
148
+ /** The button says what the player will hear: off by the game's own toggle, off because vmOS is muted, or on. */
149
+ function drawSound() {
150
+ const label = soundLabel(!saved.muted, desktopSound());
151
+ soundButton.setAttribute("aria-pressed", String(label.pressed));
152
+ soundButton.textContent = label.text;
153
+ soundButton.title = label.title;
154
+ }
155
+ /** The game's own toggle: an extra mute that can silence the game but never turns on what vmOS has muted. */
128
156
  function setSound(on: boolean) {
129
- saved.muted = !on;
130
- music.setMuted(!on);
131
- soundButton.setAttribute("aria-pressed", String(on));
132
- soundButton.textContent = on ? "♪ Sound on" : "♪ Sound off";
157
+ saved = { ...saved, muted: !on };
158
+ if (audio) audio.muted = !on;
159
+ drawSound();
133
160
  }
134
161
 
135
162
  // ---- Flow: title, count-in and song, results ----
163
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;
164
+ /** Choose the next track and show it on the title card and in the stage's colours. */
165
+ function choose(index: number) {
166
+ chosen = index;
167
+ const next = TRACKS[index]!, best = saved.bests[next.id] ?? 0;
168
+ trackName.textContent = next.name;
169
+ trackMood.textContent = `${next.mood} ${next.bpm} beats a minute${best > 0 ? `, your best ${best.toLocaleString("en-US")}` : ""}.`;
170
+ upNext.textContent = `Next up: ${next.name}`;
171
+ stage.setColours(next.colours);
172
+ }
173
+ /** The section marks on the progress bar, for this track's sections. */
174
+ function drawSections() {
175
+ for (const mark of Array.from(progress.querySelectorAll("i"))) mark.remove();
176
+ for (const section of sectionsOf(track)) {
177
+ const mark = document.createElement("i");
178
+ mark.style.flex = String(section.beats);
179
+ progress.insertBefore(mark, played);
180
+ }
181
+ }
182
+
136
183
  function begin() {
137
184
  report(); // a previous round's score goes to the host before the next starts
138
185
  const seed = saved.rounds + 1;
139
- game = createGame(seed);
186
+ track = TRACKS[chosen]!;
187
+ game = createGame(track, seed);
140
188
  songTime = 0;
141
189
  lastMilestone = 0;
142
190
  shownCount = -1;
143
- music.start(seed);
144
- music.setMuted(saved.muted);
191
+ nowPlaying.textContent = track.name;
192
+ drawSections();
193
+ stage.setColours(track.colours);
194
+ music.start(track, seed);
145
195
  phase = "playing";
146
196
  intro.hidden = done.hidden = true;
147
197
  hud.hidden = pads.hidden = false;
@@ -149,7 +199,7 @@ function begin() {
149
199
  cat.setMood("neutral");
150
200
  stage.frame("play", motion.matches);
151
201
  drawScore();
152
- say.textContent = "Get ready.";
202
+ say.textContent = `${track.name}. Get ready.`;
153
203
  canvas.focus();
154
204
  }
155
205
 
@@ -158,9 +208,13 @@ function end() {
158
208
  music.stop();
159
209
  stage.hideNotes();
160
210
  const { score, bestCombo, counts } = game.state, result = gradeRound(counts);
161
- const newBest = score > saved.best && score > 0;
162
- saved = { ...saved, best: Math.max(saved.best, score), rounds: saved.rounds + 1 };
211
+ const trackBest = saved.bests[track.id] ?? 0, newBest = score > trackBest && score > 0;
212
+ saved = recordRound(saved, track.id, score);
163
213
  save();
214
+ element("done-track").textContent = track.name;
215
+ element("done-track-best").textContent = `Best on this track: ${saved.bests[track.id]!.toLocaleString("en-US")}${saved.best > saved.bests[track.id]! ? ` · overall ${saved.best.toLocaleString("en-US")}` : ""}`;
216
+ // Dance again plays another track, never this one twice in a row.
217
+ choose(pickTrack(TRACKS.length, shuffle + saved.rounds, TRACK_IDS.indexOf(track.id)));
164
218
  hud.hidden = pads.hidden = combo.hidden = true;
165
219
  call.textContent = "";
166
220
  element("grade").textContent = result.grade;
@@ -175,7 +229,7 @@ function end() {
175
229
  stage.frame("title", motion.matches);
176
230
  cat.setMood(result.grade === "S" || result.grade === "A" || result.grade === "B" ? "happy" : result.grade === "D" ? "sad" : "neutral");
177
231
  if (result.grade === "S" || result.grade === "A") { cat.celebrate(); stage.confetti(); }
178
- say.textContent = `Song over. Grade ${result.grade}, ${score} points, ${result.accuracy.toFixed(1)} percent accuracy.${newBest ? " New best!" : ""}`;
232
+ say.textContent = `${track.name} over. Grade ${result.grade}, ${score} points, ${result.accuracy.toFixed(1)} percent accuracy.${newBest ? " New best!" : ""}`;
179
233
  againButton.focus();
180
234
  // The host owns the final results screen and may replace this frame once it has the score, so
181
235
  // the card above gets a few seconds first. If the host declines (it accepts one score per open
@@ -232,17 +286,18 @@ function drawScore() {
232
286
  showCombo(state.combo);
233
287
  }
234
288
  function drawHud(now: number) {
235
- const percent = Math.max(0, Math.min(100, Math.floor((now / SONG_SECONDS) * 100)));
289
+ const percent = Math.max(0, Math.min(100, Math.floor((now / songSeconds(track)) * 100)));
236
290
  if (percent !== shownProgress) {
237
291
  shownProgress = percent;
238
292
  played.style.width = `${percent}%`;
239
293
  progress.setAttribute("aria-valuenow", String(percent));
240
294
  }
241
- // Count-in: 3, 2, 1, Go! on the four clicks.
242
- const count = now < COUNT_IN_BEATS * BEAT_SECONDS ? Math.max(0, Math.floor(now / BEAT_SECONDS)) : 4;
243
- if (count !== shownCount && count < 4) {
295
+ // Count-in: the clicks count down to Go! (3, 2, 1, Go! in four; 2, 1, Go! in a waltz's three).
296
+ const clicks = countInBeats(track), beat = beatSeconds(track);
297
+ const count = now < clicks * beat ? Math.max(0, Math.floor(now / beat)) : clicks;
298
+ if (count !== shownCount && count < clicks) {
244
299
  call.dataset.kind = "count";
245
- call.textContent = ["3", "2", "1", "Go!"][count]!;
300
+ call.textContent = count === clicks - 1 ? "Go!" : String(clicks - 1 - count);
246
301
  pop(call, true);
247
302
  }
248
303
  shownCount = count;
@@ -285,7 +340,7 @@ async function boot() {
285
340
  onContextLost() {
286
341
  // GPU resources are gone. Pause the song with the game so nothing is judged blind.
287
342
  contextLost = paused = true;
288
- music.setActive(false);
343
+ if (audio) audio.paused = true;
289
344
  lostText.textContent = "The graphics stopped. Waiting for them to come back…";
290
345
  resumeButton.hidden = true;
291
346
  lost.hidden = false;
@@ -301,7 +356,7 @@ async function boot() {
301
356
  resumeButton.addEventListener("click", () => {
302
357
  lost.hidden = true;
303
358
  paused = false;
304
- if (host.lifecycle.current().active) music.setActive(true);
359
+ if (audio) audio.paused = false;
305
360
  canvas.focus();
306
361
  });
307
362
  createLoop(host, {
@@ -309,18 +364,18 @@ async function boot() {
309
364
  const seconds = stepMs / 1000;
310
365
  if (paused) return;
311
366
  idleClock += seconds;
312
- let beat = idleClock * 0.9, section: SectionName = "intro", energy = 0.35;
367
+ let beat = idleClock * 0.9, section: SectionRole = "intro", energy = 0.35;
313
368
  if (phase === "playing") {
314
369
  tickClock(seconds);
315
370
  const now = songTime;
316
- music.pump();
371
+ music.pump(now);
317
372
  catchUp();
318
373
  drawHud(now);
319
- beat = now / BEAT_SECONDS;
320
- section = sectionAt(Math.max(0, beat)).name;
374
+ beat = now / beatSeconds(track);
375
+ section = sectionAt(track, Math.max(0, beat)).role;
321
376
  energy = ENERGY[section];
322
377
  stage.notes(now, game.each);
323
- if (now >= SONG_SECONDS) end();
378
+ if (now >= songSeconds(track)) end();
324
379
  } else if (phase === "results") {
325
380
  energy = 0.5;
326
381
  section = "outro";
@@ -340,11 +395,13 @@ async function boot() {
340
395
  if (!contextLost) renderer.render(stage.scene, stage.camera);
341
396
  },
342
397
  });
343
- host.lifecycle.onChanged(state => { if (!paused) music.setActive(state.active); });
398
+ host.sound?.onChanged(drawSound);
344
399
 
345
- saved = parseSaved(await host.checkpoint.read().catch(() => null));
400
+ saved = readProgress(await host.checkpoint.read().catch(() => null), TRACK_IDS);
346
401
  setSound(!saved.muted);
347
- bestLine.textContent = saved.rounds > 0 ? `Best: ${saved.best.toLocaleString("en-US")} over ${saved.rounds} song${saved.rounds === 1 ? "" : "s"}.` : "One song, about a minute.";
402
+ bestLine.textContent = saved.rounds > 0 ? `Best: ${saved.best.toLocaleString("en-US")} over ${plural(saved.rounds, "song")}.` : `${TRACKS.length} tracks, about a minute each.`;
403
+ choose(pickTrack(TRACKS.length, shuffle, saved.last === null ? null : TRACK_IDS.indexOf(saved.last)));
404
+ nextTrackButton.addEventListener("click", () => choose((chosen + 1) % TRACKS.length));
348
405
  stage.frame("title", true);
349
406
  startButton.textContent = "Start dancing";
350
407
  startButton.disabled = false;
@@ -352,7 +409,7 @@ async function boot() {
352
409
  againButton.addEventListener("click", begin);
353
410
  await host.ready();
354
411
  startButton.focus();
355
- window.addEventListener("pagehide", () => { report(); music.dispose(); cat.dispose(); stage.dispose(); renderer.dispose(); host.destroy(); }, { once: true });
412
+ window.addEventListener("pagehide", () => { report(); music.dispose(); audio?.close(); cat.dispose(); stage.dispose(); renderer.dispose(); host.destroy(); }, { once: true });
356
413
  }
357
414
  canvas.tabIndex = 0;
358
415
  void boot();