@open-artifact/runtime 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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Open Artifact
2
+ Copyright 2026 Jim Liu 宝玉
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ It was formerly published as baoyu-design.
package/README.md CHANGED
@@ -1,3 +1,6 @@
1
- # Temporary Holding Version
1
+ # @open-artifact/runtime
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The window.openartifact page runtime: capability contracts, the local provider and the Shell protocol.
4
+
5
+ Part of [Open Artifact](https://github.com/JimLiu/open-artifact): slide decks, design canvases and whiteboards an agent makes
6
+ and you view, edit and comment on in one local page. Source: [`packages/runtime`](https://github.com/JimLiu/open-artifact/tree/main/packages/runtime).
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@open-artifact/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The window.openartifact page runtime: capability contracts, the local provider and the Shell protocol.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.d.ts",
9
+ "default": "./src/index.js"
10
+ },
11
+ "./capabilities": {
12
+ "types": "./src/capabilities.d.ts",
13
+ "default": "./src/capabilities.js"
14
+ },
15
+ "./http-api": {
16
+ "types": "./src/http-api.d.ts",
17
+ "default": "./src/http-api.js"
18
+ },
19
+ "./untrusted": {
20
+ "types": "./src/untrusted.d.ts",
21
+ "default": "./src/untrusted.js"
22
+ },
23
+ "./package.json": "./package.json"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "LICENSE",
28
+ "NOTICE"
29
+ ],
30
+ "dependencies": {
31
+ "@open-artifact/protocol": "0.1.0"
32
+ },
33
+ "license": "Apache-2.0",
34
+ "author": {
35
+ "name": "Jim Liu 宝玉",
36
+ "url": "https://github.com/JimLiu"
37
+ },
38
+ "homepage": "https://github.com/JimLiu/open-artifact#readme",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/JimLiu/open-artifact.git",
42
+ "directory": "packages/runtime"
43
+ },
44
+ "bugs": {
45
+ "url": "https://github.com/JimLiu/open-artifact/issues"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ }
50
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The page side of the Shell's capability broker.
3
+ *
4
+ * Inside the Open Artifact Shell, `window.openartifact` does not call its
5
+ * backend itself: every call goes to the Shell by `postMessage`, the Shell
6
+ * runs it and answers, and it lets
7
+ * the Shell see and mediate what a page does: an agent turn needs a click,
8
+ * one event connection serves the page, and a page whose broker was
9
+ * rewired learns which calls may not have run.
10
+ *
11
+ * The messages are `cap_*` in `@open-artifact/protocol`'s `shell.ts`:
12
+ *
13
+ * page → Shell cap_want {cap, protocol, base} once per capability
14
+ * Shell → page cap_grant {cap, ok, gen, config?}
15
+ * page → Shell cap {id, cap, method, args, gen} every call
16
+ * Shell → page cap_r {id, result | error} · cap_ack {id} · cap_ev {cap, event, data} · cap_rewired {gen, caps?}
17
+ *
18
+ * A Shell that does not answer the first `cap_want` (an older daemon, or a
19
+ * page framed by something else under the Shell's frame name) leaves the
20
+ * page on its fallback provider, the local type server.
21
+ */
22
+ import { type CapabilityName } from './capabilities.ts';
23
+ import type { CapabilityProvider } from './client.ts';
24
+ /**
25
+ * The methods the broker carries, per capability. The Shell runs nothing
26
+ * else: a name outside this table is refused before it reaches a backend.
27
+ * Listener methods (`onChange`, `onStatus`, `onPeers`) are not calls; they
28
+ * listen to `cap_ev`.
29
+ */
30
+ export declare const BROKERED_METHODS: {
31
+ readonly [K in CapabilityName]: readonly string[];
32
+ };
33
+ /**
34
+ * The `cap_ev` event each listener method follows, per capability
35
+ * (`room.onPeers` → `peers`). The Shell subscribes to every listener method
36
+ * named here once per granted capability and forwards its events.
37
+ */
38
+ export declare const BROKERED_EVENTS: {
39
+ readonly artifact: {
40
+ readonly onChange: "files";
41
+ };
42
+ readonly agent: {
43
+ readonly onStatus: "status";
44
+ };
45
+ readonly room: {
46
+ readonly onPeers: "peers";
47
+ readonly onMessage: "message";
48
+ };
49
+ readonly db: {
50
+ readonly onChange: "change";
51
+ };
52
+ readonly comments: {
53
+ readonly onChange: "threads";
54
+ };
55
+ readonly history: {
56
+ readonly onChange: "change";
57
+ };
58
+ };
59
+ /** Options of {@link createShellProvider}. */
60
+ export interface ShellProviderOptions {
61
+ /** The Shell's origin; defaults to {@link shellOrigin}. */
62
+ origin?: string;
63
+ /** The window the Shell is in; defaults to `window.parent`. */
64
+ target?: Window;
65
+ /** The page's API base sent with `cap_want`; defaults to the page's directory. */
66
+ base?: string;
67
+ /** Used when the Shell does not broker capabilities. Default: {@link createLocalProvider}. */
68
+ fallback?: CapabilityProvider;
69
+ /** Milliseconds to wait for the first `cap_grant` before falling back. Default 1500. */
70
+ wantTimeoutMs?: number;
71
+ }
72
+ /**
73
+ * A provider that brokers every capability through the Shell, falling back
74
+ * to `options.fallback` when the Shell never grants.
75
+ */
76
+ export declare function createShellProvider(options?: ShellProviderOptions): CapabilityProvider;
77
+ /**
78
+ * The provider a page should use: brokered through the Shell when it is in
79
+ * one, otherwise the local type server.
80
+ */
81
+ export declare function createPageProvider(options?: {
82
+ base?: string;
83
+ }): CapabilityProvider;
package/src/broker.js ADDED
@@ -0,0 +1,323 @@
1
+ /**
2
+ * The page side of the Shell's capability broker.
3
+ *
4
+ * Inside the Open Artifact Shell, `window.openartifact` does not call its
5
+ * backend itself: every call goes to the Shell by `postMessage`, the Shell
6
+ * runs it and answers, and it lets
7
+ * the Shell see and mediate what a page does: an agent turn needs a click,
8
+ * one event connection serves the page, and a page whose broker was
9
+ * rewired learns which calls may not have run.
10
+ *
11
+ * The messages are `cap_*` in `@open-artifact/protocol`'s `shell.ts`:
12
+ *
13
+ * page → Shell cap_want {cap, protocol, base} once per capability
14
+ * Shell → page cap_grant {cap, ok, gen, config?}
15
+ * page → Shell cap {id, cap, method, args, gen} every call
16
+ * Shell → page cap_r {id, result | error} · cap_ack {id} · cap_ev {cap, event, data} · cap_rewired {gen, caps?}
17
+ *
18
+ * A Shell that does not answer the first `cap_want` (an older daemon, or a
19
+ * page framed by something else under the Shell's frame name) leaves the
20
+ * page on its fallback provider, the local type server.
21
+ */
22
+ import { CAP_NAME, CAP_PROTOCOL, REWIRED_MESSAGE, } from '@open-artifact/protocol';
23
+ import { ArtifactError, } from "./capabilities.js";
24
+ import { createLocalProvider } from "./local-provider.js";
25
+ import { shellOrigin } from "./shell.js";
26
+ /**
27
+ * The methods the broker carries, per capability. The Shell runs nothing
28
+ * else: a name outside this table is refused before it reaches a backend.
29
+ * Listener methods (`onChange`, `onStatus`, `onPeers`) are not calls; they
30
+ * listen to `cap_ev`.
31
+ */
32
+ export const BROKERED_METHODS = {
33
+ artifact: ['title', 'list', 'readText', 'readBytes', 'publish'],
34
+ assets: ['upload'],
35
+ user: ['me'],
36
+ agent: ['send', 'status'],
37
+ room: ['self', 'presence', 'peers', 'emit'],
38
+ downloads: ['save'],
39
+ db: ['get', 'list', 'write'],
40
+ comments: ['list', 'create', 'reply', 'setResolved', 'move', 'remove', 'sendToAgent'],
41
+ history: ['list', 'files', 'read', 'readBytes', 'diff', 'restore', 'dismissNotice'],
42
+ };
43
+ /**
44
+ * The `cap_ev` event each listener method follows, per capability
45
+ * (`room.onPeers` → `peers`). The Shell subscribes to every listener method
46
+ * named here once per granted capability and forwards its events.
47
+ */
48
+ export const BROKERED_EVENTS = {
49
+ artifact: { onChange: 'files' },
50
+ agent: { onStatus: 'status' },
51
+ room: { onPeers: 'peers', onMessage: 'message' },
52
+ db: { onChange: 'change' },
53
+ comments: { onChange: 'threads' },
54
+ history: { onChange: 'change' },
55
+ };
56
+ const CALL_TIMEOUT = { downloads: 150_000, assets: 272_000, user: 20_000 };
57
+ const DEFAULT_CALL_TIMEOUT = 130_000;
58
+ /** After `cap_ack` (a consent prompt, a queue): the long deadline. */
59
+ const ACKED_TIMEOUT = 900_000;
60
+ /** Capabilities whose calls resolve `null` instead of rejecting when cut or timed out. */
61
+ const RESOLVES_NULL = new Set(['user']);
62
+ /** Rebuilds the error a Shell sent. */
63
+ function toArtifactError(error) {
64
+ const code = (error?.code ?? 'unavailable');
65
+ return new ArtifactError(code, error?.message ?? 'The Shell refused the call.', error?.paths);
66
+ }
67
+ /** A per-load prefix plus a counter, like the frame runtime's call ids. */
68
+ function idMaker() {
69
+ const prefix = Math.random().toString(36).slice(2, 10);
70
+ let seq = 0;
71
+ return () => `${prefix}${(++seq).toString(36)}`;
72
+ }
73
+ /**
74
+ * A provider that brokers every capability through the Shell, falling back
75
+ * to `options.fallback` when the Shell never grants.
76
+ */
77
+ export function createShellProvider(options = {}) {
78
+ const origin = options.origin ?? shellOrigin();
79
+ const fallback = options.fallback ?? createLocalProvider();
80
+ if (!origin || typeof window === 'undefined')
81
+ return fallback;
82
+ const target = options.target ?? window.parent;
83
+ const base = new URL(options.base ?? './', location.href).toString();
84
+ const wantTimeoutMs = options.wantTimeoutMs ?? 1500;
85
+ const nextId = idMaker();
86
+ /** `true` once a grant arrived, `false` once the first want timed out. */
87
+ let brokered = null;
88
+ let gen = 0;
89
+ const pending = new Map();
90
+ const grants = new Map();
91
+ const listeners = new Map();
92
+ const post = (message, gesture = false) => {
93
+ // `includeUserActivation` lets the Shell see a click behind the call
94
+ // (Chromium); other browsers ignore the option.
95
+ target.postMessage(message, gesture ? { targetOrigin: origin, includeUserActivation: true } : { targetOrigin: origin });
96
+ };
97
+ /** Ends a call that will get no answer. */
98
+ const cut = (id, entry, message) => {
99
+ pending.delete(id);
100
+ if (entry.timer)
101
+ clearTimeout(entry.timer);
102
+ if (RESOLVES_NULL.has(entry.cap))
103
+ entry.resolve(null);
104
+ else
105
+ entry.reject(new ArtifactError('unavailable', message));
106
+ };
107
+ const armTimer = (id, entry, ms) => {
108
+ if (entry.timer)
109
+ clearTimeout(entry.timer);
110
+ entry.timer = setTimeout(() => {
111
+ if (pending.get(id) === entry)
112
+ cut(id, entry, 'The Shell did not answer in time.');
113
+ }, ms);
114
+ };
115
+ const onMessage = (event) => {
116
+ if (event.source !== target || event.origin !== origin)
117
+ return;
118
+ const data = event.data;
119
+ if (!data || typeof data !== 'object' || typeof data.openArtifact !== 'string' || !data.openArtifact.startsWith('cap_'))
120
+ return;
121
+ switch (data.openArtifact) {
122
+ case 'cap_grant': {
123
+ brokered = true;
124
+ if (typeof data.gen === 'number' && Number.isInteger(data.gen) && data.gen >= 0)
125
+ gen = data.gen;
126
+ const waiting = grants.get(data.cap);
127
+ grants.delete(data.cap);
128
+ for (const done of waiting ?? [])
129
+ done(data);
130
+ break;
131
+ }
132
+ case 'cap_r': {
133
+ const entry = pending.get(data.id);
134
+ if (!entry)
135
+ return;
136
+ pending.delete(data.id);
137
+ if (entry.timer)
138
+ clearTimeout(entry.timer);
139
+ if (data.error)
140
+ entry.reject(toArtifactError(data.error));
141
+ else
142
+ entry.resolve(data.result);
143
+ break;
144
+ }
145
+ case 'cap_ack': {
146
+ // Consent or slow work: the call gets the long deadline.
147
+ const entry = pending.get(data.id);
148
+ if (entry)
149
+ armTimer(data.id, entry, ACKED_TIMEOUT);
150
+ break;
151
+ }
152
+ case 'cap_ev':
153
+ for (const listener of listeners.get(`${data.cap}:${data.event}`) ?? []) {
154
+ try {
155
+ listener(data.data);
156
+ }
157
+ catch (error) {
158
+ queueMicrotask(() => {
159
+ throw error;
160
+ });
161
+ }
162
+ }
163
+ break;
164
+ case 'cap_rewired': {
165
+ // As the frame runtime's modules do: a new generation cuts every call sent
166
+ // under another one, and `caps` (when given) lists what the broker
167
+ // still serves, so calls to anything else are cut too.
168
+ if (typeof data.gen !== 'number' || !Number.isInteger(data.gen) || data.gen < 0)
169
+ return;
170
+ const caps = Array.isArray(data.caps) ? new Set(data.caps) : null;
171
+ for (const [id, entry] of [...pending]) {
172
+ if (entry.gen !== data.gen || (caps && !caps.has(entry.cap)))
173
+ cut(id, entry, REWIRED_MESSAGE);
174
+ }
175
+ gen = data.gen;
176
+ break;
177
+ }
178
+ default:
179
+ break;
180
+ }
181
+ };
182
+ window.addEventListener('message', onMessage);
183
+ const want = (cap) => new Promise((resolve) => {
184
+ const list = grants.get(cap) ?? [];
185
+ list.push(resolve);
186
+ grants.set(cap, list);
187
+ post({ openArtifact: 'cap_want', cap, protocol: CAP_PROTOCOL, base });
188
+ setTimeout(() => {
189
+ const waiting = grants.get(cap);
190
+ if (!waiting?.includes(resolve))
191
+ return;
192
+ waiting.splice(waiting.indexOf(resolve), 1);
193
+ if (brokered === null)
194
+ brokered = false;
195
+ resolve(null);
196
+ }, wantTimeoutMs);
197
+ });
198
+ const call = (cap, method, args, gesture = false) => new Promise((resolve, reject) => {
199
+ const id = nextId();
200
+ const entry = { cap, gen, resolve, reject, timer: null };
201
+ pending.set(id, entry);
202
+ armTimer(id, entry, CALL_TIMEOUT[cap] ?? DEFAULT_CALL_TIMEOUT);
203
+ post({ openArtifact: 'cap', id, cap, method, args, gen }, gesture);
204
+ });
205
+ const listen = (cap, event, listener) => {
206
+ const key = `${cap}:${event}`;
207
+ const set = listeners.get(key) ?? new Set();
208
+ set.add(listener);
209
+ listeners.set(key, set);
210
+ return () => void set.delete(listener);
211
+ };
212
+ /** Builds the page's namespace for a granted capability. */
213
+ const build = (cap, config) => {
214
+ const c = (method, args = [], gesture = false) => call(cap, method, args, gesture);
215
+ switch (cap) {
216
+ case 'artifact': {
217
+ const ns = {
218
+ id: String(config.id ?? ''),
219
+ title: () => c('title'),
220
+ list: () => c('list'),
221
+ readText: (path) => c('readText', [path]),
222
+ readBytes: (path) => c('readBytes', [path]),
223
+ publish: (batch) => c('publish', [batch]),
224
+ onChange: (listener) => listen('artifact', BROKERED_EVENTS.artifact.onChange, listener),
225
+ };
226
+ return ns;
227
+ }
228
+ case 'assets': {
229
+ const ns = { upload: (data, opts) => c('upload', opts ? [data, opts] : [data]) };
230
+ return ns;
231
+ }
232
+ case 'user': {
233
+ // Answered from the grant, like the frame runtime's `user.config`.
234
+ const viewer = config.me;
235
+ const ns = { me: () => (viewer ? Promise.resolve({ ...viewer }) : c('me')) };
236
+ return ns;
237
+ }
238
+ case 'agent': {
239
+ const ns = {
240
+ send: (request, opts) => c('send', opts ? [request, opts] : [request], true),
241
+ status: () => c('status'),
242
+ onStatus: (listener) => listen('agent', BROKERED_EVENTS.agent.onStatus, listener),
243
+ };
244
+ return ns;
245
+ }
246
+ case 'room': {
247
+ let self = null;
248
+ const ns = {
249
+ self: () => (self ??= c('self')),
250
+ presence: (patch) => c('presence', [patch]),
251
+ peers: () => c('peers'),
252
+ onPeers: (listener) => listen('room', BROKERED_EVENTS.room.onPeers, listener),
253
+ emit: (topic, data) => c('emit', [topic, data]),
254
+ onMessage: (listener) => listen('room', BROKERED_EVENTS.room.onMessage, listener),
255
+ };
256
+ return ns;
257
+ }
258
+ case 'db': {
259
+ const ns = {
260
+ get: (path) => c('get', [path]),
261
+ list: (collection) => c('list', [collection]),
262
+ write: (writes) => c('write', [writes]),
263
+ onChange: (listener) => listen('db', BROKERED_EVENTS.db.onChange, listener),
264
+ };
265
+ return ns;
266
+ }
267
+ case 'comments': {
268
+ const ns = {
269
+ list: () => c('list'),
270
+ create: (input) => c('create', [input]),
271
+ reply: (threadId, text) => c('reply', [threadId, text]),
272
+ setResolved: (threadId, resolved) => c('setResolved', [threadId, resolved]),
273
+ move: (threadId, anchor, location) => c('move', location ? [threadId, anchor, location] : [threadId, anchor]),
274
+ remove: (threadId, messageId) => c('remove', messageId ? [threadId, messageId] : [threadId]),
275
+ sendToAgent: (threadId) => c('sendToAgent', [threadId], true),
276
+ onChange: (listener) => listen('comments', BROKERED_EVENTS.comments.onChange, listener),
277
+ };
278
+ return ns;
279
+ }
280
+ case 'history': {
281
+ const ns = {
282
+ list: () => c('list'),
283
+ files: (n) => c('files', [n]),
284
+ read: (n, path) => c('read', [n, path]),
285
+ readBytes: (n, path) => c('readBytes', [n, path]),
286
+ diff: (n, path) => c('diff', [n, path]),
287
+ restore: (n, paths) => c('restore', paths ? [n, paths] : [n]),
288
+ dismissNotice: (id) => c('dismissNotice', [id]),
289
+ onChange: (listener) => listen('history', BROKERED_EVENTS.history.onChange, listener),
290
+ };
291
+ return ns;
292
+ }
293
+ case 'downloads': {
294
+ const ns = { save: (file) => c('save', [file], true) };
295
+ return ns;
296
+ }
297
+ default:
298
+ return null;
299
+ }
300
+ };
301
+ return {
302
+ async get(name) {
303
+ if (!CAP_NAME.test(name) || !(name in BROKERED_METHODS))
304
+ return null;
305
+ if (brokered === false)
306
+ return fallback.get(name);
307
+ const grant = await want(name);
308
+ if (!grant)
309
+ return brokered ? null : fallback.get(name);
310
+ if (!grant.ok)
311
+ return null;
312
+ return build(name, grant.config ?? {});
313
+ },
314
+ };
315
+ }
316
+ /**
317
+ * The provider a page should use: brokered through the Shell when it is in
318
+ * one, otherwise the local type server.
319
+ */
320
+ export function createPageProvider(options = {}) {
321
+ const fallback = createLocalProvider(options);
322
+ return shellOrigin() ? createShellProvider({ ...options, fallback }) : fallback;
323
+ }