@rollrook-ai/sdk 0.0.0-stage → 0.1.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 (143) hide show
  1. package/dist/agents.d.ts +9 -0
  2. package/dist/agents.d.ts.map +1 -0
  3. package/dist/agents.js +13 -0
  4. package/dist/agents.js.map +1 -0
  5. package/dist/assets.d.ts +35 -0
  6. package/dist/assets.d.ts.map +1 -0
  7. package/dist/assets.js +66 -0
  8. package/dist/assets.js.map +1 -0
  9. package/dist/assistant.d.ts +76 -0
  10. package/dist/assistant.d.ts.map +1 -0
  11. package/dist/assistant.js +161 -0
  12. package/dist/assistant.js.map +1 -0
  13. package/dist/audio.d.ts +55 -0
  14. package/dist/audio.d.ts.map +1 -0
  15. package/dist/audio.js +82 -0
  16. package/dist/audio.js.map +1 -0
  17. package/dist/bridge.d.ts +51 -0
  18. package/dist/bridge.d.ts.map +1 -0
  19. package/dist/bridge.js +78 -0
  20. package/dist/bridge.js.map +1 -0
  21. package/dist/calendar.d.ts +33 -0
  22. package/dist/calendar.d.ts.map +1 -0
  23. package/dist/calendar.js +63 -0
  24. package/dist/calendar.js.map +1 -0
  25. package/dist/context.d.ts +19 -0
  26. package/dist/context.d.ts.map +1 -0
  27. package/dist/context.js +25 -0
  28. package/dist/context.js.map +1 -0
  29. package/dist/errors.d.ts +74 -0
  30. package/dist/errors.d.ts.map +1 -0
  31. package/dist/errors.js +111 -0
  32. package/dist/errors.js.map +1 -0
  33. package/dist/events.d.ts +36 -0
  34. package/dist/events.d.ts.map +1 -0
  35. package/dist/events.js +81 -0
  36. package/dist/events.js.map +1 -0
  37. package/dist/files.d.ts +29 -0
  38. package/dist/files.d.ts.map +1 -0
  39. package/dist/files.js +43 -0
  40. package/dist/files.js.map +1 -0
  41. package/dist/index.d.ts +84 -0
  42. package/dist/index.d.ts.map +1 -0
  43. package/dist/index.js +78 -0
  44. package/dist/index.js.map +1 -0
  45. package/dist/mock/index.d.ts +4 -0
  46. package/dist/mock/index.d.ts.map +1 -0
  47. package/dist/mock/index.js +3 -0
  48. package/dist/mock/index.js.map +1 -0
  49. package/dist/mock/mock-host.d.ts +255 -0
  50. package/dist/mock/mock-host.d.ts.map +1 -0
  51. package/dist/mock/mock-host.js +1274 -0
  52. package/dist/mock/mock-host.js.map +1 -0
  53. package/dist/mock/samples.d.ts +56 -0
  54. package/dist/mock/samples.d.ts.map +1 -0
  55. package/dist/mock/samples.js +283 -0
  56. package/dist/mock/samples.js.map +1 -0
  57. package/dist/mock/toolbar.d.ts +95 -0
  58. package/dist/mock/toolbar.d.ts.map +1 -0
  59. package/dist/mock/toolbar.js +279 -0
  60. package/dist/mock/toolbar.js.map +1 -0
  61. package/dist/net.d.ts +13 -0
  62. package/dist/net.d.ts.map +1 -0
  63. package/dist/net.js +26 -0
  64. package/dist/net.js.map +1 -0
  65. package/dist/plugin.d.ts +11 -0
  66. package/dist/plugin.d.ts.map +1 -0
  67. package/dist/plugin.js +13 -0
  68. package/dist/plugin.js.map +1 -0
  69. package/dist/raven.d.ts +51 -0
  70. package/dist/raven.d.ts.map +1 -0
  71. package/dist/raven.js +100 -0
  72. package/dist/raven.js.map +1 -0
  73. package/dist/segment-display.d.ts +93 -0
  74. package/dist/segment-display.d.ts.map +1 -0
  75. package/dist/segment-display.js +324 -0
  76. package/dist/segment-display.js.map +1 -0
  77. package/dist/settings.d.ts +19 -0
  78. package/dist/settings.d.ts.map +1 -0
  79. package/dist/settings.js +27 -0
  80. package/dist/settings.js.map +1 -0
  81. package/dist/storage.d.ts +28 -0
  82. package/dist/storage.d.ts.map +1 -0
  83. package/dist/storage.js +54 -0
  84. package/dist/storage.js.map +1 -0
  85. package/dist/system.d.ts +19 -0
  86. package/dist/system.d.ts.map +1 -0
  87. package/dist/system.js +24 -0
  88. package/dist/system.js.map +1 -0
  89. package/dist/theme.d.ts +51 -0
  90. package/dist/theme.d.ts.map +1 -0
  91. package/dist/theme.js +85 -0
  92. package/dist/theme.js.map +1 -0
  93. package/dist/types.d.ts +278 -0
  94. package/dist/types.d.ts.map +1 -0
  95. package/dist/types.js +2 -0
  96. package/dist/types.js.map +1 -0
  97. package/dist/ui.d.ts +57 -0
  98. package/dist/ui.d.ts.map +1 -0
  99. package/dist/ui.js +78 -0
  100. package/dist/ui.js.map +1 -0
  101. package/dist/usage.d.ts +14 -0
  102. package/dist/usage.d.ts.map +1 -0
  103. package/dist/usage.js +19 -0
  104. package/dist/usage.js.map +1 -0
  105. package/dist/video.d.ts +11 -0
  106. package/dist/video.d.ts.map +1 -0
  107. package/dist/video.js +17 -0
  108. package/dist/video.js.map +1 -0
  109. package/dist/wire.d.ts +214 -0
  110. package/dist/wire.d.ts.map +1 -0
  111. package/dist/wire.js +538 -0
  112. package/dist/wire.js.map +1 -0
  113. package/package.json +39 -4
  114. package/src/agents.ts +14 -0
  115. package/src/assets.ts +80 -0
  116. package/src/assistant.ts +185 -0
  117. package/src/audio.ts +90 -0
  118. package/src/bridge.ts +96 -0
  119. package/src/calendar.ts +68 -0
  120. package/src/context.ts +28 -0
  121. package/src/errors.ts +131 -0
  122. package/src/events.ts +90 -0
  123. package/src/files.ts +47 -0
  124. package/src/index.ts +152 -0
  125. package/src/mock/index.ts +3 -0
  126. package/src/mock/mock-host.ts +1408 -0
  127. package/src/mock/samples.ts +300 -0
  128. package/src/mock/toolbar.ts +321 -0
  129. package/src/net.ts +27 -0
  130. package/src/plugin.ts +14 -0
  131. package/src/raven.ts +116 -0
  132. package/src/segment-display.ts +377 -0
  133. package/src/settings.ts +29 -0
  134. package/src/storage.ts +59 -0
  135. package/src/system.ts +26 -0
  136. package/src/theme.ts +97 -0
  137. package/src/types.ts +327 -0
  138. package/src/ui.ts +88 -0
  139. package/src/usage.ts +21 -0
  140. package/src/video.ts +17 -0
  141. package/src/wire.ts +608 -0
  142. package/theme.css +407 -0
  143. package/README.md +0 -3
@@ -0,0 +1,1408 @@
1
+ import { AssetsApi } from "../assets.js";
2
+ import { AssistantApi } from "../assistant.js";
3
+ import { Bridge } from "../bridge.js";
4
+ import type { BridgeHandler } from "../bridge.js";
5
+ import { CalendarApi } from "../calendar.js";
6
+ import { ContextApi } from "../context.js";
7
+ import { Events } from "../events.js";
8
+ import { StorageApi } from "../storage.js";
9
+ import { ThemeApi } from "../theme.js";
10
+ import type { CalendarItem, CalendarMove, JsonObject, JsonValue, RavenAnswer, ToolPhase, ViewSlot } from "../types.js";
11
+ import { Wire } from "../wire.js";
12
+ import { MockSamples } from "./samples.js";
13
+ import { MockToolbar } from "./toolbar.js";
14
+
15
+ /** How the mock host is set up. */
16
+ export interface MockHostOptions {
17
+ /** The plugin's `rollrook-plugin.json`: its id, version, views, settings and permissions are used. */
18
+ manifest?: unknown;
19
+ /** The permissions to grant, instead of the manifest's; all are granted when neither is given. */
20
+ list_permissions?: string[];
21
+ /** The view this page is; by default the `rr-view` query parameter, the view whose entry is this page, or the first view. */
22
+ view_id?: string;
23
+ /** Start in the dark theme. Defaults to the theme last switched to, then the browser's preference. */
24
+ is_dark?: boolean;
25
+ /** Start in the high-contrast theme. */
26
+ is_high_contrast?: boolean;
27
+ /** How long Raven thinks before it starts answering, in milliseconds. */
28
+ raven_delay_ms?: number;
29
+ /** Show the floating toolbar with the theme and visibility switches. Defaults to true in a top-level page. */
30
+ show_toolbar?: boolean;
31
+ /** The RollRook version the mock reports. */
32
+ app_version?: string;
33
+ }
34
+
35
+ /** A view of the manifest, as the mock reads it. */
36
+ export interface MockView {
37
+ id: string;
38
+ slot: ViewSlot;
39
+ entry: string;
40
+ width: number | undefined;
41
+ height: number | undefined;
42
+ }
43
+
44
+ /**
45
+ * A stand-in for RollRook in an ordinary browser, so a plugin can be built
46
+ * with `vite dev`. It installs the same bridge RollRook does
47
+ * (`window.webkit.messageHandlers.rollrook`, `window.__rollrook`, the theme's
48
+ * CSS variables) and answers every method: storage, files and settings live
49
+ * in `localStorage`, Raven gives canned answers with `raven.turn` events,
50
+ * agents, usage and audio return sample data that moves, popovers open as
51
+ * an overlay, and instances in other frames and tabs of the same origin
52
+ * reach one another through a broadcast channel. A plugin with a background
53
+ * view gets it running in a hidden frame of one open page, which answers
54
+ * assistant tools (`call_tool`) and `calendar.move`; calendar items are kept
55
+ * in `localStorage` and read with `calendar_items`.
56
+ */
57
+ export class MockHost {
58
+ /** The prefix of every `localStorage` key the mock writes. */
59
+ static readonly STORAGE_PREFIX = "rollrook-mock";
60
+
61
+ /** The `localStorage` key that remembers the theme the toolbar switched to. */
62
+ static readonly THEME_KEY = "rollrook-mock/theme";
63
+
64
+ /** The `localStorage` key that remembers whether the high-contrast theme is on. */
65
+ static readonly CONTRAST_KEY = "rollrook-mock/high-contrast";
66
+
67
+ /** The query parameter naming the view a page is. */
68
+ static readonly VIEW_PARAMETER = "rr-view";
69
+
70
+ /** The id of the `<style>` holding the theme's variables, as RollRook names it. */
71
+ static readonly THEME_STYLE_ID = "rollrook-theme";
72
+
73
+ /** The permissions every plugin has without asking. */
74
+ static readonly LIST_DEFAULT_PERMISSIONS = ["context", "storage", "files", "settings", "ui", "system", "plugin"];
75
+
76
+ /** Raven's default delay before answering. */
77
+ static readonly RAVEN_DELAY_MS = 900;
78
+
79
+ /** How many pieces Raven's answer streams in. */
80
+ static readonly RAVEN_CHUNK_COUNT = 8;
81
+
82
+ /** The time between two streamed pieces. */
83
+ static readonly RAVEN_CHUNK_INTERVAL_MS = 90;
84
+
85
+ /** The largest total size of the storage values, as the host enforces it. */
86
+ static readonly STORAGE_MAX_BYTES = 5 * 1024 * 1024;
87
+
88
+ /** How long a usage read takes in the mock. */
89
+ static readonly USAGE_READ_MS = 1200;
90
+
91
+ /** How often the mock reads usage by itself. */
92
+ static readonly USAGE_INTERVAL_MS = 30_000;
93
+
94
+ /** How often the meters send levels, about 30 times a second. */
95
+ static readonly METER_INTERVAL_MS = 33;
96
+
97
+ /** The message a popover frame posts to its opener to close. */
98
+ static readonly CLOSE_POPOVER_MESSAGE = "rollrook-mock/close-popover";
99
+
100
+ /** The lock the page running the background view holds, so only one page of the origin runs it. */
101
+ static readonly BACKGROUND_LOCK_PREFIX = "rollrook-mock/background";
102
+
103
+ /** The message a popover or settings view in a frame sends its opener to change its height. */
104
+ static readonly HEIGHT_MESSAGE = "rollrook-mock/height";
105
+
106
+ /** A settings view's height when its manifest gives none. */
107
+ static readonly SETTINGS_DEFAULT_HEIGHT = 320;
108
+
109
+ /** The width of the sheet a settings view shows in, as Settings' pane. */
110
+ static readonly SETTINGS_SHEET_WIDTH = 520;
111
+
112
+ /** The largest a popover or settings view may be. */
113
+ static readonly VIEW_MAX_SIZE = 800;
114
+
115
+ private readonly plugin_id: string;
116
+ private readonly plugin_version: string;
117
+ private readonly app_version: string;
118
+ private readonly instance_id: string;
119
+ private readonly view: MockView;
120
+ private readonly list_views: MockView[];
121
+ private readonly map_setting_defaults: JsonObject;
122
+ private readonly set_permissions: Set<string> | undefined;
123
+ private readonly raven_delay_ms: number;
124
+ private readonly map_conversations = new Map<string, RavenAnswer>();
125
+ private readonly set_timeouts = new Set<ReturnType<typeof setTimeout>>();
126
+ private readonly set_intervals = new Set<ReturnType<typeof setInterval>>();
127
+ private readonly toolbar: MockToolbar | undefined;
128
+ private readonly channel: BroadcastChannel | undefined;
129
+ private readonly list_tracks: JsonObject[];
130
+ private readonly on_window_message = (event: MessageEvent): void => this.receive_window_message(event);
131
+ private popover: HTMLElement | undefined = undefined;
132
+ private meter_timer: ReturnType<typeof setInterval> | undefined = undefined;
133
+ private background_frame: HTMLIFrameElement | undefined = undefined;
134
+ private release_background: (() => void) | undefined = undefined;
135
+ private is_dark: boolean;
136
+ private is_high_contrast: boolean;
137
+ private is_shown = true;
138
+ private is_audio_enabled = true;
139
+ private is_usage_refreshing = false;
140
+ private usage_read_at = new Date();
141
+ private conversation_count = 0;
142
+ private reported_width: number | undefined = undefined;
143
+
144
+ private constructor(options: MockHostOptions) {
145
+ const manifest = Wire.is_record(options.manifest) ? options.manifest : {};
146
+ this.plugin_id = typeof manifest["id"] === "string" ? manifest["id"] : "dev.plugin";
147
+ this.plugin_version = typeof manifest["version"] === "string" ? manifest["version"] : "0.0.0";
148
+ this.app_version = options.app_version ?? "0.7.0";
149
+ this.instance_id = `mock-${Math.random().toString(36).slice(2, 10)}`;
150
+ this.list_views = MockHost.read_views(manifest);
151
+ this.view = MockHost.pick_view(this.list_views, options.view_id);
152
+ this.map_setting_defaults = MockHost.read_setting_defaults(manifest);
153
+ this.set_permissions = MockHost.granted_permissions(options);
154
+ this.raven_delay_ms = options.raven_delay_ms ?? MockHost.RAVEN_DELAY_MS;
155
+ this.is_dark = options.is_dark ?? MockHost.stored_flag(MockHost.THEME_KEY, "dark") ?? MockHost.prefers_dark();
156
+ this.is_high_contrast = options.is_high_contrast ?? MockHost.stored_flag(MockHost.CONTRAST_KEY, "on") ?? false;
157
+ this.list_tracks = this.sample_tracks();
158
+ this.channel = typeof BroadcastChannel === "function"
159
+ ? new BroadcastChannel(`${MockHost.STORAGE_PREFIX}/${this.plugin_id}`)
160
+ : undefined;
161
+ const is_top = typeof window === "undefined" || window.top === window;
162
+ this.toolbar = options.show_toolbar ?? is_top
163
+ ? new MockToolbar({
164
+ on_toggle_theme: () => this.toggle_theme(),
165
+ on_toggle_contrast: () => this.toggle_contrast(),
166
+ on_open_settings: this.list_views.some((view: MockView) => view.slot === "settings")
167
+ ? () => this.open_settings_view()
168
+ : undefined,
169
+ on_toggle_visibility: () => this.show(!this.is_shown),
170
+ })
171
+ : undefined;
172
+ }
173
+
174
+ /**
175
+ * Install the mock host on the page, unless RollRook's own bridge is
176
+ * there already.
177
+ *
178
+ * @param options - the manifest, the view, permissions and behaviour
179
+ * @returns the mock host, or undefined inside RollRook
180
+ */
181
+ static install(options: MockHostOptions = {}): MockHost | undefined {
182
+ if (Bridge.is_available()) {
183
+ return undefined;
184
+ }
185
+ const host = new MockHost(options);
186
+ host.attach();
187
+ return host;
188
+ }
189
+
190
+ /** The view this page is, as the mock picked it from the manifest. */
191
+ get current_view(): MockView {
192
+ return this.view;
193
+ }
194
+
195
+ /** The width a footbar view last reported with `ui.width`, or undefined. */
196
+ get width(): number | undefined {
197
+ return this.reported_width;
198
+ }
199
+
200
+ /** Remove the bridge, the theme, the toolbar, the popover and every pending timer. */
201
+ uninstall(): void {
202
+ for (const timer of this.set_timeouts) {
203
+ clearTimeout(timer);
204
+ }
205
+ for (const timer of this.set_intervals) {
206
+ clearInterval(timer);
207
+ }
208
+ this.set_timeouts.clear();
209
+ this.set_intervals.clear();
210
+ this.stop_meters();
211
+ this.close_popover();
212
+ this.release_background?.();
213
+ this.release_background = undefined;
214
+ this.background_frame?.remove();
215
+ this.background_frame = undefined;
216
+ this.channel?.close();
217
+ window.removeEventListener("message", this.on_window_message);
218
+ this.toolbar?.remove();
219
+ document.getElementById(MockHost.THEME_STYLE_ID)?.remove();
220
+ Reflect.deleteProperty(globalThis, "webkit");
221
+ Reflect.deleteProperty(globalThis, ContextApi.GLOBAL_NAME);
222
+ }
223
+
224
+ /** Switch between the light and the dark theme, as the user would in RollRook. */
225
+ toggle_theme(): void {
226
+ this.is_dark = !this.is_dark;
227
+ localStorage.setItem(MockHost.THEME_KEY, this.is_dark ? "dark" : "light");
228
+ this.change_theme();
229
+ this.channel?.postMessage({ kind: "theme", isDark: this.is_dark, isHighContrast: this.is_high_contrast });
230
+ }
231
+
232
+ /** Switch the high-contrast theme on or off. */
233
+ toggle_contrast(): void {
234
+ this.is_high_contrast = !this.is_high_contrast;
235
+ localStorage.setItem(MockHost.CONTRAST_KEY, this.is_high_contrast ? "on" : "off");
236
+ this.change_theme();
237
+ this.channel?.postMessage({ kind: "theme", isDark: this.is_dark, isHighContrast: this.is_high_contrast });
238
+ }
239
+
240
+ /**
241
+ * Show or hide the view, as RollRook does when the user switches tabs.
242
+ *
243
+ * @param is_shown - whether the view is shown
244
+ */
245
+ show(is_shown: boolean): void {
246
+ this.is_shown = is_shown;
247
+ this.toolbar?.render_visibility(is_shown);
248
+ this.emit("visibility", { isShown: is_shown });
249
+ }
250
+
251
+ /**
252
+ * Deliver an event through `window.__rollrookEvent`, as RollRook does.
253
+ *
254
+ * @param name - the event's name
255
+ * @param payload - the payload in wire form
256
+ */
257
+ emit(name: string, payload: JsonValue): void {
258
+ const receiver: unknown = Reflect.get(globalThis, Events.RECEIVER_NAME);
259
+ if (typeof receiver === "function") {
260
+ receiver(name, payload);
261
+ }
262
+ }
263
+
264
+ /**
265
+ * The items the plugin last published to the calendar.
266
+ *
267
+ * @returns the items in wire form, as RollRook received them
268
+ */
269
+ calendar_items(): JsonObject[] {
270
+ const stored = localStorage.getItem(this.calendar_key());
271
+ const value: unknown = stored === null ? [] : JSON.parse(stored);
272
+ return Array.isArray(value) ? value.filter((item: unknown): item is JsonObject => Wire.is_record(item) && Wire.is_json(item)) : [];
273
+ }
274
+
275
+ /**
276
+ * Click one of the plugin's calendar items, as the user would in
277
+ * RollRook: the first dock view receives `calendar.open`, else the first
278
+ * sidebar view, else the background view, in every open page showing it.
279
+ *
280
+ * @param id - the item's id
281
+ */
282
+ open_calendar_item(id: string): void {
283
+ const payload: JsonObject = { id };
284
+ this.channel?.postMessage({ kind: "calendar.open", payload });
285
+ if (this.receives_calendar_open()) {
286
+ this.emit("calendar.open", payload);
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Drag one of the plugin's calendar items to new times, as the user
292
+ * would in RollRook: the background view receives `calendar.move`, or
293
+ * every view when the plugin has none.
294
+ *
295
+ * @param move - the item's id and its new times, ISO 8601
296
+ */
297
+ move_calendar_item(move: CalendarMove): void {
298
+ const payload: JsonObject = { id: move.id };
299
+ for (const [key, value] of Object.entries({ start: move.start, end: move.end, due: move.due })) {
300
+ if (value !== undefined) {
301
+ payload[key] = value;
302
+ }
303
+ }
304
+ this.channel?.postMessage({ kind: "calendar.move", payload });
305
+ if (this.receives_calendar_move()) {
306
+ this.emit("calendar.move", payload);
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Call one of the plugin's assistant tools, as RollRook's assistant
312
+ * does, in the background view this page runs or is.
313
+ *
314
+ * @param name - the tool's name
315
+ * @param input - its input
316
+ * @param phase - `preview` or `run`
317
+ * @returns what the tool returned
318
+ * @throws Error when no background view runs in this page, or as the tool fails
319
+ */
320
+ async call_tool(name: string, input: JsonObject, phase: ToolPhase = "run"): Promise<JsonObject> {
321
+ const target: object | null | undefined = this.view.slot === "background"
322
+ ? globalThis
323
+ : this.background_frame?.contentWindow;
324
+ const receiver: unknown = target === null || target === undefined
325
+ ? undefined
326
+ : Reflect.get(target, AssistantApi.RECEIVER_NAME);
327
+ if (typeof receiver !== "function") {
328
+ throw new Error("failed: no background view answers tools in this page");
329
+ }
330
+ const result: unknown = await receiver(name, input, phase);
331
+ if (!Wire.is_record(result) || !Wire.is_json(result)) {
332
+ throw new Error(`failed: the tool ${name} did not return a JSON object`);
333
+ }
334
+ return result as JsonObject;
335
+ }
336
+
337
+ /**
338
+ * Answer one bridge message, as RollRook's handler does: resolve with the
339
+ * result or reject with an error whose message begins with its code.
340
+ *
341
+ * @param message - the posted message
342
+ * @returns the method's result
343
+ */
344
+ async handle(message: unknown): Promise<JsonValue> {
345
+ const record = Wire.is_record(message) ? message : {};
346
+ const method = record["method"];
347
+ const params = Wire.is_record(record["params"]) ? record["params"] : {};
348
+ if (typeof method !== "string") {
349
+ throw new Error("invalid: the message has no method");
350
+ }
351
+ this.check_permission(method, params);
352
+ switch (method) {
353
+ case "context.get":
354
+ return this.context();
355
+ case "storage.get":
356
+ return this.storage_get(params);
357
+ case "storage.set":
358
+ return this.storage_set(params);
359
+ case "storage.delete":
360
+ return this.storage_delete(params);
361
+ case "storage.keys":
362
+ return { keys: this.storage_keys() };
363
+ case "files.read":
364
+ return this.files_read(params);
365
+ case "files.write":
366
+ return this.files_write(params);
367
+ case "files.list":
368
+ return this.files_list(params);
369
+ case "files.delete":
370
+ return this.files_delete(params);
371
+ case "settings.get":
372
+ return { values: this.setting_values() };
373
+ case "settings.set":
374
+ return this.settings_set(params);
375
+ case "ui.toast":
376
+ this.toolbar?.toast(MockHost.string_param(params, "text"));
377
+ return {};
378
+ case "ui.badge":
379
+ this.toolbar?.render_badge(typeof params["text"] === "string" ? params["text"] : undefined);
380
+ return {};
381
+ case "ui.caption":
382
+ this.toolbar?.toast(typeof params["text"] === "string" ? `Caption: ${params["text"]}` : "Caption cleared");
383
+ return {};
384
+ case "ui.height":
385
+ return this.ui_height(params);
386
+ case "system.searchCities":
387
+ return this.search_cities(params);
388
+ case "ui.width":
389
+ return this.ui_width(params);
390
+ case "ui.openView":
391
+ return this.open_view(params);
392
+ case "ui.popover":
393
+ return this.open_popover(params);
394
+ case "ui.closePopover":
395
+ this.request_close_popover();
396
+ return {};
397
+ case "ui.openSettings":
398
+ return this.open_settings(params);
399
+ case "system.openURL":
400
+ return this.open_url(params);
401
+ case "plugin.broadcast":
402
+ return this.broadcast(params);
403
+ case "raven.ask":
404
+ return this.raven_ask(params);
405
+ case "raven.answer":
406
+ return this.raven_answer(params);
407
+ case "raven.open":
408
+ this.conversation(params);
409
+ this.toolbar?.toast("Raven would open this conversation");
410
+ return {};
411
+ case "agents.list":
412
+ return { agents: MockSamples.LIST_AGENTS };
413
+ case "usage.list":
414
+ return this.usage_snapshot();
415
+ case "usage.refresh":
416
+ this.refresh_usage();
417
+ return {};
418
+ case "audio.status":
419
+ return { isEnabled: this.is_audio_enabled, isPermitted: true };
420
+ case "audio.enable":
421
+ return this.audio_enable(params);
422
+ case "audio.requestPermission":
423
+ return { isPermitted: true };
424
+ case "audio.list":
425
+ if (!this.is_audio_enabled) {
426
+ throw new Error("failed: the mixer is off");
427
+ }
428
+ return { tracks: this.list_tracks };
429
+ case "audio.update":
430
+ return this.audio_update(params, false);
431
+ case "audio.reset":
432
+ return this.audio_update(params, true);
433
+ case "audio.meters":
434
+ return this.audio_meters(params);
435
+ case "video.togglePicture":
436
+ MockHost.number_param(params, "sessionId");
437
+ MockHost.number_param(params, "tabId");
438
+ this.toolbar?.toast("RollRook would show the tab's video in the sidebar");
439
+ return {};
440
+ case "net.fetch":
441
+ return this.net_fetch(params);
442
+ case "calendar.publish":
443
+ return this.calendar_publish(params);
444
+ default:
445
+ throw new Error(`unknown: no method ${method}`);
446
+ }
447
+ }
448
+
449
+ private attach(): void {
450
+ const handler: BridgeHandler & Record<string, unknown> = {
451
+ postMessage: (message: unknown) => this.handle(message),
452
+ [Bridge.MOCK_MARKER]: true,
453
+ };
454
+ const webkit: unknown = Reflect.get(globalThis, "webkit");
455
+ if (Wire.is_record(webkit) && Wire.is_record(webkit["messageHandlers"])) {
456
+ webkit["messageHandlers"][Bridge.HANDLER_NAME] = handler;
457
+ } else {
458
+ Reflect.set(globalThis, "webkit", { messageHandlers: { [Bridge.HANDLER_NAME]: handler } });
459
+ }
460
+ Reflect.set(globalThis, ContextApi.GLOBAL_NAME, this.context());
461
+ this.publish_theme();
462
+ this.toolbar?.attach();
463
+ if (this.channel !== undefined) {
464
+ this.channel.onmessage = (event: MessageEvent) => this.receive_channel_message(event.data);
465
+ }
466
+ window.addEventListener("message", this.on_window_message);
467
+ if (this.set_permissions === undefined || this.set_permissions.has("agents.read")) {
468
+ this.repeat(() => this.refresh_usage(), MockHost.USAGE_INTERVAL_MS);
469
+ }
470
+ this.start_background();
471
+ }
472
+
473
+ private start_background(): void {
474
+ const view = this.list_views.find((candidate: MockView) => candidate.slot === "background");
475
+ const is_top = typeof window !== "undefined" && window.top === window;
476
+ if (view === undefined || !is_top || this.view.slot === "background") {
477
+ return;
478
+ }
479
+ const spawn = (): void => {
480
+ const url = new URL(view.entry, location.href);
481
+ url.searchParams.set(MockHost.VIEW_PARAMETER, view.id);
482
+ const frame = document.createElement("iframe");
483
+ frame.src = url.href;
484
+ frame.title = "Background view";
485
+ frame.setAttribute("aria-hidden", "true");
486
+ frame.tabIndex = -1;
487
+ frame.style.cssText = "position:fixed;width:0;height:0;border:0;visibility:hidden;pointer-events:none;";
488
+ document.body.append(frame);
489
+ this.background_frame = frame;
490
+ };
491
+ if (typeof navigator === "undefined" || navigator.locks === undefined) {
492
+ spawn();
493
+ return;
494
+ }
495
+ const held = new Promise<void>((resolve) => {
496
+ this.release_background = resolve;
497
+ });
498
+ navigator.locks.request(`${MockHost.BACKGROUND_LOCK_PREFIX}/${this.plugin_id}`, () => {
499
+ spawn();
500
+ return held;
501
+ }).catch((err: unknown) => console.error(err));
502
+ }
503
+
504
+ private receives_calendar_open(): boolean {
505
+ const opened = this.list_views.find((candidate: MockView) => candidate.slot === "dock")
506
+ ?? this.list_views.find((candidate: MockView) => candidate.slot === "sidebar")
507
+ ?? this.list_views.find((candidate: MockView) => candidate.slot === "background");
508
+ return opened?.id === this.view.id;
509
+ }
510
+
511
+ private receives_calendar_move(): boolean {
512
+ const has_background = this.list_views.some((candidate: MockView) => candidate.slot === "background");
513
+ return has_background ? this.view.slot === "background" : true;
514
+ }
515
+
516
+ private calendar_key(): string {
517
+ return `${MockHost.STORAGE_PREFIX}/${this.plugin_id}/calendar`;
518
+ }
519
+
520
+ private calendar_publish(params: Record<string, unknown>): JsonValue {
521
+ const items = params["items"];
522
+ if (!Array.isArray(items)) {
523
+ throw new Error("invalid: items must be an array");
524
+ }
525
+ if (items.length > CalendarApi.ITEM_LIMIT) {
526
+ throw new Error(`invalid: calendar.publish takes at most ${CalendarApi.ITEM_LIMIT} items`);
527
+ }
528
+ const list_items: JsonObject[] = [];
529
+ const set_ids = new Set<string>();
530
+ for (const item of items) {
531
+ if (!Wire.is_record(item) || !Wire.is_json(item) || typeof item["id"] !== "string" || typeof item["title"] !== "string") {
532
+ throw new Error("invalid: each item has an id and a title");
533
+ }
534
+ const placed: CalendarItem = {
535
+ id: item["id"],
536
+ title: item["title"],
537
+ };
538
+ for (const key of ["start", "end", "due"] as const) {
539
+ const value = item[key];
540
+ if (value === undefined || value === null) {
541
+ continue;
542
+ }
543
+ if (typeof value !== "string" || Number.isNaN(new Date(value).getTime())) {
544
+ throw new Error(`invalid: ${key} of ${item["id"]} is not an ISO 8601 time`);
545
+ }
546
+ placed[key] = value;
547
+ }
548
+ if (!CalendarApi.is_placed(placed)) {
549
+ throw new Error(`invalid: ${item["id"]} needs a start and an end, or a due`);
550
+ }
551
+ if (set_ids.has(item["id"])) {
552
+ throw new Error(`invalid: two items have the id ${item["id"]}`);
553
+ }
554
+ const color = item["color"];
555
+ if (color !== undefined && color !== null && (typeof color !== "string" || !CalendarApi.COLOR_PATTERN.test(color))) {
556
+ throw new Error(`invalid: the item ${item["id"]}'s color is not #rrggbb`);
557
+ }
558
+ set_ids.add(item["id"]);
559
+ list_items.push(item as JsonObject);
560
+ }
561
+ localStorage.setItem(this.calendar_key(), JSON.stringify(list_items));
562
+ return {};
563
+ }
564
+
565
+ private theme(): JsonObject {
566
+ return MockSamples.theme(this.is_dark, this.is_high_contrast);
567
+ }
568
+
569
+ private context(): JsonObject {
570
+ return {
571
+ protocol: Bridge.PROTOCOL,
572
+ pluginId: this.plugin_id,
573
+ pluginVersion: this.plugin_version,
574
+ appVersion: this.app_version,
575
+ viewId: this.view.id,
576
+ slot: this.view.slot,
577
+ instanceId: this.instance_id,
578
+ theme: this.theme(),
579
+ };
580
+ }
581
+
582
+ private change_theme(): void {
583
+ this.publish_theme();
584
+ this.emit("theme", this.theme());
585
+ }
586
+
587
+ private publish_theme(): void {
588
+ const theme = Wire.theme(this.theme());
589
+ const list_declarations = Object.entries(ThemeApi.map_variables).map(
590
+ ([key, variable]) => `${variable}: ${String(Reflect.get(theme.colors, key))};`,
591
+ );
592
+ list_declarations.push(`${ThemeApi.FONT_VARIABLE}: ${MockSamples.FONT};`);
593
+ list_declarations.push(`color-scheme: ${theme.is_dark ? "dark" : "light"};`);
594
+ let style = document.getElementById(MockHost.THEME_STYLE_ID);
595
+ if (style === null) {
596
+ style = document.createElement("style");
597
+ style.id = MockHost.THEME_STYLE_ID;
598
+ document.head.prepend(style);
599
+ }
600
+ style.textContent = `:root { ${list_declarations.join(" ")} }`;
601
+ const context: unknown = Reflect.get(globalThis, ContextApi.GLOBAL_NAME);
602
+ if (Wire.is_record(context)) {
603
+ context["theme"] = this.theme();
604
+ }
605
+ }
606
+
607
+ private receive_channel_message(data: unknown): void {
608
+ if (!Wire.is_record(data)) {
609
+ return;
610
+ }
611
+ if (data["kind"] === "theme" && typeof data["isDark"] === "boolean" && typeof data["isHighContrast"] === "boolean") {
612
+ this.is_dark = data["isDark"];
613
+ this.is_high_contrast = data["isHighContrast"];
614
+ this.change_theme();
615
+ } else if (data["kind"] === "settings") {
616
+ this.emit("settings.changed", { values: this.setting_values() });
617
+ } else if (data["kind"] === "message" && Wire.is_json(data["payload"])) {
618
+ this.emit("message", data["payload"]);
619
+ } else if (data["kind"] === "calendar.open" && this.receives_calendar_open() && Wire.is_json(data["payload"])) {
620
+ this.emit("calendar.open", data["payload"]);
621
+ } else if (data["kind"] === "calendar.move" && this.receives_calendar_move() && Wire.is_json(data["payload"])) {
622
+ this.emit("calendar.move", data["payload"]);
623
+ }
624
+ }
625
+
626
+ private receive_window_message(event: MessageEvent): void {
627
+ if (event.origin !== location.origin) {
628
+ return;
629
+ }
630
+ if (event.data === MockHost.CLOSE_POPOVER_MESSAGE) {
631
+ this.close_popover();
632
+ } else if (
633
+ Wire.is_record(event.data)
634
+ && event.data["type"] === MockHost.HEIGHT_MESSAGE
635
+ && typeof event.data["height"] === "number"
636
+ && this.popover !== undefined
637
+ ) {
638
+ MockToolbar.resize_popover(this.popover, event.data["height"]);
639
+ }
640
+ }
641
+
642
+ private check_permission(method: string, params: Record<string, unknown>): void {
643
+ if (this.set_permissions === undefined) {
644
+ return;
645
+ }
646
+ const map_needed: Record<string, string> = {
647
+ raven: "raven",
648
+ agents: "agents.read",
649
+ usage: "agents.read",
650
+ audio: "audio",
651
+ video: "video",
652
+ };
653
+ const needed = map_needed[method.split(".")[0] ?? ""];
654
+ if (needed !== undefined && !this.set_permissions.has(needed)) {
655
+ throw new Error(`permission: ${method} needs the ${needed} permission`);
656
+ }
657
+ if (method === "net.fetch") {
658
+ const host = MockHost.url_of(params).hostname;
659
+ if (!this.may_fetch(host)) {
660
+ throw new Error(`permission: net.fetch to ${host} needs the net:${host} permission`);
661
+ }
662
+ }
663
+ }
664
+
665
+ private may_fetch(host: string): boolean {
666
+ for (const permission of this.set_permissions ?? []) {
667
+ if (!permission.startsWith("net:")) {
668
+ continue;
669
+ }
670
+ const pattern = permission.slice("net:".length);
671
+ if (pattern === "*" || pattern === host) {
672
+ return true;
673
+ }
674
+ if (pattern.startsWith("*.") && host.endsWith(pattern.slice(1))) {
675
+ return true;
676
+ }
677
+ }
678
+ return false;
679
+ }
680
+
681
+ private storage_key(key: string): string {
682
+ return `${MockHost.STORAGE_PREFIX}/${this.plugin_id}/storage/${key}`;
683
+ }
684
+
685
+ private files_key(path: string): string {
686
+ return `${MockHost.STORAGE_PREFIX}/${this.plugin_id}/files/${path}`;
687
+ }
688
+
689
+ private settings_key(): string {
690
+ return `${MockHost.STORAGE_PREFIX}/${this.plugin_id}/settings`;
691
+ }
692
+
693
+ private storage_get(params: Record<string, unknown>): JsonValue {
694
+ const stored = localStorage.getItem(this.storage_key(MockHost.storage_key_param(params)));
695
+ const value: unknown = stored === null ? null : JSON.parse(stored);
696
+ return { value: Wire.is_json(value) ? value : null };
697
+ }
698
+
699
+ private storage_set(params: Record<string, unknown>): JsonValue {
700
+ const key = MockHost.storage_key_param(params);
701
+ const value = params["value"];
702
+ if (value === undefined || !Wire.is_json(value)) {
703
+ throw new Error("invalid: value must be JSON");
704
+ }
705
+ const text = JSON.stringify(value);
706
+ let total = text.length;
707
+ for (const other of this.storage_keys()) {
708
+ if (other !== key) {
709
+ total += localStorage.getItem(this.storage_key(other))?.length ?? 0;
710
+ }
711
+ }
712
+ if (total > MockHost.STORAGE_MAX_BYTES) {
713
+ throw new Error("failed: storage is full (5 MB)");
714
+ }
715
+ localStorage.setItem(this.storage_key(key), text);
716
+ return {};
717
+ }
718
+
719
+ private storage_delete(params: Record<string, unknown>): JsonValue {
720
+ localStorage.removeItem(this.storage_key(MockHost.storage_key_param(params)));
721
+ return {};
722
+ }
723
+
724
+ private storage_keys(): string[] {
725
+ const prefix = this.storage_key("");
726
+ return MockHost.local_keys().filter((key: string) => key.startsWith(prefix)).map(
727
+ (key: string) => key.slice(prefix.length),
728
+ ).sort();
729
+ }
730
+
731
+ private files_read(params: Record<string, unknown>): JsonValue {
732
+ const path = MockHost.path_param(params, false);
733
+ const text = localStorage.getItem(this.files_key(path));
734
+ if (text === null) {
735
+ throw new Error(`failed: no file ${path}`);
736
+ }
737
+ return { text };
738
+ }
739
+
740
+ private files_write(params: Record<string, unknown>): JsonValue {
741
+ const path = MockHost.path_param(params, false);
742
+ if (this.list_paths_under(path).length > 0) {
743
+ throw new Error(`failed: ${path} cannot be written: it is a folder`);
744
+ }
745
+ localStorage.setItem(this.files_key(path), MockHost.string_param(params, "text"));
746
+ return {};
747
+ }
748
+
749
+ private files_list(params: Record<string, unknown>): JsonValue {
750
+ const path = MockHost.path_param(params, true);
751
+ const list_paths = this.list_paths_under(path);
752
+ if (path !== "" && list_paths.length === 0) {
753
+ throw new Error(`failed: no folder ${path}`);
754
+ }
755
+ const prefix = path === "" ? "" : `${path}/`;
756
+ const map_entries = new Map<string, JsonObject>();
757
+ for (const file_path of list_paths) {
758
+ const rest = file_path.slice(prefix.length);
759
+ const slash = rest.indexOf("/");
760
+ if (slash >= 0) {
761
+ const name = rest.slice(0, slash);
762
+ map_entries.set(name, {
763
+ name,
764
+ isDirectory: true,
765
+ size: 0,
766
+ });
767
+ } else {
768
+ const text = localStorage.getItem(this.files_key(file_path)) ?? "";
769
+ map_entries.set(rest, {
770
+ name: rest,
771
+ isDirectory: false,
772
+ size: new TextEncoder().encode(text).length,
773
+ });
774
+ }
775
+ }
776
+ const list_entries = [...map_entries.values()];
777
+ list_entries.sort((a, b) => String(a["name"]).localeCompare(String(b["name"])));
778
+ return { entries: list_entries };
779
+ }
780
+
781
+ private files_delete(params: Record<string, unknown>): JsonValue {
782
+ const path = MockHost.path_param(params, false);
783
+ const list_paths = localStorage.getItem(this.files_key(path)) === null
784
+ ? this.list_paths_under(path)
785
+ : [path];
786
+ if (list_paths.length === 0) {
787
+ throw new Error(`failed: ${path} cannot be deleted`);
788
+ }
789
+ for (const file_path of list_paths) {
790
+ localStorage.removeItem(this.files_key(file_path));
791
+ }
792
+ return {};
793
+ }
794
+
795
+ private list_paths_under(path: string): string[] {
796
+ const prefix = this.files_key(path === "" ? "" : `${path}/`);
797
+ const root = this.files_key("");
798
+ return MockHost.local_keys().filter((key: string) => key.startsWith(prefix)).map(
799
+ (key: string) => key.slice(root.length),
800
+ );
801
+ }
802
+
803
+ private stored_settings(): JsonObject {
804
+ const stored = localStorage.getItem(this.settings_key());
805
+ const value: unknown = stored === null ? {} : JSON.parse(stored);
806
+ return Wire.is_record(value) && Wire.is_json(value) && !Array.isArray(value) ? { ...value } : {};
807
+ }
808
+
809
+ private setting_values(): JsonObject {
810
+ return {
811
+ ...this.map_setting_defaults,
812
+ ...this.stored_settings(),
813
+ };
814
+ }
815
+
816
+ private settings_set(params: Record<string, unknown>): JsonValue {
817
+ const key = MockHost.string_param(params, "key");
818
+ const value = params["value"];
819
+ if (!(key in this.map_setting_defaults)) {
820
+ throw new Error(`invalid: the manifest declares no setting ${key}`);
821
+ }
822
+ if (value === undefined || !Wire.is_json(value)) {
823
+ throw new Error(`invalid: the setting ${key} takes JSON`);
824
+ }
825
+ const map_stored = this.stored_settings();
826
+ map_stored[key] = value;
827
+ localStorage.setItem(this.settings_key(), JSON.stringify(map_stored));
828
+ this.emit("settings.changed", { values: this.setting_values() });
829
+ this.channel?.postMessage({ kind: "settings" });
830
+ return {};
831
+ }
832
+
833
+ private ui_width(params: Record<string, unknown>): JsonValue {
834
+ const width = MockHost.number_param(params, "width");
835
+ if (width <= 0) {
836
+ throw new Error("invalid: a width is a positive number of points");
837
+ }
838
+ this.reported_width = width;
839
+ return {};
840
+ }
841
+
842
+ private open_view(params: Record<string, unknown>): JsonValue {
843
+ const view = this.view_param(params);
844
+ if (view.slot !== "dock" && view.slot !== "sidebar") {
845
+ throw new Error(`invalid: ${view.id} is not a dock or sidebar view`);
846
+ }
847
+ this.toolbar?.toast(`RollRook would show the view ${view.id}`);
848
+ return {};
849
+ }
850
+
851
+ private open_popover(params: Record<string, unknown>): JsonValue {
852
+ const view = this.view_param(params);
853
+ if (view.slot !== "popover") {
854
+ throw new Error(`invalid: ${view.id} is not a popover view`);
855
+ }
856
+ this.close_popover();
857
+ const url = new URL(view.entry, location.href);
858
+ url.searchParams.set(MockHost.VIEW_PARAMETER, view.id);
859
+ this.popover = MockToolbar.popover({
860
+ url: url.href,
861
+ width: view.width ?? MockToolbar.POPOVER_DEFAULT_SIZE,
862
+ height: view.height ?? MockToolbar.POPOVER_DEFAULT_SIZE,
863
+ on_dismiss: () => this.close_popover(),
864
+ is_sheet: false,
865
+ });
866
+ return {};
867
+ }
868
+
869
+ private open_settings_view(): boolean {
870
+ const view = this.list_views.find((candidate: MockView) => candidate.slot === "settings");
871
+ if (view === undefined) {
872
+ return false;
873
+ }
874
+ this.close_popover();
875
+ const url = new URL(view.entry, location.href);
876
+ url.searchParams.set(MockHost.VIEW_PARAMETER, view.id);
877
+ this.popover = MockToolbar.popover({
878
+ url: url.href,
879
+ width: MockHost.SETTINGS_SHEET_WIDTH,
880
+ height: view.height ?? MockHost.SETTINGS_DEFAULT_HEIGHT,
881
+ on_dismiss: () => this.close_popover(),
882
+ is_sheet: true,
883
+ });
884
+ return true;
885
+ }
886
+
887
+ private ui_height(params: Record<string, unknown>): JsonValue {
888
+ const height = MockHost.number_param(params, "height");
889
+ if (height < 1 || height > MockHost.VIEW_MAX_SIZE) {
890
+ throw new Error(`invalid: a height is from 1 to ${MockHost.VIEW_MAX_SIZE} points`);
891
+ }
892
+ if (this.view.slot !== "popover" && this.view.slot !== "settings") {
893
+ throw new Error("invalid: only a popover or a settings view sets its height");
894
+ }
895
+ if (window.parent !== window) {
896
+ window.parent.postMessage({ type: MockHost.HEIGHT_MESSAGE, height }, location.origin);
897
+ }
898
+ return {};
899
+ }
900
+
901
+ private search_cities(params: Record<string, unknown>): JsonValue {
902
+ const query = params["query"];
903
+ if (typeof query !== "string") {
904
+ throw new Error("invalid: query is a string");
905
+ }
906
+ return { cities: MockSamples.search_cities(query) };
907
+ }
908
+
909
+ private request_close_popover(): void {
910
+ if (this.popover !== undefined) {
911
+ this.close_popover();
912
+ } else if (window.parent !== window) {
913
+ window.parent.postMessage(MockHost.CLOSE_POPOVER_MESSAGE, location.origin);
914
+ }
915
+ }
916
+
917
+ private close_popover(): void {
918
+ const popover = this.popover;
919
+ this.popover = undefined;
920
+ if (popover !== undefined) {
921
+ MockToolbar.dismiss_popover(popover);
922
+ }
923
+ }
924
+
925
+ private open_settings(params: Record<string, unknown>): JsonValue {
926
+ const pane = params["pane"];
927
+ if (pane !== "plugin" && pane !== "codeAgents") {
928
+ throw new Error("invalid: pane is plugin or codeAgents");
929
+ }
930
+ if (pane === "plugin" && window.parent === window && this.open_settings_view()) {
931
+ return {};
932
+ }
933
+ this.toolbar?.toast(pane === "plugin" ? "RollRook would open this plugin's settings" : "RollRook would open the code agent accounts");
934
+ return {};
935
+ }
936
+
937
+ private open_url(params: Record<string, unknown>): JsonValue {
938
+ const text = MockHost.string_param(params, "url");
939
+ let url: URL;
940
+ try {
941
+ url = new URL(text);
942
+ } catch (err: unknown) {
943
+ throw new Error(`invalid: ${text} is not a URL`, { cause: err });
944
+ }
945
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
946
+ throw new Error(`invalid: ${text} is not http or https`);
947
+ }
948
+ window.open(url.href, "_blank", "noopener");
949
+ return {};
950
+ }
951
+
952
+ private broadcast(params: Record<string, unknown>): JsonValue {
953
+ const message = params["message"];
954
+ if (message === undefined || !Wire.is_json(message)) {
955
+ throw new Error("invalid: message must be JSON");
956
+ }
957
+ this.channel?.postMessage({
958
+ kind: "message",
959
+ payload: {
960
+ fromViewId: this.view.id,
961
+ fromInstanceId: this.instance_id,
962
+ message,
963
+ },
964
+ });
965
+ return {};
966
+ }
967
+
968
+ private raven_ask(params: Record<string, unknown>): JsonValue {
969
+ const prompt = MockHost.string_param(params, "prompt");
970
+ if (prompt.trim() === "") {
971
+ throw new Error("invalid: the prompt is empty");
972
+ }
973
+ let conversation_id: string;
974
+ if (params["conversationId"] === undefined || params["conversationId"] === null) {
975
+ this.conversation_count += 1;
976
+ conversation_id = `mock-conversation-${this.conversation_count}`;
977
+ } else {
978
+ conversation_id = MockHost.string_param(params, "conversationId");
979
+ this.conversation(params);
980
+ }
981
+ const previous = this.map_conversations.get(conversation_id)?.answer ?? "";
982
+ this.map_conversations.set(conversation_id, {
983
+ is_running: true,
984
+ answer: previous,
985
+ });
986
+ this.later(() => this.stream_answer(conversation_id, MockSamples.answer(prompt), 1), this.raven_delay_ms);
987
+ this.emit_turn(conversation_id);
988
+ return { conversationId: conversation_id };
989
+ }
990
+
991
+ private stream_answer(conversation_id: string, answer: string, chunk_index: number): void {
992
+ const list_words = answer.split(/(?<=\s)/);
993
+ const word_count = Math.ceil(list_words.length * chunk_index / MockHost.RAVEN_CHUNK_COUNT);
994
+ const is_last = chunk_index >= MockHost.RAVEN_CHUNK_COUNT;
995
+ this.map_conversations.set(conversation_id, {
996
+ is_running: !is_last,
997
+ answer: is_last ? answer : list_words.slice(0, word_count).join(""),
998
+ });
999
+ this.emit_turn(conversation_id);
1000
+ if (!is_last) {
1001
+ this.later(
1002
+ () => this.stream_answer(conversation_id, answer, chunk_index + 1),
1003
+ MockHost.RAVEN_CHUNK_INTERVAL_MS,
1004
+ );
1005
+ }
1006
+ }
1007
+
1008
+ private emit_turn(conversation_id: string): void {
1009
+ const state = this.map_conversations.get(conversation_id);
1010
+ if (state !== undefined) {
1011
+ this.emit("raven.turn", {
1012
+ conversationId: conversation_id,
1013
+ isRunning: state.is_running,
1014
+ answer: state.answer,
1015
+ });
1016
+ }
1017
+ }
1018
+
1019
+ private raven_answer(params: Record<string, unknown>): JsonValue {
1020
+ const state = this.conversation(params);
1021
+ return {
1022
+ isRunning: state.is_running,
1023
+ answer: state.answer,
1024
+ };
1025
+ }
1026
+
1027
+ private conversation(params: Record<string, unknown>): RavenAnswer {
1028
+ const conversation_id = MockHost.string_param(params, "conversationId");
1029
+ const state = this.map_conversations.get(conversation_id);
1030
+ if (state === undefined) {
1031
+ throw new Error(`invalid: ${conversation_id} is not a conversation this plugin started`);
1032
+ }
1033
+ return state;
1034
+ }
1035
+
1036
+ private usage_snapshot(): JsonObject {
1037
+ return {
1038
+ accounts: MockSamples.accounts(this.usage_read_at),
1039
+ isRefreshing: this.is_usage_refreshing,
1040
+ nextRefreshAt: this.is_usage_refreshing
1041
+ ? null
1042
+ : new Date(this.usage_read_at.getTime() + MockHost.USAGE_INTERVAL_MS).toISOString(),
1043
+ };
1044
+ }
1045
+
1046
+ private refresh_usage(): void {
1047
+ if (this.is_usage_refreshing) {
1048
+ return;
1049
+ }
1050
+ this.is_usage_refreshing = true;
1051
+ this.emit("usage.changed", this.usage_snapshot());
1052
+ this.later(() => {
1053
+ this.is_usage_refreshing = false;
1054
+ this.usage_read_at = new Date();
1055
+ this.emit("usage.changed", this.usage_snapshot());
1056
+ }, MockHost.USAGE_READ_MS);
1057
+ }
1058
+
1059
+ private sample_tracks(): JsonObject[] {
1060
+ const assets = new AssetsApi();
1061
+ const track = (target: JsonObject, name: string, icon_url: string, is_playing: boolean): JsonObject => ({
1062
+ target,
1063
+ name,
1064
+ iconURL: icon_url,
1065
+ isPlaying: is_playing,
1066
+ isCapturing: false,
1067
+ hasVideo: target["kind"] === "tab",
1068
+ settings: { ...MockSamples.DEFAULT_AUDIO_SETTINGS },
1069
+ });
1070
+ return [
1071
+ track({ kind: "app", bundleId: "com.apple.Music" }, "Music", assets.app_icon("com.apple.Music"), true),
1072
+ track({ kind: "tab", sessionId: 1, tabId: 42 }, "Lo-fi beats to focus to", assets.app_icon("com.google.Chrome"), true),
1073
+ track({ kind: "app", bundleId: "com.tinyspeck.slackmacgap" }, "Slack", assets.app_icon("com.tinyspeck.slackmacgap"), false),
1074
+ ];
1075
+ }
1076
+
1077
+ private audio_enable(params: Record<string, unknown>): JsonValue {
1078
+ if (typeof params["isEnabled"] !== "boolean") {
1079
+ throw new Error("invalid: isEnabled must be a boolean");
1080
+ }
1081
+ this.is_audio_enabled = params["isEnabled"];
1082
+ if (!this.is_audio_enabled) {
1083
+ this.stop_meters();
1084
+ }
1085
+ return {};
1086
+ }
1087
+
1088
+ private audio_update(params: Record<string, unknown>, is_reset: boolean): JsonValue {
1089
+ const key = MockHost.target_key(params["target"]);
1090
+ const track = this.list_tracks.find((candidate: JsonObject) => MockHost.target_key(candidate["target"]) === key);
1091
+ if (track === undefined) {
1092
+ throw new Error(`failed: no track ${key}`);
1093
+ }
1094
+ const current = Wire.is_record(track["settings"]) ? track["settings"] : {};
1095
+ const changes = is_reset ? MockSamples.DEFAULT_AUDIO_SETTINGS : params["settings"];
1096
+ if (!Wire.is_record(changes)) {
1097
+ throw new Error("invalid: settings must be an object");
1098
+ }
1099
+ const merged: JsonObject = {};
1100
+ for (const [name, default_value] of Object.entries(MockSamples.DEFAULT_AUDIO_SETTINGS)) {
1101
+ const value = name in changes ? changes[name] : current[name];
1102
+ merged[name] = MockHost.clamp_audio_setting(name, value, default_value);
1103
+ }
1104
+ track["settings"] = merged;
1105
+ this.emit("audio.tracks", { tracks: this.list_tracks });
1106
+ return {};
1107
+ }
1108
+
1109
+ private audio_meters(params: Record<string, unknown>): JsonValue {
1110
+ if (typeof params["isOn"] !== "boolean") {
1111
+ throw new Error("invalid: isOn must be a boolean");
1112
+ }
1113
+ this.stop_meters();
1114
+ if (params["isOn"]) {
1115
+ const started_at = performance.now();
1116
+ this.meter_timer = setInterval(() => this.send_levels(performance.now() - started_at), MockHost.METER_INTERVAL_MS);
1117
+ }
1118
+ return {};
1119
+ }
1120
+
1121
+ private send_levels(elapsed_ms: number): void {
1122
+ if (!this.is_shown || !this.is_audio_enabled) {
1123
+ return;
1124
+ }
1125
+ const list_levels: JsonObject[] = this.list_tracks.map((track: JsonObject, index: number) => {
1126
+ const settings = Wire.is_record(track["settings"]) ? track["settings"] : {};
1127
+ const is_silent = track["isPlaying"] !== true || settings["isMuted"] === true;
1128
+ const volume = typeof settings["volume"] === "number" ? settings["volume"] : 1;
1129
+ const phase = elapsed_ms / 1000 + index * 1.7;
1130
+ const level = (offset: number): number => is_silent
1131
+ ? 0
1132
+ : Math.min(1, volume * (0.35 + 0.25 * Math.sin(phase * 2.3 + offset) + 0.2 * Math.abs(Math.sin(phase * 7.1 + offset))));
1133
+ return {
1134
+ key: MockHost.target_key(track["target"]),
1135
+ left: level(0),
1136
+ right: level(0.9),
1137
+ };
1138
+ });
1139
+ this.emit("audio.levels", { levels: list_levels });
1140
+ }
1141
+
1142
+ private stop_meters(): void {
1143
+ clearInterval(this.meter_timer);
1144
+ this.meter_timer = undefined;
1145
+ }
1146
+
1147
+ private async net_fetch(params: Record<string, unknown>): Promise<JsonValue> {
1148
+ const url = MockHost.url_of(params);
1149
+ const map_headers: Record<string, string> = {};
1150
+ if (Wire.is_record(params["headers"])) {
1151
+ for (const [name, value] of Object.entries(params["headers"])) {
1152
+ if (typeof value === "string") {
1153
+ map_headers[name] = value;
1154
+ }
1155
+ }
1156
+ }
1157
+ const init: RequestInit = {
1158
+ method: typeof params["method"] === "string" ? params["method"] : "GET",
1159
+ headers: map_headers,
1160
+ };
1161
+ if (typeof params["body"] === "string") {
1162
+ init.body = params["body"];
1163
+ }
1164
+ let response: Response;
1165
+ try {
1166
+ response = await fetch(url, init);
1167
+ } catch (err: unknown) {
1168
+ throw new Error(`failed: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
1169
+ }
1170
+ const map_reply_headers: JsonObject = {};
1171
+ response.headers.forEach((value: string, name: string) => {
1172
+ map_reply_headers[name.toLowerCase()] = value;
1173
+ });
1174
+ return {
1175
+ status: response.status,
1176
+ headers: map_reply_headers,
1177
+ body: await response.text(),
1178
+ };
1179
+ }
1180
+
1181
+ private view_param(params: Record<string, unknown>): MockView {
1182
+ const view_id = MockHost.string_param(params, "viewId");
1183
+ const view = this.list_views.find((candidate: MockView) => candidate.id === view_id);
1184
+ if (view === undefined) {
1185
+ throw new Error(`invalid: the manifest has no view ${view_id}`);
1186
+ }
1187
+ return view;
1188
+ }
1189
+
1190
+ private later(action: () => void, delay_ms: number): void {
1191
+ const timer = setTimeout(() => {
1192
+ this.set_timeouts.delete(timer);
1193
+ action();
1194
+ }, delay_ms);
1195
+ this.set_timeouts.add(timer);
1196
+ }
1197
+
1198
+ private repeat(action: () => void, interval_ms: number): void {
1199
+ this.set_intervals.add(setInterval(action, interval_ms));
1200
+ }
1201
+
1202
+ private static read_views(manifest: Record<string, unknown>): MockView[] {
1203
+ const list_views: MockView[] = [];
1204
+ const views = manifest["views"];
1205
+ if (Array.isArray(views)) {
1206
+ for (const raw of views) {
1207
+ if (!Wire.is_record(raw) || typeof raw["id"] !== "string" || typeof raw["entry"] !== "string") {
1208
+ continue;
1209
+ }
1210
+ const slot = Wire.LIST_SLOTS.find((candidate: ViewSlot) => candidate === raw["slot"]) ?? "dock";
1211
+ list_views.push({
1212
+ id: raw["id"],
1213
+ slot,
1214
+ entry: raw["entry"],
1215
+ width: typeof raw["width"] === "number" ? raw["width"] : undefined,
1216
+ height: typeof raw["height"] === "number" ? raw["height"] : undefined,
1217
+ });
1218
+ }
1219
+ } else if (typeof manifest["main"] === "string") {
1220
+ list_views.push({
1221
+ id: "main",
1222
+ slot: "dock",
1223
+ entry: manifest["main"],
1224
+ width: undefined,
1225
+ height: undefined,
1226
+ });
1227
+ }
1228
+ return list_views;
1229
+ }
1230
+
1231
+ private static pick_view(list_views: MockView[], view_id: string | undefined): MockView {
1232
+ const query_id = typeof location === "undefined"
1233
+ ? null
1234
+ : new URLSearchParams(location.search).get(MockHost.VIEW_PARAMETER);
1235
+ const wanted_id = view_id ?? query_id;
1236
+ const page = typeof location === "undefined" ? "" : location.pathname.split("/").at(-1) ?? "";
1237
+ const page_name = page === "" ? "index.html" : page;
1238
+ return list_views.find((view: MockView) => view.id === wanted_id)
1239
+ ?? list_views.find((view: MockView) => view.entry.split("/").at(-1) === page_name && view.slot !== "popover")
1240
+ ?? list_views.find((view: MockView) => view.entry.split("/").at(-1) === page_name)
1241
+ ?? list_views.find((view: MockView) => view.slot !== "popover" && view.slot !== "settings" && view.slot !== "background")
1242
+ ?? {
1243
+ id: "main",
1244
+ slot: "dock",
1245
+ entry: "index.html",
1246
+ width: undefined,
1247
+ height: undefined,
1248
+ };
1249
+ }
1250
+
1251
+ private static read_setting_defaults(manifest: Record<string, unknown>): JsonObject {
1252
+ const map_defaults: JsonObject = {};
1253
+ const settings = manifest["settings"];
1254
+ if (!Array.isArray(settings)) {
1255
+ return map_defaults;
1256
+ }
1257
+ for (const raw of settings) {
1258
+ if (!Wire.is_record(raw) || typeof raw["key"] !== "string") {
1259
+ continue;
1260
+ }
1261
+ const value = raw["default"];
1262
+ map_defaults[raw["key"]] = value !== undefined && Wire.is_json(value) ? value : MockHost.fallback_setting(raw);
1263
+ }
1264
+ return map_defaults;
1265
+ }
1266
+
1267
+ private static fallback_setting(raw: Record<string, unknown>): JsonValue {
1268
+ switch (raw["type"]) {
1269
+ case "string":
1270
+ return "";
1271
+ case "number":
1272
+ return typeof raw["min"] === "number" ? raw["min"] : 0;
1273
+ case "boolean":
1274
+ return false;
1275
+ case "enum": {
1276
+ const options = raw["options"];
1277
+ const first: unknown = Array.isArray(options) ? options[0] : undefined;
1278
+ return Wire.is_record(first) && typeof first["value"] === "string" ? first["value"] : null;
1279
+ }
1280
+ default:
1281
+ return null;
1282
+ }
1283
+ }
1284
+
1285
+ private static clamp_audio_setting(name: string, value: unknown, default_value: JsonValue): JsonValue {
1286
+ const map_ranges: Record<string, [number, number]> = {
1287
+ volume: [0, 2],
1288
+ pan: [-1, 1],
1289
+ width: [0, 2],
1290
+ reverbMix: [0, 1],
1291
+ };
1292
+ const range = map_ranges[name];
1293
+ if (range !== undefined) {
1294
+ return typeof value === "number" ? Math.min(range[1], Math.max(range[0], value)) : default_value;
1295
+ }
1296
+ if (name === "equalizerGains") {
1297
+ return Array.isArray(value) && value.length === 10
1298
+ ? value.map((gain: unknown) => typeof gain === "number" ? Math.min(12, Math.max(-12, gain)) : 0)
1299
+ : default_value;
1300
+ }
1301
+ if (name === "reverbRoom") {
1302
+ return Wire.LIST_REVERB_ROOMS.find((room: string) => room === value) ?? default_value;
1303
+ }
1304
+ return typeof value === typeof default_value && Wire.is_json(value) ? value : default_value;
1305
+ }
1306
+
1307
+ private static target_key(raw: unknown): string {
1308
+ if (!Wire.is_record(raw)) {
1309
+ throw new Error("invalid: target must be an object");
1310
+ }
1311
+ if (raw["kind"] === "app" && typeof raw["bundleId"] === "string") {
1312
+ return `app:${raw["bundleId"]}`;
1313
+ }
1314
+ if (raw["kind"] === "tab" && typeof raw["sessionId"] === "number" && typeof raw["tabId"] === "number") {
1315
+ return `tab:${raw["sessionId"]}:${raw["tabId"]}`;
1316
+ }
1317
+ throw new Error("invalid: target is { kind: app, bundleId } or { kind: tab, sessionId, tabId }");
1318
+ }
1319
+
1320
+ private static granted_permissions(options: MockHostOptions): Set<string> | undefined {
1321
+ if (options.list_permissions !== undefined) {
1322
+ return new Set([...MockHost.LIST_DEFAULT_PERMISSIONS, ...options.list_permissions]);
1323
+ }
1324
+ const manifest = options.manifest;
1325
+ if (!Wire.is_record(manifest)) {
1326
+ return undefined;
1327
+ }
1328
+ const permissions = manifest["permissions"];
1329
+ const list_permissions = Array.isArray(permissions)
1330
+ ? permissions.filter((permission: unknown) => typeof permission === "string")
1331
+ : [];
1332
+ return new Set([...MockHost.LIST_DEFAULT_PERMISSIONS, ...list_permissions]);
1333
+ }
1334
+
1335
+ private static stored_flag(key: string, on_value: string): boolean | undefined {
1336
+ const stored = localStorage.getItem(key);
1337
+ return stored === null ? undefined : stored === on_value;
1338
+ }
1339
+
1340
+ private static prefers_dark(): boolean {
1341
+ return typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches;
1342
+ }
1343
+
1344
+ private static local_keys(): string[] {
1345
+ const list_keys: string[] = [];
1346
+ for (let index = 0; index < localStorage.length; index += 1) {
1347
+ const key = localStorage.key(index);
1348
+ if (key !== null) {
1349
+ list_keys.push(key);
1350
+ }
1351
+ }
1352
+ return list_keys;
1353
+ }
1354
+
1355
+ private static string_param(params: Record<string, unknown>, name: string): string {
1356
+ const value = params[name];
1357
+ if (typeof value !== "string") {
1358
+ throw new Error(`invalid: ${name} must be a string`);
1359
+ }
1360
+ return value;
1361
+ }
1362
+
1363
+ private static number_param(params: Record<string, unknown>, name: string): number {
1364
+ const value = params[name];
1365
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1366
+ throw new Error(`invalid: ${name} must be a number`);
1367
+ }
1368
+ return value;
1369
+ }
1370
+
1371
+ private static storage_key_param(params: Record<string, unknown>): string {
1372
+ const key = MockHost.string_param(params, "key");
1373
+ if (key.length > StorageApi.KEY_MAX_LENGTH) {
1374
+ throw new Error(`invalid: keys are at most ${StorageApi.KEY_MAX_LENGTH} characters`);
1375
+ }
1376
+ return key;
1377
+ }
1378
+
1379
+ private static path_param(params: Record<string, unknown>, may_be_root: boolean): string {
1380
+ const raw = params["path"];
1381
+ const path = raw === undefined && may_be_root ? "" : MockHost.string_param(params, "path");
1382
+ if (path.startsWith("/") || path.startsWith("~") || path.includes("\\")) {
1383
+ throw new Error(`invalid: ${path} is not a relative path`);
1384
+ }
1385
+ const list_parts = path.split("/").filter((part: string) => part !== "" && part !== ".");
1386
+ if (list_parts.includes("..")) {
1387
+ throw new Error(`invalid: ${path} leaves the data folder`);
1388
+ }
1389
+ if (!may_be_root && list_parts.length === 0) {
1390
+ throw new Error("invalid: the path is empty");
1391
+ }
1392
+ return list_parts.join("/");
1393
+ }
1394
+
1395
+ private static url_of(params: Record<string, unknown>): URL {
1396
+ const text = MockHost.string_param(params, "url");
1397
+ let url: URL;
1398
+ try {
1399
+ url = new URL(text);
1400
+ } catch (err: unknown) {
1401
+ throw new Error(`invalid: ${text} is not a URL`, { cause: err });
1402
+ }
1403
+ if (url.protocol !== "https:") {
1404
+ throw new Error("invalid: net.fetch takes an https URL");
1405
+ }
1406
+ return url;
1407
+ }
1408
+ }