@vibechain/os 0.5.1 → 0.6.0

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 (59) hide show
  1. package/AGENTS.md +52 -11
  2. package/README.md +115 -20
  3. package/SECURITY.md +6 -4
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +74 -5
  6. package/dist/app-host.js +94 -6
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/app-wire.d.ts +186 -6
  10. package/dist/app-wire.js +213 -7
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -1
  14. package/dist/browser.js +2 -1
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +5 -3
  17. package/dist/check.js +11 -4
  18. package/dist/cli.js +3 -1
  19. package/dist/commands.d.ts +6 -0
  20. package/dist/commands.js +17 -0
  21. package/dist/fake-services.d.ts +88 -0
  22. package/dist/fake-services.js +132 -0
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1 -1
  25. package/dist/links.d.ts +13 -0
  26. package/dist/links.js +17 -1
  27. package/dist/listing.d.ts +12 -0
  28. package/dist/listing.js +49 -1
  29. package/dist/manifest.d.ts +76 -1
  30. package/dist/manifest.js +170 -5
  31. package/dist/os.d.ts +83 -5
  32. package/dist/os.js +179 -15
  33. package/dist/preview-parent.d.ts +21 -2
  34. package/dist/preview-parent.js +101 -8
  35. package/dist/preview-surfaces.d.ts +36 -0
  36. package/dist/preview-surfaces.js +84 -0
  37. package/dist/preview-ui.js +1 -1
  38. package/dist/preview.js +4 -2
  39. package/dist/templates/plain/game.js +3 -1
  40. package/dist/testing.d.ts +50 -7
  41. package/dist/testing.js +137 -13
  42. package/dist/transport.d.ts +4 -1
  43. package/dist/transport.js +2 -2
  44. package/dist/vibemarket-os.js +1 -1
  45. package/examples/paw-beat/README.md +38 -10
  46. package/examples/paw-beat/cat.ts +13 -0
  47. package/examples/paw-beat/game.ts +290 -123
  48. package/examples/paw-beat/index.html +20 -4
  49. package/examples/paw-beat/main.ts +156 -48
  50. package/examples/paw-beat/music.ts +72 -337
  51. package/examples/paw-beat/stage.ts +23 -9
  52. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  53. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  54. package/examples/paw-beat/synth.ts +477 -0
  55. package/examples/paw-beat/tracks.ts +286 -0
  56. package/examples/paw-beat/vibemarket.json +15 -8
  57. package/examples/vibexp-app/plain/game.ts +6 -2
  58. package/package.json +7 -1
  59. package/skill.md +471 -0
@@ -1,16 +1,29 @@
1
1
  import type { GameFinishInput } from "./completion.ts";
2
- import { type AppLifecycle } from "./app-protocol.ts";
3
- import { type Player, type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
2
+ import { type AppLifecycle, type AppSound } from "./app-protocol.ts";
3
+ import { type Achievement, type Friend, type Invite, type InviteOptions, type Leaderboard, type LeaderboardQuery, type Player, type Product, type Receipt, type ShareOptions, type WireCard, type WirePack, type WirePackSummary } from "./app-wire.ts";
4
4
  export interface AppSession {
5
5
  lifecycle(value: AppLifecycle): void;
6
6
  close(): void;
7
+ /** Tell the app the desktop's sound (`app.sound`, any protocol; clients before 0.5.2 ignore it). */
8
+ sound(value: AppSound): void;
7
9
  /**
8
10
  * Ask a protocol 2 app for its current frame (`app.capture` / `app.frame`): a PNG, JPEG or WebP data URL, or null when
9
11
  * there is none (protocol 1, no hello yet, the app has no picture, the timeout, the session ended, a newer capture took
10
12
  * over). One capture is pending at a time. Never rejects.
11
13
  */
12
14
  capture(timeoutMs?: number): Promise<string | null>;
15
+ /**
16
+ * SDK 0.6: a friend's invite reached the player while this app is open (`app.invite`; the app's `os.onInvite` hears it).
17
+ * Sent only to a client that said hello (protocol 2); a 0.5 client ignores the event. Returns whether it was sent. The
18
+ * invite the app was opened with is not sent this way: the host answers it from `AppHostServices.launch`. Optional only so
19
+ * that objects written against 0.5 still type-check; the controller's sessions always have it.
20
+ */
21
+ invite?(value: Invite): boolean;
13
22
  }
23
+ /** A finished round as the host hears it: the score, and since SDK 0.6 the board it is for when the app named one. */
24
+ export type AppFinish = GameFinishInput & {
25
+ board?: string;
26
+ };
14
27
  /**
15
28
  * `current`: this generation is the live one (its frame is mounted for this app and the page is shown). `foreground`: its
16
29
  * window is in front. A generation that is current but not in the foreground is backgrounded: the host keeps its frame
@@ -24,8 +37,9 @@ export interface AppAttachOptions {
24
37
  current: () => boolean;
25
38
  foreground?: () => boolean;
26
39
  ready: () => void;
27
- finish?: (result: Readonly<GameFinishInput>) => void;
28
40
  fault: (message: string) => void;
41
+ /** the app's first finish: its score, and the board to post it to when it named one (SDK 0.6; else the default `score` board) */
42
+ finish?: (result: Readonly<AppFinish>) => void;
29
43
  progress?: (fraction: number) => void;
30
44
  }
31
45
  /**
@@ -69,7 +83,52 @@ export interface AppHostServices {
69
83
  player(): Promise<Player>;
70
84
  maximize(on: boolean): Promise<void>;
71
85
  fullscreen(on: boolean): Promise<void>;
86
+ /**
87
+ * Whether a user activation (a click, a tap, a key) reached the app's window within the last `withinMs` milliseconds; the
88
+ * desk's own check, as for showPack. Without it every call that needs a click answers `needs-click`.
89
+ */
90
+ clicked?(withinMs: number): boolean;
91
+ /**
92
+ * A board read (`os.leaderboard`), every option resolved: `board` defaults to "score", `scope` to "everyone", `period` to
93
+ * "all", `limit` (1 to 50) to 10. Answer that board and period with at most `limit` entries. Supplying it also lists
94
+ * FINISH_BOARD_FEATURE, so `os.finish({ score, board })` names its board to `AppAttachOptions.finish`.
95
+ */
96
+ leaderboard?(query: LeaderboardQuery): Promise<Leaderboard>;
97
+ /** Open the vmOS leaderboard panel on `board` (default "score") and resolve when the player closes it. */
98
+ showLeaderboard?(board: string): Promise<void>;
99
+ /** Record an achievement: `{ unlocked: true }` only the first time (and show the toast); `invalid` for an undeclared id. */
100
+ unlock?(id: string): Promise<{
101
+ unlocked: boolean;
102
+ }>;
103
+ /** The app's declared achievements with the player's state; secret locked ones as SECRET_ACHIEVEMENT_NAME, "" and no icon. At most 50. */
104
+ achievements?(): Promise<Achievement[]>;
105
+ /** The player's friends who installed this app, at most 100, ordered playing, online, offline, then by name. */
106
+ friends?(): Promise<Friend[]>;
107
+ /** The invite this app was opened with (`os.launch.invite`), or null; asked once per frame load, so answer the same for the whole open. */
108
+ launch?(): Promise<Invite | null>;
109
+ /** Open the invite sheet; resolve with how many friends were invited (1 to 10) once the player confirms, `{ sent: 0 }` when they close it. */
110
+ invite?(options: InviteOptions): Promise<{
111
+ sent: number;
112
+ }>;
113
+ /** Open the share sheet; resolve `{ shared: false }` when the player closes it without posting. */
114
+ share?(options: ShareOptions): Promise<{
115
+ shared: boolean;
116
+ }>;
117
+ /** The approved version's products with `owned` (a permanent product the player bought; always false for a consumable). At most 50. */
118
+ products?(): Promise<Product[]>;
119
+ /** Draw the spend dialog for `product` and spend on confirmation; the receipt (the existing one for an owned permanent product). */
120
+ buy?(product: string): Promise<Receipt>;
121
+ /** Permanent receipts and consumables not yet consumed, at most 100. */
122
+ purchases?(): Promise<Receipt[]>;
123
+ /** Mark a consumable receipt consumed; consuming it again is not an error; `invalid` for an unknown or permanent receipt. */
124
+ consume?(receipt: string): Promise<void>;
125
+ /** A 5-minute signed receipt token (at most 1,500 characters) for a `network` app's server; `not-permitted` otherwise. */
126
+ receiptToken?(receipt: string): Promise<string>;
127
+ /** Open an app's page in MiniVibe (`os.open("vmos://app/<appId>")`). */
128
+ showApp?(app: string): Promise<void>;
72
129
  }
130
+ /** The 0.6 features a host lists: each method whose handler it supplies, and the finish board with a board read. */
131
+ export declare function apps4Features(services: AppHostServices): string[];
73
132
  export interface AppControllerOptions {
74
133
  /** protocol 2 and the apps3 lifetime (15 minutes idle, 4 hours absolute); without it the controller is exactly protocol 1 */
75
134
  services?: AppHostServices;
@@ -97,17 +156,27 @@ export interface AppFrameOptions {
97
156
  fault: (message: string) => void;
98
157
  /** whether the app's window is in front (AppAttachOptions); `setActive` tells the app the same */
99
158
  foreground?: () => boolean;
100
- finish?: (result: Readonly<GameFinishInput>) => void;
159
+ finish?: (result: Readonly<AppFinish>) => void;
101
160
  /** protocol 2: the app's loading progress, 0 to 1, for the host's loading bar */
102
161
  progress?: (fraction: number) => void;
162
+ /**
163
+ * The desktop's sound when the frame connects (0.5.2). It reaches the app with the port, ahead of any answer, so a 0.5.2
164
+ * `connect()` has it when it resolves; send every change with `setSound`. Without it the app hears nothing about sound and
165
+ * plays at full volume.
166
+ */
167
+ sound?: AppSound;
103
168
  }
104
- /** One mounted frame. `setActive` sends the app its lifecycle's `active` flag; `resize` keeps it. */
169
+ /** One mounted frame. `setActive` sends the app its lifecycle's `active` flag; `resize` keeps it; `setSound` sends the desktop's sound. */
105
170
  export interface MountedAppFrame {
106
171
  resize(width: number, height: number): void;
107
172
  setActive(active: boolean): void;
108
173
  dispose(): void;
174
+ /** the desktop's sound changed (the taskbar speaker or the volume): the app hears it at once, and a frame that connects later on connecting */
175
+ setSound(sound: AppSound): void;
109
176
  /** the app's current frame as a data URL (see `AppSession.capture`), or null; also null when there is no session or it ended */
110
177
  capture(timeoutMs?: number): Promise<string | null>;
178
+ /** SDK 0.6: a friend's invite arrived while the app is open (see `AppSession.invite`); false when the app cannot hear it */
179
+ invite?(value: Invite): boolean;
111
180
  }
112
181
  /**
113
182
  * Caller supplies the already-validated immutable URL, including this generation's fragment. With a protocol 2
package/dist/app-host.js CHANGED
@@ -1,8 +1,19 @@
1
1
  import { CHANNEL } from "./channel.js";
2
2
  import { appRuntimeRefusal } from "./app-runtime.js";
3
- import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson } from "./app-protocol.js";
4
- import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, CARD_ID, cardArtPath, coverArtPath, AppHostError, appRequest2, cardsRevision, frameImage, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireCard, wirePack, wirePackSummary, wirePlayer, } from "./app-wire.js";
3
+ import { APP_FRAGMENT, APP_LIMITS, FRAME_MESSAGE_BYTES, appJson, appNonce, checkpointJson, createAppNonce, lifecycleValue, parseAppEnvelope, parseAppJson, soundValue } from "./app-protocol.js";
4
+ import { APP_FEATURES_2, APP_METHODS_2, APP_SESSION_LIMITS, APPS4_LIMITS, APPS4_METHODS, CARD_ID, FINISH_BOARD_FEATURE, PLAYER_RULES, cardArtPath, coverArtPath, AppHostError, appRequest2, apps4Problem, cardsRevision, frameImage, entryRoot, methodRule, saveJson, saveValue, utf8Bytes, wireAchievement, wireCard, wireFriend, wireInvite, wireLeaderboard, wirePack, wirePackSummary, wirePlayer, wireProduct, wireReceipt, } from "./app-wire.js";
5
5
  import { packSlug } from "./manifest.js";
6
+ /** The AppHostServices member that answers each 0.6 method. */
7
+ const HANDLERS = Object.freeze({
8
+ "leaderboard.get": "leaderboard", "leaderboard.show": "showLeaderboard", "achievement.unlock": "unlock", "achievements.list": "achievements",
9
+ "friends.list": "friends", "app.launch": "launch", "invite.open": "invite", "share.open": "share", "products.list": "products", "product.buy": "buy",
10
+ "purchases.list": "purchases", "purchase.consume": "consume", "purchase.token": "receiptToken", "app.show": "showApp",
11
+ });
12
+ const apps4 = (method) => APPS4_METHODS.includes(method);
13
+ /** The 0.6 features a host lists: each method whose handler it supplies, and the finish board with a board read. */
14
+ export function apps4Features(services) {
15
+ return [...APPS4_METHODS.filter(method => typeof services[HANDLERS[method]] === "function"), ...(services.leaderboard ? [FINISH_BOARD_FEATURE] : [])];
16
+ }
6
17
  /**
7
18
  * An apps3 session's request: protocol 1 methods exactly as `parseAppEnvelope` admits them, `host.hello` before hello, and
8
19
  * after hello every protocol 2 method within its request bound. Anything else throws (the session ends).
@@ -38,6 +49,9 @@ const MESSAGE = {
38
49
  slug: "That is not a pack slug.",
39
50
  after: "That page cursor is not valid.",
40
51
  unavailable: "The host could not answer that now; try again.",
52
+ unsupported: "This host does not offer that.",
53
+ guest: "Guests cannot do that; sign in with Steam first.",
54
+ click: "That needs a fresh click in the app.",
41
55
  };
42
56
  /** A single installation/window owns only the JSON this same app host-accepted. */
43
57
  export function createAppController(clock = () => performance.now(), options = {}) {
@@ -154,6 +168,7 @@ export function createAppController(clock = () => performance.now(), options = {
154
168
  const handle = {
155
169
  lifecycle(value) { if (current())
156
170
  port.postMessage(appJson({ session, event: "app.lifecycle", state: lifecycleValue(value) }, APP_LIMITS.responseBytes)); },
171
+ sound(value) { send({ session, event: "app.sound", state: soundValue(value) }, 256); },
157
172
  close,
158
173
  capture(timeoutMs = APP_SESSION_LIMITS.captureMs) {
159
174
  endCapture(null);
@@ -171,6 +186,12 @@ export function createAppController(clock = () => performance.now(), options = {
171
186
  }
172
187
  });
173
188
  },
189
+ invite(value) {
190
+ if (!hello || !current())
191
+ return false;
192
+ send({ session, event: "app.invite", state: wireInvite(value) }, 2 * 1024);
193
+ return true;
194
+ },
174
195
  };
175
196
  active = handle;
176
197
  activeFault = attachOptions.fault;
@@ -212,7 +233,7 @@ export function createAppController(clock = () => performance.now(), options = {
212
233
  throw new AppHostError("unavailable", MESSAGE.unavailable);
213
234
  } };
214
235
  switch (request.method) {
215
- case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : [])], root: entryRoot(services.entry) };
236
+ case "host.hello": return { protocol: 2, guest: services.guest, features: [...APP_FEATURES_2, ...(services.showCard ? ["card.show"] : []), ...apps4Features(services)], root: entryRoot(services.entry) };
216
237
  case "ui.progress":
217
238
  // ignored once the app is ready
218
239
  if (!ready) {
@@ -285,6 +306,51 @@ export function createAppController(clock = () => performance.now(), options = {
285
306
  case "display.fullscreen":
286
307
  await services.fullscreen(request.on);
287
308
  return { completed: true };
309
+ default: return answer4(services, request, check);
310
+ }
311
+ };
312
+ /** A 0.6 answer, after reply2's checks: the handler's value, checked against its strict wire shape. */
313
+ const answer4 = async (services, request, check) => {
314
+ const list = (value, max, item) => { if (!Array.isArray(value) || value.length > max)
315
+ throw Error(); return value.map(item); };
316
+ switch (request.method) {
317
+ case "leaderboard.get": {
318
+ const query = { board: request.board ?? "score", scope: request.scope ?? "everyone", period: request.period ?? "all", limit: request.limit ?? APPS4_LIMITS.boardRowsDefault };
319
+ return { leaderboard: check(await services.leaderboard(query), value => wireLeaderboard(value, query)) };
320
+ }
321
+ case "leaderboard.show":
322
+ await services.showLeaderboard(request.board ?? "score");
323
+ return { shown: true };
324
+ case "achievement.unlock": return check(await services.unlock(request.id), value => { if (!value || typeof value.unlocked !== "boolean")
325
+ throw Error(); return { unlocked: value.unlocked }; });
326
+ case "achievements.list": return { achievements: check(await services.achievements(), value => list(value, 50, wireAchievement)) };
327
+ case "friends.list": return { friends: check(await services.friends(), value => list(value, APPS4_LIMITS.friendsMax, wireFriend)) };
328
+ case "app.launch": return { invite: check(await services.launch(), value => value === null ? null : wireInvite(value)) };
329
+ case "invite.open": {
330
+ const { method: _method, ...options } = request;
331
+ return check(await services.invite(options), value => { if (!value || !Number.isInteger(value.sent) || value.sent < 0 || value.sent > APPS4_LIMITS.inviteRecipients)
332
+ throw Error(); return { sent: value.sent }; });
333
+ }
334
+ case "share.open": {
335
+ const { method: _method, ...options } = request;
336
+ return check(await services.share(options), value => { if (!value || typeof value.shared !== "boolean")
337
+ throw Error(); return { shared: value.shared }; });
338
+ }
339
+ case "products.list": return { products: check(await services.products(), value => list(value, 50, wireProduct)) };
340
+ case "product.buy": return { receipt: check(await services.buy(request.product), value => { const receipt = wireReceipt(value); if (receipt.product !== request.product)
341
+ throw Error(); return receipt; }) };
342
+ case "purchases.list": return { purchases: check(await services.purchases(), value => list(value, APPS4_LIMITS.receiptsMax, wireReceipt)) };
343
+ case "purchase.consume":
344
+ await services.consume(request.receipt);
345
+ return { completed: true };
346
+ case "purchase.token": return { token: check(await services.receiptToken(request.receipt), value => {
347
+ if (typeof value !== "string" || value.length < PLAYER_RULES.tokenMin || value.length > PLAYER_RULES.tokenMax || !PLAYER_RULES.token.test(value))
348
+ throw Error();
349
+ return value;
350
+ }) };
351
+ case "app.show":
352
+ await services.showApp(request.app);
353
+ return { shown: true };
288
354
  }
289
355
  };
290
356
  port.onmessage = (event) => {
@@ -370,14 +436,14 @@ export function createAppController(clock = () => performance.now(), options = {
370
436
  result = { completed: true };
371
437
  break;
372
438
  case "game.finish":
373
- if (completion && completion.score !== request.score) {
439
+ if (completion && (completion.score !== request.score || completion.board !== request.board)) {
374
440
  // an apps3 host answers a changed score as a policy refusal; protocol 1 hosts end the session as before
375
441
  if (!apps3)
376
442
  throw Error("This game has already finished.");
377
443
  send({ session, id, error: "This game has already finished.", code: "invalid" }, APP_LIMITS.responseBytes);
378
444
  return;
379
445
  }
380
- completion ??= Object.freeze({ score: request.score });
446
+ completion ??= Object.freeze({ score: request.score, ...(request.board === undefined ? {} : { board: request.board }) });
381
447
  result = { completed: true };
382
448
  break;
383
449
  case "app.checkpoint.get":
@@ -408,6 +474,18 @@ export function createAppController(clock = () => performance.now(), options = {
408
474
  const state = !ready ? "L" : foreground() ? "F" : "B";
409
475
  if (!rule.states.includes(state))
410
476
  throw new AppHostError("not-permitted", MESSAGE.states);
477
+ // 0.6: the handler, the arguments, guests and the click, before the soft rate counts the call (AppHostServices)
478
+ if (apps4(method)) {
479
+ if (typeof services[HANDLERS[method]] !== "function")
480
+ throw new AppHostError("unsupported", MESSAGE.unsupported);
481
+ const problem = apps4Problem(request);
482
+ if (problem)
483
+ throw new AppHostError("invalid", problem);
484
+ if (rule.guest && services.guest)
485
+ throw new AppHostError("guest", MESSAGE.guest);
486
+ if (rule.click !== undefined && services.clicked?.(rule.click) !== true)
487
+ throw new AppHostError("needs-click", MESSAGE.click);
488
+ }
411
489
  // leaving fullscreen is always allowed (section 9.2)
412
490
  if (rule.rate && !(request.method === "display.fullscreen" && !request.on)) {
413
491
  const key = rule.bucket ?? method;
@@ -461,7 +539,7 @@ export function mountAppFrame(frame, options) {
461
539
  throw Error("Invalid app frame challenge.");
462
540
  const protocol2 = options.controller.protocol === 2;
463
541
  let ended = false, loaded = false, connected = false, bootstrapMessages = 0, session, readied = false;
464
- let bounds = lifecycleValue({ active: true, width: 0, height: 0 });
542
+ let bounds = lifecycleValue({ active: true, width: 0, height: 0 }), sound = options.sound === undefined ? null : soundValue(options.sound);
465
543
  const slow = () => fault("App took too long to become ready.");
466
544
  const dispose = () => { if (ended)
467
545
  return; ended = true; clearTimeout(timeout); clearTimeout(ceiling); frame.removeEventListener("load", load); window.removeEventListener("message", connect); session?.close(); };
@@ -510,6 +588,8 @@ export function mountAppFrame(frame, options) {
510
588
  throw Error("App frame is unavailable.");
511
589
  frame.contentWindow.postMessage({ channel: CHANNEL, challenge: options.challenge, session: nonce, ...(protocol2 ? { protocol: 2 } : {}) }, "*", [ports.port2]);
512
590
  session.lifecycle(bounds);
591
+ if (sound)
592
+ session.sound(sound);
513
593
  }
514
594
  catch {
515
595
  ports.port1.close();
@@ -525,8 +605,16 @@ export function mountAppFrame(frame, options) {
525
605
  resize(width, height) { bounds = lifecycleValue({ active: bounds.active, width: Math.min(4096, Math.max(0, Math.floor(width))), height: Math.min(4096, Math.max(0, Math.floor(height))) }); session?.lifecycle(bounds); },
526
606
  setActive(active) { if (active === bounds.active)
527
607
  return; bounds = lifecycleValue({ ...bounds, active }); session?.lifecycle(bounds); },
608
+ setSound(next) {
609
+ const value = soundValue(next);
610
+ if (sound && sound.muted === value.muted && sound.volume === value.volume)
611
+ return;
612
+ sound = value;
613
+ session?.sound(value);
614
+ },
528
615
  dispose,
529
616
  capture(timeoutMs) { return ended || !session ? Promise.resolve(null) : session.capture(timeoutMs); },
617
+ invite(value) { return !ended && session?.invite?.(value) === true; },
530
618
  };
531
619
  }
532
620
  /**
@@ -66,6 +66,14 @@ export interface VibeMarketAppSdk {
66
66
  current(): Readonly<AppLifecycle>;
67
67
  onChanged(listener: (state: Readonly<AppLifecycle>) => void): () => void;
68
68
  };
69
+ /**
70
+ * The desktop's sound (0.5.2): audible at full volume until the host says otherwise, then every change. Optional only so
71
+ * that objects written against 0.5.1 still type-check; `connectVibeMarketApp()` always provides it.
72
+ */
73
+ sound?: {
74
+ current(): Readonly<AppSound>;
75
+ onChanged(listener: (sound: Readonly<AppSound>) => void): () => void;
76
+ };
69
77
  /** The desktop camera asks for a picture: by default the largest canvas is sent; register a handler (canvas, data URL or null) to draw your own. Latest wins; returns unsubscribe. */
70
78
  onCapture?(handler: () => HTMLCanvasElement | string | null | Promise<HTMLCanvasElement | string | null>): () => void;
71
79
  destroy(): void;
@@ -81,4 +89,17 @@ export declare function parseAppEnvelope(input: unknown, session: string): {
81
89
  id: string;
82
90
  request: AppRequest | AppFrameRequest;
83
91
  };
92
+ /**
93
+ * The desktop's sound for this app (the `app.sound` event, any protocol): `muted` when the taskbar speaker (or the desktop's
94
+ * games sound) is off, `volume` the level games play at, from 0 to 1 (the website's desk sends master volume × its Games fader). The host is the one source of truth; an app follows it (`createAudio` from `@vibechain/os/audio` does). A host
95
+ * that predates it sends nothing, and the SDK reads that as audible at full volume.
96
+ */
97
+ export interface AppSound {
98
+ muted: boolean;
99
+ volume: number;
100
+ }
101
+ export declare const AUDIBLE: Readonly<AppSound>;
102
+ export declare function soundValue(input: unknown): Readonly<AppSound>;
103
+ /** Whether anything an app plays can be heard. */
104
+ export declare const audible: (sound: Readonly<AppSound>) => boolean;
84
105
  export declare function lifecycleValue(input: unknown): Readonly<AppLifecycle>;
@@ -117,6 +117,15 @@ export function parseAppEnvelope(input, session) {
117
117
  return { id: input.id, request: { method: request.method, value: checkpointValue(request.value) } };
118
118
  throw Error("This app has no permission for that method.");
119
119
  }
120
+ export const AUDIBLE = Object.freeze({ muted: false, volume: 1 });
121
+ export function soundValue(input) {
122
+ if (!plain(input) || !exact(input, ["muted", "volume"]) || typeof input.muted !== "boolean"
123
+ || typeof input.volume !== "number" || !Number.isFinite(input.volume) || input.volume < 0 || input.volume > 1)
124
+ throw Error("Invalid app sound.");
125
+ return Object.freeze({ muted: input.muted, volume: input.volume });
126
+ }
127
+ /** Whether anything an app plays can be heard. */
128
+ export const audible = (sound) => !sound.muted && sound.volume > 0;
120
129
  export function lifecycleValue(input) {
121
130
  if (!plain(input) || !exact(input, ["active", "width", "height"]) || typeof input.active !== "boolean"
122
131
  || typeof input.width !== "number" || !Number.isInteger(input.width) || input.width < 0 || input.width > 4096
@@ -1,6 +1,11 @@
1
1
  import { captureId, frameImage, type AppRequest, type AppValue } from "./app-protocol.ts";
2
- /** The nine stable error codes (section 11.3). Messages may change; codes never do. */
3
- export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed"];
2
+ import { type LeaderboardFormat, type LeaderboardOrder, type ProductKind } from "./manifest.ts";
3
+ /**
4
+ * The stable error codes (VM_OS_APPS_3.md section 11.3, nine since 0.5; VM_OS_APPS_4.md section 9 added four in 0.6:
5
+ * `cancelled`, `insufficient`, `limit` and `guest`). Messages may change; codes never do. A 0.5 client reads a code it does
6
+ * not know as `unavailable`, and a host answers the 0.6 codes only to the 0.6 methods, which a 0.5 client never sends.
7
+ */
8
+ export declare const OS_ERROR_CODES: readonly ["unsupported", "not-permitted", "invalid", "too-large", "rate-limited", "needs-click", "unavailable", "timeout", "closed", "cancelled", "insufficient", "limit", "guest"];
4
9
  export type OsErrorCode = typeof OS_ERROR_CODES[number];
5
10
  export declare const osErrorCode: (value: unknown) => value is OsErrorCode;
6
11
  /** Session-wide numbers of an apps3 host and a protocol 2 client (sections 9 and 10.1). */
@@ -35,6 +40,14 @@ export declare const APP_SESSION_LIMITS: Readonly<{
35
40
  clientPerMinute: 100;
36
41
  /** a player token is reused while more than this remains */
37
42
  tokenReuseMs: 60000;
43
+ /**
44
+ * SDK 0.6: how recent the click must be for a call that opens a vmOS surface over the app (share, invite, the leaderboard
45
+ * panel, an app link), and for `buy` (VM_OS_APPS_4.md section 8.2: a click within the last second)
46
+ */
47
+ clickMs: 5000;
48
+ buyClickMs: 1000;
49
+ /** SDK 0.6: how long the SDK waits for a call answered only when the player closes a vmOS surface (buy, share, invite, the panel) */
50
+ surfaceMs: number;
38
51
  }>;
39
52
  export declare const RARITIES: readonly ["common", "rare", "epic", "legendary", "mythic"];
40
53
  export type Rarity = typeof RARITIES[number];
@@ -111,7 +124,123 @@ export interface AppHello {
111
124
  features: string[];
112
125
  root: string;
113
126
  }
114
- export type AppRequest2 = AppRequest | {
127
+ export type BoardScope = "everyone" | "friends";
128
+ export type BoardPeriod = "all" | "week";
129
+ export declare const BOARD_SCOPES: readonly ["everyone", "friends"];
130
+ export declare const BOARD_PERIODS: readonly ["all", "week"];
131
+ /** A row of a board. `picture` is the player's picture (absolute in the SDK; on the wire the path after the version prefix). */
132
+ export interface LeaderboardEntry {
133
+ rank: number;
134
+ handle: string;
135
+ name: string;
136
+ picture: string | null;
137
+ score: number;
138
+ you: boolean;
139
+ }
140
+ /** A board read: up to `limit` rows from the top, and the player's own place (also when outside `entries`), or null. */
141
+ export interface Leaderboard {
142
+ board: string;
143
+ name: string;
144
+ order: LeaderboardOrder;
145
+ format: LeaderboardFormat;
146
+ period: BoardPeriod;
147
+ entries: LeaderboardEntry[];
148
+ you: {
149
+ rank: number;
150
+ score: number;
151
+ } | null;
152
+ }
153
+ /**
154
+ * One of the app's achievements and whether the player has it. `at` is when it was unlocked (epoch milliseconds) or null. A
155
+ * secret achievement the player has not unlocked comes as `name` "Secret achievement", an empty description and no icon.
156
+ * `icon` is absolute in the SDK; on the wire it is the bundle path the manifest names.
157
+ */
158
+ export interface Achievement {
159
+ id: string;
160
+ name: string;
161
+ description: string;
162
+ icon: string | null;
163
+ secret: boolean;
164
+ unlocked: boolean;
165
+ at: number | null;
166
+ }
167
+ export declare const PRESENCES: readonly ["playing", "online", "offline"];
168
+ export type Presence = typeof PRESENCES[number];
169
+ /** A friend of the player who has this app installed, with the public fields of a player and a coarse presence. */
170
+ export interface Friend {
171
+ handle: string;
172
+ name: string;
173
+ picture: string | null;
174
+ presence: Presence;
175
+ }
176
+ /** An invite to this app from a friend: their handle, and the `data` the sender's app attached (or null). */
177
+ export interface Invite {
178
+ from: string;
179
+ data: string | null;
180
+ }
181
+ /** A product the manifest declares, as approved, and whether the player owns it (a `permanent` product they bought). */
182
+ export interface Product {
183
+ id: string;
184
+ name: string;
185
+ description: string;
186
+ price: number;
187
+ kind: ProductKind;
188
+ owned: boolean;
189
+ }
190
+ /** A purchase. `consumed` is true once the app called `consume` on a consumable; a permanent product's receipt is never consumed. */
191
+ export interface Receipt {
192
+ id: string;
193
+ product: string;
194
+ kind: ProductKind;
195
+ price: number;
196
+ at: number;
197
+ consumed: boolean;
198
+ }
199
+ /** A board read as the host passes it to its handler: every option resolved to its value or default. */
200
+ export interface LeaderboardQuery {
201
+ board: string;
202
+ scope: BoardScope;
203
+ period: BoardPeriod;
204
+ limit: number;
205
+ }
206
+ export interface InviteOptions {
207
+ to?: string;
208
+ text?: string;
209
+ data?: string;
210
+ }
211
+ export interface ShareOptions {
212
+ text?: string;
213
+ score?: number;
214
+ board?: string;
215
+ }
216
+ /** The numbers of VM_OS_APPS_4.md sections 3 to 8 that the SDK and the host check on every call. */
217
+ export declare const APPS4_LIMITS: Readonly<{
218
+ boardRowsMax: 50;
219
+ boardRowsDefault: 10;
220
+ inviteText: 80;
221
+ inviteData: 256;
222
+ inviteRecipients: 10;
223
+ shareText: 140;
224
+ friendsMax: 100;
225
+ receiptsMax: 100;
226
+ timeScoreMax: 86400000;
227
+ }>;
228
+ /** A receipt id as the backend issues it. */
229
+ export declare const RECEIPT_ID: RegExp;
230
+ /** An app id, as a manifest's `id` admits it. */
231
+ export declare const APP_ID: RegExp;
232
+ export declare const appId: (value: unknown) => value is string;
233
+ /** The feature a host lists when `finish({ score, board })` reaches its board; without it the SDK sends `{ score }` only. */
234
+ export declare const FINISH_BOARD_FEATURE = "game.finish.board";
235
+ /** The name a secret achievement shows until it is unlocked. */
236
+ export declare const SECRET_ACHIEVEMENT_NAME = "Secret achievement";
237
+ export type AppRequest2 = Exclude<AppRequest, {
238
+ method: "game.finish";
239
+ }> | {
240
+ method: "game.finish";
241
+ score: number;
242
+ board?: string;
243
+ } | {
115
244
  method: "host.hello";
116
245
  protocol: 2;
117
246
  sdk: string;
@@ -141,17 +270,52 @@ export type AppRequest2 = AppRequest | {
141
270
  } | {
142
271
  method: "display.maximize" | "display.fullscreen" | "cards.watch";
143
272
  on: boolean;
273
+ } | {
274
+ method: "leaderboard.get";
275
+ board?: string;
276
+ scope?: BoardScope;
277
+ period?: BoardPeriod;
278
+ limit?: number;
279
+ } | {
280
+ method: "leaderboard.show";
281
+ board?: string;
282
+ } | {
283
+ method: "achievement.unlock";
284
+ id: string;
285
+ } | {
286
+ method: "achievements.list" | "friends.list" | "app.launch" | "products.list" | "purchases.list";
287
+ } | ({
288
+ method: "invite.open";
289
+ } & InviteOptions) | ({
290
+ method: "share.open";
291
+ } & ShareOptions) | {
292
+ method: "product.buy";
293
+ product: string;
294
+ } | {
295
+ method: "purchase.consume" | "purchase.token";
296
+ receipt: string;
297
+ } | {
298
+ method: "app.show";
299
+ app: string;
144
300
  };
145
301
  export type AppMethod2 = AppRequest2["method"];
146
302
  /** L loading (before ready), F ready and in front, B behind another window (the grace). */
147
303
  type States = "LFB" | "L" | "F";
148
- /** `bucket` names a soft rate shared by several methods (pack.show and card.show: one per 10 s together). */
304
+ /**
305
+ * `bucket` names a soft rate shared by several methods (pack.show, card.show and app.show: one per 10 s together). 0.6 adds:
306
+ * `click`, a user activation in the app's window within this many milliseconds, checked by the host before the call runs
307
+ * (`needs-click`); `guest`, refused for a guest (`guest`); `surface`, answered only when the player closes a vmOS surface,
308
+ * so the SDK waits `APP_SESSION_LIMITS.surfaceMs` instead of the usual 10 s.
309
+ */
149
310
  interface MethodRule {
150
311
  request: number;
151
312
  response: number;
152
313
  rate?: readonly [count: number, windowMs: number];
153
314
  bucket?: string;
154
315
  states: States;
316
+ click?: number;
317
+ guest?: true;
318
+ surface?: true;
155
319
  }
156
320
  /**
157
321
  * Request and response JSON bounds (of the request object and the result), the soft rate (answered `rate-limited`) and the
@@ -159,9 +323,13 @@ interface MethodRule {
159
323
  * is this package's addition to the contract's table: it is how the host learns the app has an `onCards` listener.
160
324
  */
161
325
  export declare const APP_METHODS_2: Readonly<Record<Exclude<AppMethod2, AppRequest["method"]>, MethodRule>>;
326
+ /** The 0.6 methods: a host lists each in hello's features only when it can answer it (AppHostServices), like `card.show`. */
327
+ export declare const APPS4_METHODS: readonly ["leaderboard.get", "leaderboard.show", "achievement.unlock", "achievements.list", "friends.list", "app.launch", "invite.open", "share.open", "products.list", "product.buy", "purchases.list", "purchase.consume", "purchase.token", "app.show"];
328
+ export type Apps4Method = typeof APPS4_METHODS[number];
162
329
  /**
163
- * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) is listed only by a host whose
164
- * services can show a card; a 0.5.0 host never lists it, and a client never sends a method its host did not list.
330
+ * Protocol 2 features a hello answers with: the methods beyond protocol 1. `card.show` (0.5.1) and the 0.6 methods are listed
331
+ * only by a host whose services answer them; a 0.5.0 host never lists them, and a client never sends a method its host did
332
+ * not list (it answers `unsupported` itself).
165
333
  */
166
334
  export declare const APP_FEATURES_2: readonly string[];
167
335
  export declare const utf8Bytes: (text: string) => number;
@@ -203,6 +371,18 @@ export declare function wirePlayer(value: unknown): Player;
203
371
  export declare const cardsRevision: (value: unknown) => value is string;
204
372
  export declare function wireCardsEvent(value: unknown): AppCardsEvent;
205
373
  export declare function wireHello(value: unknown): AppHello;
374
+ /** A board read as the host sends it; `query`, when given, is what was asked (the answer must be that board and period). */
375
+ export declare function wireLeaderboard(value: unknown, query?: Pick<LeaderboardQuery, "board" | "period" | "limit">): Leaderboard;
376
+ export declare function wireAchievement(value: unknown): Achievement;
377
+ export declare function wireFriend(value: unknown): Friend;
378
+ export declare function wireInvite(value: unknown): Invite;
379
+ export declare function wireProduct(value: unknown): Product;
380
+ export declare function wireReceipt(value: unknown): Receipt;
381
+ /**
382
+ * Why a 0.6 request's values are not acceptable (`invalid`), or null: the exact rules of VM_OS_APPS_4.md sections 3 to 8 on top
383
+ * of `appRequest2`'s structural check. The SDK refuses before sending and the host refuses again before its handler runs.
384
+ */
385
+ export declare function apps4Problem(request: AppRequest2): string | null;
206
386
  /** The version prefix relative to the entry document: `./` for `index.html`, `../` for `app/index.html`. */
207
387
  export declare const entryRoot: (entry: string) => string;
208
388
  export { captureId, frameImage };