@botiverse/porthole 0.5.1 → 0.7.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 (167) hide show
  1. package/README.md +41 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +208 -13
  4. package/dist/bridge/navigation.d.ts +1 -6
  5. package/dist/bridge/navigation.js +11 -0
  6. package/dist/bridge/refusal.d.ts +5 -1
  7. package/dist/bridge/refusal.js +16 -0
  8. package/dist/bridge/types.d.ts +41 -4
  9. package/dist/check/check.d.ts +19 -3
  10. package/dist/check/check.js +55 -8
  11. package/dist/check/files.d.ts +26 -0
  12. package/dist/check/files.js +307 -0
  13. package/dist/check/instrument.d.ts +3 -0
  14. package/dist/check/lint.js +31 -12
  15. package/dist/check/page-source.js +1 -1
  16. package/dist/check/page.js +14 -0
  17. package/dist/check/tools.d.ts +23 -0
  18. package/dist/check/tools.js +27 -3
  19. package/dist/compile/policy.d.ts +34 -0
  20. package/dist/compile/policy.js +74 -0
  21. package/dist/config/capabilities.d.ts +62 -3
  22. package/dist/config/capabilities.js +20 -0
  23. package/dist/config/schema.d.ts +32 -0
  24. package/dist/config/validate.d.ts +1 -1
  25. package/dist/config/validate.js +74 -5
  26. package/dist/conformance/harness-source.js +1 -1
  27. package/dist/conformance/index.d.ts +1 -0
  28. package/dist/conformance/index.js +2 -0
  29. package/dist/conformance/runtime.d.ts +58 -0
  30. package/dist/conformance/runtime.js +314 -0
  31. package/dist/files/paths.d.ts +99 -0
  32. package/dist/files/paths.js +263 -0
  33. package/dist/files/types.d.ts +24 -0
  34. package/dist/files/types.js +83 -0
  35. package/dist/guide/gates.d.ts +3 -0
  36. package/dist/guide/gates.js +19 -0
  37. package/dist/guide/guide.d.ts +2 -0
  38. package/dist/guide/guide.js +44 -32
  39. package/dist/guide/limits.js +4 -4
  40. package/dist/guide/runtime.d.ts +13 -0
  41. package/dist/guide/runtime.js +202 -0
  42. package/dist/host/create-host.js +45 -0
  43. package/dist/host/locate.js +8 -0
  44. package/dist/host/locator.js +7 -0
  45. package/dist/host/types.d.ts +18 -0
  46. package/dist/index.d.ts +13 -4
  47. package/dist/index.js +16 -3
  48. package/dist/isolation/types.d.ts +8 -0
  49. package/dist/presets/presets.d.ts +6 -0
  50. package/dist/presets/presets.js +1 -0
  51. package/dist/protocol/adapter.d.ts +4 -0
  52. package/dist/protocol/mcp-apps.d.ts +6 -0
  53. package/dist/protocol/mcp-apps.js +6 -0
  54. package/dist/protocol/runtime-calls.d.ts +28 -0
  55. package/dist/protocol/runtime-calls.js +113 -0
  56. package/dist/protocol/shell-adapter.js +52 -3
  57. package/dist/react/dialog.js +31 -0
  58. package/dist/react/frame.d.ts +13 -0
  59. package/dist/react/frame.js +6 -0
  60. package/dist/runtime/contract.d.ts +193 -0
  61. package/dist/runtime/contract.js +216 -0
  62. package/dist/runtime/db.d.ts +153 -0
  63. package/dist/runtime/db.js +398 -0
  64. package/dist/runtime/declaration.d.ts +86 -0
  65. package/dist/runtime/declaration.js +266 -0
  66. package/dist/runtime/levels.d.ts +33 -0
  67. package/dist/runtime/levels.js +41 -0
  68. package/dist/runtime/requests.d.ts +125 -0
  69. package/dist/runtime/requests.js +199 -0
  70. package/dist/runtime/segments.d.ts +8 -0
  71. package/dist/runtime/segments.js +14 -0
  72. package/dist/runtime/types.generated.d.ts +1 -0
  73. package/dist/runtime/types.generated.js +19 -0
  74. package/dist/server/files.d.ts +57 -0
  75. package/dist/server/files.js +338 -0
  76. package/dist/server/host.d.ts +44 -2
  77. package/dist/server/host.js +42 -2
  78. package/dist/server/index.d.ts +5 -2
  79. package/dist/server/index.js +5 -1
  80. package/dist/server/keys.d.ts +8 -0
  81. package/dist/server/keys.js +34 -0
  82. package/dist/server/pseudonym.d.ts +9 -0
  83. package/dist/server/pseudonym.js +20 -0
  84. package/dist/server/server.d.ts +0 -5
  85. package/dist/server/server.js +468 -24
  86. package/dist/server/types.d.ts +118 -5
  87. package/dist/shell/document.d.ts +27 -0
  88. package/dist/shell/document.js +46 -2
  89. package/dist/shell/legacy.d.ts +21 -0
  90. package/dist/shell/legacy.js +63 -0
  91. package/dist/shell/plan.d.ts +17 -1
  92. package/dist/shell/plan.js +13 -2
  93. package/dist/shell/runtime.d.ts +2 -1
  94. package/dist/shell/runtime.js +114 -46
  95. package/dist/shell/use.d.ts +15 -0
  96. package/dist/shell/use.js +235 -0
  97. package/docs/ADOPTING.md +142 -5
  98. package/docs/ARCHITECTURE.md +34 -5
  99. package/docs/DECISIONS.md +716 -7
  100. package/docs/DESIGN.md +97 -3
  101. package/package.json +3 -1
  102. package/src/bridge/bridge.ts +281 -17
  103. package/src/bridge/navigation.ts +12 -0
  104. package/src/bridge/refusal.ts +16 -0
  105. package/src/bridge/types.ts +46 -4
  106. package/src/check/check.ts +100 -14
  107. package/src/check/files.ts +384 -0
  108. package/src/check/instrument.ts +3 -0
  109. package/src/check/lint.ts +33 -12
  110. package/src/check/page.ts +14 -0
  111. package/src/check/tools.ts +52 -3
  112. package/src/compile/policy.ts +92 -0
  113. package/src/config/capabilities.ts +49 -2
  114. package/src/config/schema.ts +32 -0
  115. package/src/config/validate.ts +107 -5
  116. package/src/conformance/index.ts +7 -0
  117. package/src/conformance/runtime.ts +573 -0
  118. package/src/files/paths.ts +323 -0
  119. package/src/files/types.ts +101 -0
  120. package/src/guide/gates.ts +25 -0
  121. package/src/guide/guide.ts +78 -52
  122. package/src/guide/limits.ts +4 -4
  123. package/src/guide/runtime.ts +244 -0
  124. package/src/host/create-host.ts +55 -0
  125. package/src/host/locate.ts +10 -0
  126. package/src/host/locator.ts +11 -0
  127. package/src/host/types.ts +18 -0
  128. package/src/index.ts +121 -0
  129. package/src/isolation/types.ts +8 -0
  130. package/src/presets/presets.ts +7 -0
  131. package/src/protocol/adapter.ts +3 -1
  132. package/src/protocol/mcp-apps.ts +7 -0
  133. package/src/protocol/runtime-calls.ts +138 -0
  134. package/src/protocol/shell-adapter.ts +56 -2
  135. package/src/react/dialog.tsx +33 -0
  136. package/src/react/frame.tsx +19 -0
  137. package/src/runtime/contract.ts +305 -0
  138. package/src/runtime/db.ts +530 -0
  139. package/src/runtime/declaration.ts +378 -0
  140. package/src/runtime/levels.ts +69 -0
  141. package/src/runtime/requests.ts +339 -0
  142. package/src/runtime/segments.ts +17 -0
  143. package/src/runtime/types.generated.ts +19 -0
  144. package/src/server/files.ts +425 -0
  145. package/src/server/host.ts +84 -3
  146. package/src/server/index.ts +22 -0
  147. package/src/server/keys.ts +53 -0
  148. package/src/server/pseudonym.ts +21 -0
  149. package/src/server/server.ts +565 -26
  150. package/src/server/types.ts +124 -4
  151. package/src/shell/document.ts +74 -4
  152. package/src/shell/legacy.ts +64 -0
  153. package/src/shell/plan.ts +37 -3
  154. package/src/shell/runtime.ts +114 -46
  155. package/src/shell/use.ts +235 -0
  156. package/types/runtime/v1/artifact.d.ts +50 -0
  157. package/types/runtime/v1/assets.d.ts +43 -0
  158. package/types/runtime/v1/chat.d.ts +13 -0
  159. package/types/runtime/v1/clipboard.d.ts +14 -0
  160. package/types/runtime/v1/comments.d.ts +24 -0
  161. package/types/runtime/v1/context.d.ts +16 -0
  162. package/types/runtime/v1/data.d.ts +29 -0
  163. package/types/runtime/v1/db.d.ts +110 -0
  164. package/types/runtime/v1/downloads.d.ts +22 -0
  165. package/types/runtime/v1/links.d.ts +13 -0
  166. package/types/runtime/v1/porthole.d.ts +44 -0
  167. package/types/runtime/v1/user.d.ts +19 -0
package/README.md CHANGED
@@ -52,6 +52,47 @@ display.setContent("<p>Hello from an agent</p>");
52
52
  In React: `<PortholeProvider>` around `<PortholeFrame config displayId title scheme content />` from
53
53
  `@botiverse/porthole/react`.
54
54
 
55
+ ## Pages made of many files
56
+
57
+ A served page may come with files of its own: a build's output, a report with its images, a
58
+ dashboard that reads its data (0.6). The store answers a manifest and the bytes by path, and the
59
+ page's relative addresses are its own version's:
60
+
61
+ ```js
62
+ source: async (id, version) => ({
63
+ files: { "index.html": { size: 397, sha256: "…" }, "assets/app.js": { size: 142870, sha256: "…" } },
64
+ read: (path) => myStore.bytes(id, version, path), // Uint8Array or a stream, whole
65
+ }),
66
+ entry: {
67
+ // "/v/3/<file>" is version 3, any other path the latest's: answer with the version's own address.
68
+ at: async (scope, path) => {
69
+ const at = versionedAddress(path), version = at?.version ?? (await latestOf(scope));
70
+ return at && { instance: pageOf(scope, version), base: versionBase(version), file: at.file, pinned: true };
71
+ },
72
+ },
73
+ ```
74
+
75
+ Each file is served from the manifest only, typed by Porthole's own table, `nosniff`, with a CSP
76
+ that opens that version's path and nothing else of its origin; `checkFileSet` checks a version's
77
+ paths and limits when it is published, `lintFiles` and `checkPage({ files })` are the agent's
78
+ side. docs/ADOPTING.md § Pages made of many files.
79
+
80
+ ## A page that is an app: the capability runtime
81
+
82
+ With `runtime: "1"` in its config (0.7), a page reaches its host through one global, for what it
83
+ declared when it was published and what its viewer's level allows:
84
+
85
+ ```js
86
+ const db = await porthole.use("db"); // a frozen namespace, or null: draw without it
87
+ const votes = db && (await db.query("votes")).docs; // a refusal rejects with error.code and a sentence
88
+ ```
89
+
90
+ The host keeps the services: its handlers (`db`, `artifact`, `assets`, `comments`; `user` is the
91
+ viewer it gives), `declareCapabilities` at publish, the viewer's level in its access
92
+ (`Grant.level`), and an asset store `/server` serves at `/_blob/<id>`. `defineRuntimeConformance`
93
+ checks the handlers. The types: `types/runtime/v1/*.d.ts`. docs/ADOPTING.md § The capability
94
+ runtime.
95
+
55
96
  ## What the agent gets
56
97
 
57
98
  ```js
@@ -1,6 +1,8 @@
1
1
  import { type CapabilityName } from "../config/capabilities.ts";
2
2
  import type { AnnotationReport } from "../annotate/types.ts";
3
3
  import type { PortholeConfig } from "../config/schema.ts";
4
+ import { type PageDeclaration } from "../runtime/declaration.ts";
5
+ import { type ViewerInfo } from "../runtime/levels.ts";
4
6
  import { type Refused } from "./refusal.ts";
5
7
  import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal } from "./types.ts";
6
8
  /**
@@ -49,6 +51,17 @@ export interface BridgeOptions {
49
51
  readonly onEvent: (event: BridgeEvent) => void;
50
52
  /** The clock, in milliseconds (tests pass their own). */
51
53
  readonly now?: () => number;
54
+ /**
55
+ * Who is viewing (P087), as the host said: each runtime method's level is checked against it,
56
+ * and the runtime's own host functions need it. Absent: 0.6's functions run unchecked, as before.
57
+ */
58
+ readonly viewer?: ViewerInfo;
59
+ /**
60
+ * What the display's page declared (P086), checked against the config (`checkDeclaration`).
61
+ * Absent: a page without one (0.6's): built-ins only through the runtime, and 0.6's globals and
62
+ * requests as before.
63
+ */
64
+ readonly declaration?: PageDeclaration | null;
52
65
  }
53
66
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
54
67
  export declare function linkTarget(value: unknown): string | null;
@@ -1,7 +1,12 @@
1
1
  import { 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 } from "./navigation.js";
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";
6
+ import { declaredMatch, } from "../runtime/declaration.js";
7
+ import { dbAccess, parseDbRequest, withMe } from "../runtime/db.js";
8
+ import { atLeast, higher } from "../runtime/levels.js";
9
+ import { isCodeAsset, parseArtifactRequest, parseAssetRequest, parseCommentRequest, } from "../runtime/requests.js";
5
10
  import { defaultReason, isRefused, pendingReason, reasonOf, } from "./refusal.js";
6
11
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
12
  const MAX_URL = 4_096;
@@ -77,15 +82,18 @@ const VALIDATORS = {
77
82
  reportError: (args, config) => {
78
83
  // A navigation the shell cancelled (P080): Porthole words it, naming the address without its
79
84
  // query; the address itself goes to the host whole.
85
+ // A frame's sealed files' address never reaches the host from here (P083): `./` instead.
80
86
  const blocked = isRecord(args) ? args.navigationBlocked : undefined;
81
87
  if (blocked !== undefined) {
82
- return typeof blocked === "string" && blocked !== "" && blocked.length <= MAX_URL
83
- ? { message: blockedNavigationMessage(blocked, config), navigationBlocked: blocked }
84
- : null;
88
+ if (typeof blocked !== "string" || blocked === "" || blocked.length > MAX_URL) {
89
+ return null;
90
+ }
91
+ const url = withoutSealedAddresses(blocked);
92
+ return { message: blockedNavigationMessage(url, config), navigationBlocked: url };
85
93
  }
86
94
  const message = isRecord(args) ? args.message : undefined;
87
95
  return typeof message === "string" && message !== ""
88
- ? { message: message.slice(0, 2_000) }
96
+ ? { message: withoutSealedAddresses(message).slice(0, 2_000) }
89
97
  : null;
90
98
  },
91
99
  copyText: (args) => {
@@ -95,6 +103,13 @@ const VALIDATORS = {
95
103
  : null;
96
104
  },
97
105
  annotate: (args) => parseReport(args),
106
+ // The runtime's own (P088-P090): their shapes and limits, before any gate.
107
+ user: (args) => (args === undefined || isRecord(args) ? {} : null),
108
+ comments: (args) => parseCommentRequest(args),
109
+ artifact: (args, config) => parseArtifactRequest(args, config.limits),
110
+ // Code-typed names only where uploaded code may run (P089, after the review).
111
+ assets: (args, config) => parseAssetRequest(args, config.limits, assetCodeRuns(config)),
112
+ db: (args) => parseDbRequest(args),
98
113
  resize: (args) => {
99
114
  if (!isRecord(args) ||
100
115
  typeof args.height !== "number" ||
@@ -135,6 +150,13 @@ export function onceConsent(consent) {
135
150
  return given;
136
151
  };
137
152
  }
153
+ /** What the page declared for one runtime capability, if it declared it. */
154
+ function declaredOf(declaration, family) {
155
+ const capabilities = declaration?.capabilities;
156
+ return capabilities !== undefined && Object.hasOwn(capabilities, family)
157
+ ? capabilities[family]
158
+ : undefined;
159
+ }
138
160
  export function createBridge(options) {
139
161
  const { config, display, handlers, onEvent } = options;
140
162
  const now = options.now ?? (() => Date.now());
@@ -161,23 +183,155 @@ export function createBridge(options) {
161
183
  calls.set(capability, recent);
162
184
  return true;
163
185
  };
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) {
188
+ const declared = declaredOf(options.declaration ?? undefined, family);
189
+ const own = methodLevel(config, family, method, declared);
190
+ if (capability !== "db" || own === null) {
191
+ return own;
192
+ }
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);
202
+ }
203
+ /**
204
+ * Whether this viewer may make this call (P087), and the call as the handler gets it: the
205
+ * call's level (the contract's, the host's, the page's; a batch's writes', a watch's read's),
206
+ * the resources and tools a page's `data` names, and a `db` call's paths (another person's data
207
+ * 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.
209
+ */
210
+ function checkAudience(capability, family, args) {
211
+ const { viewer } = options;
212
+ const declaration = options.declaration ?? undefined;
213
+ const method = methodOf(capability, args);
214
+ if (method === null) {
215
+ return args;
216
+ }
217
+ const needed = levelOf(capability, family, method, args);
218
+ if (viewer === undefined) {
219
+ if (RUNTIME_HOST_FUNCTIONS.includes(capability)) {
220
+ return "level";
221
+ }
222
+ // 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;
224
+ }
225
+ if (needed !== null && !atLeast(viewer.level, needed)) {
226
+ return "level";
227
+ }
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
+ }
236
+ }
237
+ if (capability === "db") {
238
+ const rules = declaration?.capabilities.db?.rules;
239
+ const access = dbAccess(args, viewer, rules);
240
+ return access.ok ? access.request : "level";
241
+ }
242
+ if (capability === "assets" && args.op === "upload") {
243
+ // What an upload may become (P089): code only an admin added where uploaded code may run.
244
+ const upload = args;
245
+ return {
246
+ ...upload,
247
+ trusted: isCodeAsset(upload.name) && assetCodeRuns(config) && atLeast(viewer.level, "admin"),
248
+ };
249
+ }
250
+ return args;
251
+ }
252
+ /**
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.
256
+ */
257
+ function precheck(capability, raw) {
258
+ if (!RUNTIME_HOST_FUNCTIONS.includes(capability)) {
259
+ return null;
260
+ }
261
+ const family = familyOf(capability);
262
+ const method = methodOf(capability, raw);
263
+ if (family === null || method === null) {
264
+ return "invalid";
265
+ }
266
+ const viewer = options.viewer;
267
+ const needed = methodLevel(config, family.name, method, declaredOf(options.declaration ?? undefined, family.name));
268
+ if (viewer === undefined || (needed !== null && !atLeast(viewer.level, needed))) {
269
+ return "level";
270
+ }
271
+ for (const gate of effectiveGates(config, capability)) {
272
+ if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
273
+ return "rate-limited";
274
+ }
275
+ }
276
+ return null;
277
+ }
164
278
  return {
165
279
  declared: (capability) => config.capabilities[capability] !== undefined,
280
+ roster: () => rosterOf(config, options.declaration === undefined || options.declaration === null
281
+ ? []
282
+ : Object.keys(options.declaration.capabilities)),
166
283
  async call(capability, raw, callOptions) {
167
284
  if (config.capabilities[capability] === undefined) {
168
285
  return refuse(capability, "not-declared");
169
286
  }
170
- const args = VALIDATORS[capability](raw, config);
171
- if (args === null) {
287
+ // The page's declaration (P086): a built-in needs none; any other runtime capability only
288
+ // a page that declared it reaches; a page with no declaration, none of the runtime's own.
289
+ const family = familyOf(capability);
290
+ // No declaration, or the host's explicit null for a page from before 0.7 (P086).
291
+ const declaration = options.declaration ?? undefined;
292
+ if (family !== null &&
293
+ !runtimeCapability(family.name).builtIn &&
294
+ (declaration === undefined
295
+ ? RUNTIME_HOST_FUNCTIONS.includes(capability)
296
+ : !Object.hasOwn(declaration.capabilities, family.name))) {
297
+ return refuse(capability, "undeclared");
298
+ }
299
+ const early = precheck(capability, raw);
300
+ if (early !== null) {
301
+ return refuse(capability, early);
302
+ }
303
+ const parsed = VALIDATORS[capability](raw, config);
304
+ if (parsed === null) {
172
305
  return refuse(capability, "invalid");
173
306
  }
174
- const gates = effectiveGates(config, capability);
307
+ if (parsed === "too_large") {
308
+ return refuse(capability, "too-large");
309
+ }
310
+ let args = parsed;
311
+ // Who may (P087): the method's level against the viewer's, the page's own narrowing.
312
+ if (family !== null) {
313
+ const audience = checkAudience(capability, family.name, args);
314
+ if (audience === "undeclared" || audience === "level") {
315
+ return refuse(capability, audience);
316
+ }
317
+ args = audience;
318
+ }
319
+ // Its host function's gates, and its method's own (after the review): all apply.
320
+ const gates = callGates(config, capability, args);
321
+ const own = new Set(effectiveGates(config, capability));
175
322
  const confirms = gates.includes("confirm");
176
323
  if (confirms && muted) {
177
324
  return refuse(capability, "muted");
178
325
  }
326
+ const method = family === null ? null : methodOf(capability, args);
179
327
  for (const gate of gates) {
180
- if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
328
+ if (typeof gate !== "object") {
329
+ continue;
330
+ }
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)) {
181
335
  return refuse(capability, "rate-limited");
182
336
  }
183
337
  }
@@ -259,11 +413,35 @@ export function createBridge(options) {
259
413
  }
260
414
  return { ok: true, value: undefined };
261
415
  }
416
+ if (capabilitySpec(capability).served === "viewer") {
417
+ // `user` (P087): the viewer the host gave the display, and nothing else.
418
+ const viewer = options.viewer;
419
+ if (viewer === undefined) {
420
+ return refuse(capability, "level");
421
+ }
422
+ return {
423
+ ok: true,
424
+ value: {
425
+ id: viewer.id ?? null,
426
+ name: viewer.name ?? null,
427
+ level: viewer.level,
428
+ },
429
+ };
430
+ }
262
431
  const handler = handlers[capability];
263
432
  if (handler === undefined) {
264
433
  return refuse(capability, "not-declared");
265
434
  }
266
- const context = { displayId: display.id, title: display.title, capability };
435
+ const family = familyOf(capability);
436
+ const declared = family === null ? undefined : declaredOf(options.declaration ?? undefined, family.name);
437
+ const context = {
438
+ displayId: display.id,
439
+ title: display.title,
440
+ capability,
441
+ ...(display.instance === undefined ? {} : { instance: display.instance }),
442
+ ...(options.viewer === undefined ? {} : { viewer: options.viewer }),
443
+ ...(declared === undefined ? {} : { declared }),
444
+ };
267
445
  // A read the content subscribes to may be answered from the host's cache, marked stale; the
268
446
  // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
269
447
  if (capability === "readData" && callOptions?.stale === true && options.cached) {
@@ -278,11 +456,28 @@ export function createBridge(options) {
278
456
  }
279
457
  }
280
458
  const subscription = callOptions?.subscription;
281
- if (capability === "subscribeData" && subscription === undefined) {
459
+ // A subscription (`subscribeData`, a `db` watch) needs its channel back.
460
+ const watches = capability === "subscribeData" ||
461
+ (capability === "db" && args.op === "watch");
462
+ if (watches && subscription === undefined) {
282
463
  return refuse(capability, "invalid");
283
464
  }
465
+ // A db answer names the viewer's own tree `me`, never their id (after the review, P088).
466
+ const viewer = options.viewer;
467
+ const channel = watches && subscription !== undefined && capability === "db"
468
+ ? {
469
+ changed: (state) => subscription.changed(withMe(state, viewer)),
470
+ signal: subscription.signal,
471
+ }
472
+ : subscription;
284
473
  try {
285
- const value = await handler(args, capability === "subscribeData" ? { ...context, ...subscription } : context);
474
+ const answered = await handler(args, watches ? { ...context, ...channel } : context);
475
+ const value = capability === "db" ? withMe(answered, viewer) : answered;
476
+ // Comments are write-only (P090): content hears whether the composer opened, never what
477
+ // the host answered beyond that (a thread, its text).
478
+ if (capability === "comments") {
479
+ return { ok: true, value: (value === true) };
480
+ }
286
481
  return { ok: true, value: value };
287
482
  }
288
483
  catch (error) {
@@ -1,10 +1,5 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
- /**
3
- * A navigation the shell cancelled (P079), as the host is told it (P080): the address, whole, on
4
- * the `navigationBlocked` event (the host's to keep), and a sentence for the content's errors
5
- * (`contentError`, which a host may give the agent that wrote it) that names the address without
6
- * its query or fragment, where a viewer's data would be.
7
- */
2
+ export declare const withoutSealedAddresses: (text: string) => string;
8
3
  /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
9
4
  export declare function addressWithoutQuery(url: string): string;
10
5
  /** What the content's errors say about a navigation the shell cancelled. */
@@ -4,8 +4,19 @@
4
4
  * (`contentError`, which a host may give the agent that wrote it) that names the address without
5
5
  * its query or fragment, where a viewer's data would be.
6
6
  */
7
+ /**
8
+ * A frame's sealed files' address (P083) is its access: whatever content says, the host is told
9
+ * it as `./`, the page's own files (the shell says it so already; content may not).
10
+ */
11
+ const SEALED = /(?:https?:\/\/[^\s"'<>/]+)?\/__porthole\/f\/[A-Za-z0-9_-]{20,}\//gu;
12
+ export const withoutSealedAddresses = (text) => text.replace(SEALED, "./");
7
13
  /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
8
14
  export function addressWithoutQuery(url) {
15
+ // A page's own file (P084), as the shell names it: its path, without query or fragment.
16
+ if (url.startsWith("./")) {
17
+ const path = url.split(/[?#]/u)[0] ?? "./";
18
+ return path === url ? path : `${path}?…`;
19
+ }
9
20
  let parsed;
10
21
  try {
11
22
  parsed = new URL(url);
@@ -11,8 +11,12 @@ import type { Refusal } from "./types.ts";
11
11
  * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
12
12
  * serve, a page where data never runs).
13
13
  * - `failed`: the host tried and couldn't.
14
+ * - `forbidden` (P087): the person viewing it may see the content but not do this (their level).
15
+ * - `conflict` (P088): what it changes moved since it was read (a document's version, the
16
+ * artifact's base): read it again, then write.
17
+ * - `too_large` (P088): more than a limit (a document, a batch, an upload, a publish).
14
18
  */
15
- export declare const REFUSAL_CODES: readonly ["consent_required", "denied", "rate_limited", "not_allowed", "failed"];
19
+ export declare const REFUSAL_CODES: readonly ["consent_required", "denied", "rate_limited", "not_allowed", "failed", "forbidden", "conflict", "too_large"];
16
20
  export type RefusalCode = (typeof REFUSAL_CODES)[number];
17
21
  /** What content is told about a refusal: the JSON-RPC error's `data`. */
18
22
  export interface RefusalReason {
@@ -9,6 +9,10 @@
9
9
  * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
10
10
  * serve, a page where data never runs).
11
11
  * - `failed`: the host tried and couldn't.
12
+ * - `forbidden` (P087): the person viewing it may see the content but not do this (their level).
13
+ * - `conflict` (P088): what it changes moved since it was read (a document's version, the
14
+ * artifact's base): read it again, then write.
15
+ * - `too_large` (P088): more than a limit (a document, a batch, an upload, a publish).
12
16
  */
13
17
  export const REFUSAL_CODES = [
14
18
  "consent_required",
@@ -16,6 +20,9 @@ export const REFUSAL_CODES = [
16
20
  "rate_limited",
17
21
  "not_allowed",
18
22
  "failed",
23
+ "forbidden",
24
+ "conflict",
25
+ "too_large",
19
26
  ];
20
27
  /** The most a refusal's message carries to content. */
21
28
  const MAX_MESSAGE = 500;
@@ -68,6 +75,9 @@ const DEFAULT_MESSAGES = {
68
75
  rate_limited: "Too many requests: try again in a minute.",
69
76
  not_allowed: "This isn't available here.",
70
77
  failed: "The app couldn't do this.",
78
+ forbidden: "You don't have permission to do this here.",
79
+ conflict: "This changed since it was read: read it again, then try again.",
80
+ too_large: "This is too large.",
71
81
  };
72
82
  /** Where a data capability's words differ: they name the data. */
73
83
  const DATA_MESSAGES = {
@@ -76,6 +86,9 @@ const DATA_MESSAGES = {
76
86
  rate_limited: "Too many data requests: try again in a minute.",
77
87
  not_allowed: "This data isn't available here.",
78
88
  failed: "The app couldn't get this data.",
89
+ forbidden: "You don't have permission to read this data.",
90
+ conflict: DEFAULT_MESSAGES.conflict,
91
+ too_large: DEFAULT_MESSAGES.too_large,
79
92
  };
80
93
  /** Each refusal's code, as content is told it. */
81
94
  const CODES = {
@@ -90,6 +103,9 @@ const CODES = {
90
103
  denied: "denied",
91
104
  "rate-limited": "rate_limited",
92
105
  failed: "failed",
106
+ undeclared: "not_allowed",
107
+ level: "forbidden",
108
+ "too-large": "too_large",
93
109
  };
94
110
  /** Refusals whose own words say more than their code's. */
95
111
  const OWN_MESSAGES = {
@@ -1,5 +1,8 @@
1
1
  import type { CapabilityArgs, CapabilityName, CapabilityResults, HandledCapability } from "../config/capabilities.ts";
2
2
  import type { InstanceRef } from "../isolation/types.ts";
3
+ import type { RuntimeCapabilityName } from "../runtime/contract.ts";
4
+ import type { DeclaredData, DeclaredDb } from "../runtime/declaration.ts";
5
+ import type { ViewerInfo } from "../runtime/levels.ts";
3
6
  import type { RefusalReason } from "./refusal.ts";
4
7
  /**
5
8
  * The host-function bridge (ARCHITECTURE § Framework layer): carries a capability call from the
@@ -13,11 +16,24 @@ export interface CallContext {
13
16
  /** The display's title, as the host gave it (never the content's words). */
14
17
  readonly title: string;
15
18
  readonly capability: CapabilityName;
19
+ /** The instance the host gave the display (which artifact, which version), if any. */
20
+ readonly instance?: InstanceRef;
21
+ /**
22
+ * Who is viewing, as the host said (P087): the bridge already checked the method's level
23
+ * against it. A host's own API checks again: it is its data's wall.
24
+ */
25
+ readonly viewer?: ViewerInfo;
26
+ /**
27
+ * The page's declaration for this capability (P086): its levels, `data`'s resources and tools,
28
+ * `db`'s rules (the fields of the one it is).
29
+ */
30
+ readonly declared?: DeclaredData & DeclaredDb;
16
31
  }
17
- export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: N extends "subscribeData" ? SubscriptionContext : CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
32
+ export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: N extends "subscribeData" ? SubscriptionContext : N extends "db" ? DbContext : CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
18
33
  /**
19
- * A subscription's context (`subscribeData`, P079): how the host tells the content its resource
20
- * changed, and when to stop.
34
+ * A subscription's context (`subscribeData`, P079; a `db` watch, P088): how the host tells the
35
+ * content its resource changed, and when to stop. A `db` watch's `changed` takes the new state
36
+ * (a snapshot, or a collection's `{ docs }`), which goes to the content as it is.
21
37
  */
22
38
  export interface SubscriptionContext extends CallContext {
23
39
  /**
@@ -29,6 +45,8 @@ export interface SubscriptionContext extends CallContext {
29
45
  /** Aborted when the content unsubscribes, its frame stops, or the display is destroyed. */
30
46
  readonly signal: AbortSignal;
31
47
  }
48
+ /** A `db` call's context: a watch's (`op: "watch"`) carries its channel back and its end. */
49
+ export type DbContext = CallContext & Partial<Pick<SubscriptionContext, "changed" | "signal">>;
32
50
  /** The host's handlers: one for each declared capability served by a handler. */
33
51
  export type CapabilityHandlers = {
34
52
  readonly [N in HandledCapability]?: CapabilityHandler<N>;
@@ -105,7 +123,20 @@ export type Refusal =
105
123
  /** The host's `consent` said no (for this display's life). */
106
124
  | "denied" | "rate-limited"
107
125
  /** The host's handler threw or rejected. */
108
- | "failed";
126
+ | "failed"
127
+ /**
128
+ * The display's page declared capabilities and not this one (P086): a built-in needs none, any
129
+ * other is reachable only by a page that declared it (and only the resources and tools it named).
130
+ */
131
+ | "undeclared"
132
+ /**
133
+ * The viewer's level doesn't reach the method's (P087), or the call reaches data that isn't
134
+ * theirs (another person's `data/users/<id>`); or the host gave the display no viewer, which a
135
+ * runtime capability needs.
136
+ */
137
+ | "level"
138
+ /** Past a limit: a document, a batch, an upload, a publish (P088). */
139
+ | "too-large";
109
140
  export type CallOutcome<T> =
110
141
  /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
111
142
  {
@@ -133,4 +164,10 @@ export interface HostFunctionBridge {
133
164
  /** Validates `args` for `capability`, applies its gates, then runs the host's handler. */
134
165
  call<N extends CapabilityName>(capability: N, args: unknown, options?: CallOptions): Promise<CallOutcome<CapabilityResults[N]>>;
135
166
  declared(capability: CapabilityName): boolean;
167
+ /**
168
+ * What the runtime offers this display (P085): each runtime capability it may `use`, with its
169
+ * methods. Empty without `config.runtime`. The same whatever the viewer's level: levels refuse
170
+ * at call time.
171
+ */
172
+ roster(): Readonly<Partial<Record<RuntimeCapabilityName, readonly string[]>>>;
136
173
  }
@@ -1,5 +1,6 @@
1
+ import type { PageDeclaration } from "../runtime/declaration.ts";
1
2
  import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
2
- import { type Finding } from "./lint.ts";
3
+ import { type FileContents, type FileFinding } from "./files.ts";
3
4
  import { type CheckCall } from "./instrument.ts";
4
5
  export type { CheckCall } from "./instrument.ts";
5
6
  /**
@@ -34,7 +35,21 @@ export interface CheckDriver {
34
35
  export interface CheckOptions {
35
36
  readonly config: PortholeConfig;
36
37
  /** The content as the agent would send it: a fragment, or a whole document. */
37
- readonly content: string;
38
+ readonly content?: string;
39
+ /**
40
+ * A page that comes with files (P081), in place of `content`: every file by its path. The whole
41
+ * set is served, as people's browsers get it, and its entry is run and measured. Needs a served
42
+ * artifact config and a driver that serves (`playwrightDriver`).
43
+ */
44
+ readonly files?: FileContents;
45
+ /** The page a set opens at (default `index.html`). */
46
+ readonly entry?: string;
47
+ /**
48
+ * Under a runtime (P085): what the page declares (default null: a page with none, so a
49
+ * declared capability is null in the check, as in a preview). Its calls are answered as a
50
+ * declining host answers, by a view-level viewer.
51
+ */
52
+ readonly declaration?: PageDeclaration | null;
38
53
  readonly driver: CheckDriver;
39
54
  /** Widths, px. Default: the manual's phone and desktop widths (`config.layout`). */
40
55
  readonly widths?: readonly number[];
@@ -92,7 +107,8 @@ export interface CheckReport {
92
107
  * refuses, overflow or cut, no lint error.
93
108
  */
94
109
  readonly ok: boolean;
95
- readonly lint: readonly Finding[];
110
+ /** What the lint found (for a page with files, each finding names its file, `path`). */
111
+ readonly lint: readonly FileFinding[];
96
112
  readonly runs: readonly CheckRun[];
97
113
  /** One short summary for the agent: each problem once, with where it happened. */
98
114
  readonly text: string;