@botiverse/porthole 0.0.1 → 0.1.1

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 (152) hide show
  1. package/LICENSE +217 -0
  2. package/dist/bridge/bridge.d.ts +39 -0
  3. package/dist/bridge/bridge.js +198 -0
  4. package/dist/bridge/types.d.ts +83 -0
  5. package/dist/bridge/types.js +1 -0
  6. package/dist/compile/compile.d.ts +35 -0
  7. package/dist/compile/compile.js +30 -0
  8. package/dist/compile/policy.d.ts +55 -0
  9. package/dist/compile/policy.js +103 -0
  10. package/dist/config/capabilities.d.ts +154 -0
  11. package/dist/config/capabilities.js +63 -0
  12. package/dist/config/schema.d.ts +152 -0
  13. package/dist/config/schema.js +11 -0
  14. package/dist/config/validate.d.ts +22 -0
  15. package/dist/config/validate.js +261 -0
  16. package/dist/conformance/behavior.d.ts +2 -0
  17. package/dist/conformance/behavior.js +426 -0
  18. package/dist/conformance/index.d.ts +101 -0
  19. package/dist/conformance/index.js +4 -0
  20. package/dist/conformance/kit.d.ts +42 -0
  21. package/dist/conformance/kit.js +24 -0
  22. package/dist/conformance/oracles.d.ts +35 -0
  23. package/dist/conformance/oracles.js +77 -0
  24. package/dist/conformance/probes.d.ts +33 -0
  25. package/dist/conformance/probes.js +876 -0
  26. package/dist/conformance/served.d.ts +75 -0
  27. package/dist/conformance/served.js +335 -0
  28. package/dist/guide/examples.d.ts +70 -0
  29. package/dist/guide/examples.js +69 -0
  30. package/dist/guide/guide.d.ts +16 -0
  31. package/dist/guide/guide.js +265 -0
  32. package/dist/host/create-host.d.ts +8 -0
  33. package/dist/host/create-host.js +292 -0
  34. package/dist/host/locate.d.ts +8 -0
  35. package/dist/host/locate.js +16 -0
  36. package/dist/host/outcome.d.ts +24 -0
  37. package/dist/host/outcome.js +134 -0
  38. package/dist/host/types.d.ts +127 -0
  39. package/dist/host/types.js +1 -0
  40. package/dist/index.d.ts +25 -0
  41. package/dist/index.js +21 -0
  42. package/dist/isolation/served.d.ts +35 -0
  43. package/dist/isolation/served.js +117 -0
  44. package/dist/isolation/types.d.ts +96 -0
  45. package/dist/isolation/types.js +2 -0
  46. package/dist/mcp/adapter.d.ts +43 -0
  47. package/dist/mcp/adapter.js +327 -0
  48. package/dist/mcp/index.d.ts +27 -0
  49. package/dist/mcp/index.js +25 -0
  50. package/dist/mcp/proxy.d.ts +25 -0
  51. package/dist/mcp/proxy.js +106 -0
  52. package/dist/mcp/view.d.ts +31 -0
  53. package/dist/mcp/view.js +72 -0
  54. package/dist/platform/types.d.ts +51 -0
  55. package/dist/platform/types.js +1 -0
  56. package/dist/platform/web.d.ts +8 -0
  57. package/dist/platform/web.js +85 -0
  58. package/dist/presets/presets.d.ts +71 -0
  59. package/dist/presets/presets.js +140 -0
  60. package/dist/protocol/adapter.d.ts +73 -0
  61. package/dist/protocol/adapter.js +1 -0
  62. package/dist/protocol/jsonrpc.d.ts +43 -0
  63. package/dist/protocol/jsonrpc.js +50 -0
  64. package/dist/protocol/mcp-apps.d.ts +79 -0
  65. package/dist/protocol/mcp-apps.js +99 -0
  66. package/dist/protocol/shell-adapter.d.ts +5 -0
  67. package/dist/protocol/shell-adapter.js +228 -0
  68. package/dist/react/dialog.d.ts +20 -0
  69. package/dist/react/dialog.js +98 -0
  70. package/dist/react/frame.d.ts +91 -0
  71. package/dist/react/frame.js +255 -0
  72. package/dist/react/index.d.ts +13 -0
  73. package/dist/react/index.js +13 -0
  74. package/dist/react/live.d.ts +24 -0
  75. package/dist/react/live.js +57 -0
  76. package/dist/server/index.d.ts +27 -0
  77. package/dist/server/index.js +26 -0
  78. package/dist/server/keys.d.ts +19 -0
  79. package/dist/server/keys.js +78 -0
  80. package/dist/server/pages.d.ts +11 -0
  81. package/dist/server/pages.js +86 -0
  82. package/dist/server/proxy.d.ts +21 -0
  83. package/dist/server/proxy.js +107 -0
  84. package/dist/server/server.d.ts +7 -0
  85. package/dist/server/server.js +542 -0
  86. package/dist/server/tickets.d.ts +8 -0
  87. package/dist/server/tickets.js +28 -0
  88. package/dist/server/types.d.ts +97 -0
  89. package/dist/server/types.js +1 -0
  90. package/dist/shell/document.d.ts +29 -0
  91. package/dist/shell/document.js +85 -0
  92. package/dist/shell/plan.d.ts +37 -0
  93. package/dist/shell/plan.js +35 -0
  94. package/dist/shell/runtime.d.ts +28 -0
  95. package/dist/shell/runtime.js +848 -0
  96. package/dist/theme/variables.d.ts +73 -0
  97. package/dist/theme/variables.js +171 -0
  98. package/dist/transport/post-message.d.ts +9 -0
  99. package/dist/transport/post-message.js +38 -0
  100. package/dist/transport/types.d.ts +15 -0
  101. package/dist/transport/types.js +1 -0
  102. package/package.json +63 -1
  103. package/src/bridge/bridge.ts +278 -0
  104. package/src/bridge/types.ts +95 -0
  105. package/src/compile/compile.ts +68 -0
  106. package/src/compile/policy.ts +130 -0
  107. package/src/config/capabilities.ts +138 -0
  108. package/src/config/schema.ts +168 -0
  109. package/src/config/validate.ts +318 -0
  110. package/src/conformance/behavior.ts +485 -0
  111. package/src/conformance/index.ts +116 -0
  112. package/src/conformance/kit.ts +63 -0
  113. package/src/conformance/oracles.ts +126 -0
  114. package/src/conformance/probes.ts +1129 -0
  115. package/src/conformance/served.ts +501 -0
  116. package/src/guide/examples.ts +74 -0
  117. package/src/guide/guide.ts +430 -0
  118. package/src/host/create-host.ts +335 -0
  119. package/src/host/locate.ts +25 -0
  120. package/src/host/outcome.ts +159 -0
  121. package/src/host/types.ts +126 -0
  122. package/src/index.ts +128 -0
  123. package/src/isolation/served.ts +151 -0
  124. package/src/isolation/types.ts +91 -0
  125. package/src/mcp/adapter.ts +441 -0
  126. package/src/mcp/index.ts +50 -0
  127. package/src/mcp/proxy.ts +117 -0
  128. package/src/mcp/view.ts +97 -0
  129. package/src/platform/types.ts +55 -0
  130. package/src/platform/web.ts +91 -0
  131. package/src/presets/presets.ts +217 -0
  132. package/src/protocol/adapter.ts +67 -0
  133. package/src/protocol/jsonrpc.ts +83 -0
  134. package/src/protocol/mcp-apps.ts +138 -0
  135. package/src/protocol/shell-adapter.ts +261 -0
  136. package/src/react/dialog.tsx +158 -0
  137. package/src/react/frame.tsx +486 -0
  138. package/src/react/index.ts +20 -0
  139. package/src/react/live.ts +76 -0
  140. package/src/server/index.ts +37 -0
  141. package/src/server/keys.ts +100 -0
  142. package/src/server/pages.ts +117 -0
  143. package/src/server/proxy.ts +131 -0
  144. package/src/server/server.ts +657 -0
  145. package/src/server/tickets.ts +30 -0
  146. package/src/server/types.ts +104 -0
  147. package/src/shell/document.ts +121 -0
  148. package/src/shell/plan.ts +69 -0
  149. package/src/shell/runtime.ts +848 -0
  150. package/src/theme/variables.ts +190 -0
  151. package/src/transport/post-message.ts +45 -0
  152. package/src/transport/types.ts +16 -0
package/LICENSE ADDED
@@ -0,0 +1,217 @@
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.
203
+
204
+
205
+ Copyright 2026 Botiverse
206
+
207
+ Licensed under the Apache License, Version 2.0 (the "License");
208
+ you may not use this file except in compliance with the License.
209
+ You may obtain a copy of the License at
210
+
211
+ http://www.apache.org/licenses/LICENSE-2.0
212
+
213
+ Unless required by applicable law or agreed to in writing, software
214
+ distributed under the License is distributed on an "AS IS" BASIS,
215
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
216
+ See the License for the specific language governing permissions and
217
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ import { type CapabilityName } from "../config/capabilities.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
3
+ import type { CapabilityHandlers, Confirm, HostFunctionBridge, Refusal } from "./types.ts";
4
+ /**
5
+ * The host-function bridge: every capability call from a frame passes here, and nowhere else
6
+ * reaches a host handler. In order: declared → arguments well formed → not muted → within its
7
+ * rate → a user gesture, if gated so → a person's confirmation, if gated so → the handler.
8
+ */
9
+ export type BridgeEvent = {
10
+ readonly type: "resize";
11
+ readonly height: number;
12
+ readonly width?: number;
13
+ } | {
14
+ readonly type: "error";
15
+ readonly message: string;
16
+ } | {
17
+ readonly type: "refused";
18
+ readonly capability: CapabilityName;
19
+ readonly refusal: Refusal;
20
+ } | {
21
+ readonly type: "muted";
22
+ };
23
+ export interface BridgeOptions {
24
+ readonly config: PortholeConfig;
25
+ readonly display: {
26
+ readonly id: string;
27
+ readonly title: string;
28
+ };
29
+ readonly handlers: CapabilityHandlers;
30
+ readonly confirm?: Confirm;
31
+ /** Whether the embedding page has user activation now; undefined where it can't tell. */
32
+ readonly userActivation?: () => boolean | undefined;
33
+ readonly onEvent: (event: BridgeEvent) => void;
34
+ /** The clock, in milliseconds (tests pass their own). */
35
+ readonly now?: () => number;
36
+ }
37
+ /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
38
+ export declare function linkTarget(value: unknown): string | null;
39
+ export declare function createBridge(options: BridgeOptions): HostFunctionBridge;
@@ -0,0 +1,198 @@
1
+ import { capabilitySpec, } from "../config/capabilities.js";
2
+ import { effectiveGates } from "../compile/policy.js";
3
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
4
+ const MAX_URL = 4_096;
5
+ /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
6
+ export function linkTarget(value) {
7
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL) {
8
+ return null;
9
+ }
10
+ let url;
11
+ try {
12
+ url = new URL(value.trim());
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ if ((url.protocol !== "https:" && url.protocol !== "http:") ||
18
+ url.username !== "" ||
19
+ url.password !== "") {
20
+ return null;
21
+ }
22
+ return url.href;
23
+ }
24
+ const VALIDATORS = {
25
+ sendPrompt: (args, config) => {
26
+ const text = isRecord(args) ? args.text : undefined;
27
+ return typeof text === "string" &&
28
+ text.trim() !== "" &&
29
+ text.length <= config.limits.maxPromptChars
30
+ ? { text }
31
+ : null;
32
+ },
33
+ openLink: (args) => {
34
+ const url = linkTarget(isRecord(args) ? args.url : undefined);
35
+ return url === null ? null : { url };
36
+ },
37
+ downloadFile: (args) => {
38
+ const contents = isRecord(args) ? args.contents : undefined;
39
+ return Array.isArray(contents) && contents.length > 0 && contents.length <= 100
40
+ ? { contents }
41
+ : null;
42
+ },
43
+ callTool: (args) => {
44
+ if (!isRecord(args) ||
45
+ typeof args.name !== "string" ||
46
+ args.name === "" ||
47
+ args.name.length > 256) {
48
+ return null;
49
+ }
50
+ const given = args.arguments ?? {};
51
+ return isRecord(given) ? { name: args.name, arguments: given } : null;
52
+ },
53
+ readData: (args) => {
54
+ const uri = isRecord(args) ? args.uri : undefined;
55
+ return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
56
+ },
57
+ setModelContext: (args) => {
58
+ if (!isRecord(args)) {
59
+ return null;
60
+ }
61
+ const { content, structuredContent } = args;
62
+ if ((content !== undefined && !Array.isArray(content)) ||
63
+ (structuredContent !== undefined && !isRecord(structuredContent))) {
64
+ return null;
65
+ }
66
+ return {
67
+ ...(content === undefined ? {} : { content }),
68
+ ...(structuredContent === undefined ? {} : { structuredContent }),
69
+ };
70
+ },
71
+ reportError: (args) => {
72
+ const message = isRecord(args) ? args.message : undefined;
73
+ return typeof message === "string" && message !== ""
74
+ ? { message: message.slice(0, 2_000) }
75
+ : null;
76
+ },
77
+ resize: (args) => {
78
+ if (!isRecord(args) ||
79
+ typeof args.height !== "number" ||
80
+ !Number.isFinite(args.height) ||
81
+ args.height < 0) {
82
+ return null;
83
+ }
84
+ const width = args.width;
85
+ return typeof width === "number" && Number.isFinite(width) && width >= 0
86
+ ? { height: args.height, width }
87
+ : { height: args.height };
88
+ },
89
+ };
90
+ export function createBridge(options) {
91
+ const { config, display, handlers, onEvent } = options;
92
+ const now = options.now ?? (() => Date.now());
93
+ const calls = new Map();
94
+ let declines = 0;
95
+ let muted = false;
96
+ const refuse = (capability, refusal, message) => {
97
+ onEvent({ type: "refused", capability, refusal });
98
+ return { ok: false, refusal, ...(message === undefined ? {} : { message }) };
99
+ };
100
+ const withinRate = (capability, perMinute) => {
101
+ const at = now();
102
+ const recent = (calls.get(capability) ?? []).filter((time) => at - time < 60_000);
103
+ if (recent.length >= perMinute) {
104
+ calls.set(capability, recent);
105
+ return false;
106
+ }
107
+ recent.push(at);
108
+ calls.set(capability, recent);
109
+ return true;
110
+ };
111
+ return {
112
+ declared: (capability) => config.capabilities[capability] !== undefined,
113
+ async call(capability, raw, callOptions) {
114
+ if (config.capabilities[capability] === undefined) {
115
+ return refuse(capability, "not-declared");
116
+ }
117
+ const args = VALIDATORS[capability](raw, config);
118
+ if (args === null) {
119
+ return refuse(capability, "invalid");
120
+ }
121
+ const gates = effectiveGates(config, capability);
122
+ const confirms = gates.includes("confirm");
123
+ if (confirms && muted) {
124
+ return refuse(capability, "muted");
125
+ }
126
+ for (const gate of gates) {
127
+ if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
128
+ return refuse(capability, "rate-limited");
129
+ }
130
+ }
131
+ if (gates.includes("user-activation")) {
132
+ const activated = callOptions?.userActivated ?? options.userActivation?.();
133
+ if (activated === false) {
134
+ return refuse(capability, "no-user-activation");
135
+ }
136
+ }
137
+ // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
138
+ // effect that needs a gesture gets one), or after `confirm` resolves accepted.
139
+ let effect = null;
140
+ const run = () => (effect ??= perform(capability, args));
141
+ if (confirms) {
142
+ if (options.confirm === undefined) {
143
+ return refuse(capability, "no-confirm");
144
+ }
145
+ let answer = false;
146
+ try {
147
+ answer = await options.confirm({ capability, args, display }, () => void run());
148
+ }
149
+ catch {
150
+ answer = effect === null ? false : "accepted";
151
+ }
152
+ if (effect === null && answer !== true && answer !== "accepted") {
153
+ if (answer === "redirected") {
154
+ return refuse(capability, "redirected");
155
+ }
156
+ // Declines in a row mute the display; a yes starts the count again.
157
+ declines += 1;
158
+ if (declines >= config.limits.declinesBeforeMute && !muted) {
159
+ muted = true;
160
+ onEvent({ type: "muted" });
161
+ }
162
+ return refuse(capability, "declined");
163
+ }
164
+ declines = 0;
165
+ }
166
+ return run();
167
+ },
168
+ };
169
+ async function perform(capability, args) {
170
+ {
171
+ if (capabilitySpec(capability).served === "event") {
172
+ if (capability === "resize") {
173
+ const size = args;
174
+ onEvent({ type: "resize", ...size });
175
+ }
176
+ else {
177
+ onEvent({ type: "error", message: args.message });
178
+ }
179
+ return { ok: true, value: undefined };
180
+ }
181
+ const handler = handlers[capability];
182
+ if (handler === undefined) {
183
+ return refuse(capability, "not-declared");
184
+ }
185
+ try {
186
+ const value = await handler(args, {
187
+ displayId: display.id,
188
+ title: display.title,
189
+ capability,
190
+ });
191
+ return { ok: true, value };
192
+ }
193
+ catch (error) {
194
+ return refuse(capability, "failed", error instanceof Error ? error.message : String(error));
195
+ }
196
+ }
197
+ }
198
+ }
@@ -0,0 +1,83 @@
1
+ import type { CapabilityArgs, CapabilityName, CapabilityResults, HandledCapability } from "../config/capabilities.ts";
2
+ /**
3
+ * The host-function bridge (ARCHITECTURE § Framework layer): carries a capability call from the
4
+ * frame to the host's handler and its result back, checking at the boundary that the capability
5
+ * is declared, that its arguments are well formed, and that every gate passes, in that order.
6
+ * Adapters decode protocol messages into calls; the bridge alone decides whether they run.
7
+ */
8
+ /** Which display a call came from. */
9
+ export interface CallContext {
10
+ readonly displayId: string;
11
+ /** The display's title, as the host gave it (never the content's words). */
12
+ readonly title: string;
13
+ readonly capability: CapabilityName;
14
+ }
15
+ export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
16
+ /** The host's handlers: one for each declared capability served by a handler. */
17
+ export type CapabilityHandlers = {
18
+ readonly [N in HandledCapability]?: CapabilityHandler<N>;
19
+ };
20
+ /** What a person is asked to confirm: the call's whole effect, not a summary the content chose. */
21
+ export type ConfirmRequest = {
22
+ [N in CapabilityName]: {
23
+ readonly capability: N;
24
+ readonly args: CapabilityArgs[N];
25
+ readonly display: {
26
+ readonly id: string;
27
+ readonly title: string;
28
+ };
29
+ };
30
+ }[CapabilityName];
31
+ /**
32
+ * What the person chose. `true`/`"accepted"`: the call goes. `false`/`"declined"`: it doesn't,
33
+ * and the decline counts toward muting the display. `"redirected"`: it doesn't go, but the person
34
+ * took it elsewhere (edited the prompt first, say), so it neither counts as a decline nor resets
35
+ * the count. The host decides which its UI's choices are.
36
+ */
37
+ export type ConfirmAnswer = boolean | "accepted" | "declined" | "redirected";
38
+ /**
39
+ * Runs the call's effect now, inside the caller's own gesture, and counts as accepted. A host
40
+ * whose effect needs the person's gesture (opening a window) calls it from the click handler of
41
+ * its own "yes" button, rather than resolving the promise and letting the effect run after.
42
+ */
43
+ export type Proceed = () => void;
44
+ /**
45
+ * Asks a person. Resolves with their answer. The host's UI, or the React binding's default
46
+ * dialog; drawn outside the frame, never inside it. `proceed` (optional to use) runs the effect
47
+ * within the "yes" click itself.
48
+ */
49
+ export type Confirm = (request: ConfirmRequest, proceed: Proceed) => Promise<ConfirmAnswer>;
50
+ /** Why a call didn't run. */
51
+ export type Refusal =
52
+ /** The config doesn't declare it. */
53
+ "not-declared"
54
+ /** Its arguments were malformed (an `openLink` that isn't http(s), an empty prompt). */
55
+ | "invalid"
56
+ /** It needed a user gesture and had none. */
57
+ | "no-user-activation"
58
+ /** It needed a confirmation and there is no `confirm` function. */
59
+ | "no-confirm"
60
+ /** The person declined. */
61
+ | "declined"
62
+ /** The person took it elsewhere (edited it first): not sent, not counted as a decline. */
63
+ | "redirected"
64
+ /** The display was muted after too many declines (until it runs again). */
65
+ | "muted" | "rate-limited"
66
+ /** The host's handler threw or rejected. */
67
+ | "failed";
68
+ export type CallOutcome<T> = {
69
+ readonly ok: true;
70
+ readonly value: T;
71
+ } | {
72
+ readonly ok: false;
73
+ readonly refusal: Refusal;
74
+ readonly message?: string;
75
+ };
76
+ /** What adapters call; one per display. */
77
+ export interface HostFunctionBridge {
78
+ /** Validates `args` for `capability`, applies its gates, then runs the host's handler. */
79
+ call<N extends CapabilityName>(capability: N, args: unknown, options?: {
80
+ readonly userActivated?: boolean;
81
+ }): Promise<CallOutcome<CapabilityResults[N]>>;
82
+ declared(capability: CapabilityName): boolean;
83
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,35 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import { type GuideTopic } from "../guide/guide.ts";
3
+ import { type ShellDocumentOptions } from "../shell/document.ts";
4
+ import { type ShellPlan } from "../shell/plan.ts";
5
+ import { type CspDirective } from "./policy.ts";
6
+ /**
7
+ * Everything derived from one config (PRINCIPLE 3): the frame's policies, the shell's wiring and
8
+ * document, and the agent manual and tool description. Compiled together from a validated config,
9
+ * so they cannot disagree; the agreement test checks that they don't.
10
+ */
11
+ export interface CompiledConfig {
12
+ readonly config: PortholeConfig;
13
+ /** The frame's CSP, directive by directive; empty in url mode (the app sends its own). */
14
+ readonly cspDirectives: readonly CspDirective[];
15
+ /** The frame's CSP: in the shell's `<meta>`, or a served document's header. */
16
+ readonly csp: string;
17
+ /** The frame's `sandbox` attribute. */
18
+ readonly sandbox: string;
19
+ /** The frame's `allow` attribute (Permissions Policy). */
20
+ readonly allow: string;
21
+ /** The frame's `referrerpolicy` attribute. */
22
+ readonly referrerPolicy: "no-referrer";
23
+ /** The `frame-src` sources the embedding page must allow (see `embedderCsp`). */
24
+ readonly embedderFrameSources: readonly string[];
25
+ /** What the shell wires; null in url mode, which has no shell. */
26
+ readonly shell: ShellPlan | null;
27
+ /** The frame's document: the policy, the base styles and the shell's runtime. */
28
+ shellDocument(options: ShellDocumentOptions): string;
29
+ /** The agent manual for `topics` (every built-in topic by default). */
30
+ guide(topics?: readonly GuideTopic[]): string;
31
+ /** The description of the host's show tool. */
32
+ toolDescription(): string;
33
+ }
34
+ /** Validates `config` and derives everything from it. Throws a `ConfigError` on a bad config. */
35
+ export declare function compile(config: PortholeConfig): CompiledConfig;
@@ -0,0 +1,30 @@
1
+ import { validateConfig } from "../config/validate.js";
2
+ import { generateGuide, generateToolDescription } from "../guide/guide.js";
3
+ import { shellDocument } from "../shell/document.js";
4
+ import { shellPlan } from "../shell/plan.js";
5
+ import { allowAttribute, embedderFrameSources, frameCspDirectives, sandboxTokens, serializeCsp, } from "./policy.js";
6
+ /** Validates `config` and derives everything from it. Throws a `ConfigError` on a bad config. */
7
+ export function compile(config) {
8
+ validateConfig(config);
9
+ const cspDirectives = frameCspDirectives(config);
10
+ const csp = serializeCsp(cspDirectives);
11
+ const shell = shellPlan(config);
12
+ return {
13
+ config,
14
+ cspDirectives,
15
+ csp,
16
+ sandbox: sandboxTokens(config).join(" "),
17
+ allow: allowAttribute(config),
18
+ referrerPolicy: "no-referrer",
19
+ embedderFrameSources: embedderFrameSources(config),
20
+ shell,
21
+ shellDocument: (options) => {
22
+ if (shell === null) {
23
+ throw new TypeError("url mode has no shell: the frame loads the app's own document");
24
+ }
25
+ return shellDocument(shell, csp, options);
26
+ },
27
+ guide: (topics) => generateGuide(config, topics),
28
+ toolDescription: () => generateToolDescription(config),
29
+ };
30
+ }
@@ -0,0 +1,55 @@
1
+ import { type CapabilityName, type Gate } from "../config/capabilities.ts";
2
+ import type { EgressConfig, PortholeConfig } from "../config/schema.ts";
3
+ /**
4
+ * The frame's policies, derived from the config: its CSP (in the shell's `<meta>` for opaque
5
+ * frames, in headers for served ones), its `sandbox` and `allow` attributes, and the `frame-src`
6
+ * the EMBEDDING page must send. Pure, so a test can tie each source back to the config.
7
+ */
8
+ /** A CSP directive: its name, then its sources. */
9
+ export type CspDirective = readonly [name: string, ...sources: string[]];
10
+ export type EgressKind = keyof EgressConfig;
11
+ /** The capabilities a config declares, in vocabulary order. */
12
+ export declare function declaredCapabilities(config: PortholeConfig): CapabilityName[];
13
+ /** The gates a declared capability runs under: its own, else the vocabulary's defaults. */
14
+ export declare function effectiveGates(config: PortholeConfig, name: CapabilityName): readonly Gate[];
15
+ /** The origins content may reach for `kind`: the base allowlist plus every declared capability's. */
16
+ export declare function egressOrigins(config: PortholeConfig, kind: EgressKind): string[];
17
+ /** Every origin content may reach, of any kind. */
18
+ export declare function allEgressOrigins(config: PortholeConfig): string[];
19
+ /**
20
+ * The frame's CSP directives. Closed by default: `default-src 'none'`, and each kind opened only
21
+ * to the config's origins. Inline code runs (agent content is inline), so the walls are origin
22
+ * isolation and egress, not script provenance. No `'self'` anywhere: an opaque frame has nothing
23
+ * of its own to load, and its `'self'` may be the embedding page's origin. Empty for url mode,
24
+ * whose app serves its own policy.
25
+ */
26
+ export declare function frameCspDirectives(config: PortholeConfig): CspDirective[];
27
+ export declare function serializeCsp(directives: readonly CspDirective[]): string;
28
+ /**
29
+ * The frame's `sandbox` tokens. Opaque: scripts only, so the frame is an opaque origin and gets
30
+ * no forms, popups, downloads, modals or top navigation. Domain: its own origin as well, which is
31
+ * safe only because that origin is a separate site from the host's (the mount refuses one that
32
+ * isn't). External (url mode): what a running web app needs to work on its own origin.
33
+ */
34
+ export declare function sandboxTokens(config: PortholeConfig): string[];
35
+ /**
36
+ * The frame's `allow` attribute (Permissions Policy). Empty: no camera, microphone, geolocation,
37
+ * clipboard, fullscreen or other powerful feature is delegated to the frame.
38
+ */
39
+ export declare function allowAttribute(_config: PortholeConfig): string;
40
+ /**
41
+ * The `frame-src` sources the EMBEDDING page must allow, and nothing else: a frame's own CSP can't
42
+ * stop it navigating itself to an external URL with data in the query, but the embedding page's
43
+ * `frame-src` governs every navigation of its frames, including self-initiated ones. `srcdoc`
44
+ * frames need no source (measured: they load under `frame-src 'none'`), so opaque content gets
45
+ * none, and can't navigate its frame even to the host's own origin (P033); served and external
46
+ * content adds its own origins, and a host its own frames (`'self'` only if it names it).
47
+ */
48
+ export declare function embedderFrameSources(config: PortholeConfig): string[];
49
+ /**
50
+ * The CSP the embedding page sends (a header, or the host's own document's policy), for every kind
51
+ * of display it shows. Frames only: no `default-src`, so the host's own scripts, styles and
52
+ * fetches stay its policy's; and no `child-src`, which the host's workers would fall back to (every
53
+ * engine Porthole supports reads frames from `frame-src`, P038).
54
+ */
55
+ export declare function embedderCsp(configs: readonly PortholeConfig[]): string;