@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
@@ -4,12 +4,19 @@ import type { PortholeConfig } from "../config/schema.ts";
4
4
  import { type PageDeclaration } from "../runtime/declaration.ts";
5
5
  import { type ViewerInfo } from "../runtime/levels.ts";
6
6
  import { type Refused } from "./refusal.ts";
7
- import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal } from "./types.ts";
7
+ import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal, Show } from "./types.ts";
8
8
  /**
9
9
  * The host-function bridge: every capability call from a frame passes here, and nowhere else
10
- * reaches a host handler. In order: declared → arguments well formed → not muted → within its
11
- * rate → a user gesture, if gated so → the viewer's consent, if gated so → a person's
12
- * confirmation, if gated so → the handler (or, for a stale-allowed read, the host's cache).
10
+ * reaches a host handler. In order (`call`): the run not stopped (`close`) → declared by the
11
+ * config → declared by the page, where it has a declaration (P086) → before the arguments are
12
+ * read (`precheck`): for the runtime's own, a method by its `op` and the viewer's level, then for
13
+ * every capability its host function's own rate (P091, P095) → arguments well formed and within
14
+ * their limits → who may (P087: the level of each method the call runs for the viewer, a page's
15
+ * named data with or without a viewer, db's rules) → not muted, if confirm-gated → the own rate
16
+ * of each method it runs (P094: a batch's writes count each) → a user gesture, if gated so → the
17
+ * viewer's consent, if gated so → a person's confirmation, if gated so (at most 10 waiting) →
18
+ * shown to the person, if gated so (P100) → the handler (or, for a read, a result the host already
19
+ * gave for it, or for a stale-allowed one the host's cache).
13
20
  */
14
21
  export type BridgeEvent = {
15
22
  readonly type: "resize";
@@ -44,6 +51,11 @@ export interface BridgeOptions {
44
51
  * such call with it, asking nothing (P080).
45
52
  */
46
53
  readonly consent?: Consent | Refused;
54
+ /**
55
+ * Puts a `show`-gated call's whole effect in front of the person before its handler runs (P100).
56
+ * Absent: those calls are refused.
57
+ */
58
+ readonly show?: Show;
47
59
  /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
48
60
  readonly cached?: DataCache;
49
61
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
@@ -72,4 +84,12 @@ export declare function linkTarget(value: unknown): string | null;
72
84
  * no answer: thrown for that call, and the next asks again.
73
85
  */
74
86
  export declare function onceConsent(consent: Consent): Consent;
75
- export declare function createBridge(options: BridgeOptions): HostFunctionBridge;
87
+ /** A display's bridge: `close()` when its run stops (a restart, its end; P095, after the review). */
88
+ export interface DisplayBridge extends HostFunctionBridge {
89
+ /**
90
+ * The run is over: every call waiting for a confirmation is refused at once, a yes that comes
91
+ * later (or its `proceed`) runs nothing, and no new call is taken.
92
+ */
93
+ close(): void;
94
+ }
95
+ export declare function createBridge(options: BridgeOptions): DisplayBridge;
@@ -1,8 +1,10 @@
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
3
  import { callGates, effectiveGates } from "../compile/policy.js";
4
- import { blockedNavigationMessage, withoutSealedAddresses } from "./navigation.js";
5
- import { RUNTIME_HOST_FUNCTIONS, familyOf, methodLevel, methodOf, assetCodeRuns, rosterOf, runtimeCapability, } from "../runtime/contract.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";
6
8
  import { declaredMatch, } from "../runtime/declaration.js";
7
9
  import { dbAccess, parseDbRequest, withMe } from "../runtime/db.js";
8
10
  import { atLeast, higher } from "../runtime/levels.js";
@@ -10,6 +12,13 @@ import { isCodeAsset, parseArtifactRequest, parseAssetRequest, parseCommentReque
10
12
  import { defaultReason, isRefused, pendingReason, reasonOf, } from "./refusal.js";
11
13
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12
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;
13
22
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
14
23
  export function linkTarget(value) {
15
24
  if (typeof value !== "string" || value.length === 0 || value.length > MAX_URL) {
@@ -34,6 +43,125 @@ function resourceUri(args) {
34
43
  const uri = isRecord(args) ? args.uri : undefined;
35
44
  return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
36
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
+ }
37
165
  const VALIDATORS = {
38
166
  sendPrompt: (args, config) => {
39
167
  const text = isRecord(args) ? args.text : undefined;
@@ -49,7 +177,11 @@ const VALIDATORS = {
49
177
  },
50
178
  downloadFile: (args) => {
51
179
  const contents = isRecord(args) ? args.contents : undefined;
52
- 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)
53
185
  ? { contents }
54
186
  : null;
55
187
  },
@@ -61,24 +193,11 @@ const VALIDATORS = {
61
193
  return null;
62
194
  }
63
195
  const given = args.arguments ?? {};
64
- return isRecord(given) ? { name: args.name, arguments: given } : null;
196
+ return isRecord(given) && isJsonData(given) ? { name: args.name, arguments: given } : null;
65
197
  },
66
198
  readData: (args) => resourceUri(args),
67
199
  subscribeData: (args) => resourceUri(args),
68
- setModelContext: (args) => {
69
- if (!isRecord(args)) {
70
- return null;
71
- }
72
- const { content, structuredContent } = args;
73
- if ((content !== undefined && !Array.isArray(content)) ||
74
- (structuredContent !== undefined && !isRecord(structuredContent))) {
75
- return null;
76
- }
77
- return {
78
- ...(content === undefined ? {} : { content }),
79
- ...(structuredContent === undefined ? {} : { structuredContent }),
80
- };
81
- },
200
+ setModelContext: (args) => modelContext(args),
82
201
  reportError: (args, config) => {
83
202
  // A navigation the shell cancelled (P080): Porthole words it, naming the address without its
84
203
  // query; the address itself goes to the host whole.
@@ -91,10 +210,14 @@ const VALIDATORS = {
91
210
  const url = withoutSealedAddresses(blocked);
92
211
  return { message: blockedNavigationMessage(url, config), navigationBlocked: url };
93
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.
94
215
  const message = isRecord(args) ? args.message : undefined;
95
- return typeof message === "string" && message !== ""
96
- ? { message: withoutSealedAddresses(message).slice(0, 2_000) }
97
- : 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 };
98
221
  },
99
222
  copyText: (args) => {
100
223
  const text = isRecord(args) ? args.text : undefined;
@@ -150,6 +273,13 @@ export function onceConsent(consent) {
150
273
  return given;
151
274
  };
152
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
+ }
153
283
  /** What the page declared for one runtime capability, if it declared it. */
154
284
  function declaredOf(declaration, family) {
155
285
  const capabilities = declaration?.capabilities;
@@ -157,12 +287,19 @@ function declaredOf(declaration, family) {
157
287
  ? capabilities[family]
158
288
  : undefined;
159
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";
160
292
  export function createBridge(options) {
161
293
  const { config, display, handlers, onEvent } = options;
162
294
  const now = options.now ?? (() => Date.now());
163
295
  const calls = new Map();
164
296
  let declines = 0;
165
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();
166
303
  const refuse = (capability, refusal, message, reason) => {
167
304
  onEvent({ type: "refused", capability, refusal });
168
305
  return {
@@ -172,67 +309,66 @@ export function createBridge(options) {
172
309
  reason: reason ?? defaultReason(capability, refusal),
173
310
  };
174
311
  };
175
- 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) => {
176
314
  const at = now();
177
- const recent = (calls.get(capability) ?? []).filter((time) => at - time < 60_000);
178
- if (recent.length >= perMinute) {
179
- 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);
180
318
  return false;
181
319
  }
182
- recent.push(at);
183
- calls.set(capability, recent);
320
+ for (let each = 0; each < times; each += 1) {
321
+ recent.push(at);
322
+ }
323
+ calls.set(key, recent);
184
324
  return true;
185
325
  };
186
- /** The least level a call needs: its method's, and a db batch's writes' or a watch's read's. */
187
- function levelOf(capability, family, method, args) {
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) {
188
331
  const declared = declaredOf(options.declaration ?? undefined, family);
189
- const own = methodLevel(config, family, method, declared);
190
- if (capability !== "db" || own === null) {
191
- return own;
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;
192
336
  }
193
- // A batch is each of its writes; a watch is a read (after the review: neither escapes the
194
- // levels of what it does).
195
- const request = args;
196
- const inner = request.op === "batch"
197
- ? request.writes.map((write) => write.op)
198
- : request.op === "watch"
199
- ? [request.path.split("/").length % 2 === 0 ? "get" : "query"]
200
- : [];
201
- return inner.reduce((most, op) => higher(most, methodLevel(config, family, op, declared) ?? most), own);
337
+ return inner.reduce((most, method) => higher(most, methodLevel(config, family, method, declared) ?? most), level);
202
338
  }
203
339
  /**
204
340
  * Whether this viewer may make this call (P087), and the call as the handler gets it: the
205
341
  * call's level (the contract's, the host's, the page's; a batch's writes', a watch's read's),
206
342
  * the resources and tools a page's `data` names, and a `db` call's paths (another person's data
207
343
  * refused, `me` resolved, the page's rules). Without a viewer: the runtime's own are refused,
208
- * and under a runtime anything above view; a 0.6 config's functions run as before.
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).
209
346
  */
210
347
  function checkAudience(capability, family, args) {
211
348
  const { viewer } = options;
212
349
  const declaration = options.declaration ?? undefined;
213
- const method = methodOf(capability, args);
214
- if (method === null) {
350
+ if (methodOf(capability, args) === null) {
215
351
  return args;
216
352
  }
217
- const needed = levelOf(capability, family, method, args);
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);
218
357
  if (viewer === undefined) {
219
358
  if (RUNTIME_HOST_FUNCTIONS.includes(capability)) {
220
359
  return "level";
221
360
  }
222
361
  // Under a runtime, a level the host set is never skipped for want of a viewer.
223
- return config.runtime !== undefined && needed !== null && needed !== "view" ? "level" : args;
362
+ if (config.runtime !== undefined && needed !== null && needed !== "view") {
363
+ return "level";
364
+ }
365
+ return named ? args : "undeclared";
224
366
  }
225
367
  if (needed !== null && !atLeast(viewer.level, needed)) {
226
368
  return "level";
227
369
  }
228
- if (family === "data" && declaration !== undefined) {
229
- const data = declaration.capabilities.data;
230
- const named = capability === "callTool"
231
- ? declaredMatch(data?.tools, args.name)
232
- : declaredMatch(data?.resources, args.uri);
233
- if (!named) {
234
- return "undeclared";
235
- }
370
+ if (!named) {
371
+ return "undeclared";
236
372
  }
237
373
  if (capability === "db") {
238
374
  const rules = declaration?.capabilities.db?.rules;
@@ -250,13 +386,14 @@ export function createBridge(options) {
250
386
  return args;
251
387
  }
252
388
  /**
253
- * The cheap checks for the runtime's own, before their arguments are read (after the review: a
254
- * malformed call costs nothing but its rate): a method by its `op`, a viewer at its level, its
255
- * host function's rate.
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).
256
393
  */
257
394
  function precheck(capability, raw) {
258
395
  if (!RUNTIME_HOST_FUNCTIONS.includes(capability)) {
259
- return null;
396
+ return withinOwnRates(capability) ? null : "rate-limited";
260
397
  }
261
398
  const family = familyOf(capability);
262
399
  const method = methodOf(capability, raw);
@@ -268,19 +405,33 @@ export function createBridge(options) {
268
405
  if (viewer === undefined || (needed !== null && !atLeast(viewer.level, needed))) {
269
406
  return "level";
270
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) {
271
412
  for (const gate of effectiveGates(config, capability)) {
272
413
  if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
273
- return "rate-limited";
414
+ return false;
274
415
  }
275
416
  }
276
- return null;
417
+ return true;
277
418
  }
278
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
+ },
279
427
  declared: (capability) => config.capabilities[capability] !== undefined,
280
428
  roster: () => rosterOf(config, options.declaration === undefined || options.declaration === null
281
429
  ? []
282
430
  : Object.keys(options.declaration.capabilities)),
283
431
  async call(capability, raw, callOptions) {
432
+ if (closed) {
433
+ return refuse(capability, "failed", STOPPED);
434
+ }
284
435
  if (config.capabilities[capability] === undefined) {
285
436
  return refuse(capability, "not-declared");
286
437
  }
@@ -316,23 +467,30 @@ export function createBridge(options) {
316
467
  }
317
468
  args = audience;
318
469
  }
319
- // Its host function's gates, and its method's own (after the review): all apply.
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.
320
472
  const gates = callGates(config, capability, args);
321
473
  const own = new Set(effectiveGates(config, capability));
322
474
  const confirms = gates.includes("confirm");
323
475
  if (confirms && muted) {
324
476
  return refuse(capability, "muted");
325
477
  }
326
- const method = family === null ? null : methodOf(capability, args);
327
- for (const gate of gates) {
328
- if (typeof gate !== "object") {
329
- continue;
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);
330
485
  }
331
- // The runtime's own were counted before their arguments were read (`precheck`).
332
- const counted = own.has(gate) && RUNTIME_HOST_FUNCTIONS.includes(capability);
333
- const key = own.has(gate) ? capability : `${capability}.${method ?? ""}`;
334
- if (!counted && !withinRate(key, gate.rateLimit.perMinute)) {
335
- return refuse(capability, "rate-limited");
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
+ }
336
494
  }
337
495
  }
338
496
  if (gates.includes("user-activation")) {
@@ -362,21 +520,92 @@ export function createBridge(options) {
362
520
  return refuse(capability, "denied");
363
521
  }
364
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
+ };
365
558
  // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
366
559
  // effect that needs a gesture gets one), or after `confirm` resolves accepted.
367
560
  let effect = null;
368
- 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));
369
567
  if (confirms) {
370
568
  if (options.confirm === undefined) {
371
569
  return refuse(capability, "no-confirm");
372
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
+ }
373
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
+ });
374
584
  try {
375
- 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
+ ]);
376
598
  }
377
599
  catch {
378
600
  answer = effect === null ? false : "accepted";
379
601
  }
602
+ finally {
603
+ waiting -= 1;
604
+ ending.delete(end);
605
+ }
606
+ if (closed && effect === null) {
607
+ return refuse(capability, "failed", STOPPED);
608
+ }
380
609
  if (effect === null && answer !== true && answer !== "accepted") {
381
610
  if (answer === "redirected") {
382
611
  return refuse(capability, "redirected");
@@ -428,6 +657,15 @@ export function createBridge(options) {
428
657
  },
429
658
  };
430
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
+ }
431
669
  const handler = handlers[capability];
432
670
  if (handler === undefined) {
433
671
  return refuse(capability, "not-declared");
@@ -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;