@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
package/src/assets.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { Bridge } from "./bridge.js";
2
+ import type { AgentHarness } from "./types.js";
3
+
4
+ /**
5
+ * URLs of the pictures RollRook shares with every plugin, served from
6
+ * `rollrook-asset://`. Outside RollRook, where that scheme does not exist,
7
+ * each helper returns a neutral placeholder as a `data:` URL instead.
8
+ */
9
+ export class AssetsApi {
10
+ /** The scheme RollRook serves its shared pictures from. */
11
+ static readonly SCHEME = "rollrook-asset://";
12
+
13
+ /** The letter each code agent's placeholder mark shows. */
14
+ static readonly map_harness_letters: Record<AgentHarness, string> = {
15
+ claude: "C",
16
+ codex: "X",
17
+ agy: "A",
18
+ };
19
+
20
+ /** The color of each code agent's placeholder mark, near its own. */
21
+ static readonly map_harness_colors: Record<AgentHarness, string> = {
22
+ claude: "#d97757",
23
+ codex: "#1c1c20",
24
+ agy: "#3b78e7",
25
+ };
26
+
27
+ /**
28
+ * @param name - the code agent
29
+ * @returns the URL of its mark, a PNG in its colors
30
+ */
31
+ harness(name: AgentHarness): string {
32
+ if (Bridge.is_native()) {
33
+ return `${AssetsApi.SCHEME}harness/${name}.png`;
34
+ }
35
+ return AssetsApi.data_url(
36
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><rect width="16" height="16" fill="${AssetsApi.map_harness_colors[name]}"/>`
37
+ + `<text x="8" y="11.4" font-family="-apple-system,sans-serif" font-size="9.5" font-weight="600" fill="#ffffff" text-anchor="middle">${AssetsApi.map_harness_letters[name]}</text></svg>`,
38
+ );
39
+ }
40
+
41
+ /**
42
+ * An interface icon, drawn in `currentColor`. Show it as a CSS mask so it
43
+ * takes the text's color: an `<img>` draws `currentColor` as black.
44
+ *
45
+ * @param name - the icon's name, as Lucide names it, e.g. `clock`
46
+ * @returns the URL of its SVG
47
+ */
48
+ icon(name: string): string {
49
+ if (Bridge.is_native()) {
50
+ return `${AssetsApi.SCHEME}icon/${encodeURIComponent(name)}.svg`;
51
+ }
52
+ return AssetsApi.data_url(
53
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="4" y="4" width="16" height="16" rx="4"/><circle cx="12" cy="12" r="2"/></svg>`,
54
+ );
55
+ }
56
+
57
+ /**
58
+ * @param bundle_id - an app's bundle identifier, e.g. `com.apple.Music`
59
+ * @returns the URL of the app's icon, a PNG
60
+ */
61
+ app_icon(bundle_id: string): string {
62
+ if (Bridge.is_native()) {
63
+ return `${AssetsApi.SCHEME}app-icon/${encodeURIComponent(bundle_id)}.png`;
64
+ }
65
+ const letter = (bundle_id.split(".").at(-1) ?? "?").charAt(0).toUpperCase();
66
+ return AssetsApi.data_url(
67
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><defs><linearGradient id="g" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#8e8e93"/><stop offset="1" stop-color="#636366"/></linearGradient></defs>`
68
+ + `<rect x="2" y="2" width="28" height="28" rx="7" fill="url(#g)"/>`
69
+ + `<text x="16" y="21.5" font-family="-apple-system,sans-serif" font-size="15" font-weight="600" fill="#fff" text-anchor="middle">${AssetsApi.escape_xml(letter)}</text></svg>`,
70
+ );
71
+ }
72
+
73
+ private static data_url(svg: string): string {
74
+ return `data:image/svg+xml,${encodeURIComponent(svg)}`;
75
+ }
76
+
77
+ private static escape_xml(text: string): string {
78
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
79
+ }
80
+ }
@@ -0,0 +1,185 @@
1
+ import { FailedError, InvalidParamsError, RollRookError, UnknownMethodError } from "./errors.js";
2
+ import type { Unsubscribe } from "./events.js";
3
+ import type { JsonObject, JsonValue, ToolPhase, ToolPreview, ToolResult, ToolUndo } from "./types.js";
4
+ import { Wire } from "./wire.js";
5
+
6
+ /** A tool's run: does what the tool says and tells the assistant what came of it. */
7
+ export type ToolRun = (input: JsonObject) => ToolResult | Promise<ToolResult>;
8
+
9
+ /** A tool's preview: says in one line what the run would do, without doing it. */
10
+ export type ToolPreviewer = (input: JsonObject) => ToolPreview | Promise<ToolPreview>;
11
+
12
+ /**
13
+ * How a tool answers: one function taking the phase, or a run and, for a tool
14
+ * the manifest declares with `confirm: true`, a preview.
15
+ */
16
+ export type ToolHandler =
17
+ | ((input: JsonObject, phase: ToolPhase) => ToolResult | ToolPreview | Promise<ToolResult | ToolPreview>)
18
+ | { run: ToolRun; preview?: ToolPreviewer };
19
+
20
+ /**
21
+ * The plugin's tools for RollRook's assistant. The manifest declares each
22
+ * under `contributes.raven.tools` with its name, description, input schema
23
+ * and whether it needs the user's approval; the background view answers
24
+ * them. RollRook calls `window.__rollrookTool(name, input, phase)` there and
25
+ * awaits the JSON it resolves with: for a tool declared with `confirm: true`
26
+ * first a `preview` (`{ summary }`, shown on a card), then a `run` once the
27
+ * user approves; for the others a `run` alone. A run's result may carry a
28
+ * `summary`, the line the conversation shows for the change, and
29
+ * `undo: { tool, input }`, which RollRook offers as Undo. RollRook names the
30
+ * tools to the assistant with a prefix (`tasks_add_task`); the page answers
31
+ * them by their own names.
32
+ */
33
+ export class AssistantApi {
34
+ /** The global function RollRook calls to run a tool. */
35
+ static readonly RECEIVER_NAME = "__rollrookTool";
36
+
37
+ /** A tool's name, as the manifest takes it: snake_case words, a letter first. */
38
+ static readonly NAME_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
39
+
40
+ /** The longest a tool's name may be. */
41
+ static readonly NAME_MAX_LENGTH = 32;
42
+
43
+ private readonly map_handlers = new Map<string, ToolHandler>();
44
+
45
+ private readonly receiver = async (name: unknown, input: unknown, phase: unknown): Promise<JsonObject> => {
46
+ try {
47
+ return await this.call(name, input, phase);
48
+ } catch (err: unknown) {
49
+ throw AssistantApi.rejection(err);
50
+ }
51
+ };
52
+
53
+ /**
54
+ * Answer a tool the manifest declares.
55
+ *
56
+ * @param name - the tool's name, snake_case, as in `contributes.raven.tools`
57
+ * @param handler - the tool's run, and its preview when it asks for approval
58
+ * @returns a function that stops answering the tool
59
+ * @throws InvalidParamsError when the name is not snake_case
60
+ */
61
+ tool(name: string, handler: ToolHandler): Unsubscribe {
62
+ if (!AssistantApi.NAME_PATTERN.test(name) || name.length > AssistantApi.NAME_MAX_LENGTH) {
63
+ throw new InvalidParamsError(`${name} is not a tool name: snake_case, at most ${AssistantApi.NAME_MAX_LENGTH} characters`);
64
+ }
65
+ this.install();
66
+ this.map_handlers.set(name, handler);
67
+ return () => {
68
+ if (this.map_handlers.get(name) === handler) {
69
+ this.map_handlers.delete(name);
70
+ }
71
+ };
72
+ }
73
+
74
+ /**
75
+ * Call a tool as RollRook does; `window.__rollrookTool` is this method.
76
+ *
77
+ * @param name - the tool's name
78
+ * @param input - its input, a JSON object (or its JSON text)
79
+ * @param phase - `preview` or `run`; `run` when not given
80
+ * @returns the preview's `{ summary }` or the run's result
81
+ * @throws UnknownMethodError for a tool the page does not answer, InvalidParamsError for bad input or a missing preview, FailedError for a result that is not a JSON object
82
+ */
83
+ async call(name: unknown, input: unknown, phase: unknown = "run"): Promise<JsonObject> {
84
+ if (typeof name !== "string") {
85
+ throw new InvalidParamsError("the tool's name is not a string");
86
+ }
87
+ const handler = this.map_handlers.get(name);
88
+ if (handler === undefined) {
89
+ throw new UnknownMethodError(`no tool ${name} in this page`);
90
+ }
91
+ if (phase !== "preview" && phase !== "run") {
92
+ throw new InvalidParamsError(`${String(phase)} is not a phase: preview or run`);
93
+ }
94
+ const record = AssistantApi.input_record(input);
95
+ let result: unknown;
96
+ if (typeof handler === "function") {
97
+ result = await handler(record, phase);
98
+ } else if (phase === "run") {
99
+ result = await handler.run(record);
100
+ } else if (handler.preview === undefined) {
101
+ throw new InvalidParamsError(`the tool ${name} has no preview`);
102
+ } else {
103
+ result = await handler.preview(record);
104
+ }
105
+ return phase === "preview" ? AssistantApi.preview_result(name, result) : AssistantApi.run_result(name, result);
106
+ }
107
+
108
+ /**
109
+ * @returns the names of the tools this page answers
110
+ */
111
+ list_tools(): string[] {
112
+ return [...this.map_handlers.keys()].sort();
113
+ }
114
+
115
+ /** Define `window.__rollrookTool` so RollRook's calls reach this object. */
116
+ install(): void {
117
+ if (Reflect.get(globalThis, AssistantApi.RECEIVER_NAME) !== this.receiver) {
118
+ Reflect.set(globalThis, AssistantApi.RECEIVER_NAME, this.receiver);
119
+ }
120
+ }
121
+
122
+ private static input_record(input: unknown): JsonObject {
123
+ let value: unknown = input ?? {};
124
+ if (typeof value === "string") {
125
+ try {
126
+ value = JSON.parse(value);
127
+ } catch (err: unknown) {
128
+ if (err instanceof SyntaxError) {
129
+ throw new InvalidParamsError(`the tool's input is not JSON: ${err.message}`);
130
+ }
131
+ throw err;
132
+ }
133
+ }
134
+ if (!Wire.is_record(value) || !Wire.is_json(value)) {
135
+ throw new InvalidParamsError("the tool's input is not a JSON object");
136
+ }
137
+ return value as JsonObject;
138
+ }
139
+
140
+ /**
141
+ * The error RollRook receives when a tool fails: its message begins with
142
+ * the code, as the bridge's own errors do (`invalid:`, `unknown:`,
143
+ * `failed:`), so the assistant can tell a bad input from a failure.
144
+ *
145
+ * @param err - what the tool threw
146
+ * @returns the error to reject with
147
+ */
148
+ static rejection(err: unknown): Error {
149
+ if (err instanceof RollRookError) {
150
+ return new Error(`${err.code}: ${err.message}`, { cause: err });
151
+ }
152
+ const message = err instanceof Error ? err.message : String(err);
153
+ return new Error(`failed: ${message}`, { cause: err });
154
+ }
155
+
156
+ private static preview_result(name: string, result: unknown): JsonObject {
157
+ if (!Wire.is_record(result) || typeof result["summary"] !== "string" || result["summary"].trim() === "") {
158
+ throw new FailedError(`the preview of ${name} did not return { summary }`);
159
+ }
160
+ const preview: ToolPreview = { summary: result["summary"] };
161
+ return { ...preview };
162
+ }
163
+
164
+ private static run_result(name: string, result: unknown): JsonObject {
165
+ if (!Wire.is_record(result) || !Wire.is_json(result)) {
166
+ throw new FailedError(`the tool ${name} did not return a JSON object`);
167
+ }
168
+ const undo: JsonValue | undefined = result["undo"];
169
+ if (undo !== undefined && !AssistantApi.is_undo(undo)) {
170
+ throw new FailedError(`the undo of ${name} is not { tool, input }`);
171
+ }
172
+ const summary: JsonValue | undefined = result["summary"];
173
+ if (summary !== undefined && typeof summary !== "string") {
174
+ throw new FailedError(`the summary of ${name} is not a string`);
175
+ }
176
+ return result as JsonObject;
177
+ }
178
+
179
+ private static is_undo(value: unknown): value is ToolUndo {
180
+ return Wire.is_record(value)
181
+ && typeof value["tool"] === "string"
182
+ && AssistantApi.NAME_PATTERN.test(value["tool"])
183
+ && Wire.is_record(value["input"]);
184
+ }
185
+ }
package/src/audio.ts ADDED
@@ -0,0 +1,90 @@
1
+ import { Bridge } from "./bridge.js";
2
+ import type { AudioSettings, AudioStatus, AudioTarget, AudioTrack } from "./types.js";
3
+ import { Wire } from "./wire.js";
4
+
5
+ /**
6
+ * RollRook's mixer: the sound of each app and Chrome tab, and its meters.
7
+ * Needs the `audio` permission. Changes arrive as `audio.tracks`, meters as
8
+ * `audio.levels`.
9
+ */
10
+ export class AudioApi {
11
+ /**
12
+ * @returns whether the mixer is on and may capture sound
13
+ */
14
+ async status(): Promise<AudioStatus> {
15
+ const record = Wire.record(await Bridge.call("audio.status"), "audio.status reply");
16
+ return {
17
+ is_enabled: Wire.boolean(record, "isEnabled", "audio.status reply"),
18
+ is_permitted: Wire.boolean(record, "isPermitted", "audio.status reply"),
19
+ };
20
+ }
21
+
22
+ /**
23
+ * Turn the mixer on or off.
24
+ *
25
+ * @param is_enabled - whether it should be on
26
+ */
27
+ async enable(is_enabled: boolean): Promise<void> {
28
+ await Bridge.call("audio.enable", { isEnabled: is_enabled });
29
+ }
30
+
31
+ /**
32
+ * Ask macOS for permission to capture sound.
33
+ *
34
+ * @returns whether it is granted
35
+ */
36
+ async request_permission(): Promise<boolean> {
37
+ const record = Wire.record(await Bridge.call("audio.requestPermission"), "audio.requestPermission reply");
38
+ return Wire.boolean(record, "isPermitted", "audio.requestPermission reply");
39
+ }
40
+
41
+ /**
42
+ * @returns the tracks the mixer shows
43
+ */
44
+ async list(): Promise<AudioTrack[]> {
45
+ return Wire.audio_tracks(await Bridge.call("audio.list")).list_tracks;
46
+ }
47
+
48
+ /**
49
+ * Change some of a track's settings; RollRook clamps each value.
50
+ *
51
+ * @param target - the track
52
+ * @param settings - the settings to change
53
+ */
54
+ async update(target: AudioTarget, settings: Partial<AudioSettings>): Promise<void> {
55
+ await Bridge.call("audio.update", {
56
+ target: Wire.audio_target_to_wire(target),
57
+ settings: Wire.audio_settings_to_wire(settings),
58
+ });
59
+ }
60
+
61
+ /**
62
+ * Put a track's settings back as they were.
63
+ *
64
+ * @param target - the track
65
+ */
66
+ async reset(target: AudioTarget): Promise<void> {
67
+ await Bridge.call("audio.reset", { target: Wire.audio_target_to_wire(target) });
68
+ }
69
+
70
+ /**
71
+ * Start or stop the meters: `audio.levels` arrives while they are on and the view shows.
72
+ *
73
+ * @param is_on - whether the meters run
74
+ */
75
+ async meters(is_on: boolean): Promise<void> {
76
+ await Bridge.call("audio.meters", { isOn: is_on });
77
+ }
78
+
79
+ /**
80
+ * The key a track's levels arrive under in `audio.levels`.
81
+ *
82
+ * @param target - the track
83
+ * @returns `app:<bundleId>` or `tab:<sessionId>:<tabId>`
84
+ */
85
+ static level_key(target: AudioTarget): string {
86
+ return target.kind === "app"
87
+ ? `app:${target.bundle_id}`
88
+ : `tab:${target.session_id}:${target.tab_id}`;
89
+ }
90
+ }
package/src/bridge.ts ADDED
@@ -0,0 +1,96 @@
1
+ import { BridgeUnavailableError, RollRookError } from "./errors.js";
2
+ import type { JsonObject } from "./types.js";
3
+ import { Wire } from "./wire.js";
4
+
5
+ /** What the page posts to RollRook's message handler. */
6
+ export interface BridgeMessage {
7
+ method: string;
8
+ params: JsonObject;
9
+ }
10
+
11
+ /** The message handler RollRook installs: `window.webkit.messageHandlers.rollrook`. */
12
+ export interface BridgeHandler {
13
+ postMessage(message: BridgeMessage): Promise<unknown>;
14
+ }
15
+
16
+ /**
17
+ * The one channel between a plugin page and RollRook. Every module of the SDK
18
+ * calls through it; plugins rarely need it directly.
19
+ */
20
+ export class Bridge {
21
+ /** The name of RollRook's script message handler. */
22
+ static readonly HANDLER_NAME = "rollrook";
23
+
24
+ /** The property a mock host sets on its handler, so the SDK can tell it from RollRook. */
25
+ static readonly MOCK_MARKER = "isMock";
26
+
27
+ /** The bridge protocol this SDK speaks. */
28
+ static readonly PROTOCOL = 1;
29
+
30
+ /**
31
+ * Find RollRook's message handler on the page.
32
+ *
33
+ * @returns the handler, or undefined outside RollRook and without a mock host
34
+ */
35
+ static handler(): BridgeHandler | undefined {
36
+ const webkit: unknown = Reflect.get(globalThis, "webkit");
37
+ if (!Wire.is_record(webkit)) {
38
+ return undefined;
39
+ }
40
+ const map_handlers = webkit["messageHandlers"];
41
+ if (!Wire.is_record(map_handlers)) {
42
+ return undefined;
43
+ }
44
+ const handler = map_handlers[Bridge.HANDLER_NAME];
45
+ return Bridge.is_handler(handler) ? handler : undefined;
46
+ }
47
+
48
+ /**
49
+ * Whether the page can reach a host, RollRook's or a mock's.
50
+ *
51
+ * @returns true when a handler is installed
52
+ */
53
+ static is_available(): boolean {
54
+ return Bridge.handler() !== undefined;
55
+ }
56
+
57
+ /**
58
+ * Whether the page runs inside RollRook itself, not a mock host.
59
+ *
60
+ * @returns true when RollRook's own handler is installed
61
+ */
62
+ static is_native(): boolean {
63
+ const handler = Bridge.handler();
64
+ return handler !== undefined && Reflect.get(handler, Bridge.MOCK_MARKER) !== true;
65
+ }
66
+
67
+ /**
68
+ * Call a bridge method.
69
+ *
70
+ * @param method - the method's name, e.g. `storage.get`
71
+ * @param params - the method's parameters
72
+ * @returns the method's result, unchecked
73
+ * @throws RollRookError, of the subclass matching the host's error code
74
+ */
75
+ static async call(method: string, params: JsonObject = {}): Promise<unknown> {
76
+ const handler = Bridge.handler();
77
+ if (handler === undefined) {
78
+ throw new BridgeUnavailableError(method);
79
+ }
80
+ try {
81
+ return await handler.postMessage({
82
+ method,
83
+ params,
84
+ });
85
+ } catch (err: unknown) {
86
+ if (err instanceof RollRookError) {
87
+ throw err;
88
+ }
89
+ throw RollRookError.from_rejection(err, method);
90
+ }
91
+ }
92
+
93
+ private static is_handler(value: unknown): value is BridgeHandler {
94
+ return Wire.is_record(value) && typeof value["postMessage"] === "function";
95
+ }
96
+ }
@@ -0,0 +1,68 @@
1
+ import { Bridge } from "./bridge.js";
2
+ import { InvalidParamsError } from "./errors.js";
3
+ import type { CalendarItem } from "./types.js";
4
+ import { Wire } from "./wire.js";
5
+
6
+ /**
7
+ * The plugin's items in RollRook's calendar. The manifest declares
8
+ * `contributes.calendar`; each publish replaces every item the plugin showed
9
+ * before. A click on an item arrives as `calendar.open` in the plugin's first
10
+ * dock view (else its first sidebar view, else its background view), which
11
+ * RollRook shows first; a drag arrives as `calendar.move` in the background
12
+ * view (else every loaded view), after which the plugin updates its own data
13
+ * and publishes again.
14
+ */
15
+ export class CalendarApi {
16
+ /** The most items RollRook takes from one plugin. */
17
+ static readonly ITEM_LIMIT = 2000;
18
+
19
+ /** The longest an item's id may be. */
20
+ static readonly ID_MAX_LENGTH = 200;
21
+
22
+ /** An item's color: `#rrggbb`. */
23
+ static readonly COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
24
+
25
+ /**
26
+ * Replace the plugin's calendar items.
27
+ *
28
+ * @param list_items - every item to show, times in ISO 8601
29
+ * @throws InvalidParamsError when there are more than 2000 items, two share an id, or one has a bad id, a color not `#rrggbb`, or neither a start and an end nor a due
30
+ */
31
+ async publish(list_items: readonly CalendarItem[]): Promise<void> {
32
+ if (list_items.length > CalendarApi.ITEM_LIMIT) {
33
+ throw new InvalidParamsError(`at most ${CalendarApi.ITEM_LIMIT} calendar items`, "calendar.publish");
34
+ }
35
+ const set_ids = new Set<string>();
36
+ for (const item of list_items) {
37
+ if (item.id === "" || item.id.length > CalendarApi.ID_MAX_LENGTH) {
38
+ throw new InvalidParamsError(`a calendar item's id is 1 to ${CalendarApi.ID_MAX_LENGTH} characters`, "calendar.publish");
39
+ }
40
+ if (item.color !== undefined && !CalendarApi.COLOR_PATTERN.test(item.color)) {
41
+ throw new InvalidParamsError(`the calendar item ${item.id}'s color is not #rrggbb`, "calendar.publish");
42
+ }
43
+ if (set_ids.has(item.id)) {
44
+ throw new InvalidParamsError(`two calendar items have the id ${item.id}`, "calendar.publish");
45
+ }
46
+ set_ids.add(item.id);
47
+ if (!CalendarApi.is_placed(item)) {
48
+ throw new InvalidParamsError(`the calendar item ${item.id} needs a start and an end, or a due`, "calendar.publish");
49
+ }
50
+ }
51
+ await Bridge.call("calendar.publish", {
52
+ items: list_items.map((item: CalendarItem) => Wire.calendar_item_to_wire(item)),
53
+ });
54
+ }
55
+
56
+ /**
57
+ * Whether an item has the times RollRook needs to place it.
58
+ *
59
+ * @param item - a calendar item
60
+ * @returns true for a start and an end (a block), or a due (a deadline)
61
+ */
62
+ static is_placed(item: CalendarItem): boolean {
63
+ if ((item.start === undefined) !== (item.end === undefined)) {
64
+ return false;
65
+ }
66
+ return item.start !== undefined || item.due !== undefined;
67
+ }
68
+ }
package/src/context.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { Bridge } from "./bridge.js";
2
+ import type { PluginContext } from "./types.js";
3
+ import { Wire } from "./wire.js";
4
+
5
+ /** The plugin's own identity and the app it runs in. */
6
+ export class ContextApi {
7
+ /** The global RollRook sets before the page's scripts run. */
8
+ static readonly GLOBAL_NAME = "__rollrook";
9
+
10
+ /**
11
+ * Ask RollRook for the current context.
12
+ *
13
+ * @returns the plugin's id and version, the app's version, the protocol and the theme
14
+ */
15
+ async get(): Promise<PluginContext> {
16
+ return Wire.context(await Bridge.call("context.get"));
17
+ }
18
+
19
+ /**
20
+ * Read the context RollRook set on the page at load, without a call.
21
+ *
22
+ * @returns the context, or undefined outside RollRook
23
+ */
24
+ current(): PluginContext | undefined {
25
+ const raw: unknown = Reflect.get(globalThis, ContextApi.GLOBAL_NAME);
26
+ return raw === undefined ? undefined : Wire.context(raw);
27
+ }
28
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The kind of failure a bridge call reports, taken from the code that begins
3
+ * the host's error message. `unavailable` is the SDK's own: the page is not
4
+ * running inside RollRook and no mock host is installed.
5
+ */
6
+ export type ErrorCode = "permission" | "invalid" | "unknown" | "failed" | "unavailable";
7
+
8
+ /**
9
+ * A failed call to RollRook. Every error the SDK throws is one of its
10
+ * subclasses, so a `catch` can narrow on the class or on `code`.
11
+ */
12
+ export class RollRookError extends Error {
13
+ /** The failure's code, as the host reported it. */
14
+ readonly code: ErrorCode;
15
+
16
+ /** The bridge method that failed, or undefined when the failure is not a call's. */
17
+ readonly method: string | undefined;
18
+
19
+ /**
20
+ * @param code - the failure's code
21
+ * @param message - the host's message, without the code
22
+ * @param method - the bridge method that failed
23
+ */
24
+ constructor(code: ErrorCode, message: string, method?: string) {
25
+ super(message);
26
+ this.name = "RollRookError";
27
+ this.code = code;
28
+ this.method = method;
29
+ }
30
+
31
+ /**
32
+ * Turn whatever a rejected bridge call delivered into the matching error.
33
+ * The host rejects with a message that begins with `permission:`,
34
+ * `invalid:`, `unknown:` or `failed:`; anything else counts as `failed`.
35
+ *
36
+ * @param reason - the rejection value
37
+ * @param method - the method that was called
38
+ * @returns the typed error
39
+ */
40
+ static from_rejection(reason: unknown, method: string): RollRookError {
41
+ const text = RollRookError.text_of(reason);
42
+ const match = RollRookError.CODE_PATTERN.exec(text);
43
+ const code = match?.[1];
44
+ const detail = (match?.[2] ?? text).trim();
45
+ switch (code) {
46
+ case "permission":
47
+ return new PermissionError(detail, method);
48
+ case "invalid":
49
+ return new InvalidParamsError(detail, method);
50
+ case "unknown":
51
+ return new UnknownMethodError(detail, method);
52
+ default:
53
+ return new FailedError(detail, method);
54
+ }
55
+ }
56
+
57
+ private static readonly CODE_PATTERN = /^\s*(permission|invalid|unknown|failed):\s*([\s\S]*)$/;
58
+
59
+ private static text_of(reason: unknown): string {
60
+ if (reason instanceof Error) {
61
+ return reason.message;
62
+ }
63
+ if (typeof reason === "string") {
64
+ return reason;
65
+ }
66
+ return String(reason);
67
+ }
68
+ }
69
+
70
+ /** The plugin's manifest does not hold the permission the method needs. */
71
+ export class PermissionError extends RollRookError {
72
+ /**
73
+ * @param message - the host's message
74
+ * @param method - the method that was refused
75
+ */
76
+ constructor(message: string, method?: string) {
77
+ super("permission", message, method);
78
+ this.name = "PermissionError";
79
+ }
80
+ }
81
+
82
+ /** The parameters were wrong: a missing field, a bad path, a key too long. */
83
+ export class InvalidParamsError extends RollRookError {
84
+ /**
85
+ * @param message - the host's message
86
+ * @param method - the method that was called
87
+ */
88
+ constructor(message: string, method?: string) {
89
+ super("invalid", message, method);
90
+ this.name = "InvalidParamsError";
91
+ }
92
+ }
93
+
94
+ /** The host does not know the method, usually because it is older than the SDK. */
95
+ export class UnknownMethodError extends RollRookError {
96
+ /**
97
+ * @param message - the host's message
98
+ * @param method - the method that was called
99
+ */
100
+ constructor(message: string, method?: string) {
101
+ super("unknown", message, method);
102
+ this.name = "UnknownMethodError";
103
+ }
104
+ }
105
+
106
+ /** The call was valid but could not be done, or the host's reply was malformed. */
107
+ export class FailedError extends RollRookError {
108
+ /**
109
+ * @param message - the host's message
110
+ * @param method - the method that was called
111
+ */
112
+ constructor(message: string, method?: string) {
113
+ super("failed", message, method);
114
+ this.name = "FailedError";
115
+ }
116
+ }
117
+
118
+ /** The page runs outside RollRook and no mock host is installed. */
119
+ export class BridgeUnavailableError extends RollRookError {
120
+ /**
121
+ * @param method - the method that could not be called
122
+ */
123
+ constructor(method: string) {
124
+ super(
125
+ "unavailable",
126
+ "not running inside RollRook; install the mock host from @rollrook-ai/sdk/mock to develop in a browser",
127
+ method,
128
+ );
129
+ this.name = "BridgeUnavailableError";
130
+ }
131
+ }