@botiverse/porthole 0.7.0 → 0.8.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 (153) hide show
  1. package/README.md +9 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/bridge/bounded-text.d.ts +34 -0
  4. package/dist/bridge/bounded-text.js +188 -0
  5. package/dist/bridge/bridge.d.ts +25 -5
  6. package/dist/bridge/bridge.js +311 -73
  7. package/dist/bridge/json-data.d.ts +28 -0
  8. package/dist/bridge/json-data.js +86 -0
  9. package/dist/bridge/navigation.d.ts +5 -0
  10. package/dist/bridge/navigation.js +7 -0
  11. package/dist/bridge/refusal.js +1 -0
  12. package/dist/bridge/types.d.ts +32 -1
  13. package/dist/check/page-source.js +1 -1
  14. package/dist/check/page.js +2 -0
  15. package/dist/compile/compile.d.ts +6 -0
  16. package/dist/compile/compile.js +3 -1
  17. package/dist/compile/policy.d.ts +38 -2
  18. package/dist/compile/policy.js +122 -7
  19. package/dist/config/capabilities.d.ts +23 -4
  20. package/dist/config/capabilities.js +12 -2
  21. package/dist/config/schema.d.ts +11 -0
  22. package/dist/config/validate.d.ts +8 -2
  23. package/dist/config/validate.js +28 -6
  24. package/dist/config/warnings.d.ts +20 -0
  25. package/dist/config/warnings.js +25 -0
  26. package/dist/conformance/behavior.js +46 -1
  27. package/dist/conformance/cookies.d.ts +15 -0
  28. package/dist/conformance/cookies.js +80 -0
  29. package/dist/conformance/harness/page.d.ts +1 -0
  30. package/dist/conformance/harness/page.js +9 -2
  31. package/dist/conformance/harness-source.js +1 -1
  32. package/dist/conformance/host-kit.js +5 -1
  33. package/dist/conformance/index.d.ts +10 -0
  34. package/dist/conformance/limits.js +38 -1
  35. package/dist/conformance/runtime.js +10 -0
  36. package/dist/conformance/served.d.ts +2 -0
  37. package/dist/conformance/served.js +737 -4
  38. package/dist/files/paths.js +4 -0
  39. package/dist/guide/gates.d.ts +7 -1
  40. package/dist/guide/gates.js +12 -0
  41. package/dist/guide/guide.js +2 -2
  42. package/dist/guide/runtime.js +11 -3
  43. package/dist/host/create-host.js +49 -37
  44. package/dist/host/pages-of-set.d.ts +43 -0
  45. package/dist/host/pages-of-set.js +196 -0
  46. package/dist/host/types.d.ts +8 -1
  47. package/dist/index.d.ts +5 -4
  48. package/dist/index.js +3 -2
  49. package/dist/mcp/adapter.js +11 -15
  50. package/dist/node/index.d.ts +36 -4
  51. package/dist/node/index.js +402 -101
  52. package/dist/presets/presets.d.ts +16 -8
  53. package/dist/presets/presets.js +39 -8
  54. package/dist/protocol/live-data.d.ts +6 -2
  55. package/dist/protocol/live-data.js +20 -1
  56. package/dist/protocol/mcp-apps.d.ts +13 -2
  57. package/dist/protocol/mcp-apps.js +10 -2
  58. package/dist/protocol/message-text.d.ts +8 -0
  59. package/dist/protocol/message-text.js +29 -0
  60. package/dist/protocol/runtime-calls.js +3 -0
  61. package/dist/protocol/shell-adapter.js +16 -22
  62. package/dist/react/context-notice.d.ts +32 -0
  63. package/dist/react/context-notice.js +28 -0
  64. package/dist/react/dialog.js +62 -18
  65. package/dist/react/frame.d.ts +12 -1
  66. package/dist/react/frame.js +79 -2
  67. package/dist/react/index.d.ts +2 -1
  68. package/dist/react/index.js +2 -1
  69. package/dist/runtime/contract.d.ts +9 -1
  70. package/dist/runtime/contract.js +31 -2
  71. package/dist/runtime/db.d.ts +41 -6
  72. package/dist/runtime/db.js +120 -16
  73. package/dist/runtime/declaration.d.ts +15 -1
  74. package/dist/runtime/declaration.js +184 -87
  75. package/dist/runtime/requests.js +27 -11
  76. package/dist/runtime/types.generated.js +1 -1
  77. package/dist/server/files.d.ts +5 -0
  78. package/dist/server/files.js +22 -7
  79. package/dist/server/host.d.ts +18 -1
  80. package/dist/server/host.js +132 -2
  81. package/dist/server/index.d.ts +1 -1
  82. package/dist/server/index.js +1 -1
  83. package/dist/server/peer.d.ts +4 -0
  84. package/dist/server/peer.js +19 -0
  85. package/dist/server/proxy.d.ts +6 -0
  86. package/dist/server/proxy.js +12 -3
  87. package/dist/server/server.js +113 -26
  88. package/dist/server/types.d.ts +6 -3
  89. package/dist/shell/document.d.ts +8 -0
  90. package/dist/shell/document.js +3 -0
  91. package/dist/shell/runtime.js +361 -14
  92. package/docs/ADOPTING.md +119 -14
  93. package/docs/ARCHITECTURE.md +13 -3
  94. package/docs/DECISIONS.md +1455 -8
  95. package/docs/DESIGN.md +79 -25
  96. package/docs/THREAT_MODEL.md +616 -0
  97. package/package.json +14 -3
  98. package/src/bridge/bounded-text.ts +240 -0
  99. package/src/bridge/bridge.ts +373 -84
  100. package/src/bridge/json-data.ts +95 -0
  101. package/src/bridge/navigation.ts +10 -0
  102. package/src/bridge/refusal.ts +1 -0
  103. package/src/bridge/types.ts +30 -1
  104. package/src/check/page.ts +2 -0
  105. package/src/compile/compile.ts +9 -1
  106. package/src/compile/policy.ts +130 -7
  107. package/src/config/capabilities.ts +22 -3
  108. package/src/config/schema.ts +11 -0
  109. package/src/config/validate.ts +43 -5
  110. package/src/config/warnings.ts +42 -0
  111. package/src/conformance/behavior.ts +54 -1
  112. package/src/conformance/cookies.ts +93 -0
  113. package/src/conformance/harness/page.ts +11 -2
  114. package/src/conformance/host-kit.ts +10 -1
  115. package/src/conformance/index.ts +10 -0
  116. package/src/conformance/limits.ts +39 -1
  117. package/src/conformance/runtime.ts +21 -0
  118. package/src/conformance/served.ts +888 -4
  119. package/src/files/paths.ts +4 -0
  120. package/src/guide/gates.ts +13 -1
  121. package/src/guide/guide.ts +3 -3
  122. package/src/guide/runtime.ts +12 -3
  123. package/src/host/create-host.ts +54 -36
  124. package/src/host/pages-of-set.ts +226 -0
  125. package/src/host/types.ts +15 -1
  126. package/src/index.ts +5 -0
  127. package/src/mcp/adapter.ts +16 -20
  128. package/src/node/index.ts +507 -116
  129. package/src/presets/presets.ts +60 -17
  130. package/src/protocol/live-data.ts +31 -3
  131. package/src/protocol/mcp-apps.ts +11 -2
  132. package/src/protocol/message-text.ts +36 -0
  133. package/src/protocol/runtime-calls.ts +3 -0
  134. package/src/protocol/shell-adapter.ts +27 -23
  135. package/src/react/context-notice.tsx +95 -0
  136. package/src/react/dialog.tsx +77 -17
  137. package/src/react/frame.tsx +101 -0
  138. package/src/react/index.ts +8 -1
  139. package/src/runtime/contract.ts +36 -2
  140. package/src/runtime/db.ts +140 -20
  141. package/src/runtime/declaration.ts +227 -89
  142. package/src/runtime/requests.ts +27 -11
  143. package/src/runtime/types.generated.ts +1 -1
  144. package/src/server/files.ts +29 -11
  145. package/src/server/host.ts +158 -3
  146. package/src/server/index.ts +1 -0
  147. package/src/server/peer.ts +21 -0
  148. package/src/server/proxy.ts +13 -3
  149. package/src/server/server.ts +139 -36
  150. package/src/server/types.ts +6 -3
  151. package/src/shell/document.ts +8 -0
  152. package/src/shell/runtime.ts +361 -14
  153. package/types/runtime/v1/context.d.ts +13 -2
@@ -0,0 +1,95 @@
1
+ /**
2
+ * JSON data, as a host function carries it to a host's handler and its dialog (P095, after the
3
+ * review): what `callTool`'s arguments, `setModelContext`'s content and a download's contents are
4
+ * in MCP, and what a host forwards to a server or a model as JSON. A frame's messages come
5
+ * structured-cloned, so they can hold what JSON can't say or says otherwise: a cycle, an object
6
+ * reached twice (a graph of 30 is 2^30 nodes as a tree), a BigInt, NaN, a boxed `String` (JSON
7
+ * writes its value; a handler gets an object), a Map, a typed array, a Date.
8
+ *
9
+ * Plain data only: null, booleans, finite numbers, strings, arrays and objects whose prototype is
10
+ * Object's or none, each object reached once (MCP's arguments are JSON: an object in two places is
11
+ * refused, the simple bound), at most `nodes` values (a field left `undefined`, allowed as JSON
12
+ * leaves it out, counts as one), `depth` levels, and `chars` characters of strings and keys
13
+ * together (after the re-review: neither a field without a value nor a long string is free).
14
+ * Each node is visited once: linear in what was sent, stopped at the budget. Never throws (a
15
+ * value whose read throws is no data).
16
+ */
17
+
18
+ export interface JsonDataLimits {
19
+ readonly nodes: number;
20
+ readonly depth: number;
21
+ /** The characters of every string and every key, together. */
22
+ readonly chars: number;
23
+ }
24
+
25
+ /**
26
+ * A call's: as many values as one db document holds (P091), nested deeper than any real one, and
27
+ * 4 MiB of text.
28
+ */
29
+ export const JSON_DATA_LIMITS: JsonDataLimits = { nodes: 100_000, depth: 64, chars: 4_194_304 };
30
+
31
+ export function isJsonData(value: unknown, limits: JsonDataLimits = JSON_DATA_LIMITS): boolean {
32
+ let nodes = limits.nodes;
33
+ let chars = limits.chars;
34
+ const seen = new WeakSet<object>();
35
+ /** Takes `length` characters from the budget: whether it still holds. */
36
+ const text = (length: number): boolean => {
37
+ chars -= length;
38
+ return chars >= 0;
39
+ };
40
+
41
+ function plain(each: unknown, depth: number): boolean {
42
+ nodes -= 1;
43
+ if (nodes < 0 || depth > limits.depth) {
44
+ return false;
45
+ }
46
+ if (typeof each === "string") {
47
+ return text(each.length);
48
+ }
49
+ if (each === null || typeof each === "boolean") {
50
+ return true;
51
+ }
52
+ if (typeof each === "number") {
53
+ return Number.isFinite(each);
54
+ }
55
+ if (typeof each !== "object" || seen.has(each)) {
56
+ return false;
57
+ }
58
+ seen.add(each);
59
+ if (Array.isArray(each)) {
60
+ const list = each as readonly unknown[];
61
+ for (let index = 0; index < list.length; index += 1) {
62
+ if (!plain(list[index], depth + 1)) {
63
+ return false;
64
+ }
65
+ }
66
+ return true;
67
+ }
68
+ const proto: unknown = Object.getPrototypeOf(each);
69
+ if (proto !== Object.prototype && proto !== null) {
70
+ return false;
71
+ }
72
+ for (const key of Object.keys(each)) {
73
+ if (!text(key.length)) {
74
+ return false;
75
+ }
76
+ const field = (each as Record<string, unknown>)[key];
77
+ if (field === undefined) {
78
+ // No value, but a field: it counts.
79
+ nodes -= 1;
80
+ if (nodes < 0) {
81
+ return false;
82
+ }
83
+ } else if (!plain(field, depth + 1)) {
84
+ return false;
85
+ }
86
+ }
87
+ return true;
88
+ }
89
+
90
+ try {
91
+ return plain(value, 0);
92
+ } catch {
93
+ return false;
94
+ }
95
+ }
@@ -14,6 +14,16 @@ import type { PortholeConfig } from "../config/schema.ts";
14
14
  const SEALED = /(?:https?:\/\/[^\s"'<>/]+)?\/__porthole\/f\/[A-Za-z0-9_-]{20,}\//gu;
15
15
  export const withoutSealedAddresses = (text: string): string => text.replace(SEALED, "./");
16
16
 
17
+ /** A sealed address's access, cut off by the end of the text: no longer one `SEALED` matches. */
18
+ const UNFINISHED = /\/__porthole\/f\/[A-Za-z0-9_-]*$/u;
19
+
20
+ /**
21
+ * `text`, at most `max` characters (S05, P095): a cut inside a sealed address's access drops what
22
+ * of it is left, so a text cut before it is scrubbed tells no part of one.
23
+ */
24
+ export const cutText = (text: string, max: number): string =>
25
+ text.length <= max ? text : text.slice(0, max).replace(UNFINISHED, "");
26
+
17
27
  /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
18
28
  export function addressWithoutQuery(url: string): string {
19
29
  // A page's own file (P084), as the shell names it: its path, without query or fragment.
@@ -123,6 +123,7 @@ const CODES: { readonly [R in Refusal]: RefusalCode } = {
123
123
  redirected: "denied",
124
124
  muted: "denied",
125
125
  "no-consent": "not_allowed",
126
+ "no-show": "not_allowed",
126
127
  denied: "denied",
127
128
  "rate-limited": "rate_limited",
128
129
  failed: "failed",
@@ -101,6 +101,13 @@ export type ConfirmRequest = {
101
101
  readonly capability: N;
102
102
  readonly args: CapabilityArgs[N];
103
103
  readonly display: ConfirmDisplay;
104
+ /**
105
+ * A confirmation only (never a consent's request): the runtime methods whose own gates
106
+ * (`CapabilityConfig.methodGates`, the contract's) asked for it, of those the call runs (P094):
107
+ * a db batch's writes' ops that need a yes, so a dialog can lead with them. Absent where only
108
+ * the host function's own gates ask.
109
+ */
110
+ readonly askedBy?: readonly string[];
104
111
  };
105
112
  }[CapabilityName];
106
113
 
@@ -119,6 +126,18 @@ export type ConfirmAnswer = boolean | "accepted" | "declined" | "redirected";
119
126
  */
120
127
  export type Proceed = () => void;
121
128
 
129
+ /**
130
+ * Puts a call's whole effect in front of the person, outside every frame (the `show` gate, P100):
131
+ * a `setModelContext` update's text and structured content, which the model reads at its next
132
+ * turns. It asks nothing; the call goes once it returns (or its promise resolves), so it resolves
133
+ * only once this very update is visible: drawn, not queued behind a render (after the review). An
134
+ * update the person never saw, because a later one of the display replaced it first, rejects:
135
+ * the call doesn't go. One that throws or rejects stops the call: nobody saw it. Each update
136
+ * replaces the display's last (MCP Apps: the host sends the model the last one), so a surface
137
+ * shows the latest per display.
138
+ */
139
+ export type Show = (request: ConfirmRequest) => void | Promise<void>;
140
+
122
141
  /**
123
142
  * Asks a person. Resolves with their answer. The host's UI, or the React binding's default
124
143
  * dialog; drawn outside the frame, never inside it. `proceed` (optional to use) runs the effect
@@ -144,10 +163,12 @@ export type Refusal =
144
163
  | "muted"
145
164
  /** It is `consent`-gated and there is no `consent` function. */
146
165
  | "no-consent"
166
+ /** It is `show`-gated and there is no `show` function: nobody could see it (P100). */
167
+ | "no-show"
147
168
  /** The host's `consent` said no (for this display's life). */
148
169
  | "denied"
149
170
  | "rate-limited"
150
- /** The host's handler threw or rejected. */
171
+ /** The host's handler threw or rejected (or its `show` did: nobody saw the call, P100). */
151
172
  | "failed"
152
173
  /**
153
174
  * The display's page declared capabilities and not this one (P086): a built-in needs none, any
@@ -182,6 +203,14 @@ export interface CallOptions {
182
203
  readonly subscription?: Pick<SubscriptionContext, "changed" | "signal">;
183
204
  /** `readData`: the host's cache may answer, marked stale (the content subscribes to it). */
184
205
  readonly stale?: boolean;
206
+ /**
207
+ * `readData`: a result the host already gave for this read (a subscription's `changed(result)`,
208
+ * the fresh read after a stale answer), and the URI it was given for. It answers the read after
209
+ * every gate a read has, without the handler or the cache (P094: a kept result is never a way
210
+ * past the read's gates); a `uri` that isn't the read's is refused (`invalid`). Ignored for any
211
+ * capability but `readData`.
212
+ */
213
+ readonly held?: { readonly uri: string; readonly value: unknown };
185
214
  }
186
215
 
187
216
  /** What adapters call; one per display. */
package/src/check/page.ts CHANGED
@@ -182,6 +182,8 @@ const check = {
182
182
  confirm: () => Promise.resolve("declined"),
183
183
  // A viewer who doesn't allow a live widget their data (P079): its calls are refused.
184
184
  consent: () => false,
185
+ // Model context goes to a surface nobody reads here (P100): the check has no person.
186
+ show: () => {},
185
187
  // A served config's instance, issued by the check's own server on this page's origin.
186
188
  locator: {
187
189
  locate: async (instance) =>
@@ -1,5 +1,6 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
2
  import { validateConfig } from "../config/validate.ts";
3
+ import type { ConfigWarning } from "../config/warnings.ts";
3
4
  import { generateGuide, generateToolDescription, type GuideTopic } from "../guide/guide.ts";
4
5
  import { shellDocument, type ShellDocumentOptions } from "../shell/document.ts";
5
6
  import { shellPlan, type ShellPlan } from "../shell/plan.ts";
@@ -19,6 +20,11 @@ import {
19
20
  */
20
21
  export interface CompiledConfig {
21
22
  readonly config: PortholeConfig;
23
+ /**
24
+ * What the config says that its host likely didn't mean (`configWarnings`): log them at startup.
25
+ * Empty for a config without any.
26
+ */
27
+ readonly warnings: readonly ConfigWarning[];
22
28
  /** The frame's CSP, directive by directive; empty in url mode (the app sends its own). */
23
29
  readonly cspDirectives: readonly CspDirective[];
24
30
  /** The frame's CSP: in the shell's `<meta>`, or a served document's header. */
@@ -43,12 +49,14 @@ export interface CompiledConfig {
43
49
 
44
50
  /** Validates `config` and derives everything from it. Throws a `ConfigError` on a bad config. */
45
51
  export function compile(config: PortholeConfig): CompiledConfig {
46
- validateConfig(config);
52
+ const warnings: ConfigWarning[] = [];
53
+ validateConfig(config, { onWarning: (warning) => warnings.push(warning) });
47
54
  const cspDirectives = frameCspDirectives(config);
48
55
  const csp = serializeCsp(cspDirectives);
49
56
  const shell = shellPlan(config);
50
57
  return {
51
58
  config,
59
+ warnings,
52
60
  cspDirectives,
53
61
  csp,
54
62
  sandbox: sandboxTokens(config).join(" "),
@@ -1,7 +1,7 @@
1
1
  import { CAPABILITIES, type CapabilityName, type Gate } from "../config/capabilities.ts";
2
2
  import type { PortholeConfig } from "../config/schema.ts";
3
3
  import { LIBRARY_PATH } from "../libraries/libraries.ts";
4
- import { assetCodeRuns, familyOf, methodGates, methodOf } from "../runtime/contract.ts";
4
+ import { assetCodeRuns, familyOf, methodGates, methodsOfCall } from "../runtime/contract.ts";
5
5
  import { ASSET_PATH } from "../runtime/requests.ts";
6
6
 
7
7
  /**
@@ -33,19 +33,28 @@ export function effectiveGates(config: PortholeConfig, name: CapabilityName): re
33
33
  }
34
34
 
35
35
  /**
36
- * The gates one call runs under: its host function's, and its runtime method's own (after the
37
- * review: `artifact.publish`, `assets.delete`, an upload whose code may run), every one applying.
36
+ * The gates one call runs under: its host function's, and the own gates of each runtime method it
37
+ * runs (after the review: `artifact.publish`, `assets.delete`, an upload whose code may run; P094:
38
+ * a db batch's writes' and a watch's read's too, `methodsOfCall`), every one applying.
38
39
  */
39
40
  export function callGates(
40
41
  config: PortholeConfig,
41
42
  name: CapabilityName,
42
43
  args: unknown,
43
44
  ): readonly Gate[] {
44
- const gates = effectiveGates(config, name);
45
+ const gates = [...effectiveGates(config, name)];
45
46
  const family = familyOf(name);
46
- const method = family === null ? null : methodOf(name, args);
47
- const own = family === null || method === null ? [] : methodGates(config, family.name, method);
48
- return own.length === 0 ? gates : [...gates, ...own.filter((gate) => !gates.includes(gate))];
47
+ if (family === null) {
48
+ return gates;
49
+ }
50
+ for (const method of new Set(methodsOfCall(name, args))) {
51
+ for (const gate of methodGates(config, family.name, method)) {
52
+ if (!gates.includes(gate)) {
53
+ gates.push(gate);
54
+ }
55
+ }
56
+ }
57
+ return gates;
49
58
  }
50
59
 
51
60
  const unique = (values: readonly string[]): string[] => [...new Set(values)];
@@ -215,6 +224,120 @@ export function sandboxTokens(config: PortholeConfig): string[] {
215
224
  }
216
225
  }
217
226
 
227
+ /**
228
+ * The `sandbox` a served document's CSP header carries (P099): the frame's own tokens, so a page
229
+ * opened on a tab of its own (a public link, a new tab, a bookmark, a frame's address opened
230
+ * outside it) holds no power it lacks in its frame: scripts on its own origin, and no popups,
231
+ * forms, downloads, modals, or navigation of another window (its opener's included). In a frame
232
+ * it repeats the frame's attribute, so it changes nothing there; it is sent on every served page,
233
+ * not only on a `Sec-Fetch-Dest: document` request, so a client that sends no fetch metadata is
234
+ * sandboxed too and one address needs no `Vary`. Domain isolation only: url mode serves the app's
235
+ * own documents, and opaque content is never served. Never in a `<meta>` (browsers ignore it there).
236
+ */
237
+ export function servedSandboxDirective(config: PortholeConfig): CspDirective | null {
238
+ return config.isolation === "domain" ? ["sandbox", ...sandboxTokens(config)] : null;
239
+ }
240
+
241
+ /** A served page's CSP header: the page's directives, then its sandbox (P099). */
242
+ export function servedDocumentCsp(
243
+ config: PortholeConfig,
244
+ directives: readonly CspDirective[],
245
+ ): string {
246
+ const sandbox = servedSandboxDirective(config);
247
+ return serializeCsp(sandbox === null ? directives : [...directives, sandbox]);
248
+ }
249
+
250
+ /**
251
+ * The features a cross-origin frame never has unless its `allow` names them (each one's default
252
+ * allowlist is `'self'`), and a served page denies itself (P099): devices, location, full screen,
253
+ * the clipboard, payments, credentials, sharing, the built-in AI models, WebMCP's `tools`, the
254
+ * local network, autofill. Every such feature Chromium lists for web pages
255
+ * (`test/reference/permissions-policy-features.json`), but client hints, `cross-origin-isolated`
256
+ * and Chromium's sample (`test/permissions-policy.test.ts` says why). Features whose default is
257
+ * `*` (a video's picture-in-picture, gamepads) are left out: a frame has them, so denying them on
258
+ * a tab would change the frame too. An engine that doesn't know a name ignores it.
259
+ */
260
+ export const FRAME_DENIED_FEATURES = [
261
+ "accelerometer",
262
+ "ambient-light-sensor",
263
+ "autofill",
264
+ "autoplay",
265
+ "bluetooth",
266
+ "camera",
267
+ "captured-surface-control",
268
+ "clipboard-read",
269
+ "clipboard-write",
270
+ "compute-pressure",
271
+ "deferred-fetch",
272
+ "device-attributes",
273
+ "digital-credentials-create",
274
+ "digital-credentials-get",
275
+ "display-capture",
276
+ "encrypted-media",
277
+ "fullscreen",
278
+ "geolocation",
279
+ "gyroscope",
280
+ "haptics",
281
+ "hid",
282
+ "identity-credentials-get",
283
+ "idle-detection",
284
+ "keyboard-map",
285
+ "language-detector",
286
+ "language-model",
287
+ "local-fonts",
288
+ "local-network",
289
+ "local-network-access",
290
+ "loopback-network",
291
+ "magnetometer",
292
+ "manual-text",
293
+ "microphone",
294
+ "midi",
295
+ "on-device-speech-recognition",
296
+ "otp-credentials",
297
+ "payment",
298
+ "publickey-credentials-create",
299
+ "publickey-credentials-get",
300
+ "publickey-credentials-remote-client-data-json",
301
+ "rewriter",
302
+ "screen-wake-lock",
303
+ "serial",
304
+ "speaker-selection",
305
+ "summarizer",
306
+ "tools",
307
+ "translator",
308
+ "unbounded-element",
309
+ "usb",
310
+ "web-app-installation",
311
+ "web-share",
312
+ "webnn",
313
+ "window-management",
314
+ "writer",
315
+ "xr-spatial-tracking",
316
+ ] as const;
317
+
318
+ /** The features a frame's `allow` attribute grants (`allowAttribute`): none but url mode's. */
319
+ export function delegatedFeatures(config: PortholeConfig): string[] {
320
+ return config.mode === "url" ? [...(config.permissions ?? [])] : [];
321
+ }
322
+
323
+ /**
324
+ * The `Permissions-Policy` header of a served page (P099): every feature of
325
+ * `FRAME_DENIED_FEATURES` its frame's `allow` doesn't grant, denied (`camera=()`), so a page on
326
+ * a tab of its own (no `allow` there) can't ask for the camera, the microphone, location or full
327
+ * screen under the content origin's name. In a frame it changes nothing: the frame's `allow`
328
+ * grants none of them, and a frame's features are the intersection of the two. Domain isolation
329
+ * only, as `servedSandboxDirective`.
330
+ */
331
+ export function servedPermissionsPolicy(config: PortholeConfig): string | null {
332
+ if (config.isolation !== "domain") {
333
+ return null;
334
+ }
335
+ const granted = new Set(delegatedFeatures(config));
336
+ return FRAME_DENIED_FEATURES.filter((feature) => !granted.has(feature))
337
+ .map((feature) => `${feature}=()`)
338
+ .join(", ");
339
+ }
340
+
218
341
  /**
219
342
  * The frame's `allow` attribute (Permissions Policy). No camera, microphone, geolocation,
220
343
  * fullscreen or other powerful feature is delegated to the frame, and the clipboard is denied by
@@ -55,11 +55,15 @@ export type CapabilityName = (typeof CAPABILITY_NAMES)[number];
55
55
  * call of any of its consent-gated capabilities, whether this content may have them (a viewer
56
56
  * allowing a widget to read their data). A no refuses every such call for the display's life;
57
57
  * no `consent` function refuses them all (fail closed).
58
+ * - `show` (P100): the host's `show` function puts the call's whole effect in front of the person,
59
+ * outside the frame, before the handler has it; it asks nothing. No `show` function, or one that
60
+ * throws, means the call is refused (fail closed).
58
61
  */
59
62
  export type Gate =
60
63
  | "user-activation"
61
64
  | "confirm"
62
65
  | "consent"
66
+ | "show"
63
67
  | { readonly rateLimit: { readonly perMinute: number } };
64
68
 
65
69
  export interface CapabilitySpec {
@@ -85,6 +89,12 @@ const rate = (perMinute: number): Gate => ({ rateLimit: { perMinute } });
85
89
  /** The most text one `copyText` call carries. */
86
90
  export const MAX_COPY_CHARS = 20_000;
87
91
 
92
+ /**
93
+ * The most one `setModelContext` update carries (P100): its text blocks' characters and its
94
+ * structured content's JSON, together. What the person is shown is all of it.
95
+ */
96
+ export const MAX_CONTEXT_CHARS = 20_000;
97
+
88
98
  export const CAPABILITIES = {
89
99
  sendPrompt: {
90
100
  defaultGates: ["user-activation", "confirm"],
@@ -104,7 +114,8 @@ export const CAPABILITIES = {
104
114
  request: { method: "ui/download-file", sdk: "app.downloadFile" },
105
115
  },
106
116
  callTool: {
107
- defaultGates: ["confirm"],
117
+ // A rate as well (P103): it needs no gesture, and a host's `confirm` may say yes by itself.
118
+ defaultGates: ["confirm", rate(30)],
108
119
  served: "handler",
109
120
  request: { method: "tools/call", sdk: "app.callServerTool" },
110
121
  },
@@ -125,8 +136,12 @@ export const CAPABILITIES = {
125
136
  global: "subscribeData",
126
137
  request: { method: "resources/subscribe" },
127
138
  },
139
+ /**
140
+ * Text for the model's next turns (P100): the content's own words, which the person never typed.
141
+ * Shown to them first by default (`show`), so nothing reaches the model they couldn't see.
142
+ */
128
143
  setModelContext: {
129
- defaultGates: [rate(30)],
144
+ defaultGates: [rate(30), "show"],
130
145
  served: "handler",
131
146
  request: { method: "ui/update-model-context", sdk: "app.updateModelContext" },
132
147
  },
@@ -176,8 +191,12 @@ export interface CapabilityArgs {
176
191
  };
177
192
  readonly readData: { readonly uri: string };
178
193
  readonly subscribeData: { readonly uri: string };
194
+ /**
195
+ * Text blocks only (the modality the host offers), each rebuilt as `{ type, text }`; structured
196
+ * content plain JSON (P100). At most `MAX_CONTEXT_CHARS` together.
197
+ */
179
198
  readonly setModelContext: {
180
- readonly content?: readonly unknown[];
199
+ readonly content?: readonly { readonly type: "text"; readonly text: string }[];
181
200
  readonly structuredContent?: Readonly<Record<string, unknown>>;
182
201
  };
183
202
  /**
@@ -40,6 +40,13 @@ export type ThemeValue = string | { readonly light: string; readonly dark: strin
40
40
  export interface CapabilityConfig {
41
41
  /** Every gate must pass. Omitted: the capability's default gates. `[]`: ungated. */
42
42
  readonly gates?: readonly Gate[];
43
+ /**
44
+ * Says that `gates` leaves out the default `show` on purpose (P100: `setModelContext`): the
45
+ * host's handler shows the person each update itself, or the content is its own. Without it,
46
+ * such gates earn a warning (`configWarnings`); with `show` in the gates, or no gates named, it
47
+ * is an error.
48
+ */
49
+ readonly withoutShow?: true;
43
50
  /** Extra `connect-src` origins this capability needs. */
44
51
  readonly connect?: readonly string[];
45
52
  /** Extra script/style/img/font/media origins this capability needs. */
@@ -58,6 +65,10 @@ export interface CapabilityConfig {
58
65
  * Gates of each runtime method it serves, by name, in place of the contract's own (after the
59
66
  * review: `artifact.publish` and `assets.delete` need a click and a yes; `assets.upload` a yes
60
67
  * where uploaded code may run). Every one applies on top of `gates`. `[]`: none of its own.
68
+ * A call that runs other methods runs under theirs too (P094): a db `batch` under each of its
69
+ * writes' (`set`, `update`, `delete`; one confirmation for the whole batch, a rate counting each
70
+ * write), a `watch` under `get`'s (a document) or `query`'s (a collection), checked when it
71
+ * starts: its updates are its answers, so a rate counts once per watch, not per update.
61
72
  */
62
73
  readonly methodGates?: Readonly<Record<string, readonly Gate[]>>;
63
74
  }
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  CAPABILITY_NAMES,
3
+ capabilitySpec,
3
4
  isCapabilityName,
4
5
  type CapabilityName,
5
6
  type Gate,
6
7
  } from "./capabilities.ts";
8
+ import { configWarnings, type ConfigWarning } from "./warnings.ts";
7
9
  import {
8
10
  RUNTIME_HOST_FUNCTIONS,
9
11
  RUNTIME_VERSIONS,
@@ -272,12 +274,20 @@ function positive(value: unknown, path: string, max = Number.MAX_SAFE_INTEGER):
272
274
  }
273
275
 
274
276
  function gate(value: unknown, path: string): asserts value is Gate {
275
- if (value === "user-activation" || value === "confirm" || value === "consent") {
277
+ if (
278
+ value === "user-activation" ||
279
+ value === "confirm" ||
280
+ value === "consent" ||
281
+ value === "show"
282
+ ) {
276
283
  return;
277
284
  }
278
285
  const limit = isObject(value) && isObject(value.rateLimit) ? value.rateLimit : null;
279
286
  if (limit === null || Object.keys(value as object).length !== 1) {
280
- fail(path, 'must be "user-activation", "confirm", "consent" or { rateLimit: { perMinute } }');
287
+ fail(
288
+ path,
289
+ 'must be "user-activation", "confirm", "consent", "show" or { rateLimit: { perMinute } }',
290
+ );
281
291
  return;
282
292
  }
283
293
  only(limit, ["perMinute"], `${path}.rateLimit`);
@@ -287,8 +297,14 @@ function gate(value: unknown, path: string): asserts value is Gate {
287
297
  const MODES = ["inline", "artifact", "mcp-app", "url"];
288
298
  const ISOLATIONS = ["opaque", "domain", "external"];
289
299
 
290
- /** Returns `input` as a config once every field checks out; throws a `ConfigError` otherwise. */
291
- export function validateConfig(input: unknown): PortholeConfig {
300
+ /**
301
+ * Returns `input` as a config once every field checks out; throws a `ConfigError` otherwise.
302
+ * `onWarning` hears each `ConfigWarning` a valid config earns (`configWarnings`).
303
+ */
304
+ export function validateConfig(
305
+ input: unknown,
306
+ options: { readonly onWarning?: (warning: ConfigWarning) => void } = {},
307
+ ): PortholeConfig {
292
308
  const config = object(input, "config");
293
309
  only(
294
310
  config,
@@ -329,7 +345,11 @@ export function validateConfig(input: unknown): PortholeConfig {
329
345
  fail(path, `is not a capability (${CAPABILITY_NAMES.join(", ")})`);
330
346
  }
331
347
  const capability = object(value, path);
332
- only(capability, ["gates", "connect", "resource", "guide", "levels", "methodGates"], path);
348
+ only(
349
+ capability,
350
+ ["gates", "connect", "resource", "guide", "levels", "methodGates", "withoutShow"],
351
+ path,
352
+ );
333
353
  if (capability.methodGates !== undefined) {
334
354
  const family = familyOf(name as CapabilityName);
335
355
  for (const [method, gates] of Object.entries(
@@ -387,6 +407,21 @@ export function validateConfig(input: unknown): PortholeConfig {
387
407
  gate(each, `${path}.gates[${index}]`),
388
408
  );
389
409
  }
410
+ // Leaving the default `show` out on purpose (P100): only where there is one, left out.
411
+ if (capability.withoutShow !== undefined) {
412
+ if (capability.withoutShow !== true) {
413
+ fail(`${path}.withoutShow`, "must be true: it says the gates leave show out on purpose");
414
+ }
415
+ if (!capabilitySpec(name as CapabilityName).defaultGates.includes("show")) {
416
+ fail(`${path}.withoutShow`, `${name} has no show gate to leave out`);
417
+ }
418
+ if (!Array.isArray(capability.gates) || (capability.gates as unknown[]).includes("show")) {
419
+ fail(
420
+ `${path}.withoutShow`,
421
+ "says show is left out, so the gates must be named, without it",
422
+ );
423
+ }
424
+ }
390
425
  sources(capability.connect, `${path}.connect`);
391
426
  sources(capability.resource, `${path}.resource`);
392
427
  if (capability.guide !== undefined && typeof capability.guide !== "string") {
@@ -680,5 +715,8 @@ export function validateConfig(input: unknown): PortholeConfig {
680
715
  });
681
716
  }
682
717
 
718
+ for (const warning of configWarnings(input as PortholeConfig)) {
719
+ options.onWarning?.(warning);
720
+ }
683
721
  return input as PortholeConfig;
684
722
  }
@@ -0,0 +1,42 @@
1
+ import { capabilitySpec, isCapabilityName } from "./capabilities.ts";
2
+ import type { PortholeConfig } from "./schema.ts";
3
+
4
+ /**
5
+ * What a valid config says that its host likely didn't mean (the review of P100): never an error,
6
+ * since the config is the host's to write. Porthole logs nothing itself (no console in library
7
+ * code): `validateConfig(config, { onWarning })` hands each one over, and `compile(config).warnings`
8
+ * (`host.compiled.warnings`) holds them, for a host to log at startup or fail its tests on.
9
+ */
10
+ export interface ConfigWarning {
11
+ /** `model-context-unshown`: a capability whose defaults have `show` lost it to named gates. */
12
+ readonly code: "model-context-unshown";
13
+ readonly path: string;
14
+ readonly message: string;
15
+ }
16
+
17
+ /**
18
+ * Each warning `config` earns. Since 0.8 (P100), `setModelContext`'s defaults have `show`; a
19
+ * config that names its gates (one written for 0.7 did, to change the rate) and leaves `show` out
20
+ * sends content's text to the model unseen, so it is said, unless `withoutShow: true` says the
21
+ * host meant it (its handler shows the person each update, or the content is its own).
22
+ */
23
+ export function configWarnings(config: PortholeConfig): readonly ConfigWarning[] {
24
+ const warnings: ConfigWarning[] = [];
25
+ for (const [name, capability] of Object.entries(config.capabilities)) {
26
+ if (
27
+ !isCapabilityName(name) ||
28
+ capability?.gates === undefined ||
29
+ !capabilitySpec(name).defaultGates.includes("show") ||
30
+ capability.gates.includes("show") ||
31
+ capability.withoutShow === true
32
+ ) {
33
+ continue;
34
+ }
35
+ warnings.push({
36
+ code: "model-context-unshown",
37
+ path: `config.capabilities.${name}.gates`,
38
+ message: `${name}'s gates leave out "show" (P100): what content tells the model reaches it without the person seeing it. Add "show" to the gates, or set withoutShow: true where your handler shows the person each update itself.`,
39
+ });
40
+ }
41
+ return warnings;
42
+ }