@botiverse/porthole 0.2.4 → 0.3.1

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 (85) hide show
  1. package/README.md +17 -11
  2. package/dist/check/check.d.ts +100 -0
  3. package/dist/check/check.js +247 -0
  4. package/dist/check/drivers.d.ts +43 -0
  5. package/dist/check/drivers.js +181 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/lint.d.ts +21 -0
  11. package/dist/check/lint.js +131 -0
  12. package/dist/check/page-source.d.ts +2 -0
  13. package/dist/check/page-source.js +2 -0
  14. package/dist/check/page.d.ts +13 -0
  15. package/dist/check/page.js +170 -0
  16. package/dist/check/tools.d.ts +61 -0
  17. package/dist/check/tools.js +140 -0
  18. package/dist/conformance/host-kit.d.ts +26 -5
  19. package/dist/conformance/host-kit.js +46 -22
  20. package/dist/conformance/index.d.ts +1 -1
  21. package/dist/conformance/reporter.d.ts +14 -0
  22. package/dist/conformance/reporter.js +28 -0
  23. package/dist/displays/displays.d.ts +61 -0
  24. package/dist/displays/displays.js +113 -0
  25. package/dist/host/client.d.ts +110 -0
  26. package/dist/host/client.js +274 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +6 -0
  29. package/dist/node/index.d.ts +26 -1
  30. package/dist/node/index.js +91 -1
  31. package/dist/react/frame.d.ts +79 -3
  32. package/dist/react/frame.js +183 -42
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/view.d.ts +54 -0
  36. package/dist/react/view.js +151 -0
  37. package/dist/server/bootstrap.d.ts +27 -0
  38. package/dist/server/bootstrap.js +63 -0
  39. package/dist/server/host.d.ts +77 -8
  40. package/dist/server/host.js +268 -11
  41. package/dist/server/index.d.ts +4 -2
  42. package/dist/server/index.js +3 -1
  43. package/dist/server/pages.d.ts +19 -0
  44. package/dist/server/pages.js +8 -0
  45. package/dist/server/proxy.d.ts +24 -0
  46. package/dist/server/proxy.js +67 -0
  47. package/dist/server/server.js +14 -1
  48. package/dist/server/types.d.ts +8 -0
  49. package/docs/ADOPTING.md +278 -108
  50. package/docs/DECISIONS.md +280 -0
  51. package/docs/DESIGN.md +84 -2
  52. package/examples/app.mjs +82 -78
  53. package/examples/conformance/page.spec.mjs +23 -0
  54. package/examples/conformance/playwright.config.mjs +3 -2
  55. package/examples/conformance/porthole.spec.mjs +6 -3
  56. package/examples/displays.mjs +21 -0
  57. package/examples/mcp/server.mjs +121 -0
  58. package/examples/node/server.mjs +16 -34
  59. package/examples/workers/worker.mjs +19 -7
  60. package/package.json +13 -1
  61. package/src/check/check.ts +386 -0
  62. package/src/check/drivers.ts +242 -0
  63. package/src/check/index.ts +22 -0
  64. package/src/check/instrument.ts +138 -0
  65. package/src/check/lint.ts +238 -0
  66. package/src/check/page-source.ts +19 -0
  67. package/src/check/page.ts +230 -0
  68. package/src/check/tools.ts +206 -0
  69. package/src/conformance/host-kit.ts +82 -27
  70. package/src/conformance/index.ts +1 -0
  71. package/src/conformance/reporter.ts +38 -0
  72. package/src/displays/displays.ts +191 -0
  73. package/src/host/client.ts +395 -0
  74. package/src/index.ts +25 -0
  75. package/src/node/index.ts +112 -2
  76. package/src/react/frame.tsx +271 -57
  77. package/src/react/index.ts +9 -0
  78. package/src/react/view.tsx +237 -0
  79. package/src/server/bootstrap.ts +97 -0
  80. package/src/server/host.ts +372 -18
  81. package/src/server/index.ts +11 -1
  82. package/src/server/pages.ts +28 -0
  83. package/src/server/proxy.ts +86 -0
  84. package/src/server/server.ts +26 -2
  85. package/src/server/types.ts +5 -0
@@ -0,0 +1,61 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import { type Finding } from "./lint.ts";
3
+ /**
4
+ * The agent's tools, as a tool list names them (P073): a name, a description and a JSON Schema
5
+ * for each, from the config, so a host lists them in one line (an MCP server's `tools/list`, an
6
+ * agent framework's tool array). The descriptions are the manual's own words.
7
+ */
8
+ /** A JSON Schema (draft 2020-12), as tool lists take it. */
9
+ export type JsonSchema = Readonly<Record<string, unknown>>;
10
+ export interface ToolDefinition {
11
+ readonly name: string;
12
+ readonly description: string;
13
+ readonly inputSchema: JsonSchema;
14
+ }
15
+ /** The topics the manual has: the built-in ones and the config's own. */
16
+ export declare function guideTopics(config: PortholeConfig): string[];
17
+ /** The tool that shows content: `{ title, html }`. */
18
+ export declare function showTool(config: PortholeConfig, options?: {
19
+ readonly name?: string;
20
+ }): ToolDefinition;
21
+ /** The tool that answers the manual: `{ topics? }`. */
22
+ export declare function guideTool(config: PortholeConfig, options?: {
23
+ readonly name?: string;
24
+ }): ToolDefinition;
25
+ /** The tool that checks content before it is shown (`checkPage`): `{ html, widths?, schemes? }`. */
26
+ export declare function checkTool(config: PortholeConfig, options?: {
27
+ readonly name?: string;
28
+ }): ToolDefinition;
29
+ /** The guide tool's answer: the manual for the topics asked, or what was wrong with the call. */
30
+ export declare function answerGuide(config: PortholeConfig, args: unknown): {
31
+ readonly text: string;
32
+ } | {
33
+ readonly error: string;
34
+ };
35
+ export type AdmitResult = {
36
+ readonly ok: true;
37
+ /** The content to show: as given, or a whole document taken as its body (a widget). */
38
+ readonly content: string;
39
+ /** Warnings (and errors, with `refuseOn: "never"`), for the tool's answer. */
40
+ readonly findings: readonly Finding[];
41
+ /** One line for the agent, or null when there's nothing to say. */
42
+ readonly note: string | null;
43
+ } | {
44
+ readonly ok: false;
45
+ readonly findings: readonly Finding[];
46
+ /** What to tell the agent: what to change, and to call the tool again. */
47
+ readonly refusal: string;
48
+ };
49
+ /**
50
+ * The show tool's check before it shows content (P073): refuses only what certainly fails or is
51
+ * cut (over the size, a document with no body where a fragment goes, nested frames,
52
+ * `document.write`); the rest is returned as warnings. `refuseOn: "never"` refuses nothing.
53
+ */
54
+ export declare function admitContent(config: PortholeConfig, content: string, options?: {
55
+ readonly refuseOn?: "error" | "never";
56
+ }): AdmitResult;
57
+ /**
58
+ * What to tell the agent when its manual changes (a display kind flipped between served and
59
+ * opaque, P073): the lines that are new, or null when the manual reads the same.
60
+ */
61
+ export declare function guideChanges(from: PortholeConfig, to: PortholeConfig): string | null;
@@ -0,0 +1,140 @@
1
+ import { BUILT_IN_TOPICS } from "../config/validate.js";
2
+ import { generateGuide, generateToolDescription } from "../guide/guide.js";
3
+ import { fragmentOf, lintContent } from "./lint.js";
4
+ const noun = (config) => config.mode === "artifact" ? "page" : config.mode === "mcp-app" ? "view" : "widget";
5
+ /** The show tool's name: the config's `guide.toolName`, else `show_<noun>`. */
6
+ const showName = (config) => config.guide.toolName ?? `show_${noun(config)}`;
7
+ /** The guide tool's name: the config's `guide.guideToolName`, else `<noun>_guide`. */
8
+ const guideName = (config) => config.guide.guideToolName ?? `${noun(config)}_guide`;
9
+ /** The topics the manual has: the built-in ones and the config's own. */
10
+ export function guideTopics(config) {
11
+ return [...BUILT_IN_TOPICS, ...Object.keys(config.guide.topics ?? {})];
12
+ }
13
+ /** The tool that shows content: `{ title, html }`. */
14
+ export function showTool(config, options = {}) {
15
+ const it = noun(config);
16
+ return {
17
+ name: options.name ?? showName(config),
18
+ description: generateToolDescription(config),
19
+ inputSchema: {
20
+ type: "object",
21
+ properties: {
22
+ title: { type: "string", description: `A short title for the ${it}, as people see it.` },
23
+ html: {
24
+ type: "string",
25
+ description: config.mode === "inline"
26
+ ? "The widget: an HTML fragment (styles, then markup, then scripts) or SVG. No <!doctype>, <html>, <head> or <body>."
27
+ : `The whole HTML ${config.mode === "mcp-app" ? "view" : "page"}.`,
28
+ },
29
+ },
30
+ required: ["title", "html"],
31
+ additionalProperties: false,
32
+ },
33
+ };
34
+ }
35
+ /** The tool that answers the manual: `{ topics? }`. */
36
+ export function guideTool(config, options = {}) {
37
+ const topics = guideTopics(config);
38
+ return {
39
+ name: options.name ?? guideName(config),
40
+ description: `The manual for ${showName(config)}: where a ${noun(config)} runs and how wide, sizes that read on a phone, colors, what the sandbox allows, and examples. Call it once before your first ${noun(config)}; ask for topics (${topics.join(", ")}) to read only those.`,
41
+ inputSchema: {
42
+ type: "object",
43
+ properties: {
44
+ topics: {
45
+ type: "array",
46
+ items: { type: "string", enum: topics },
47
+ description: "The topics to read. Default: all of them.",
48
+ },
49
+ },
50
+ additionalProperties: false,
51
+ },
52
+ };
53
+ }
54
+ /** The tool that checks content before it is shown (`checkPage`): `{ html, widths?, schemes? }`. */
55
+ export function checkTool(config, options = {}) {
56
+ const it = noun(config);
57
+ return {
58
+ name: options.name ?? `check_${it}`,
59
+ description: `Runs a ${it} in the real sandbox before anyone sees it, at phone and desktop width, in light and dark, and says what went wrong: what it throws, what the sandbox blocks, what fails to load, what overflows its width or gets cut. Call it with the ${it} you mean to show with ${showName(config)}, fix what it reports, then show it.`,
60
+ inputSchema: {
61
+ type: "object",
62
+ properties: {
63
+ html: { type: "string", description: `The ${it}, as you would show it.` },
64
+ widths: {
65
+ type: "array",
66
+ items: { type: "integer", minimum: 200, maximum: 2_000 },
67
+ description: "Widths to run it at, px. Default: the phone's and the desktop's.",
68
+ },
69
+ schemes: {
70
+ type: "array",
71
+ items: { type: "string", enum: ["light", "dark"] },
72
+ description: "Color schemes to run it in. Default: both (light only where the app doesn't theme it).",
73
+ },
74
+ },
75
+ required: ["html"],
76
+ additionalProperties: false,
77
+ },
78
+ };
79
+ }
80
+ /** The guide tool's answer: the manual for the topics asked, or what was wrong with the call. */
81
+ export function answerGuide(config, args) {
82
+ const topics = guideTopics(config);
83
+ const asked = args !== null && typeof args === "object" && !Array.isArray(args)
84
+ ? args.topics
85
+ : undefined;
86
+ if (asked === undefined) {
87
+ return { text: generateGuide(config, topics) };
88
+ }
89
+ if (!Array.isArray(asked) || asked.some((each) => typeof each !== "string")) {
90
+ return { error: `topics is a list of topic names: ${topics.join(", ")}.` };
91
+ }
92
+ const unknown = asked.filter((each) => !topics.includes(each));
93
+ if (unknown.length > 0) {
94
+ return {
95
+ error: `No topic ${unknown.map((each) => JSON.stringify(each)).join(", ")}: the topics are ${topics.join(", ")}.`,
96
+ };
97
+ }
98
+ return { text: generateGuide(config, asked.length === 0 ? topics : asked) };
99
+ }
100
+ const said = (finding) => `${finding.line === undefined ? "" : `line ${finding.line}: `}${finding.message}`;
101
+ /**
102
+ * The show tool's check before it shows content (P073): refuses only what certainly fails or is
103
+ * cut (over the size, a document with no body where a fragment goes, nested frames,
104
+ * `document.write`); the rest is returned as warnings. `refuseOn: "never"` refuses nothing.
105
+ */
106
+ export function admitContent(config, content, options = {}) {
107
+ const findings = lintContent(config, content);
108
+ const errors = findings.filter((each) => each.severity === "error");
109
+ if (errors.length > 0 && (options.refuseOn ?? "error") === "error") {
110
+ return {
111
+ ok: false,
112
+ findings,
113
+ refusal: `Not shown. Change this, then call ${showName(config)} again:\n${errors.map((each) => `- ${said(each)}`).join("\n")}`,
114
+ };
115
+ }
116
+ const document = findings.some((each) => each.rule === "document" && each.severity === "warning");
117
+ const shown = document ? (fragmentOf(content) ?? content) : content;
118
+ return {
119
+ ok: true,
120
+ content: shown,
121
+ findings,
122
+ note: findings.length === 0
123
+ ? null
124
+ : `Shown. Fix these next time:\n${findings.map((each) => `- ${said(each)}`).join("\n")}`,
125
+ };
126
+ }
127
+ /**
128
+ * What to tell the agent when its manual changes (a display kind flipped between served and
129
+ * opaque, P073): the lines that are new, or null when the manual reads the same.
130
+ */
131
+ export function guideChanges(from, to) {
132
+ const text = (config) => [generateToolDescription(config), generateGuide(config, guideTopics(config))].join("\n");
133
+ const before = new Set(text(from).split("\n"));
134
+ const after = text(to).split("\n");
135
+ const added = after.filter((line) => line.trim() !== "" && !before.has(line));
136
+ if (added.length === 0) {
137
+ return null;
138
+ }
139
+ return `The manual for ${showName(to)} changed. It now says:\n${added.map((line) => `- ${line.replace(/^- /u, "")}`).join("\n")}`;
140
+ }
@@ -1,5 +1,6 @@
1
1
  import { type Page, type TestType } from "@playwright/test";
2
2
  import type { PortholeConfig } from "../config/schema.ts";
3
+ import type { Displays } from "../displays/displays.ts";
3
4
  import type { FrameLocation, InstanceRef } from "../isolation/types.ts";
4
5
  import { type EntryConformanceHost } from "./entry.ts";
5
6
  export { conformancePage } from "./page.ts";
@@ -38,8 +39,19 @@ export interface HostConformanceOptions {
38
39
  };
39
40
  /** Or the location for an instance, got the test's own way. */
40
41
  readonly locate?: (instance: InstanceRef, page: Page) => Promise<FrameLocation>;
41
- /** The config a served instance is framed under (the app's served config for its preset). */
42
- readonly config: (instance: InstanceRef) => PortholeConfig;
42
+ /**
43
+ * The config a served instance is framed under (the app's served config for its preset). Or
44
+ * `displays` with `contentSource` (P072), which say it for every kind.
45
+ */
46
+ readonly config?: (instance: InstanceRef) => PortholeConfig;
47
+ /** The app's display kinds (`defineDisplays`), in place of `config`. */
48
+ readonly displays?: Displays;
49
+ /**
50
+ * The content source `displays` serve from (`http://*.content.localhost:8790`). A function is
51
+ * asked when a case needs it (P074): a test server's port that isn't known when the spec file
52
+ * loads.
53
+ */
54
+ readonly contentSource?: string | (() => string);
43
55
  /**
44
56
  * The instances the served cases ask for, each for the scope a case names (may be async: a
45
57
  * page published on demand, `onDemand`). Give what the app serves; the cases for the rest are
@@ -109,9 +121,18 @@ export interface ConformanceProject {
109
121
  * preferences its WebRTC probe needs (loopback ICE). Pass `devices` from `@playwright/test`
110
122
  * (P071).
111
123
  */
112
- export declare function conformanceProjects(devices: Readonly<Record<string, Record<string, unknown>>>, options?: {
113
- readonly engines?: readonly ("chromium" | "webkit" | "firefox")[];
114
- }): ConformanceProject[];
124
+ export interface ConformanceProjectsOptions {
125
+ readonly engines?: readonly ConformanceProject["name"][];
126
+ /** Added to every project's `use` (a trace setting, `ignoreHTTPSErrors`, a `baseURL`). */
127
+ readonly use?: Readonly<Record<string, unknown>>;
128
+ /**
129
+ * Each engine's launch options, merged with Porthole's own (P074): a system browser's
130
+ * `executablePath` and `args` (`{ chromium: { executablePath: "/usr/bin/chromium" } }`, on a box
131
+ * Playwright has no Chromium build for). Firefox's preferences add to the ones its probes need.
132
+ */
133
+ readonly launchOptions?: Partial<Readonly<Record<ConformanceProject["name"], Readonly<Record<string, unknown>>>>>;
134
+ }
135
+ export declare function conformanceProjects(devices: Readonly<Record<string, Record<string, unknown>>>, options?: ConformanceProjectsOptions): ConformanceProject[];
115
136
  /**
116
137
  * Registers the leak and served suites against an app's real page, in a spec file of the app's
117
138
  * (so `-g "\[1\.connect\]"` selects one). The served cases for instances the app didn't give are
@@ -69,6 +69,13 @@ async function frameIn(page, id) {
69
69
  }
70
70
  /** The leak and served hosts on an app's real page, for an app that registers the cases itself. */
71
71
  export function hostConformance(options) {
72
+ const { displays, contentSource } = options;
73
+ const configOf = options.config ??
74
+ (displays !== undefined && contentSource !== undefined
75
+ ? (instance) => displays.configFor(instance, typeof contentSource === "function" ? contentSource() : contentSource)
76
+ : () => {
77
+ throw new TypeError("hostConformance needs config, or displays with contentSource");
78
+ });
72
79
  let current = null;
73
80
  const opened = new WeakSet();
74
81
  const hits = new Map();
@@ -172,7 +179,7 @@ export function hostConformance(options) {
172
179
  ...(options.issue.headers === undefined ? {} : { headers: options.issue.headers }),
173
180
  }
174
181
  : { location: await locate(instance) };
175
- const id = await invoke(page, "show", options.config(instance), instance, where, given.content);
182
+ const id = await invoke(page, "show", configOf(instance), instance, where, given.content);
176
183
  let origin = null;
177
184
  await expect
178
185
  .poll(async () => {
@@ -240,7 +247,7 @@ export function hostConformance(options) {
240
247
  async frame(page, url) {
241
248
  await ready(page);
242
249
  const instance = await served.artifact("entry", "1");
243
- const id = await invoke(page, "show", options.config(instance), instance, {
250
+ const id = await invoke(page, "show", configOf(instance), instance, {
244
251
  location: { url, origin: new URL(url).origin },
245
252
  });
246
253
  return {
@@ -338,30 +345,47 @@ export function onDemand(make) {
338
345
  return found;
339
346
  };
340
347
  }
341
- /**
342
- * The Playwright projects to run the suite on: Chromium, WebKit and Firefox, Firefox with the
343
- * preferences its WebRTC probe needs (loopback ICE). Pass `devices` from `@playwright/test`
344
- * (P071).
345
- */
348
+ const recordOf = (value) => value !== null && typeof value === "object" ? value : {};
346
349
  export function conformanceProjects(devices, options = {}) {
347
- const all = [
348
- { name: "chromium", use: { ...devices["Desktop Chrome"] } },
349
- { name: "webkit", use: { ...devices["Desktop Safari"] } },
350
- {
351
- name: "firefox",
352
- use: {
353
- ...devices["Desktop Firefox"],
354
- launchOptions: {
355
- firefoxUserPrefs: {
356
- "media.peerconnection.ice.loopback": true,
357
- "media.peerconnection.ice.obfuscate_host_addresses": false,
358
- },
359
- },
350
+ const DEVICE = {
351
+ chromium: "Desktop Chrome",
352
+ webkit: "Desktop Safari",
353
+ firefox: "Desktop Firefox",
354
+ };
355
+ /** Porthole's own launch options: Firefox's WebRTC probe needs loopback ICE. */
356
+ const OWN = {
357
+ chromium: {},
358
+ webkit: {},
359
+ firefox: {
360
+ firefoxUserPrefs: {
361
+ "media.peerconnection.ice.loopback": true,
362
+ "media.peerconnection.ice.obfuscate_host_addresses": false,
360
363
  },
361
364
  },
362
- ];
365
+ };
363
366
  const engines = options.engines ?? ["chromium", "webkit", "firefox"];
364
- return all.filter((project) => engines.includes(project.name));
367
+ return ["chromium", "webkit", "firefox"]
368
+ .filter((name) => engines.includes(name))
369
+ .map((name) => {
370
+ const given = { ...recordOf(options.use?.launchOptions), ...options.launchOptions?.[name] };
371
+ const prefs = {
372
+ ...recordOf(OWN[name].firefoxUserPrefs),
373
+ ...recordOf(given.firefoxUserPrefs),
374
+ };
375
+ const launchOptions = {
376
+ ...OWN[name],
377
+ ...given,
378
+ ...(Object.keys(prefs).length === 0 ? {} : { firefoxUserPrefs: prefs }),
379
+ };
380
+ return {
381
+ name,
382
+ use: {
383
+ ...devices[DEVICE[name]],
384
+ ...options.use,
385
+ ...(Object.keys(launchOptions).length === 0 ? {} : { launchOptions }),
386
+ },
387
+ };
388
+ });
365
389
  }
366
390
  /**
367
391
  * Registers the leak and served suites against an app's real page, in a spec file of the app's
@@ -102,4 +102,4 @@ export { defineLeakSuite, leakTests, PROBES, type ConformanceFixtures, type Conf
102
102
  export { httpOracle, settle, udpOracle, type HttpOracle, type UdpOracle } from "./oracles.ts";
103
103
  export { defineServedSuite, servedTests, type ServedConformanceHost, type ServedDisplay, type ServedSuiteOptions, } from "./served.ts";
104
104
  export { entryTests, type EntryConformanceHost, type EntrySuiteOptions } from "./entry.ts";
105
- export { conformancePage, conformanceProjects, defineHostConformance, harnessScript, hostConformance, onDemand, type ConformanceProject, type HostConformance, type HostConformanceOptions, } from "./host-kit.ts";
105
+ export { conformancePage, conformanceProjects, defineHostConformance, harnessScript, hostConformance, onDemand, type ConformanceProject, type ConformanceProjectsOptions, type HostConformance, type HostConformanceOptions, } from "./host-kit.ts";
@@ -0,0 +1,14 @@
1
+ import type { FullResult, Reporter, TestCase, TestResult } from "@playwright/test/reporter";
2
+ /**
3
+ * A Playwright reporter that says why each conformance case was skipped (P074): the list and line
4
+ * reporters show a skipped case as "-" with no reason, and an inapplicable probe ("the page's own
5
+ * CSP, which an opaque frame inherits, blocks … (connect-src)") is a fact worth reading.
6
+ *
7
+ * reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
8
+ */
9
+ export default class SkipReasons implements Reporter {
10
+ #private;
11
+ printsToStdio(): boolean;
12
+ onTestEnd(test: TestCase, result: TestResult): void;
13
+ onEnd(_result: FullResult): void;
14
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A Playwright reporter that says why each conformance case was skipped (P074): the list and line
3
+ * reporters show a skipped case as "-" with no reason, and an inapplicable probe ("the page's own
4
+ * CSP, which an opaque frame inherits, blocks … (connect-src)") is a fact worth reading.
5
+ *
6
+ * reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
7
+ */
8
+ export default class SkipReasons {
9
+ #skipped = new Map();
10
+ printsToStdio() {
11
+ return true;
12
+ }
13
+ onTestEnd(test, result) {
14
+ if (result.status !== "skipped") {
15
+ return;
16
+ }
17
+ const reason = [...result.annotations, ...test.annotations].find((each) => each.type === "skip" && each.description !== undefined && each.description !== "")?.description ?? "skipped";
18
+ const title = test.title.length > 90 ? `${test.title.slice(0, 89)}…` : test.title;
19
+ this.#skipped.set(`${title}\u0000${reason}`, `${title}: ${reason}`);
20
+ }
21
+ onEnd(_result) {
22
+ if (this.#skipped.size === 0) {
23
+ return;
24
+ }
25
+ const lines = [...this.#skipped.values()].toSorted();
26
+ process.stdout.write(`\nSkipped (${lines.length}), and why:\n${lines.map((each) => ` - ${each}`).join("\n")}\n`);
27
+ }
28
+ }
@@ -0,0 +1,61 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import type { InstanceRef } from "../isolation/types.ts";
3
+ import { type PresetOptions, type UrlPresetOptions } from "../presets/presets.ts";
4
+ /**
5
+ * Every kind of display an app shows, in one registry (P072): the server serves under it, the
6
+ * page frames under it, its CSP and the agent's manual come from it, and the conformance runner
7
+ * checks it. One place for a kind's options, where apps kept four copies that drifted.
8
+ *
9
+ * const displays = defineDisplays({
10
+ * widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {} } } },
11
+ * page: { preset: "artifact", options: { layout: { kind: "fill" } } },
12
+ * preview: { preset: "url" }, // url mode: served only
13
+ * });
14
+ *
15
+ * A kind's name is the preset name its documents carry (`ServedDocument`'s `preset`): an
16
+ * artifact names `artifact` unless it says otherwise, so a stored-pages app calls its kind
17
+ * `artifact`, or puts `preset: "page"` in its instances.
18
+ */
19
+ export type DisplayKind = {
20
+ readonly preset: "inlineWidget" | "artifact" | "mcpApp";
21
+ readonly options?: PresetOptions;
22
+ /** Options added when served on content origins (domain isolation): storage, egress. */
23
+ readonly served?: Omit<PresetOptions, "isolation" | "contentOrigins">;
24
+ } | {
25
+ /** A running app by URL: served only. */
26
+ readonly preset: "url";
27
+ readonly options?: Omit<UrlPresetOptions, "contentOrigins">;
28
+ };
29
+ export interface Displays<N extends string = string> {
30
+ readonly kinds: readonly N[];
31
+ /** The kind's config in an opaque frame (no content origins). Url kinds have none: throws. */
32
+ opaque(kind: N): PortholeConfig;
33
+ /**
34
+ * Every kind's config served from `contentSource` (`https://*.example-usercontent.com`): made
35
+ * once per source. Null, with `problem(source)` saying why, where a kind can't be served so.
36
+ */
37
+ served(contentSource: string): Readonly<Record<N, PortholeConfig>> | null;
38
+ /** Why `served(contentSource)` is null, or null. */
39
+ problem(contentSource: string): string | null;
40
+ /** The config an instance shows under: its kind, served (a source) or opaque (null). */
41
+ configFor(instance: InstanceRef, contentSource: string | null): PortholeConfig;
42
+ /** The kind an instance's document names, or null. */
43
+ kindOf(instance: InstanceRef): N | null;
44
+ /**
45
+ * The page's `frame-src`, without a ContentHost (a dev server, a desktop shell): every kind's
46
+ * frames, served or opaque, and the authorize route's path when clean addresses frame.
47
+ */
48
+ frameSources(contentSource: string | null, options?: {
49
+ readonly authorizeUrl?: string;
50
+ }): readonly string[];
51
+ /** The same, as a `frame-src` directive. */
52
+ embedderCsp(contentSource: string | null, options?: {
53
+ readonly authorizeUrl?: string;
54
+ }): string;
55
+ /**
56
+ * The kind's config for the agent's manual and tool description, served or opaque, without a
57
+ * real content origin (the manual names none).
58
+ */
59
+ guideConfig(kind: N, mode: "served" | "opaque"): PortholeConfig;
60
+ }
61
+ export declare function defineDisplays<N extends string>(kinds: Readonly<Record<N, DisplayKind>>): Displays<N>;
@@ -0,0 +1,113 @@
1
+ import { embedderFrameSourcesOf } from "../compile/policy.js";
2
+ import { ConfigError } from "../config/validate.js";
3
+ import { presets } from "../presets/presets.js";
4
+ /** A content source for a manual written before any content origin exists. */
5
+ const GUIDE_SOURCE = "https://*.porthole-content.invalid";
6
+ export function defineDisplays(kinds) {
7
+ const names = Object.keys(kinds);
8
+ if (names.length === 0) {
9
+ throw new TypeError("defineDisplays needs at least one kind");
10
+ }
11
+ const kindOf = (name) => {
12
+ const kind = kinds[name];
13
+ if (kind === undefined) {
14
+ throw new TypeError(`No display kind ${JSON.stringify(name)} (defineDisplays)`);
15
+ }
16
+ return kind;
17
+ };
18
+ const build = (name, source) => {
19
+ const kind = kindOf(name);
20
+ if (kind.preset === "url") {
21
+ if (source === null) {
22
+ throw new TypeError(`The display kind ${JSON.stringify(name)} is a url-mode app: served only`);
23
+ }
24
+ return presets.url({ ...kind.options, contentOrigins: [source] });
25
+ }
26
+ const options = kind.options ?? {};
27
+ return presets[kind.preset](source === null
28
+ ? options
29
+ : { ...options, ...kind.served, isolation: "domain", contentOrigins: [source] });
30
+ };
31
+ // Made once each: a page that asks every render gets the same objects.
32
+ const opaque = new Map();
33
+ const served = new Map();
34
+ const servedOf = (source) => {
35
+ let found = served.get(source);
36
+ if (found === undefined) {
37
+ try {
38
+ found = Object.fromEntries(names.map((name) => [name, build(name, source)]));
39
+ }
40
+ catch (error) {
41
+ if (!(error instanceof ConfigError) && !(error instanceof TypeError)) {
42
+ throw error;
43
+ }
44
+ found = error.message;
45
+ }
46
+ served.set(source, found);
47
+ }
48
+ return found;
49
+ };
50
+ const displays = {
51
+ kinds: names,
52
+ opaque(name) {
53
+ let found = opaque.get(name);
54
+ if (found === undefined) {
55
+ found = build(name, null);
56
+ opaque.set(name, found);
57
+ }
58
+ return found;
59
+ },
60
+ served(source) {
61
+ const found = servedOf(source);
62
+ return typeof found === "string" ? null : found;
63
+ },
64
+ problem(source) {
65
+ const found = servedOf(source);
66
+ return typeof found === "string" ? found : null;
67
+ },
68
+ kindOf(instance) {
69
+ const { document } = instance;
70
+ const named = document.kind === "shell"
71
+ ? document.preset
72
+ : document.kind === "artifact"
73
+ ? (document.preset ?? "artifact")
74
+ : document.kind === "mcp-proxy"
75
+ ? (document.preset ?? "mcpApp")
76
+ : (names.find((name) => kinds[name]?.preset === "url") ?? null);
77
+ return named !== null && names.includes(named) ? named : null;
78
+ },
79
+ configFor(instance, source) {
80
+ const name = displays.kindOf(instance);
81
+ if (name === null) {
82
+ throw new TypeError(`No display kind for an instance of kind ${instance.document.kind} (defineDisplays: ${names.join(", ")})`);
83
+ }
84
+ if (source === null) {
85
+ return displays.opaque(name);
86
+ }
87
+ const all = displays.served(source);
88
+ if (all === null) {
89
+ throw new TypeError(displays.problem(source) ?? "Not servable");
90
+ }
91
+ return all[name];
92
+ },
93
+ frameSources(source, options = {}) {
94
+ const configs = source === null
95
+ ? names
96
+ .filter((name) => kinds[name]?.preset !== "url")
97
+ .map((name) => displays.opaque(name))
98
+ : Object.values(displays.served(source) ?? {});
99
+ const authorize = options.authorizeUrl === undefined
100
+ ? []
101
+ : [`${new URL(options.authorizeUrl).origin}${new URL(options.authorizeUrl).pathname}`];
102
+ return [...embedderFrameSourcesOf(configs), ...authorize];
103
+ },
104
+ embedderCsp(source, options = {}) {
105
+ const sources = displays.frameSources(source, options);
106
+ return `frame-src ${sources.length === 0 ? "'none'" : sources.join(" ")}`;
107
+ },
108
+ guideConfig(name, mode) {
109
+ return mode === "opaque" ? displays.opaque(name) : build(name, GUIDE_SOURCE);
110
+ },
111
+ };
112
+ return displays;
113
+ }