@botiverse/porthole 0.6.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 (208) hide show
  1. package/README.md +25 -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 +38 -5
  6. package/dist/bridge/bridge.js +469 -39
  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.d.ts +5 -1
  12. package/dist/bridge/refusal.js +17 -0
  13. package/dist/bridge/types.d.ts +73 -5
  14. package/dist/check/check.d.ts +7 -0
  15. package/dist/check/check.js +1 -0
  16. package/dist/check/instrument.d.ts +3 -0
  17. package/dist/check/lint.js +4 -2
  18. package/dist/check/page-source.js +1 -1
  19. package/dist/check/page.js +16 -0
  20. package/dist/check/tools.js +2 -3
  21. package/dist/compile/compile.d.ts +6 -0
  22. package/dist/compile/compile.js +3 -1
  23. package/dist/compile/policy.d.ts +55 -0
  24. package/dist/compile/policy.js +157 -0
  25. package/dist/config/capabilities.d.ts +85 -7
  26. package/dist/config/capabilities.js +32 -2
  27. package/dist/config/schema.d.ts +35 -0
  28. package/dist/config/validate.d.ts +9 -3
  29. package/dist/config/validate.js +92 -8
  30. package/dist/config/warnings.d.ts +20 -0
  31. package/dist/config/warnings.js +25 -0
  32. package/dist/conformance/behavior.js +46 -1
  33. package/dist/conformance/cookies.d.ts +15 -0
  34. package/dist/conformance/cookies.js +80 -0
  35. package/dist/conformance/harness/page.d.ts +1 -0
  36. package/dist/conformance/harness/page.js +9 -2
  37. package/dist/conformance/harness-source.js +1 -1
  38. package/dist/conformance/host-kit.js +5 -1
  39. package/dist/conformance/index.d.ts +11 -0
  40. package/dist/conformance/index.js +2 -0
  41. package/dist/conformance/limits.js +38 -1
  42. package/dist/conformance/runtime.d.ts +58 -0
  43. package/dist/conformance/runtime.js +324 -0
  44. package/dist/conformance/served.d.ts +2 -0
  45. package/dist/conformance/served.js +737 -4
  46. package/dist/files/paths.js +4 -0
  47. package/dist/guide/gates.d.ts +9 -0
  48. package/dist/guide/gates.js +31 -0
  49. package/dist/guide/guide.d.ts +2 -0
  50. package/dist/guide/guide.js +35 -33
  51. package/dist/guide/limits.js +4 -4
  52. package/dist/guide/runtime.d.ts +13 -0
  53. package/dist/guide/runtime.js +210 -0
  54. package/dist/host/create-host.js +73 -37
  55. package/dist/host/locate.js +8 -0
  56. package/dist/host/locator.js +7 -0
  57. package/dist/host/pages-of-set.d.ts +43 -0
  58. package/dist/host/pages-of-set.js +196 -0
  59. package/dist/host/types.d.ts +26 -1
  60. package/dist/index.d.ts +11 -4
  61. package/dist/index.js +11 -2
  62. package/dist/isolation/types.d.ts +8 -0
  63. package/dist/mcp/adapter.js +11 -15
  64. package/dist/node/index.d.ts +36 -4
  65. package/dist/node/index.js +402 -101
  66. package/dist/presets/presets.d.ts +22 -8
  67. package/dist/presets/presets.js +40 -8
  68. package/dist/protocol/live-data.d.ts +6 -2
  69. package/dist/protocol/live-data.js +20 -1
  70. package/dist/protocol/mcp-apps.d.ts +13 -2
  71. package/dist/protocol/mcp-apps.js +10 -2
  72. package/dist/protocol/message-text.d.ts +8 -0
  73. package/dist/protocol/message-text.js +29 -0
  74. package/dist/protocol/runtime-calls.d.ts +28 -0
  75. package/dist/protocol/runtime-calls.js +116 -0
  76. package/dist/protocol/shell-adapter.js +64 -25
  77. package/dist/react/context-notice.d.ts +32 -0
  78. package/dist/react/context-notice.js +28 -0
  79. package/dist/react/dialog.js +91 -16
  80. package/dist/react/frame.d.ts +25 -1
  81. package/dist/react/frame.js +85 -2
  82. package/dist/react/index.d.ts +2 -1
  83. package/dist/react/index.js +2 -1
  84. package/dist/runtime/contract.d.ts +201 -0
  85. package/dist/runtime/contract.js +245 -0
  86. package/dist/runtime/db.d.ts +188 -0
  87. package/dist/runtime/db.js +502 -0
  88. package/dist/runtime/declaration.d.ts +100 -0
  89. package/dist/runtime/declaration.js +363 -0
  90. package/dist/runtime/levels.d.ts +33 -0
  91. package/dist/runtime/levels.js +41 -0
  92. package/dist/runtime/requests.d.ts +125 -0
  93. package/dist/runtime/requests.js +215 -0
  94. package/dist/runtime/segments.d.ts +8 -0
  95. package/dist/runtime/segments.js +14 -0
  96. package/dist/runtime/types.generated.d.ts +1 -0
  97. package/dist/runtime/types.generated.js +19 -0
  98. package/dist/server/files.d.ts +19 -1
  99. package/dist/server/files.js +115 -6
  100. package/dist/server/host.d.ts +24 -2
  101. package/dist/server/host.js +137 -2
  102. package/dist/server/index.d.ts +3 -2
  103. package/dist/server/index.js +2 -1
  104. package/dist/server/peer.d.ts +4 -0
  105. package/dist/server/peer.js +19 -0
  106. package/dist/server/proxy.d.ts +6 -0
  107. package/dist/server/proxy.js +12 -3
  108. package/dist/server/pseudonym.d.ts +9 -0
  109. package/dist/server/pseudonym.js +20 -0
  110. package/dist/server/server.d.ts +0 -5
  111. package/dist/server/server.js +318 -52
  112. package/dist/server/types.d.ts +74 -2
  113. package/dist/shell/document.d.ts +16 -0
  114. package/dist/shell/document.js +19 -2
  115. package/dist/shell/legacy.d.ts +21 -0
  116. package/dist/shell/legacy.js +63 -0
  117. package/dist/shell/plan.d.ts +17 -1
  118. package/dist/shell/plan.js +13 -2
  119. package/dist/shell/runtime.js +390 -56
  120. package/dist/shell/use.d.ts +15 -0
  121. package/dist/shell/use.js +235 -0
  122. package/docs/ADOPTING.md +205 -15
  123. package/docs/ARCHITECTURE.md +34 -5
  124. package/docs/DECISIONS.md +1867 -11
  125. package/docs/DESIGN.md +137 -17
  126. package/docs/THREAT_MODEL.md +616 -0
  127. package/package.json +16 -3
  128. package/src/bridge/bounded-text.ts +240 -0
  129. package/src/bridge/bridge.ts +601 -51
  130. package/src/bridge/json-data.ts +95 -0
  131. package/src/bridge/navigation.ts +10 -0
  132. package/src/bridge/refusal.ts +17 -0
  133. package/src/bridge/types.ts +76 -5
  134. package/src/check/check.ts +8 -0
  135. package/src/check/instrument.ts +3 -0
  136. package/src/check/lint.ts +4 -2
  137. package/src/check/page.ts +16 -0
  138. package/src/check/tools.ts +2 -3
  139. package/src/compile/compile.ts +9 -1
  140. package/src/compile/policy.ts +177 -0
  141. package/src/config/capabilities.ts +71 -5
  142. package/src/config/schema.ts +35 -0
  143. package/src/config/validate.ts +141 -8
  144. package/src/config/warnings.ts +42 -0
  145. package/src/conformance/behavior.ts +54 -1
  146. package/src/conformance/cookies.ts +93 -0
  147. package/src/conformance/harness/page.ts +11 -2
  148. package/src/conformance/host-kit.ts +10 -1
  149. package/src/conformance/index.ts +17 -0
  150. package/src/conformance/limits.ts +39 -1
  151. package/src/conformance/runtime.ts +594 -0
  152. package/src/conformance/served.ts +888 -4
  153. package/src/files/paths.ts +4 -0
  154. package/src/guide/gates.ts +37 -0
  155. package/src/guide/guide.ts +61 -55
  156. package/src/guide/limits.ts +4 -4
  157. package/src/guide/runtime.ts +253 -0
  158. package/src/host/create-host.ts +88 -36
  159. package/src/host/locate.ts +10 -0
  160. package/src/host/locator.ts +11 -0
  161. package/src/host/pages-of-set.ts +226 -0
  162. package/src/host/types.ts +33 -1
  163. package/src/index.ts +94 -0
  164. package/src/isolation/types.ts +8 -0
  165. package/src/mcp/adapter.ts +16 -20
  166. package/src/node/index.ts +507 -116
  167. package/src/presets/presets.ts +67 -17
  168. package/src/protocol/live-data.ts +31 -3
  169. package/src/protocol/mcp-apps.ts +11 -2
  170. package/src/protocol/message-text.ts +36 -0
  171. package/src/protocol/runtime-calls.ts +141 -0
  172. package/src/protocol/shell-adapter.ts +79 -26
  173. package/src/react/context-notice.tsx +95 -0
  174. package/src/react/dialog.tsx +108 -15
  175. package/src/react/frame.tsx +120 -0
  176. package/src/react/index.ts +8 -1
  177. package/src/runtime/contract.ts +339 -0
  178. package/src/runtime/db.ts +650 -0
  179. package/src/runtime/declaration.ts +516 -0
  180. package/src/runtime/levels.ts +69 -0
  181. package/src/runtime/requests.ts +355 -0
  182. package/src/runtime/segments.ts +17 -0
  183. package/src/runtime/types.generated.ts +19 -0
  184. package/src/server/files.ts +138 -7
  185. package/src/server/host.ts +170 -3
  186. package/src/server/index.ts +4 -0
  187. package/src/server/peer.ts +21 -0
  188. package/src/server/proxy.ts +13 -3
  189. package/src/server/pseudonym.ts +21 -0
  190. package/src/server/server.ts +370 -57
  191. package/src/server/types.ts +73 -2
  192. package/src/shell/document.ts +29 -4
  193. package/src/shell/legacy.ts +64 -0
  194. package/src/shell/plan.ts +37 -3
  195. package/src/shell/runtime.ts +390 -56
  196. package/src/shell/use.ts +235 -0
  197. package/types/runtime/v1/artifact.d.ts +50 -0
  198. package/types/runtime/v1/assets.d.ts +43 -0
  199. package/types/runtime/v1/chat.d.ts +13 -0
  200. package/types/runtime/v1/clipboard.d.ts +14 -0
  201. package/types/runtime/v1/comments.d.ts +24 -0
  202. package/types/runtime/v1/context.d.ts +27 -0
  203. package/types/runtime/v1/data.d.ts +29 -0
  204. package/types/runtime/v1/db.d.ts +110 -0
  205. package/types/runtime/v1/downloads.d.ts +22 -0
  206. package/types/runtime/v1/links.d.ts +13 -0
  207. package/types/runtime/v1/porthole.d.ts +44 -0
  208. package/types/runtime/v1/user.d.ts +19 -0
@@ -1,10 +1,24 @@
1
- import { MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
1
+ import { MAX_CONTEXT_CHARS, MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
2
2
  import { parseReport } from "../annotate/validate.js";
3
- import { effectiveGates } from "../compile/policy.js";
4
- import { blockedNavigationMessage, withoutSealedAddresses } from "./navigation.js";
3
+ import { callGates, effectiveGates } from "../compile/policy.js";
4
+ import { boundedText } from "./bounded-text.js";
5
+ import { isJsonData } from "./json-data.js";
6
+ import { blockedNavigationMessage, cutText, withoutSealedAddresses } from "./navigation.js";
7
+ import { RUNTIME_HOST_FUNCTIONS, familyOf, methodGates, methodLevel, methodOf, methodsOfCall, assetCodeRuns, rosterOf, runtimeCapability, } from "../runtime/contract.js";
8
+ import { declaredMatch, } from "../runtime/declaration.js";
9
+ import { dbAccess, parseDbRequest, withMe } from "../runtime/db.js";
10
+ import { atLeast, higher } from "../runtime/levels.js";
11
+ import { isCodeAsset, parseArtifactRequest, parseAssetRequest, parseCommentRequest, } from "../runtime/requests.js";
5
12
  import { defaultReason, isRefused, pendingReason, reasonOf, } from "./refusal.js";
6
13
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
14
  const MAX_URL = 4_096;
15
+ /**
16
+ * The most confirmations one display has waiting at once (P095): past it a call is refused as
17
+ * rate-limited, asking no one (and counted as no decline).
18
+ */
19
+ const MAX_WAITING_CONFIRMS = 10;
20
+ /** The most of an error report the host is told. */
21
+ const MAX_ERROR_CHARS = 2_000;
8
22
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
9
23
  export function linkTarget(value) {
10
24
  if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL) {
@@ -29,6 +43,125 @@ function resourceUri(args) {
29
43
  const uri = isRecord(args) ? args.uri : undefined;
30
44
  return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
31
45
  }
46
+ /** The most text blocks one model context update holds. */
47
+ const MAX_CONTEXT_BLOCKS = 100;
48
+ /**
49
+ * What a person can't see but a model reads (the review of P100): format characters (zero-width
50
+ * ones, bidi controls, the tags U+E0000–E007F, a soft hyphen, a byte-order mark), variation
51
+ * selectors (U+FE00–FE0F, U+E0100–E01EF), private-use characters, lone surrogates, every
52
+ * default-ignorable code point (the re-check: U+034F, Mongolian's free variation selectors, the
53
+ * Hangul fillers, Khmer's inherent vowels), and controls other than a new line and a tab. An update with any is refused, never escaped: an escaped one
54
+ * reads to the model differently from what the person was shown.
55
+ */
56
+ const UNSEEN = /[\p{Cf}\p{Co}\p{Cs}\p{Default_Ignorable_Code_Point}\u{FE00}-\u{FE0F}\u{E0100}-\u{E01EF}]|[^\P{Cc}\n\t]/u;
57
+ /**
58
+ * The parts of real emoji that draw as nothing alone, allowed only where an emoji has them (the
59
+ * re-review of P100): U+FE0E or U+FE0F directly after a pictograph, or after a keycap base
60
+ * (`[0-9#*]`) that U+20E3 follows; U+200D only between two pictographs, a selector or a skin tone
61
+ * after the first. Each carries at most one choice beside a visible emoji (a selector there or
62
+ * not, a joiner there or not), never letters a model would read. Tag characters stay refused:
63
+ * subdivision flags too.
64
+ */
65
+ const EMOJI_PARTS = "(?<=\\p{Extended_Pictographic})[\\uFE0E\\uFE0F]|(?<=[0-9#*])[\\uFE0E\\uFE0F](?=\\u20E3)|(?<=\\p{Extended_Pictographic}[\\uFE0F\\p{Emoji_Modifier}]?)\\u200D(?=\\p{Extended_Pictographic})";
66
+ /**
67
+ * The scripts whose letters U+200C and U+200D shape (Unicode's notes on the joiners: the cursive
68
+ * scripts, where they break or make a join, and the Indic ones and Myanmar, where they choose a
69
+ * conjunct, a half form or a ligature), by Script_Extensions.
70
+ */
71
+ const SHAPING_SCRIPTS = [
72
+ "Arabic",
73
+ "Syriac",
74
+ "Nko",
75
+ "Mongolian",
76
+ "Devanagari",
77
+ "Bengali",
78
+ "Gurmukhi",
79
+ "Gujarati",
80
+ "Oriya",
81
+ "Tamil",
82
+ "Telugu",
83
+ "Kannada",
84
+ "Malayalam",
85
+ "Sinhala",
86
+ "Myanmar",
87
+ ];
88
+ const SHAPED = `[${SHAPING_SCRIPTS.map((name) => `\\p{scx=${name}}`).join("")}]`;
89
+ /**
90
+ * A joiner or non-joiner between two letters or marks of those scripts (Persian's می‌خواهم, a
91
+ * Hindi half form): the shape it chooses is what the person sees. One at a letter boundary, never
92
+ * doubled, first or last, or beside a letter of another script.
93
+ */
94
+ const SHAPING_JOINERS = `(?<=[\\p{L}\\p{M}])(?<=${SHAPED})[\\u200C\\u200D](?=[\\p{L}\\p{M}])(?=${SHAPED})`;
95
+ /** What may be invisible alone and is allowed where it is seen: one pass, on the text as sent. */
96
+ const SEEN_IN_PLACE = new RegExp(`${EMOJI_PARTS}|${SHAPING_JOINERS}`, "gu");
97
+ /** Whether `text` holds what a person can't see, the parts of emoji and shaped letters aside. */
98
+ const unseen = (text) => UNSEEN.test(text.replace(SEEN_IN_PLACE, ""));
99
+ /** Whether any string in `value`, a key or a value, holds what can't be seen (bounded JSON data). */
100
+ function holdsUnseen(value) {
101
+ if (typeof value === "string") {
102
+ return unseen(value);
103
+ }
104
+ if (value === null || typeof value !== "object") {
105
+ return false;
106
+ }
107
+ if (Array.isArray(value)) {
108
+ return value.some(holdsUnseen);
109
+ }
110
+ return Object.entries(value).some(([key, each]) => unseen(key) || holdsUnseen(each));
111
+ }
112
+ /**
113
+ * A model context update (P100), as the person is shown it and the model reads it: text blocks
114
+ * only (what the host offers, `updateModelContext: { text, structuredContent }`), each rebuilt as
115
+ * `{ type, text }` so nothing rides along unshown (`_meta`, `annotations`); structured content
116
+ * JSON data by P095's one rule (`isJsonData`: each object once, no cycles, bounded); at most
117
+ * `MAX_CONTEXT_CHARS` together as the person is shown it, its JSON measured only once that walk
118
+ * has bounded it; nothing in a text or a string they can't see (`UNSEEN`).
119
+ */
120
+ function modelContext(args) {
121
+ if (!isRecord(args)) {
122
+ return null;
123
+ }
124
+ const { content, structuredContent } = args;
125
+ let chars = 0;
126
+ let blocks;
127
+ if (content !== undefined) {
128
+ if (!Array.isArray(content) || content.length > MAX_CONTEXT_BLOCKS) {
129
+ return null;
130
+ }
131
+ blocks = [];
132
+ for (const block of content) {
133
+ if (!isRecord(block) ||
134
+ block.type !== "text" ||
135
+ typeof block.text !== "string" ||
136
+ unseen(block.text)) {
137
+ return null;
138
+ }
139
+ chars += block.text.length;
140
+ if (chars > MAX_CONTEXT_CHARS) {
141
+ return "too_large";
142
+ }
143
+ blocks.push({ type: "text", text: block.text });
144
+ }
145
+ }
146
+ if (structuredContent !== undefined) {
147
+ // P095's one rule for JSON data; then this update's own size, as the person is shown it.
148
+ if (!isRecord(structuredContent) || !isJsonData(structuredContent)) {
149
+ return null;
150
+ }
151
+ chars += JSON.stringify(structuredContent).length;
152
+ if (chars > MAX_CONTEXT_CHARS) {
153
+ return "too_large";
154
+ }
155
+ // Within the size now: each string, value or key, is walked once.
156
+ if (holdsUnseen(structuredContent)) {
157
+ return null;
158
+ }
159
+ }
160
+ return {
161
+ ...(blocks === undefined ? {} : { content: blocks }),
162
+ ...(structuredContent === undefined ? {} : { structuredContent }),
163
+ };
164
+ }
32
165
  const VALIDATORS = {
33
166
  sendPrompt: (args, config) => {
34
167
  const text = isRecord(args) ? args.text : undefined;
@@ -44,7 +177,11 @@ const VALIDATORS = {
44
177
  },
45
178
  downloadFile: (args) => {
46
179
  const contents = isRecord(args) ? args.contents : undefined;
47
- return Array.isArray(contents) && contents.length > 0 && contents.length <= 100
180
+ // Plain, bounded JSON only (P095): what reaches the dialog and the handler is what MCP says.
181
+ return Array.isArray(contents) &&
182
+ contents.length > 0 &&
183
+ contents.length <= 100 &&
184
+ isJsonData(contents)
48
185
  ? { contents }
49
186
  : null;
50
187
  },
@@ -56,24 +193,11 @@ const VALIDATORS = {
56
193
  return null;
57
194
  }
58
195
  const given = args.arguments ?? {};
59
- return isRecord(given) ? { name: args.name, arguments: given } : null;
196
+ return isRecord(given) && isJsonData(given) ? { name: args.name, arguments: given } : null;
60
197
  },
61
198
  readData: (args) => resourceUri(args),
62
199
  subscribeData: (args) => resourceUri(args),
63
- setModelContext: (args) => {
64
- if (!isRecord(args)) {
65
- return null;
66
- }
67
- const { content, structuredContent } = args;
68
- if ((content !== undefined && !Array.isArray(content)) ||
69
- (structuredContent !== undefined && !isRecord(structuredContent))) {
70
- return null;
71
- }
72
- return {
73
- ...(content === undefined ? {} : { content }),
74
- ...(structuredContent === undefined ? {} : { structuredContent }),
75
- };
76
- },
200
+ setModelContext: (args) => modelContext(args),
77
201
  reportError: (args, config) => {
78
202
  // A navigation the shell cancelled (P080): Porthole words it, naming the address without its
79
203
  // query; the address itself goes to the host whole.
@@ -86,10 +210,14 @@ const VALIDATORS = {
86
210
  const url = withoutSealedAddresses(blocked);
87
211
  return { message: blockedNavigationMessage(url, config), navigationBlocked: url };
88
212
  }
213
+ // What content said (S05, P095): any value, read only now, after its rate (`precheck`), into
214
+ // bounded text, then scrubbed, then cut to what the host is told.
89
215
  const message = isRecord(args) ? args.message : undefined;
90
- return typeof message === "string" && message !== ""
91
- ? { message: withoutSealedAddresses(message).slice(0, 2_000) }
92
- : null;
216
+ if (message === undefined) {
217
+ return null;
218
+ }
219
+ const text = cutText(withoutSealedAddresses(boundedText(message)), MAX_ERROR_CHARS);
220
+ return text === "" ? null : { message: text };
93
221
  },
94
222
  copyText: (args) => {
95
223
  const text = isRecord(args) ? args.text : undefined;
@@ -98,6 +226,13 @@ const VALIDATORS = {
98
226
  : null;
99
227
  },
100
228
  annotate: (args) => parseReport(args),
229
+ // The runtime's own (P088-P090): their shapes and limits, before any gate.
230
+ user: (args) => (args === undefined || isRecord(args) ? {} : null),
231
+ comments: (args) => parseCommentRequest(args),
232
+ artifact: (args, config) => parseArtifactRequest(args, config.limits),
233
+ // Code-typed names only where uploaded code may run (P089, after the review).
234
+ assets: (args, config) => parseAssetRequest(args, config.limits, assetCodeRuns(config)),
235
+ db: (args) => parseDbRequest(args),
101
236
  resize: (args) => {
102
237
  if (!isRecord(args) ||
103
238
  typeof args.height !== "number" ||
@@ -138,12 +273,33 @@ export function onceConsent(consent) {
138
273
  return given;
139
274
  };
140
275
  }
276
+ /** Whether a page's `data` names the resource or tool a data call is for (P086). */
277
+ function dataNamed(declaration, capability, args) {
278
+ const data = declaration.capabilities.data;
279
+ return capability === "callTool"
280
+ ? declaredMatch(data?.tools, args.name)
281
+ : declaredMatch(data?.resources, args.uri);
282
+ }
283
+ /** What the page declared for one runtime capability, if it declared it. */
284
+ function declaredOf(declaration, family) {
285
+ const capabilities = declaration?.capabilities;
286
+ return capabilities !== undefined && Object.hasOwn(capabilities, family)
287
+ ? capabilities[family]
288
+ : undefined;
289
+ }
290
+ /** What a stopped display's calls are refused with (the host's words; its frame is gone). */
291
+ const STOPPED = "the display stopped before this was answered";
141
292
  export function createBridge(options) {
142
293
  const { config, display, handlers, onEvent } = options;
143
294
  const now = options.now ?? (() => Date.now());
144
295
  const calls = new Map();
145
296
  let declines = 0;
146
297
  let muted = false;
298
+ /** Confirmations asked and not yet answered: a frame's calls can't queue without end (P095). */
299
+ let waiting = 0;
300
+ /** Closed (`close`): its run stopped. What each waiting confirmation's wait is ended by. */
301
+ let closed = false;
302
+ const ending = new Set();
147
303
  const refuse = (capability, refusal, message, reason) => {
148
304
  onEvent({ type: "refused", capability, refusal });
149
305
  return {
@@ -153,35 +309,188 @@ export function createBridge(options) {
153
309
  reason: reason ?? defaultReason(capability, refusal),
154
310
  };
155
311
  };
156
- const withinRate = (capability, perMinute) => {
312
+ /** Counts `times` calls against `key`'s rate, unless they would pass it (then none). */
313
+ const withinRate = (key, perMinute, times = 1) => {
157
314
  const at = now();
158
- const recent = (calls.get(capability) ?? []).filter((time) => at - time < 60_000);
159
- if (recent.length >= perMinute) {
160
- calls.set(capability, recent);
315
+ const recent = (calls.get(key) ?? []).filter((time) => at - time < 60_000);
316
+ if (recent.length + times > perMinute) {
317
+ calls.set(key, recent);
161
318
  return false;
162
319
  }
163
- recent.push(at);
164
- calls.set(capability, recent);
320
+ for (let each = 0; each < times; each += 1) {
321
+ recent.push(at);
322
+ }
323
+ calls.set(key, recent);
165
324
  return true;
166
325
  };
326
+ /**
327
+ * The least level a call needs: the highest of the methods it runs (its own, a db batch's
328
+ * writes', a watch's read's: after the review, neither escapes the levels of what it does).
329
+ */
330
+ function levelOf(capability, family, args) {
331
+ const declared = declaredOf(options.declaration ?? undefined, family);
332
+ const [own, ...inner] = methodsOfCall(capability, args);
333
+ const level = own === undefined ? null : methodLevel(config, family, own, declared);
334
+ if (level === null) {
335
+ return null;
336
+ }
337
+ return inner.reduce((most, method) => higher(most, methodLevel(config, family, method, declared) ?? most), level);
338
+ }
339
+ /**
340
+ * Whether this viewer may make this call (P087), and the call as the handler gets it: the
341
+ * call's level (the contract's, the host's, the page's; a batch's writes', a watch's read's),
342
+ * the resources and tools a page's `data` names, and a `db` call's paths (another person's data
343
+ * refused, `me` resolved, the page's rules). Without a viewer: the runtime's own are refused,
344
+ * and under a runtime anything above view; a 0.6 config's functions run as before. The names a
345
+ * page's declaration gives are held whether or not there is a viewer (P094).
346
+ */
347
+ function checkAudience(capability, family, args) {
348
+ const { viewer } = options;
349
+ const declaration = options.declaration ?? undefined;
350
+ if (methodOf(capability, args) === null) {
351
+ return args;
352
+ }
353
+ const needed = levelOf(capability, family, args);
354
+ // What the page's `data` names (P086): the declaration's word, not the viewer's, so it holds
355
+ // without a viewer too (P094). A page with no declaration is 0.6's: the host's handlers decide.
356
+ const named = family !== "data" || declaration === undefined || dataNamed(declaration, capability, args);
357
+ if (viewer === undefined) {
358
+ if (RUNTIME_HOST_FUNCTIONS.includes(capability)) {
359
+ return "level";
360
+ }
361
+ // Under a runtime, a level the host set is never skipped for want of a viewer.
362
+ if (config.runtime !== undefined && needed !== null && needed !== "view") {
363
+ return "level";
364
+ }
365
+ return named ? args : "undeclared";
366
+ }
367
+ if (needed !== null && !atLeast(viewer.level, needed)) {
368
+ return "level";
369
+ }
370
+ if (!named) {
371
+ return "undeclared";
372
+ }
373
+ if (capability === "db") {
374
+ const rules = declaration?.capabilities.db?.rules;
375
+ const access = dbAccess(args, viewer, rules);
376
+ return access.ok ? access.request : "level";
377
+ }
378
+ if (capability === "assets" && args.op === "upload") {
379
+ // What an upload may become (P089): code only an admin added where uploaded code may run.
380
+ const upload = args;
381
+ return {
382
+ ...upload,
383
+ trusted: isCodeAsset(upload.name) && assetCodeRuns(config) && atLeast(viewer.level, "admin"),
384
+ };
385
+ }
386
+ return args;
387
+ }
388
+ /**
389
+ * The cheap checks, before a call's arguments are read (after the review: a malformed call
390
+ * costs nothing but its rate): for the runtime's own, a method by its `op` and a viewer at its
391
+ * level; for every capability, its host function's rate (P095: what content says, in any shape,
392
+ * is read only within it).
393
+ */
394
+ function precheck(capability, raw) {
395
+ if (!RUNTIME_HOST_FUNCTIONS.includes(capability)) {
396
+ return withinOwnRates(capability) ? null : "rate-limited";
397
+ }
398
+ const family = familyOf(capability);
399
+ const method = methodOf(capability, raw);
400
+ if (family === null || method === null) {
401
+ return "invalid";
402
+ }
403
+ const viewer = options.viewer;
404
+ const needed = methodLevel(config, family.name, method, declaredOf(options.declaration ?? undefined, family.name));
405
+ if (viewer === undefined || (needed !== null && !atLeast(viewer.level, needed))) {
406
+ return "level";
407
+ }
408
+ return withinOwnRates(capability) ? null : "rate-limited";
409
+ }
410
+ /** Whether a call is within its host function's own rates, each counted. */
411
+ function withinOwnRates(capability) {
412
+ for (const gate of effectiveGates(config, capability)) {
413
+ if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
414
+ return false;
415
+ }
416
+ }
417
+ return true;
418
+ }
167
419
  return {
420
+ close() {
421
+ closed = true;
422
+ // Each ends a wait; the wait leaves the set later, in its own `finally`.
423
+ for (const end of ending) {
424
+ end();
425
+ }
426
+ },
168
427
  declared: (capability) => config.capabilities[capability] !== undefined,
428
+ roster: () => rosterOf(config, options.declaration === undefined || options.declaration === null
429
+ ? []
430
+ : Object.keys(options.declaration.capabilities)),
169
431
  async call(capability, raw, callOptions) {
432
+ if (closed) {
433
+ return refuse(capability, "failed", STOPPED);
434
+ }
170
435
  if (config.capabilities[capability] === undefined) {
171
436
  return refuse(capability, "not-declared");
172
437
  }
173
- const args = VALIDATORS[capability](raw, config);
174
- if (args === null) {
438
+ // The page's declaration (P086): a built-in needs none; any other runtime capability only
439
+ // a page that declared it reaches; a page with no declaration, none of the runtime's own.
440
+ const family = familyOf(capability);
441
+ // No declaration, or the host's explicit null for a page from before 0.7 (P086).
442
+ const declaration = options.declaration ?? undefined;
443
+ if (family !== null &&
444
+ !runtimeCapability(family.name).builtIn &&
445
+ (declaration === undefined
446
+ ? RUNTIME_HOST_FUNCTIONS.includes(capability)
447
+ : !Object.hasOwn(declaration.capabilities, family.name))) {
448
+ return refuse(capability, "undeclared");
449
+ }
450
+ const early = precheck(capability, raw);
451
+ if (early !== null) {
452
+ return refuse(capability, early);
453
+ }
454
+ const parsed = VALIDATORS[capability](raw, config);
455
+ if (parsed === null) {
175
456
  return refuse(capability, "invalid");
176
457
  }
177
- const gates = effectiveGates(config, capability);
458
+ if (parsed === "too_large") {
459
+ return refuse(capability, "too-large");
460
+ }
461
+ let args = parsed;
462
+ // Who may (P087): the method's level against the viewer's, the page's own narrowing.
463
+ if (family !== null) {
464
+ const audience = checkAudience(capability, family.name, args);
465
+ if (audience === "undeclared" || audience === "level") {
466
+ return refuse(capability, audience);
467
+ }
468
+ args = audience;
469
+ }
470
+ // Its host function's gates, and the own gates of each method it runs (after the review;
471
+ // P094: a db batch's writes', a watch's read's): all apply.
472
+ const gates = callGates(config, capability, args);
473
+ const own = new Set(effectiveGates(config, capability));
178
474
  const confirms = gates.includes("confirm");
179
475
  if (confirms && muted) {
180
476
  return refuse(capability, "muted");
181
477
  }
182
- for (const gate of gates) {
183
- if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
184
- return refuse(capability, "rate-limited");
478
+ // Its host function's own rate was counted before its arguments were read (`precheck`).
479
+ // A method's rate counts each time the call runs it, with its direct calls: a batch of
480
+ // three sets is three sets (P094).
481
+ if (family !== null) {
482
+ const times = new Map();
483
+ for (const method of methodsOfCall(capability, args)) {
484
+ times.set(method, (times.get(method) ?? 0) + 1);
485
+ }
486
+ for (const [method, count] of times) {
487
+ for (const gate of methodGates(config, family.name, method)) {
488
+ if (typeof gate === "object" &&
489
+ !own.has(gate) &&
490
+ !withinRate(`${capability}.${method}`, gate.rateLimit.perMinute, count)) {
491
+ return refuse(capability, "rate-limited");
492
+ }
493
+ }
185
494
  }
186
495
  }
187
496
  if (gates.includes("user-activation")) {
@@ -211,21 +520,92 @@ export function createBridge(options) {
211
520
  return refuse(capability, "denied");
212
521
  }
213
522
  }
523
+ // The run may have stopped while the viewer's consent was awaited: then no one is asked.
524
+ if (closed) {
525
+ return refuse(capability, "failed", STOPPED);
526
+ }
527
+ // Shown to the person first (P100): only a call that will go, so after their yes; nobody
528
+ // shown it (no `show`, one that failed, a run that stopped meanwhile), it doesn't go.
529
+ const shows = gates.includes("show");
530
+ if (shows && options.show === undefined) {
531
+ return refuse(capability, "no-show");
532
+ }
533
+ const shown = async () => {
534
+ let end = () => { };
535
+ const ended = new Promise((resolve) => {
536
+ end = () => resolve(STOPPED);
537
+ ending.add(end);
538
+ });
539
+ try {
540
+ // Called now (inside a confirm's click, where it runs from `proceed`); a show that never
541
+ // ends is ended by `close`, like a confirmation.
542
+ await Promise.race([
543
+ (async () => options.show?.({ capability, args, display }))(),
544
+ ended,
545
+ ]);
546
+ }
547
+ catch (error) {
548
+ return refuse(capability, "failed", error instanceof Error ? error.message : String(error));
549
+ }
550
+ finally {
551
+ ending.delete(end);
552
+ }
553
+ if (closed) {
554
+ return refuse(capability, "failed", STOPPED);
555
+ }
556
+ return perform(capability, args, callOptions);
557
+ };
214
558
  // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
215
559
  // effect that needs a gesture gets one), or after `confirm` resolves accepted.
216
560
  let effect = null;
217
- const run = () => (effect ??= perform(capability, args, callOptions));
561
+ // Never once the bridge is closed: a yes to a stopped run's request does nothing.
562
+ const run = () => (effect ??= closed
563
+ ? Promise.resolve(refuse(capability, "failed", STOPPED))
564
+ : shows
565
+ ? shown()
566
+ : perform(capability, args, callOptions));
218
567
  if (confirms) {
219
568
  if (options.confirm === undefined) {
220
569
  return refuse(capability, "no-confirm");
221
570
  }
571
+ if (waiting >= MAX_WAITING_CONFIRMS) {
572
+ return refuse(capability, "rate-limited", undefined, {
573
+ code: "rate_limited",
574
+ message: "Too many confirmations are waiting: try again once they are answered.",
575
+ });
576
+ }
222
577
  let answer = false;
578
+ waiting += 1;
579
+ let end = () => { };
580
+ const ended = new Promise((resolve) => {
581
+ end = () => resolve(STOPPED);
582
+ ending.add(end);
583
+ });
223
584
  try {
224
- answer = await options.confirm({ capability, args, display }, () => void run());
585
+ // Which of the methods the call runs asked for this yes (P094): a batch's gated writes.
586
+ const askedBy = family === null
587
+ ? []
588
+ : [...new Set(methodsOfCall(capability, args))].filter((each) => methodGates(config, family.name, each).includes("confirm"));
589
+ answer = await Promise.race([
590
+ options.confirm({
591
+ capability,
592
+ args,
593
+ display,
594
+ ...(askedBy.length === 0 ? {} : { askedBy }),
595
+ }, () => void run()),
596
+ ended,
597
+ ]);
225
598
  }
226
599
  catch {
227
600
  answer = effect === null ? false : "accepted";
228
601
  }
602
+ finally {
603
+ waiting -= 1;
604
+ ending.delete(end);
605
+ }
606
+ if (closed && effect === null) {
607
+ return refuse(capability, "failed", STOPPED);
608
+ }
229
609
  if (effect === null && answer !== true && answer !== "accepted") {
230
610
  if (answer === "redirected") {
231
611
  return refuse(capability, "redirected");
@@ -262,11 +642,44 @@ export function createBridge(options) {
262
642
  }
263
643
  return { ok: true, value: undefined };
264
644
  }
645
+ if (capabilitySpec(capability).served === "viewer") {
646
+ // `user` (P087): the viewer the host gave the display, and nothing else.
647
+ const viewer = options.viewer;
648
+ if (viewer === undefined) {
649
+ return refuse(capability, "level");
650
+ }
651
+ return {
652
+ ok: true,
653
+ value: {
654
+ id: viewer.id ?? null,
655
+ name: viewer.name ?? null,
656
+ level: viewer.level,
657
+ },
658
+ };
659
+ }
660
+ // A result the host already gave for this read (a subscription's `changed(result)`, the
661
+ // fresh read after a stale answer), past every gate a read has (P094): no handler is asked,
662
+ // and none is needed (P079).
663
+ if (capability === "readData" && callOptions?.held !== undefined) {
664
+ // Kept for another URI (an adapter that mixed its keys): no answer, never that one's data.
665
+ return callOptions.held.uri === args.uri
666
+ ? { ok: true, value: callOptions.held.value }
667
+ : refuse(capability, "invalid");
668
+ }
265
669
  const handler = handlers[capability];
266
670
  if (handler === undefined) {
267
671
  return refuse(capability, "not-declared");
268
672
  }
269
- const context = { displayId: display.id, title: display.title, capability };
673
+ const family = familyOf(capability);
674
+ const declared = family === null ? undefined : declaredOf(options.declaration ?? undefined, family.name);
675
+ const context = {
676
+ displayId: display.id,
677
+ title: display.title,
678
+ capability,
679
+ ...(display.instance === undefined ? {} : { instance: display.instance }),
680
+ ...(options.viewer === undefined ? {} : { viewer: options.viewer }),
681
+ ...(declared === undefined ? {} : { declared }),
682
+ };
270
683
  // A read the content subscribes to may be answered from the host's cache, marked stale; the
271
684
  // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
272
685
  if (capability === "readData" && callOptions?.stale === true && options.cached) {
@@ -281,11 +694,28 @@ export function createBridge(options) {
281
694
  }
282
695
  }
283
696
  const subscription = callOptions?.subscription;
284
- if (capability === "subscribeData" && subscription === undefined) {
697
+ // A subscription (`subscribeData`, a `db` watch) needs its channel back.
698
+ const watches = capability === "subscribeData" ||
699
+ (capability === "db" && args.op === "watch");
700
+ if (watches && subscription === undefined) {
285
701
  return refuse(capability, "invalid");
286
702
  }
703
+ // A db answer names the viewer's own tree `me`, never their id (after the review, P088).
704
+ const viewer = options.viewer;
705
+ const channel = watches && subscription !== undefined && capability === "db"
706
+ ? {
707
+ changed: (state) => subscription.changed(withMe(state, viewer)),
708
+ signal: subscription.signal,
709
+ }
710
+ : subscription;
287
711
  try {
288
- const value = await handler(args, capability === "subscribeData" ? { ...context, ...subscription } : context);
712
+ const answered = await handler(args, watches ? { ...context, ...channel } : context);
713
+ const value = capability === "db" ? withMe(answered, viewer) : answered;
714
+ // Comments are write-only (P090): content hears whether the composer opened, never what
715
+ // the host answered beyond that (a thread, its text).
716
+ if (capability === "comments") {
717
+ return { ok: true, value: (value === true) };
718
+ }
289
719
  return { ok: true, value: value };
290
720
  }
291
721
  catch (error) {
@@ -0,0 +1,28 @@
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
+ export interface JsonDataLimits {
18
+ readonly nodes: number;
19
+ readonly depth: number;
20
+ /** The characters of every string and every key, together. */
21
+ readonly chars: number;
22
+ }
23
+ /**
24
+ * A call's: as many values as one db document holds (P091), nested deeper than any real one, and
25
+ * 4 MiB of text.
26
+ */
27
+ export declare const JSON_DATA_LIMITS: JsonDataLimits;
28
+ export declare function isJsonData(value: unknown, limits?: JsonDataLimits): boolean;