@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
@@ -0,0 +1,323 @@
1
+ import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+
3
+ /**
4
+ * A version made of files (P081): the rules a published path follows, the limits a version is
5
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
6
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
7
+ * only, never on a filesystem.
8
+ */
9
+
10
+ /** The most files a version holds, by default. */
11
+ export const DEFAULT_MAX_FILES = 1_000;
12
+ /** The largest file of a version, bytes, by default (25 MiB). */
13
+ export const DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024;
14
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
15
+ export const DEFAULT_MAX_VERSION_BYTES = 100 * 1024 * 1024;
16
+ /** The longest path, characters, and the longest segment of one. */
17
+ export const MAX_FILE_PATH_CHARS = 512;
18
+ export const MAX_SEGMENT_CHARS = 255;
19
+ /** The page a version opens at by default. */
20
+ export const DEFAULT_ENTRY = "index.html";
21
+
22
+ /**
23
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
24
+ * origin of its own. Opaque frames have no origin to serve them from.
25
+ */
26
+ export const servesFiles = (config: PortholeConfig): boolean =>
27
+ config.mode === "artifact" && config.isolation === "domain";
28
+
29
+ export interface FileLimits {
30
+ readonly maxFiles: number;
31
+ readonly maxFileBytes: number;
32
+ readonly maxVersionBytes: number;
33
+ }
34
+
35
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
36
+ export function fileLimits(limits?: Partial<Limits> | null): FileLimits {
37
+ return {
38
+ maxFiles: limits?.maxFiles ?? DEFAULT_MAX_FILES,
39
+ maxFileBytes: limits?.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES,
40
+ maxVersionBytes: limits?.maxVersionBytes ?? DEFAULT_MAX_VERSION_BYTES,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * What a request's path can never hold once decoded, and a published path never holds: control
46
+ * and format characters (`Cc`, `Cf`: a right-to-left override, a zero-width space, a BOM would make
47
+ * a path read as another), and `\ % ? #`.
48
+ */
49
+ // oxlint-disable-next-line no-control-regex -- control characters are what it refuses
50
+ const FORBIDDEN = /[\p{Cc}\p{Cf}\\%?#]/u;
51
+
52
+ /**
53
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
54
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
55
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
56
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
57
+ */
58
+ export function filePathProblem(path: unknown): string | null {
59
+ if (typeof path !== "string" || path.length === 0) {
60
+ return "a path is a non-empty string";
61
+ }
62
+ if (path.length > MAX_FILE_PATH_CHARS) {
63
+ return `a path is at most ${MAX_FILE_PATH_CHARS} characters`;
64
+ }
65
+ if (path.startsWith("/")) {
66
+ return "a path is relative: no leading /";
67
+ }
68
+ if (path.endsWith("/")) {
69
+ return "a path names a file: no trailing /";
70
+ }
71
+ const forbidden = FORBIDDEN.exec(path);
72
+ if (forbidden !== null) {
73
+ const char = forbidden[0];
74
+ return `a path holds no ${char === "\\" || char === "%" || char === "?" || char === "#" ? char : "control or format character"}`;
75
+ }
76
+ if (path.normalize("NFC") !== path) {
77
+ return "a path is in Unicode NFC";
78
+ }
79
+ const segments = path.split("/");
80
+ for (const segment of segments) {
81
+ if (segment === "") {
82
+ return "a path has no empty segment (//)";
83
+ }
84
+ if (segment === "." || segment === "..") {
85
+ return `a path has no ${segment} segment`;
86
+ }
87
+ if (segment.length > MAX_SEGMENT_CHARS) {
88
+ return `a path's segment is at most ${MAX_SEGMENT_CHARS} characters`;
89
+ }
90
+ if (segment.startsWith(" ") || segment.endsWith(" ")) {
91
+ return "a path's segment doesn't start or end with a space";
92
+ }
93
+ }
94
+ if (segments[0] === "__porthole") {
95
+ return "__porthole/ is Porthole's own";
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /** A published path's metadata, as far as the checks read it. */
101
+ export interface FileSetEntryLike {
102
+ readonly size: number;
103
+ }
104
+
105
+ export interface FileSetProblem {
106
+ /** The path it is about, where it is about one. */
107
+ readonly path?: string;
108
+ readonly code: "path" | "collision" | "count" | "size" | "total" | "entry";
109
+ /** What to change, for the agent or the person publishing. */
110
+ readonly message: string;
111
+ }
112
+
113
+ const sizeOf = (bytes: number): string =>
114
+ bytes >= 1024 * 1024
115
+ ? `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`
116
+ : bytes >= 1024
117
+ ? `${Math.round(bytes / 1024)} KiB`
118
+ : `${bytes} bytes`;
119
+
120
+ /**
121
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
122
+ * two paths that differ only in case, and no path that is both a file and a directory; the
123
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
124
+ * `fileLimits`). Empty when it may be published.
125
+ */
126
+ export function checkFileSet(
127
+ files: Readonly<Record<string, FileSetEntryLike>>,
128
+ options: { readonly entry?: string; readonly limits?: FileLimits } = {},
129
+ ): FileSetProblem[] {
130
+ const limits = options.limits ?? fileLimits();
131
+ const problems: FileSetProblem[] = [];
132
+ const paths = Object.keys(files);
133
+ if (paths.length > limits.maxFiles) {
134
+ problems.push({
135
+ code: "count",
136
+ message: `${paths.length} files: a version holds at most ${limits.maxFiles}`,
137
+ });
138
+ }
139
+ const folded = new Map<string, string>();
140
+ const directories = new Set<string>();
141
+ let total = 0;
142
+ for (const path of paths) {
143
+ const problem = filePathProblem(path);
144
+ if (problem !== null) {
145
+ problems.push({ path, code: "path", message: `${JSON.stringify(path)}: ${problem}` });
146
+ continue;
147
+ }
148
+ const lower = path.toLowerCase();
149
+ const other = folded.get(lower);
150
+ if (other !== undefined) {
151
+ problems.push({
152
+ path,
153
+ code: "collision",
154
+ message: `${JSON.stringify(path)} and ${JSON.stringify(other)} differ only in case: rename one`,
155
+ });
156
+ } else {
157
+ folded.set(lower, path);
158
+ }
159
+ const segments = path.split("/");
160
+ for (let index = 1; index < segments.length; index += 1) {
161
+ directories.add(segments.slice(0, index).join("/"));
162
+ }
163
+ const size = files[path]?.size;
164
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) {
165
+ problems.push({ path, code: "size", message: `${JSON.stringify(path)}: no size` });
166
+ continue;
167
+ }
168
+ if (size > limits.maxFileBytes) {
169
+ problems.push({
170
+ path,
171
+ code: "size",
172
+ message: `${JSON.stringify(path)} is ${sizeOf(size)}: a file is at most ${sizeOf(limits.maxFileBytes)}`,
173
+ });
174
+ }
175
+ total += size;
176
+ }
177
+ for (const path of paths) {
178
+ if (directories.has(path)) {
179
+ problems.push({
180
+ path,
181
+ code: "collision",
182
+ message: `${JSON.stringify(path)} is a file and a directory: rename one`,
183
+ });
184
+ }
185
+ }
186
+ if (total > limits.maxVersionBytes) {
187
+ problems.push({
188
+ code: "total",
189
+ message: `The files are ${sizeOf(total)} together: a version holds at most ${sizeOf(limits.maxVersionBytes)}`,
190
+ });
191
+ }
192
+ const entry = options.entry ?? DEFAULT_ENTRY;
193
+ if (!Object.hasOwn(files, entry)) {
194
+ problems.push({
195
+ path: entry,
196
+ code: "entry",
197
+ message: `No ${JSON.stringify(entry)}: the page the version opens at is one of its files`,
198
+ });
199
+ }
200
+ return problems;
201
+ }
202
+
203
+ /**
204
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
205
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
206
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
207
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
208
+ * `/` stays (a directory).
209
+ */
210
+ export function requestFilePath(raw: string): string | null {
211
+ if (raw.length > MAX_FILE_PATH_CHARS * 3 + 1) {
212
+ return null;
213
+ }
214
+ const segments = raw.split("/");
215
+ const decoded: string[] = [];
216
+ for (const [index, segment] of segments.entries()) {
217
+ if (segment === "") {
218
+ // Only the last segment may be empty: a directory's trailing slash (or the base itself).
219
+ if (index !== segments.length - 1) {
220
+ return null;
221
+ }
222
+ decoded.push("");
223
+ continue;
224
+ }
225
+ let value: string;
226
+ try {
227
+ value = decodeURIComponent(segment);
228
+ } catch {
229
+ return null;
230
+ }
231
+ if (value === "." || value === ".." || value.includes("/") || FORBIDDEN.test(value)) {
232
+ return null;
233
+ }
234
+ decoded.push(value);
235
+ }
236
+ return decoded.join("/");
237
+ }
238
+
239
+ /** What a request's path finds in a version's manifest. */
240
+ export type FileLookup =
241
+ /** The file to answer with, and its status (404 for a `404.html`). */
242
+ | { readonly kind: "file"; readonly path: string; readonly status: 200 | 404 }
243
+ /** The canonical address: `dir` → `dir/` (or `page/` → `page`), relative to the base. */
244
+ | { readonly kind: "redirect"; readonly to: string }
245
+ /** Nothing: a plain 404. */
246
+ | { readonly kind: "none" };
247
+
248
+ export interface LookupOptions {
249
+ /** The page the version opens at (default `index.html`). */
250
+ readonly entry?: string;
251
+ /** A single-page app's routes: a navigation that finds nothing answers the entry. */
252
+ readonly spa?: boolean;
253
+ /** Whether the request is a navigation (a page loading), not a subresource. */
254
+ readonly navigation: boolean;
255
+ }
256
+
257
+ /**
258
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
259
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
260
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
261
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
262
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
263
+ */
264
+ export function lookupFile(
265
+ has: (path: string) => boolean,
266
+ path: string,
267
+ options: LookupOptions,
268
+ ): FileLookup {
269
+ const entry = options.entry ?? DEFAULT_ENTRY;
270
+ if (path === "") {
271
+ if (!has(entry)) {
272
+ return notFound(has, "", options);
273
+ }
274
+ // An entry in a directory opens there, so its relative addresses are its directory's.
275
+ return entry.includes("/")
276
+ ? { kind: "redirect", to: entry }
277
+ : { kind: "file", path: entry, status: 200 };
278
+ }
279
+ if (path.endsWith("/")) {
280
+ const index = `${path}index.html`;
281
+ if (has(index)) {
282
+ return { kind: "file", path: index, status: 200 };
283
+ }
284
+ const page = `${path.slice(0, -1)}.html`;
285
+ if (has(page)) {
286
+ return { kind: "redirect", to: path.slice(0, -1) };
287
+ }
288
+ return notFound(has, path, options);
289
+ }
290
+ if (has(path)) {
291
+ return { kind: "file", path, status: 200 };
292
+ }
293
+ if (has(`${path}.html`)) {
294
+ return { kind: "file", path: `${path}.html`, status: 200 };
295
+ }
296
+ if (has(`${path}/index.html`)) {
297
+ return { kind: "redirect", to: `${path}/` };
298
+ }
299
+ return notFound(has, path, options);
300
+ }
301
+
302
+ function notFound(
303
+ has: (path: string) => boolean,
304
+ path: string,
305
+ options: LookupOptions,
306
+ ): FileLookup {
307
+ if (!options.navigation) {
308
+ return { kind: "none" };
309
+ }
310
+ const entry = options.entry ?? DEFAULT_ENTRY;
311
+ if (options.spa === true && has(entry)) {
312
+ return { kind: "file", path: entry, status: 200 };
313
+ }
314
+ // The nearest 404.html: in the request's directory, then each one above it.
315
+ const segments = path.split("/").slice(0, -1);
316
+ for (let depth = segments.length; depth >= 0; depth -= 1) {
317
+ const candidate = [...segments.slice(0, depth), "404.html"].join("/");
318
+ if (has(candidate)) {
319
+ return { kind: "file", path: candidate, status: 404 };
320
+ }
321
+ }
322
+ return { kind: "none" };
323
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The media type a file of a set is served with (P081): Porthole's own table, by the path's
3
+ * extension, never the uploader's word and never sniffed. A file whose extension isn't here is
4
+ * `application/octet-stream`, served as a download. Pure: any runtime.
5
+ */
6
+
7
+ /** How a type is served: a page (in the shell), a script (it may run as a worker), or a file. */
8
+ export type FileRole = "page" | "script" | "file";
9
+
10
+ export interface FileType {
11
+ /** The `content-type` header. */
12
+ readonly type: string;
13
+ readonly role: FileRole;
14
+ }
15
+
16
+ const UTF8 = "; charset=utf-8";
17
+
18
+ /** Extension (lowercase, no dot) to media type. Standard web types only. */
19
+ const TABLE: Readonly<Record<string, string>> = {
20
+ html: `text/html${UTF8}`,
21
+ htm: `text/html${UTF8}`,
22
+ css: `text/css${UTF8}`,
23
+ js: `text/javascript${UTF8}`,
24
+ mjs: `text/javascript${UTF8}`,
25
+ cjs: `text/javascript${UTF8}`,
26
+ json: `application/json${UTF8}`,
27
+ map: `application/json${UTF8}`,
28
+ webmanifest: `application/manifest+json${UTF8}`,
29
+ txt: `text/plain${UTF8}`,
30
+ md: `text/markdown${UTF8}`,
31
+ markdown: `text/markdown${UTF8}`,
32
+ csv: `text/csv${UTF8}`,
33
+ tsv: `text/tab-separated-values${UTF8}`,
34
+ xml: `application/xml${UTF8}`,
35
+ vtt: `text/vtt${UTF8}`,
36
+ svg: "image/svg+xml",
37
+ png: "image/png",
38
+ jpg: "image/jpeg",
39
+ jpeg: "image/jpeg",
40
+ gif: "image/gif",
41
+ webp: "image/webp",
42
+ avif: "image/avif",
43
+ ico: "image/x-icon",
44
+ bmp: "image/bmp",
45
+ woff: "font/woff",
46
+ woff2: "font/woff2",
47
+ ttf: "font/ttf",
48
+ otf: "font/otf",
49
+ mp3: "audio/mpeg",
50
+ wav: "audio/wav",
51
+ ogg: "audio/ogg",
52
+ oga: "audio/ogg",
53
+ opus: "audio/ogg",
54
+ m4a: "audio/mp4",
55
+ flac: "audio/flac",
56
+ aac: "audio/aac",
57
+ mp4: "video/mp4",
58
+ m4v: "video/mp4",
59
+ webm: "video/webm",
60
+ ogv: "video/ogg",
61
+ wasm: "application/wasm",
62
+ pdf: "application/pdf",
63
+ glb: "model/gltf-binary",
64
+ gltf: `model/gltf+json${UTF8}`,
65
+ zip: "application/zip",
66
+ };
67
+
68
+ /** What a file whose extension isn't in the table is served as: a download. */
69
+ export const UNKNOWN_TYPE = "application/octet-stream";
70
+
71
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
72
+ export function extensionOf(path: string): string {
73
+ const last = path.slice(path.lastIndexOf("/") + 1);
74
+ const dot = last.lastIndexOf(".");
75
+ return dot <= 0 ? "" : last.slice(dot + 1).toLowerCase();
76
+ }
77
+
78
+ /** The type a path is served with, and how. */
79
+ export function fileTypeOf(path: string): FileType {
80
+ const extension = extensionOf(path);
81
+ const type = Object.hasOwn(TABLE, extension) ? TABLE[extension] : undefined;
82
+ if (type === undefined) {
83
+ return { type: UNKNOWN_TYPE, role: "file" };
84
+ }
85
+ const role: FileRole =
86
+ extension === "html" || extension === "htm"
87
+ ? "page"
88
+ : type.startsWith("text/javascript")
89
+ ? "script"
90
+ : "file";
91
+ return { type, role };
92
+ }
93
+
94
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
95
+ export const knownType = (path: string): boolean => fileTypeOf(path).type !== UNKNOWN_TYPE;
96
+
97
+ /** Whether a path names a page: an `.html` file. */
98
+ export const isPagePath = (path: string): boolean => fileTypeOf(path).role === "page";
99
+
100
+ /** Every extension the table knows, for the manual and tests. */
101
+ export const KNOWN_EXTENSIONS: readonly string[] = Object.keys(TABLE);
@@ -0,0 +1,25 @@
1
+ import type { Gate } from "../config/capabilities.ts";
2
+
3
+ /** How a capability's gates read to the author: one sentence each. */
4
+ export function gateWords(gates: readonly Gate[], effect: string): string {
5
+ const sentences: string[] = [];
6
+ if (gates.includes("consent")) {
7
+ sentences.push(
8
+ "The first data call asks the person to allow it; if they don't, every one fails with code denied (show that the data isn't allowed, not an error).",
9
+ );
10
+ }
11
+ if (gates.includes("confirm")) {
12
+ sentences.push(
13
+ `The app shows the person ${effect} first, and nothing happens unless they confirm.`,
14
+ );
15
+ }
16
+ if (gates.includes("user-activation")) {
17
+ sentences.push("Call it from a click (it needs one).");
18
+ }
19
+ for (const gate of gates) {
20
+ if (typeof gate === "object") {
21
+ sentences.push(`At most ${gate.rateLimit.perMinute} a minute.`);
22
+ }
23
+ }
24
+ return sentences.join(" ");
25
+ }
@@ -14,11 +14,14 @@ import {
14
14
  librarySources,
15
15
  type EgressKind,
16
16
  } from "../compile/policy.ts";
17
+ import { fileLimits, servesFiles } from "../files/paths.ts";
17
18
  import { VENDORED_LIBRARIES, libraryPath } from "../libraries/libraries.ts";
18
19
  import { shellPlan } from "../shell/plan.ts";
19
20
  import { themeDefault } from "../theme/variables.ts";
20
21
  import { GUIDE_EXAMPLES } from "./examples.ts";
21
22
  import { manualLimits, sizeWords } from "./limits.ts";
23
+ import { gateWords } from "./gates.ts";
24
+ import { capabilitiesTopic, runtimeEntries, runtimeToolWords } from "./runtime.ts";
22
25
 
23
26
  /**
24
27
  * The agent manual and the tool description, generated from the config (PRINCIPLE 3, 10): the
@@ -108,6 +111,23 @@ const sourcesFor = (config: PortholeConfig, kind: EgressKind): string[] => [
108
111
  /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
109
112
  const servesLibraries = (config: PortholeConfig): boolean => librarySources(config).length > 0;
110
113
 
114
+ /** The manual's lines on a page's own files (P081-P084), where it may have them. */
115
+ function files(config: PortholeConfig): string | null {
116
+ if (!servesFiles(config)) {
117
+ return null;
118
+ }
119
+ const limits = fileLimits(config.limits);
120
+ const downloads = config.capabilities.downloadFile !== undefined;
121
+ return lines(
122
+ "Files: a page may come with files of its own (stylesheets, scripts and modules, images, fonts, data, workers, other pages), published beside it, with index.html the page it opens at.",
123
+ '- Name them by relative path (./style.css, assets/app.js, data.json), never with a leading / or a full address: a page loads only its own version\'s files. fetch("./data.json") works; a module\'s imports and a worker\'s script resolve from the module (new Worker(new URL("./worker.js", import.meta.url))).',
124
+ `- A link to another of your pages (about.html, or about; docs/ for docs/index.html) opens it in place. A link to any other file doesn't open: show an image with <img>${downloads ? `, offer a file with ${config.runtime === undefined ? "downloadFile" : "downloads.save"}` : ""}. A missing path shows your 404.html, if you publish one.`,
125
+ "- Paths are case-sensitive, relative, with no .., //, \\, %, ? or #. Each file is served as its extension says (.html a page, .js and .mjs scripts, .css, .json, .txt, .svg, .png, .woff2, .mp4, …), never as what it holds; an extension the server doesn't know is a download.",
126
+ '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.',
127
+ `- At most ${limits.maxFiles.toLocaleString("en-US")} files, ${sizeWords(limits.maxFileBytes)} each (a page under ${sizeWords(config.limits.maxBytes)}) and ${sizeWords(limits.maxVersionBytes)} in all.`,
128
+ );
129
+ }
130
+
111
131
  /** What content may load, in prose, from the same origins the CSP lists. */
112
132
  function network(config: PortholeConfig): string {
113
133
  const kinds: EgressKind[] = ["script", "style", "font", "img", "media", "connect"];
@@ -117,7 +137,7 @@ function network(config: PortholeConfig): string {
117
137
  if (open.length === 0) {
118
138
  // A live widget's data comes from the app alone (P079), and its scripts from Porthole's copies.
119
139
  const data = declaredCapabilities(config).includes("readData")
120
- ? " Your data comes only from the app (readData)."
140
+ ? ` Your data comes only from the app (${config.runtime === undefined ? "readData" : "data.read"}).`
121
141
  : "";
122
142
  return servesLibraries(config)
123
143
  ? `Network: none. Nothing loads from outside (no scripts, styles, fonts, images or data from any server) and any fetch fails, so write everything inline; the only scripts that load are the libraries below, from this frame's own address.${data}`
@@ -242,6 +262,8 @@ function widget(c: Context): string {
242
262
  "The sandbox:",
243
263
  ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`),
244
264
  `Keep it under ${sizeWords(limits.maxBytes)}.`,
265
+ servesFiles(config) ? "" : null,
266
+ files(config),
245
267
  loadsScripts(config)
246
268
  ? "\nLibraries: pin an exact version at least two weeks old (chart.js@4.4.1 in its URL), never @latest or a range, so the code can't be swapped under you and draws the same every time."
247
269
  : null,
@@ -377,30 +399,6 @@ function chart(c: Context): string {
377
399
  );
378
400
  }
379
401
 
380
- /** How a capability's gates read to the author: one sentence each. */
381
- function gateWords(gates: readonly Gate[], effect: string): string {
382
- const sentences: string[] = [];
383
- if (gates.includes("consent")) {
384
- sentences.push(
385
- "The first data call asks the person to allow it; if they don't, every one fails with code denied (show that the data isn't allowed, not an error).",
386
- );
387
- }
388
- if (gates.includes("confirm")) {
389
- sentences.push(
390
- `The app shows the person ${effect} first, and nothing happens unless they confirm.`,
391
- );
392
- }
393
- if (gates.includes("user-activation")) {
394
- sentences.push("Call it from a click (it needs one).");
395
- }
396
- for (const gate of gates) {
397
- if (typeof gate === "object") {
398
- sentences.push(`At most ${gate.rateLimit.perMinute} a minute.`);
399
- }
400
- }
401
- return sentences.join(" ");
402
- }
403
-
404
402
  /**
405
403
  * What a data refusal tells content (P080): the codes and the sentence, for the author to draw. With
406
404
  * the shell's globals they are the error's own fields; without, the JSON-RPC error's data.
@@ -448,16 +446,33 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
448
446
  reportError: (c) =>
449
447
  `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
450
448
  resize: () => "",
449
+ // The runtime's own: taught as porthole.use's methods (runtimeEntries), never alone.
450
+ user: () => "",
451
+ comments: () => "",
452
+ artifact: () => "",
453
+ assets: () => "",
454
+ db: () => "",
451
455
  };
452
456
 
457
+ /** The shell's own capabilities, which content never calls by name: taught as they are. */
458
+ const SHELL_OWN: readonly CapabilityName[] = ["annotate", "reportError", "resize"];
459
+
453
460
  function interactive(c: Context): string {
454
461
  const { config, noun } = c;
455
- const entries = declaredCapabilities(config)
456
- .map((name) => {
457
- const own = config.capabilities[name]?.guide;
458
- return own === undefined ? ENTRIES[name](c, effectiveGates(config, name)) : `- ${own}`;
459
- })
460
- .filter((entry) => entry !== "");
462
+ // Under the capability runtime (P085), what content calls is porthole.use's methods.
463
+ const runtime = config.runtime !== undefined;
464
+ const entries = [
465
+ ...(runtime ? runtimeEntries(config) : []),
466
+ ...declaredCapabilities(config)
467
+ .filter(
468
+ (name) =>
469
+ !runtime || SHELL_OWN.includes(name) || config.capabilities[name]?.guide !== undefined,
470
+ )
471
+ .map((name) => {
472
+ const own = config.capabilities[name]?.guide;
473
+ return own === undefined ? ENTRIES[name](c, effectiveGates(config, name)) : `- ${own}`;
474
+ }),
475
+ ].filter((entry) => entry !== "");
461
476
  const stated = manualLimits(config, "");
462
477
  const stored = stated.find((limit) => limit.id === "storage");
463
478
  const state = stored === undefined ? null : `- ${stored.text}`;
@@ -476,18 +491,27 @@ const TOPICS: Readonly<Record<BuiltInTopic, (c: Context) => string>> = {
476
491
  widget,
477
492
  chart,
478
493
  interactive,
494
+ capabilities: (c) => capabilitiesTopic(c.config, c.noun),
479
495
  };
480
496
 
497
+ /** The built-in topics a config has: the capabilities topic only with a runtime (P085). */
498
+ export function builtInTopics(config: PortholeConfig): readonly BuiltInTopic[] {
499
+ return BUILT_IN_TOPICS.filter(
500
+ (topic) => topic !== "capabilities" || config.runtime !== undefined,
501
+ );
502
+ }
503
+
481
504
  /** The manual for `topics`, in the order asked (all built-in topics by default). */
482
505
  export function generateGuide(config: PortholeConfig, topics?: readonly GuideTopic[]): string {
483
506
  const c = context(config);
484
507
  const own = config.guide.topics ?? {};
485
- return (topics ?? BUILT_IN_TOPICS)
508
+ return (topics ?? builtInTopics(config))
486
509
  .map((topic) => {
487
- if (Object.hasOwn(TOPICS, topic)) {
510
+ // A built-in topic the config has; a 0.6 config's own `capabilities` stays its own.
511
+ if (Object.hasOwn(TOPICS, topic) && builtInTopics(config).includes(topic as BuiltInTopic)) {
488
512
  return TOPICS[topic as BuiltInTopic](c);
489
513
  }
490
- const text = own[topic];
514
+ const text = Object.hasOwn(own, topic) ? own[topic] : undefined;
491
515
  if (text === undefined) {
492
516
  throw new RangeError(`No guide topic ${JSON.stringify(topic)}`);
493
517
  }
@@ -525,24 +549,26 @@ export function generateToolDescription(config: PortholeConfig): string {
525
549
  : origins.length === 0
526
550
  ? `loading only ${fromAnywhere}`
527
551
  : `loading only from ${origins.join(", ")}${fromAnywhere === "" ? "" : `, and ${fromAnywhere}`}`;
528
- const globals = declaredCapabilities(config).flatMap((name) => {
529
- const spec = capabilitySpec(name);
530
- if (spec.global === undefined || !c.global(spec.global)) {
552
+ const globals = (config.runtime === undefined ? declaredCapabilities(config) : []).flatMap(
553
+ (name) => {
554
+ const spec = capabilitySpec(name);
555
+ if (spec.global === undefined || !c.global(spec.global)) {
556
+ return [];
557
+ }
558
+ if (spec.global === "sendPrompt") {
559
+ return ["sendPrompt(text) asks the person to send text to you as their message."];
560
+ }
561
+ if (spec.global === "openLink") {
562
+ return ["openLink(url) asks the person to open a link."];
563
+ }
564
+ if (spec.global === "readData") {
565
+ return [
566
+ `readData(uri)${c.global("subscribeData") ? " and subscribeData(uri, onData)" : ""} read the app's data, as the person viewing it may see it.`,
567
+ ];
568
+ }
531
569
  return [];
532
- }
533
- if (spec.global === "sendPrompt") {
534
- return ["sendPrompt(text) asks the person to send text to you as their message."];
535
- }
536
- if (spec.global === "openLink") {
537
- return ["openLink(url) asks the person to open a link."];
538
- }
539
- if (spec.global === "readData") {
540
- return [
541
- `readData(uri)${c.global("subscribeData") ? " and subscribeData(uri, onData)" : ""} read the app's data, as the person viewing it may see it.`,
542
- ];
543
- }
544
- return [];
545
- });
570
+ },
571
+ );
546
572
  const read =
547
573
  config.guide.guideToolName === undefined
548
574
  ? ""
@@ -555,7 +581,7 @@ export function generateToolDescription(config: PortholeConfig): string {
555
581
  config.theme.documents === "never"
556
582
  ? "always in light (the app doesn't theme it)"
557
583
  : "in the person's light or dark theme through CSS variables";
558
- return `${what} ${where}, ${theme}, ${net}. ${globals.join(" ")}${read} Each time it is shown it runs again from this code.`.replace(
584
+ return `${what} ${where}, ${theme}, ${net}. ${globals.join(" ")} ${runtimeToolWords(config)}${read} Each time it is shown it runs again from this code.`.replace(
559
585
  / {2,}/gu,
560
586
  " ",
561
587
  );