@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,206 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import { BUILT_IN_TOPICS } from "../config/validate.ts";
3
+ import { generateGuide, generateToolDescription } from "../guide/guide.ts";
4
+ import { fragmentOf, lintContent, type Finding } from "./lint.ts";
5
+
6
+ /**
7
+ * The agent's tools, as a tool list names them (P073): a name, a description and a JSON Schema
8
+ * for each, from the config, so a host lists them in one line (an MCP server's `tools/list`, an
9
+ * agent framework's tool array). The descriptions are the manual's own words.
10
+ */
11
+
12
+ /** A JSON Schema (draft 2020-12), as tool lists take it. */
13
+ export type JsonSchema = Readonly<Record<string, unknown>>;
14
+
15
+ export interface ToolDefinition {
16
+ readonly name: string;
17
+ readonly description: string;
18
+ readonly inputSchema: JsonSchema;
19
+ }
20
+
21
+ const noun = (config: PortholeConfig) =>
22
+ config.mode === "artifact" ? "page" : config.mode === "mcp-app" ? "view" : "widget";
23
+
24
+ /** The show tool's name: the config's `guide.toolName`, else `show_<noun>`. */
25
+ const showName = (config: PortholeConfig) => config.guide.toolName ?? `show_${noun(config)}`;
26
+ /** The guide tool's name: the config's `guide.guideToolName`, else `<noun>_guide`. */
27
+ const guideName = (config: PortholeConfig) => config.guide.guideToolName ?? `${noun(config)}_guide`;
28
+
29
+ /** The topics the manual has: the built-in ones and the config's own. */
30
+ export function guideTopics(config: PortholeConfig): string[] {
31
+ return [...BUILT_IN_TOPICS, ...Object.keys(config.guide.topics ?? {})];
32
+ }
33
+
34
+ /** The tool that shows content: `{ title, html }`. */
35
+ export function showTool(
36
+ config: PortholeConfig,
37
+ options: { readonly name?: string } = {},
38
+ ): ToolDefinition {
39
+ const it = noun(config);
40
+ return {
41
+ name: options.name ?? showName(config),
42
+ description: generateToolDescription(config),
43
+ inputSchema: {
44
+ type: "object",
45
+ properties: {
46
+ title: { type: "string", description: `A short title for the ${it}, as people see it.` },
47
+ html: {
48
+ type: "string",
49
+ description:
50
+ config.mode === "inline"
51
+ ? "The widget: an HTML fragment (styles, then markup, then scripts) or SVG. No <!doctype>, <html>, <head> or <body>."
52
+ : `The whole HTML ${config.mode === "mcp-app" ? "view" : "page"}.`,
53
+ },
54
+ },
55
+ required: ["title", "html"],
56
+ additionalProperties: false,
57
+ },
58
+ };
59
+ }
60
+
61
+ /** The tool that answers the manual: `{ topics? }`. */
62
+ export function guideTool(
63
+ config: PortholeConfig,
64
+ options: { readonly name?: string } = {},
65
+ ): ToolDefinition {
66
+ const topics = guideTopics(config);
67
+ return {
68
+ name: options.name ?? guideName(config),
69
+ 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.`,
70
+ inputSchema: {
71
+ type: "object",
72
+ properties: {
73
+ topics: {
74
+ type: "array",
75
+ items: { type: "string", enum: topics },
76
+ description: "The topics to read. Default: all of them.",
77
+ },
78
+ },
79
+ additionalProperties: false,
80
+ },
81
+ };
82
+ }
83
+
84
+ /** The tool that checks content before it is shown (`checkPage`): `{ html, widths?, schemes? }`. */
85
+ export function checkTool(
86
+ config: PortholeConfig,
87
+ options: { readonly name?: string } = {},
88
+ ): ToolDefinition {
89
+ const it = noun(config);
90
+ return {
91
+ name: options.name ?? `check_${it}`,
92
+ 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.`,
93
+ inputSchema: {
94
+ type: "object",
95
+ properties: {
96
+ html: { type: "string", description: `The ${it}, as you would show it.` },
97
+ widths: {
98
+ type: "array",
99
+ items: { type: "integer", minimum: 200, maximum: 2_000 },
100
+ description: "Widths to run it at, px. Default: the phone's and the desktop's.",
101
+ },
102
+ schemes: {
103
+ type: "array",
104
+ items: { type: "string", enum: ["light", "dark"] },
105
+ description:
106
+ "Color schemes to run it in. Default: both (light only where the app doesn't theme it).",
107
+ },
108
+ },
109
+ required: ["html"],
110
+ additionalProperties: false,
111
+ },
112
+ };
113
+ }
114
+
115
+ /** The guide tool's answer: the manual for the topics asked, or what was wrong with the call. */
116
+ export function answerGuide(
117
+ config: PortholeConfig,
118
+ args: unknown,
119
+ ): { readonly text: string } | { readonly error: string } {
120
+ const topics = guideTopics(config);
121
+ const asked =
122
+ args !== null && typeof args === "object" && !Array.isArray(args)
123
+ ? (args as { topics?: unknown }).topics
124
+ : undefined;
125
+ if (asked === undefined) {
126
+ return { text: generateGuide(config, topics) };
127
+ }
128
+ if (!Array.isArray(asked) || asked.some((each) => typeof each !== "string")) {
129
+ return { error: `topics is a list of topic names: ${topics.join(", ")}.` };
130
+ }
131
+ const unknown = (asked as string[]).filter((each) => !topics.includes(each));
132
+ if (unknown.length > 0) {
133
+ return {
134
+ error: `No topic ${unknown.map((each) => JSON.stringify(each)).join(", ")}: the topics are ${topics.join(", ")}.`,
135
+ };
136
+ }
137
+ return { text: generateGuide(config, asked.length === 0 ? topics : (asked as string[])) };
138
+ }
139
+
140
+ export type AdmitResult =
141
+ | {
142
+ readonly ok: true;
143
+ /** The content to show: as given, or a whole document taken as its body (a widget). */
144
+ readonly content: string;
145
+ /** Warnings (and errors, with `refuseOn: "never"`), for the tool's answer. */
146
+ readonly findings: readonly Finding[];
147
+ /** One line for the agent, or null when there's nothing to say. */
148
+ readonly note: string | null;
149
+ }
150
+ | {
151
+ readonly ok: false;
152
+ readonly findings: readonly Finding[];
153
+ /** What to tell the agent: what to change, and to call the tool again. */
154
+ readonly refusal: string;
155
+ };
156
+
157
+ const said = (finding: Finding) =>
158
+ `${finding.line === undefined ? "" : `line ${finding.line}: `}${finding.message}`;
159
+
160
+ /**
161
+ * The show tool's check before it shows content (P073): refuses only what certainly fails or is
162
+ * cut (over the size, a document with no body where a fragment goes, nested frames,
163
+ * `document.write`); the rest is returned as warnings. `refuseOn: "never"` refuses nothing.
164
+ */
165
+ export function admitContent(
166
+ config: PortholeConfig,
167
+ content: string,
168
+ options: { readonly refuseOn?: "error" | "never" } = {},
169
+ ): AdmitResult {
170
+ const findings = lintContent(config, content);
171
+ const errors = findings.filter((each) => each.severity === "error");
172
+ if (errors.length > 0 && (options.refuseOn ?? "error") === "error") {
173
+ return {
174
+ ok: false,
175
+ findings,
176
+ refusal: `Not shown. Change this, then call ${showName(config)} again:\n${errors.map((each) => `- ${said(each)}`).join("\n")}`,
177
+ };
178
+ }
179
+ const document = findings.some((each) => each.rule === "document" && each.severity === "warning");
180
+ const shown = document ? (fragmentOf(content) ?? content) : content;
181
+ return {
182
+ ok: true,
183
+ content: shown,
184
+ findings,
185
+ note:
186
+ findings.length === 0
187
+ ? null
188
+ : `Shown. Fix these next time:\n${findings.map((each) => `- ${said(each)}`).join("\n")}`,
189
+ };
190
+ }
191
+
192
+ /**
193
+ * What to tell the agent when its manual changes (a display kind flipped between served and
194
+ * opaque, P073): the lines that are new, or null when the manual reads the same.
195
+ */
196
+ export function guideChanges(from: PortholeConfig, to: PortholeConfig): string | null {
197
+ const text = (config: PortholeConfig) =>
198
+ [generateToolDescription(config), generateGuide(config, guideTopics(config))].join("\n");
199
+ const before = new Set(text(from).split("\n"));
200
+ const after = text(to).split("\n");
201
+ const added = after.filter((line) => line.trim() !== "" && !before.has(line));
202
+ if (added.length === 0) {
203
+ return null;
204
+ }
205
+ return `The manual for ${showName(to)} changed. It now says:\n${added.map((line) => `- ${line.replace(/^- /u, "")}`).join("\n")}`;
206
+ }
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
3
3
  import { runInThisContext } from "node:vm";
4
4
  import { expect, type Frame, type Page, type TestInfo, type TestType } from "@playwright/test";
5
5
  import type { PortholeConfig } from "../config/schema.ts";
6
+ import type { Displays } from "../displays/displays.ts";
6
7
  import type { FrameLocation, InstanceRef } from "../isolation/types.ts";
7
8
  import { entryTests, type EntryConformanceHost } from "./entry.ts";
8
9
  export { conformancePage } from "./page.ts";
@@ -43,8 +44,19 @@ export interface HostConformanceOptions {
43
44
  readonly issue?: { readonly url: string; readonly headers?: Readonly<Record<string, string>> };
44
45
  /** Or the location for an instance, got the test's own way. */
45
46
  readonly locate?: (instance: InstanceRef, page: Page) => Promise<FrameLocation>;
46
- /** The config a served instance is framed under (the app's served config for its preset). */
47
- readonly config: (instance: InstanceRef) => PortholeConfig;
47
+ /**
48
+ * The config a served instance is framed under (the app's served config for its preset). Or
49
+ * `displays` with `contentSource` (P072), which say it for every kind.
50
+ */
51
+ readonly config?: (instance: InstanceRef) => PortholeConfig;
52
+ /** The app's display kinds (`defineDisplays`), in place of `config`. */
53
+ readonly displays?: Displays;
54
+ /**
55
+ * The content source `displays` serve from (`http://*.content.localhost:8790`). A function is
56
+ * asked when a case needs it (P074): a test server's port that isn't known when the spec file
57
+ * loads.
58
+ */
59
+ readonly contentSource?: string | (() => string);
48
60
  /**
49
61
  * The instances the served cases ask for, each for the scope a case names (may be async: a
50
62
  * page published on demand, `onDemand`). Give what the app serves; the cases for the rest are
@@ -170,6 +182,18 @@ export interface HostConformance {
170
182
 
171
183
  /** The leak and served hosts on an app's real page, for an app that registers the cases itself. */
172
184
  export function hostConformance(options: HostConformanceOptions): HostConformance {
185
+ const { displays, contentSource } = options;
186
+ const configOf =
187
+ options.config ??
188
+ (displays !== undefined && contentSource !== undefined
189
+ ? (instance: InstanceRef) =>
190
+ displays.configFor(
191
+ instance,
192
+ typeof contentSource === "function" ? contentSource() : contentSource,
193
+ )
194
+ : () => {
195
+ throw new TypeError("hostConformance needs config, or displays with contentSource");
196
+ });
173
197
  let current: Page | null = null;
174
198
  const opened = new WeakSet<Page>();
175
199
  const hits = new Map<string, number>();
@@ -288,14 +312,7 @@ export function hostConformance(options: HostConformanceOptions): HostConformanc
288
312
  ...(options.issue.headers === undefined ? {} : { headers: options.issue.headers }),
289
313
  }
290
314
  : { location: await locate(instance) };
291
- const id = await invoke(
292
- page,
293
- "show",
294
- options.config(instance),
295
- instance,
296
- where,
297
- given.content,
298
- );
315
+ const id = await invoke(page, "show", configOf(instance), instance, where, given.content);
299
316
  let origin: string | null = null;
300
317
  await expect
301
318
  .poll(
@@ -371,7 +388,7 @@ export function hostConformance(options: HostConformanceOptions): HostConformanc
371
388
  async frame(page, url) {
372
389
  await ready(page);
373
390
  const instance = await served.artifact("entry", "1");
374
- const id = await invoke(page, "show", options.config(instance), instance, {
391
+ const id = await invoke(page, "show", configOf(instance), instance, {
375
392
  location: { url, origin: new URL(url).origin },
376
393
  });
377
394
  return {
@@ -492,28 +509,66 @@ export interface ConformanceProject {
492
509
  * preferences its WebRTC probe needs (loopback ICE). Pass `devices` from `@playwright/test`
493
510
  * (P071).
494
511
  */
512
+ export interface ConformanceProjectsOptions {
513
+ readonly engines?: readonly ConformanceProject["name"][];
514
+ /** Added to every project's `use` (a trace setting, `ignoreHTTPSErrors`, a `baseURL`). */
515
+ readonly use?: Readonly<Record<string, unknown>>;
516
+ /**
517
+ * Each engine's launch options, merged with Porthole's own (P074): a system browser's
518
+ * `executablePath` and `args` (`{ chromium: { executablePath: "/usr/bin/chromium" } }`, on a box
519
+ * Playwright has no Chromium build for). Firefox's preferences add to the ones its probes need.
520
+ */
521
+ readonly launchOptions?: Partial<
522
+ Readonly<Record<ConformanceProject["name"], Readonly<Record<string, unknown>>>>
523
+ >;
524
+ }
525
+
526
+ const recordOf = (value: unknown): Record<string, unknown> =>
527
+ value !== null && typeof value === "object" ? (value as Record<string, unknown>) : {};
528
+
495
529
  export function conformanceProjects(
496
530
  devices: Readonly<Record<string, Record<string, unknown>>>,
497
- options: { readonly engines?: readonly ("chromium" | "webkit" | "firefox")[] } = {},
531
+ options: ConformanceProjectsOptions = {},
498
532
  ): ConformanceProject[] {
499
- const all: ConformanceProject[] = [
500
- { name: "chromium", use: { ...devices["Desktop Chrome"] } },
501
- { name: "webkit", use: { ...devices["Desktop Safari"] } },
502
- {
503
- name: "firefox",
504
- use: {
505
- ...devices["Desktop Firefox"],
506
- launchOptions: {
507
- firefoxUserPrefs: {
508
- "media.peerconnection.ice.loopback": true,
509
- "media.peerconnection.ice.obfuscate_host_addresses": false,
510
- },
511
- },
533
+ const DEVICE = {
534
+ chromium: "Desktop Chrome",
535
+ webkit: "Desktop Safari",
536
+ firefox: "Desktop Firefox",
537
+ } as const;
538
+ /** Porthole's own launch options: Firefox's WebRTC probe needs loopback ICE. */
539
+ const OWN: Readonly<Record<ConformanceProject["name"], Record<string, unknown>>> = {
540
+ chromium: {},
541
+ webkit: {},
542
+ firefox: {
543
+ firefoxUserPrefs: {
544
+ "media.peerconnection.ice.loopback": true,
545
+ "media.peerconnection.ice.obfuscate_host_addresses": false,
512
546
  },
513
547
  },
514
- ];
548
+ };
515
549
  const engines = options.engines ?? ["chromium", "webkit", "firefox"];
516
- return all.filter((project) => engines.includes(project.name));
550
+ return (["chromium", "webkit", "firefox"] as const)
551
+ .filter((name) => engines.includes(name))
552
+ .map((name) => {
553
+ const given = { ...recordOf(options.use?.launchOptions), ...options.launchOptions?.[name] };
554
+ const prefs = {
555
+ ...recordOf(OWN[name].firefoxUserPrefs),
556
+ ...recordOf(given.firefoxUserPrefs),
557
+ };
558
+ const launchOptions = {
559
+ ...OWN[name],
560
+ ...given,
561
+ ...(Object.keys(prefs).length === 0 ? {} : { firefoxUserPrefs: prefs }),
562
+ };
563
+ return {
564
+ name,
565
+ use: {
566
+ ...devices[DEVICE[name]],
567
+ ...options.use,
568
+ ...(Object.keys(launchOptions).length === 0 ? {} : { launchOptions }),
569
+ },
570
+ };
571
+ });
517
572
  }
518
573
 
519
574
  /**
@@ -129,6 +129,7 @@ export {
129
129
  hostConformance,
130
130
  onDemand,
131
131
  type ConformanceProject,
132
+ type ConformanceProjectsOptions,
132
133
  type HostConformance,
133
134
  type HostConformanceOptions,
134
135
  } from "./host-kit.ts";
@@ -0,0 +1,38 @@
1
+ import type { FullResult, Reporter, TestCase, TestResult } from "@playwright/test/reporter";
2
+
3
+ /**
4
+ * A Playwright reporter that says why each conformance case was skipped (P074): the list and line
5
+ * reporters show a skipped case as "-" with no reason, and an inapplicable probe ("the page's own
6
+ * CSP, which an opaque frame inherits, blocks … (connect-src)") is a fact worth reading.
7
+ *
8
+ * reporter: [["list"], ["@botiverse/porthole/conformance/reporter"]],
9
+ */
10
+ export default class SkipReasons implements Reporter {
11
+ readonly #skipped = new Map<string, string>();
12
+
13
+ printsToStdio(): boolean {
14
+ return true;
15
+ }
16
+
17
+ onTestEnd(test: TestCase, result: TestResult): void {
18
+ if (result.status !== "skipped") {
19
+ return;
20
+ }
21
+ const reason =
22
+ [...result.annotations, ...test.annotations].find(
23
+ (each) => each.type === "skip" && each.description !== undefined && each.description !== "",
24
+ )?.description ?? "skipped";
25
+ const title = test.title.length > 90 ? `${test.title.slice(0, 89)}…` : test.title;
26
+ this.#skipped.set(`${title}\u0000${reason}`, `${title}: ${reason}`);
27
+ }
28
+
29
+ onEnd(_result: FullResult): void {
30
+ if (this.#skipped.size === 0) {
31
+ return;
32
+ }
33
+ const lines = [...this.#skipped.values()].toSorted();
34
+ process.stdout.write(
35
+ `\nSkipped (${lines.length}), and why:\n${lines.map((each) => ` - ${each}`).join("\n")}\n`,
36
+ );
37
+ }
38
+ }
@@ -0,0 +1,191 @@
1
+ import { embedderFrameSourcesOf } from "../compile/policy.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
3
+ import { ConfigError } from "../config/validate.ts";
4
+ import type { InstanceRef } from "../isolation/types.ts";
5
+ import { presets, type PresetOptions, type UrlPresetOptions } from "../presets/presets.ts";
6
+
7
+ /**
8
+ * Every kind of display an app shows, in one registry (P072): the server serves under it, the
9
+ * page frames under it, its CSP and the agent's manual come from it, and the conformance runner
10
+ * checks it. One place for a kind's options, where apps kept four copies that drifted.
11
+ *
12
+ * const displays = defineDisplays({
13
+ * widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {} } } },
14
+ * page: { preset: "artifact", options: { layout: { kind: "fill" } } },
15
+ * preview: { preset: "url" }, // url mode: served only
16
+ * });
17
+ *
18
+ * A kind's name is the preset name its documents carry (`ServedDocument`'s `preset`): an
19
+ * artifact names `artifact` unless it says otherwise, so a stored-pages app calls its kind
20
+ * `artifact`, or puts `preset: "page"` in its instances.
21
+ */
22
+
23
+ export type DisplayKind =
24
+ | {
25
+ readonly preset: "inlineWidget" | "artifact" | "mcpApp";
26
+ readonly options?: PresetOptions;
27
+ /** Options added when served on content origins (domain isolation): storage, egress. */
28
+ readonly served?: Omit<PresetOptions, "isolation" | "contentOrigins">;
29
+ }
30
+ | {
31
+ /** A running app by URL: served only. */
32
+ readonly preset: "url";
33
+ readonly options?: Omit<UrlPresetOptions, "contentOrigins">;
34
+ };
35
+
36
+ /** A content source for a manual written before any content origin exists. */
37
+ const GUIDE_SOURCE = "https://*.porthole-content.invalid";
38
+
39
+ export interface Displays<N extends string = string> {
40
+ readonly kinds: readonly N[];
41
+ /** The kind's config in an opaque frame (no content origins). Url kinds have none: throws. */
42
+ opaque(kind: N): PortholeConfig;
43
+ /**
44
+ * Every kind's config served from `contentSource` (`https://*.example-usercontent.com`): made
45
+ * once per source. Null, with `problem(source)` saying why, where a kind can't be served so.
46
+ */
47
+ served(contentSource: string): Readonly<Record<N, PortholeConfig>> | null;
48
+ /** Why `served(contentSource)` is null, or null. */
49
+ problem(contentSource: string): string | null;
50
+ /** The config an instance shows under: its kind, served (a source) or opaque (null). */
51
+ configFor(instance: InstanceRef, contentSource: string | null): PortholeConfig;
52
+ /** The kind an instance's document names, or null. */
53
+ kindOf(instance: InstanceRef): N | null;
54
+ /**
55
+ * The page's `frame-src`, without a ContentHost (a dev server, a desktop shell): every kind's
56
+ * frames, served or opaque, and the authorize route's path when clean addresses frame.
57
+ */
58
+ frameSources(
59
+ contentSource: string | null,
60
+ options?: { readonly authorizeUrl?: string },
61
+ ): readonly string[];
62
+ /** The same, as a `frame-src` directive. */
63
+ embedderCsp(contentSource: string | null, options?: { readonly authorizeUrl?: string }): string;
64
+ /**
65
+ * The kind's config for the agent's manual and tool description, served or opaque, without a
66
+ * real content origin (the manual names none).
67
+ */
68
+ guideConfig(kind: N, mode: "served" | "opaque"): PortholeConfig;
69
+ }
70
+
71
+ export function defineDisplays<N extends string>(
72
+ kinds: Readonly<Record<N, DisplayKind>>,
73
+ ): Displays<N> {
74
+ const names = Object.keys(kinds) as N[];
75
+ if (names.length === 0) {
76
+ throw new TypeError("defineDisplays needs at least one kind");
77
+ }
78
+ const kindOf = (name: N): DisplayKind => {
79
+ const kind = kinds[name];
80
+ if (kind === undefined) {
81
+ throw new TypeError(`No display kind ${JSON.stringify(name)} (defineDisplays)`);
82
+ }
83
+ return kind;
84
+ };
85
+ const build = (name: N, source: string | null): PortholeConfig => {
86
+ const kind = kindOf(name);
87
+ if (kind.preset === "url") {
88
+ if (source === null) {
89
+ throw new TypeError(
90
+ `The display kind ${JSON.stringify(name)} is a url-mode app: served only`,
91
+ );
92
+ }
93
+ return presets.url({ ...kind.options, contentOrigins: [source] });
94
+ }
95
+ const options = kind.options ?? {};
96
+ return presets[kind.preset](
97
+ source === null
98
+ ? options
99
+ : { ...options, ...kind.served, isolation: "domain", contentOrigins: [source] },
100
+ );
101
+ };
102
+ // Made once each: a page that asks every render gets the same objects.
103
+ const opaque = new Map<N, PortholeConfig>();
104
+ const served = new Map<string, Readonly<Record<N, PortholeConfig>> | string>();
105
+ const servedOf = (source: string) => {
106
+ let found = served.get(source);
107
+ if (found === undefined) {
108
+ try {
109
+ found = Object.fromEntries(names.map((name) => [name, build(name, source)])) as Record<
110
+ N,
111
+ PortholeConfig
112
+ >;
113
+ } catch (error) {
114
+ if (!(error instanceof ConfigError) && !(error instanceof TypeError)) {
115
+ throw error;
116
+ }
117
+ found = error.message;
118
+ }
119
+ served.set(source, found);
120
+ }
121
+ return found;
122
+ };
123
+ const displays: Displays<N> = {
124
+ kinds: names,
125
+ opaque(name) {
126
+ let found = opaque.get(name);
127
+ if (found === undefined) {
128
+ found = build(name, null);
129
+ opaque.set(name, found);
130
+ }
131
+ return found;
132
+ },
133
+ served(source) {
134
+ const found = servedOf(source);
135
+ return typeof found === "string" ? null : found;
136
+ },
137
+ problem(source) {
138
+ const found = servedOf(source);
139
+ return typeof found === "string" ? found : null;
140
+ },
141
+ kindOf(instance) {
142
+ const { document } = instance;
143
+ const named =
144
+ document.kind === "shell"
145
+ ? document.preset
146
+ : document.kind === "artifact"
147
+ ? (document.preset ?? "artifact")
148
+ : document.kind === "mcp-proxy"
149
+ ? (document.preset ?? "mcpApp")
150
+ : (names.find((name) => kinds[name]?.preset === "url") ?? null);
151
+ return named !== null && names.includes(named as N) ? (named as N) : null;
152
+ },
153
+ configFor(instance, source) {
154
+ const name = displays.kindOf(instance);
155
+ if (name === null) {
156
+ throw new TypeError(
157
+ `No display kind for an instance of kind ${instance.document.kind} (defineDisplays: ${names.join(", ")})`,
158
+ );
159
+ }
160
+ if (source === null) {
161
+ return displays.opaque(name);
162
+ }
163
+ const all = displays.served(source);
164
+ if (all === null) {
165
+ throw new TypeError(displays.problem(source) ?? "Not servable");
166
+ }
167
+ return all[name];
168
+ },
169
+ frameSources(source, options = {}) {
170
+ const configs =
171
+ source === null
172
+ ? names
173
+ .filter((name) => kinds[name]?.preset !== "url")
174
+ .map((name) => displays.opaque(name))
175
+ : Object.values<PortholeConfig>(displays.served(source) ?? {});
176
+ const authorize =
177
+ options.authorizeUrl === undefined
178
+ ? []
179
+ : [`${new URL(options.authorizeUrl).origin}${new URL(options.authorizeUrl).pathname}`];
180
+ return [...embedderFrameSourcesOf(configs), ...authorize];
181
+ },
182
+ embedderCsp(source, options = {}) {
183
+ const sources = displays.frameSources(source, options);
184
+ return `frame-src ${sources.length === 0 ? "'none'" : sources.join(" ")}`;
185
+ },
186
+ guideConfig(name, mode) {
187
+ return mode === "opaque" ? displays.opaque(name) : build(name, GUIDE_SOURCE);
188
+ },
189
+ };
190
+ return displays;
191
+ }