@botiverse/porthole 0.6.0 → 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 (145) hide show
  1. package/README.md +16 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +200 -8
  4. package/dist/bridge/refusal.d.ts +5 -1
  5. package/dist/bridge/refusal.js +16 -0
  6. package/dist/bridge/types.d.ts +41 -4
  7. package/dist/check/check.d.ts +7 -0
  8. package/dist/check/check.js +1 -0
  9. package/dist/check/instrument.d.ts +3 -0
  10. package/dist/check/lint.js +4 -2
  11. package/dist/check/page-source.js +1 -1
  12. package/dist/check/page.js +14 -0
  13. package/dist/check/tools.js +2 -3
  14. package/dist/compile/policy.d.ts +19 -0
  15. package/dist/compile/policy.js +42 -0
  16. package/dist/config/capabilities.d.ts +62 -3
  17. package/dist/config/capabilities.js +20 -0
  18. package/dist/config/schema.d.ts +24 -0
  19. package/dist/config/validate.d.ts +1 -1
  20. package/dist/config/validate.js +66 -4
  21. package/dist/conformance/harness-source.js +1 -1
  22. package/dist/conformance/index.d.ts +1 -0
  23. package/dist/conformance/index.js +2 -0
  24. package/dist/conformance/runtime.d.ts +58 -0
  25. package/dist/conformance/runtime.js +314 -0
  26. package/dist/guide/gates.d.ts +3 -0
  27. package/dist/guide/gates.js +19 -0
  28. package/dist/guide/guide.d.ts +2 -0
  29. package/dist/guide/guide.js +34 -32
  30. package/dist/guide/limits.js +4 -4
  31. package/dist/guide/runtime.d.ts +13 -0
  32. package/dist/guide/runtime.js +202 -0
  33. package/dist/host/create-host.js +24 -0
  34. package/dist/host/locate.js +8 -0
  35. package/dist/host/locator.js +7 -0
  36. package/dist/host/types.d.ts +18 -0
  37. package/dist/index.d.ts +8 -2
  38. package/dist/index.js +9 -1
  39. package/dist/isolation/types.d.ts +8 -0
  40. package/dist/presets/presets.d.ts +6 -0
  41. package/dist/presets/presets.js +1 -0
  42. package/dist/protocol/runtime-calls.d.ts +28 -0
  43. package/dist/protocol/runtime-calls.js +113 -0
  44. package/dist/protocol/shell-adapter.js +48 -3
  45. package/dist/react/dialog.js +31 -0
  46. package/dist/react/frame.d.ts +13 -0
  47. package/dist/react/frame.js +6 -0
  48. package/dist/runtime/contract.d.ts +193 -0
  49. package/dist/runtime/contract.js +216 -0
  50. package/dist/runtime/db.d.ts +153 -0
  51. package/dist/runtime/db.js +398 -0
  52. package/dist/runtime/declaration.d.ts +86 -0
  53. package/dist/runtime/declaration.js +266 -0
  54. package/dist/runtime/levels.d.ts +33 -0
  55. package/dist/runtime/levels.js +41 -0
  56. package/dist/runtime/requests.d.ts +125 -0
  57. package/dist/runtime/requests.js +199 -0
  58. package/dist/runtime/segments.d.ts +8 -0
  59. package/dist/runtime/segments.js +14 -0
  60. package/dist/runtime/types.generated.d.ts +1 -0
  61. package/dist/runtime/types.generated.js +19 -0
  62. package/dist/server/files.d.ts +14 -1
  63. package/dist/server/files.js +97 -3
  64. package/dist/server/host.d.ts +6 -1
  65. package/dist/server/host.js +5 -0
  66. package/dist/server/index.d.ts +2 -1
  67. package/dist/server/index.js +1 -0
  68. package/dist/server/pseudonym.d.ts +9 -0
  69. package/dist/server/pseudonym.js +20 -0
  70. package/dist/server/server.d.ts +0 -5
  71. package/dist/server/server.js +214 -35
  72. package/dist/server/types.d.ts +69 -0
  73. package/dist/shell/document.d.ts +8 -0
  74. package/dist/shell/document.js +16 -2
  75. package/dist/shell/legacy.d.ts +21 -0
  76. package/dist/shell/legacy.js +63 -0
  77. package/dist/shell/plan.d.ts +17 -1
  78. package/dist/shell/plan.js +13 -2
  79. package/dist/shell/runtime.js +29 -42
  80. package/dist/shell/use.d.ts +15 -0
  81. package/dist/shell/use.js +235 -0
  82. package/docs/ADOPTING.md +91 -6
  83. package/docs/ARCHITECTURE.md +22 -3
  84. package/docs/DECISIONS.md +415 -6
  85. package/docs/DESIGN.md +66 -0
  86. package/package.json +3 -1
  87. package/src/bridge/bridge.ts +273 -12
  88. package/src/bridge/refusal.ts +16 -0
  89. package/src/bridge/types.ts +46 -4
  90. package/src/check/check.ts +8 -0
  91. package/src/check/instrument.ts +3 -0
  92. package/src/check/lint.ts +4 -2
  93. package/src/check/page.ts +14 -0
  94. package/src/check/tools.ts +2 -3
  95. package/src/compile/policy.ts +54 -0
  96. package/src/config/capabilities.ts +49 -2
  97. package/src/config/schema.ts +24 -0
  98. package/src/config/validate.ts +99 -4
  99. package/src/conformance/index.ts +7 -0
  100. package/src/conformance/runtime.ts +573 -0
  101. package/src/guide/gates.ts +25 -0
  102. package/src/guide/guide.ts +59 -53
  103. package/src/guide/limits.ts +4 -4
  104. package/src/guide/runtime.ts +244 -0
  105. package/src/host/create-host.ts +34 -0
  106. package/src/host/locate.ts +10 -0
  107. package/src/host/locator.ts +11 -0
  108. package/src/host/types.ts +18 -0
  109. package/src/index.ts +89 -0
  110. package/src/isolation/types.ts +8 -0
  111. package/src/presets/presets.ts +7 -0
  112. package/src/protocol/runtime-calls.ts +138 -0
  113. package/src/protocol/shell-adapter.ts +52 -3
  114. package/src/react/dialog.tsx +33 -0
  115. package/src/react/frame.tsx +19 -0
  116. package/src/runtime/contract.ts +305 -0
  117. package/src/runtime/db.ts +530 -0
  118. package/src/runtime/declaration.ts +378 -0
  119. package/src/runtime/levels.ts +69 -0
  120. package/src/runtime/requests.ts +339 -0
  121. package/src/runtime/segments.ts +17 -0
  122. package/src/runtime/types.generated.ts +19 -0
  123. package/src/server/files.ts +117 -4
  124. package/src/server/host.ts +12 -0
  125. package/src/server/index.ts +3 -0
  126. package/src/server/pseudonym.ts +21 -0
  127. package/src/server/server.ts +247 -37
  128. package/src/server/types.ts +68 -0
  129. package/src/shell/document.ts +21 -4
  130. package/src/shell/legacy.ts +64 -0
  131. package/src/shell/plan.ts +37 -3
  132. package/src/shell/runtime.ts +29 -42
  133. package/src/shell/use.ts +235 -0
  134. package/types/runtime/v1/artifact.d.ts +50 -0
  135. package/types/runtime/v1/assets.d.ts +43 -0
  136. package/types/runtime/v1/chat.d.ts +13 -0
  137. package/types/runtime/v1/clipboard.d.ts +14 -0
  138. package/types/runtime/v1/comments.d.ts +24 -0
  139. package/types/runtime/v1/context.d.ts +16 -0
  140. package/types/runtime/v1/data.d.ts +29 -0
  141. package/types/runtime/v1/db.d.ts +110 -0
  142. package/types/runtime/v1/downloads.d.ts +22 -0
  143. package/types/runtime/v1/links.d.ts +13 -0
  144. package/types/runtime/v1/porthole.d.ts +44 -0
  145. package/types/runtime/v1/user.d.ts +19 -0
@@ -102,4 +102,5 @@ 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 { defineRuntimeConformance, type RuntimeCase, type RuntimeConformanceOptions, } from "./runtime.ts";
105
106
  export { conformancePage, conformanceProjects, defineHostConformance, harnessScript, hostConformance, onDemand, type ConformanceProject, type ConformanceProjectsOptions, type HostConformance, type HostConformanceOptions, } from "./host-kit.ts";
@@ -4,5 +4,7 @@ export { httpOracle, settle, udpOracle } from "./oracles.js";
4
4
  export { defineServedSuite, servedTests, } from "./served.js";
5
5
  // Redirect entry's cases (P068).
6
6
  export { entryTests } from "./entry.js";
7
+ // The capability runtime's cases an app runs against its own handlers (P085-P090): no browser.
8
+ export { defineRuntimeConformance, } from "./runtime.js";
7
9
  // The runner an app points at its real page and issue endpoint (P066).
8
10
  export { conformancePage, conformanceProjects, defineHostConformance, harnessScript, hostConformance, onDemand, } from "./host-kit.js";
@@ -0,0 +1,58 @@
1
+ import type { CapabilityHandlers } from "../bridge/types.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
3
+ import type { InstanceRef } from "../isolation/types.ts";
4
+ import type { ViewerInfo } from "../runtime/levels.ts";
5
+ import type { AssetStore } from "../server/types.ts";
6
+ /**
7
+ * The capability runtime's host conformance (P085–P090): cases an app runs against its own
8
+ * handlers (the ones it gives `createHost`), through Porthole's real bridge, as a page would call
9
+ * them, and straight to the handler, as a page that got past the bridge would (the app's API is
10
+ * its data's wall). No browser and no test runner: each case is a function that throws on a
11
+ * failure; register them with yours (P041), `for (const each of cases) test(each.name, each.run)`.
12
+ *
13
+ * What a host's services must do: `db` versions every write and refuses a stale one (`conflict`),
14
+ * applies a batch whole or not at all, follows a document, keeps each person's `data/users/<id>`
15
+ * theirs and the page's rules; `artifact` answers its current version and refuses a publish from
16
+ * a base that moved, or by someone below admin; `assets` stores an upload where `/server` serves
17
+ * it, lists it, and removes it; `comments` answers only whether the composer opened.
18
+ */
19
+ export interface RuntimeConformanceOptions {
20
+ /** The config the handlers serve under, its runtime capabilities declared. */
21
+ readonly config: PortholeConfig;
22
+ /**
23
+ * Fresh handlers for one artifact, made for each case (a new artifact, a clean store): the
24
+ * functions the app passes `createHost`.
25
+ */
26
+ readonly handlers: () => CapabilityHandlers | Promise<CapabilityHandlers>;
27
+ /** People at each level; `other` is a second person at interact (whose data isn't `interact`'s). */
28
+ readonly viewers: {
29
+ readonly view: ViewerInfo;
30
+ readonly interact: ViewerInfo;
31
+ readonly admin: ViewerInfo;
32
+ readonly other: ViewerInfo;
33
+ };
34
+ /** The instance the handlers act on, as the app's mount names it. */
35
+ readonly instance?: InstanceRef;
36
+ /** The asset store `/server` serves from (`ServerOptions.assets`), to see an upload served. */
37
+ readonly assets?: (handlers: CapabilityHandlers) => AssetStore;
38
+ /**
39
+ * The app's own API for the same artifact, signed in as `viewer` with that person's real session
40
+ * (after the review): the raw mode. The cases that go past the bridge then call it with a
41
+ * forged context (a viewer claiming to be the owner, no rules), as a page that got past the
42
+ * bridge could, so an API that trusts `context.viewer` or `context.declared` fails them. Without
43
+ * it they call `handlers` with an honest context, which can't catch that: never trust
44
+ * `context.viewer` or `context.declared` for what your data allows.
45
+ */
46
+ readonly api?: (handlers: CapabilityHandlers, viewer: ViewerInfo) => CapabilityHandlers | Promise<CapabilityHandlers>;
47
+ /** The page's db rules the cases declare (default: `config` writable by admins only). */
48
+ readonly rules?: Readonly<Record<string, {
49
+ read?: ViewerInfo["level"];
50
+ write?: ViewerInfo["level"];
51
+ }>>;
52
+ }
53
+ export interface RuntimeCase {
54
+ readonly name: string;
55
+ run(): Promise<void>;
56
+ }
57
+ /** The runtime's conformance cases for an app's handlers. */
58
+ export declare function defineRuntimeConformance(options: RuntimeConformanceOptions): readonly RuntimeCase[];
@@ -0,0 +1,314 @@
1
+ import { createBridge } from "../bridge/bridge.js";
2
+ import { isRefused } from "../bridge/refusal.js";
3
+ import { RUNTIME_VERSION } from "../runtime/contract.js";
4
+ import { checkDeclaration } from "../runtime/declaration.js";
5
+ import { ASSET_ID, assetUrl } from "../runtime/requests.js";
6
+ class ConformanceFailure extends Error {
7
+ name = "ConformanceFailure";
8
+ }
9
+ function expect(condition, message) {
10
+ if (!condition) {
11
+ throw new ConformanceFailure(message);
12
+ }
13
+ }
14
+ const codeOf = (outcome) => outcome.ok ? null : (outcome.reason?.code ?? null);
15
+ const ok = (outcome, what) => {
16
+ if (!outcome.ok) {
17
+ throw new ConformanceFailure(`${what}: refused (${outcome.refusal}, ${outcome.reason?.code ?? "no code"}): ${outcome.message ?? ""}`);
18
+ }
19
+ return outcome.value;
20
+ };
21
+ /** The runtime's conformance cases for an app's handlers. */
22
+ export function defineRuntimeConformance(options) {
23
+ const { config, viewers } = options;
24
+ const rules = options.rules ?? { config: { write: "admin" } };
25
+ const declared = {
26
+ ...(config.capabilities.db === undefined ? {} : { db: { rules } }),
27
+ ...(config.capabilities.artifact === undefined ? {} : { artifact: {} }),
28
+ ...(config.capabilities.assets === undefined ? {} : { assets: {} }),
29
+ };
30
+ const declaration = checkDeclaration({ capabilities: declared, runtime: RUNTIME_VERSION }, config);
31
+ const display = {
32
+ id: "conformance",
33
+ title: "Runtime conformance",
34
+ ...(options.instance === undefined ? {} : { instance: options.instance }),
35
+ };
36
+ /** A page's calls as `viewer`, through the bridge. */
37
+ const as = (handlers, viewer) => {
38
+ const bridge = createBridge({
39
+ config,
40
+ display,
41
+ handlers,
42
+ declaration,
43
+ viewer,
44
+ // Gates the person answers are the app's UI: a yes here, so the services are what's tested.
45
+ confirm: () => Promise.resolve(true),
46
+ consent: () => true,
47
+ userActivation: () => true,
48
+ onEvent: () => { },
49
+ });
50
+ return (capability, args, subscription) => bridge.call(capability, args, subscription);
51
+ };
52
+ /** A call straight to the handler, as a page past the bridge would make it (the app's wall). */
53
+ const direct = async (handlers, capability, args, viewer) => {
54
+ const raw = options.api === undefined ? null : await options.api(handlers, viewer);
55
+ const handler = (raw ?? handlers)[capability];
56
+ if (handler === undefined) {
57
+ throw new ConformanceFailure(`no ${capability} handler`);
58
+ }
59
+ try {
60
+ const value = await handler(args, {
61
+ displayId: display.id,
62
+ title: display.title,
63
+ capability,
64
+ ...(options.instance === undefined ? {} : { instance: options.instance }),
65
+ // The raw mode forges what a page past the bridge would claim; else the honest context.
66
+ ...(raw === null
67
+ ? { viewer, ...(capability === "db" ? { declared: { rules } } : {}) }
68
+ : {
69
+ viewer: { level: "owner", ...(viewer.id === undefined ? {} : { id: viewer.id }) },
70
+ declared: {},
71
+ }),
72
+ });
73
+ return { ok: true, value };
74
+ }
75
+ catch (error) {
76
+ return { ok: false, code: isRefused(error) ? error.code : null };
77
+ }
78
+ };
79
+ /** An access for the instance, as `/server` asks the store with it. */
80
+ const access = {
81
+ instance: options.instance ?? {
82
+ scope: "conformance",
83
+ document: { kind: "artifact", id: "page", version: "1" },
84
+ },
85
+ viewer: "conformance",
86
+ origin: "https://conformance.invalid",
87
+ expiresAt: Date.now() + 3_600_000,
88
+ };
89
+ const cases = [];
90
+ const add = (name, run) => {
91
+ cases.push({ name, run: async () => run(await options.handlers()) });
92
+ };
93
+ if (config.capabilities.db !== undefined) {
94
+ add("db: a set is read back, versioned from 1", async (handlers) => {
95
+ const call = as(handlers, viewers.interact);
96
+ const set = ok(await call("db", { op: "set", path: "notes/a", data: { text: "hi" } }), "set");
97
+ expect(set.version === 1, "a first write is version 1");
98
+ const got = ok(await call("db", { op: "get", path: "notes/a" }), "get");
99
+ expect(got.exists && got.version === 1 && got.data?.text === "hi", "get reads it back");
100
+ const missing = ok(await call("db", { op: "get", path: "notes/none" }), "get");
101
+ expect(!missing.exists && missing.version === 0, "a missing document: exists false, version 0");
102
+ });
103
+ add("db: a write that names a stale version, or none for a document that exists, is a conflict", async (handlers) => {
104
+ const call = as(handlers, viewers.interact);
105
+ ok(await call("db", { op: "set", path: "notes/a", data: { n: 1 } }), "set");
106
+ expect(codeOf(await call("db", { op: "set", path: "notes/a", data: { n: 2 } })) === "conflict", "set without ifVersion over an existing document: conflict");
107
+ expect(codeOf(await call("db", { op: "update", path: "notes/a", data: { n: 2 }, ifVersion: 7 })) === "conflict", "update with a stale ifVersion: conflict");
108
+ const updated = ok(await call("db", { op: "update", path: "notes/a", data: { m: 3 }, ifVersion: 1 }), "update");
109
+ expect(updated.version === 2, "an update with the right version is the next one");
110
+ const got = ok(await call("db", { op: "get", path: "notes/a" }), "get");
111
+ expect(got.data?.n === 1 && got.data?.m === 3, "update merges fields");
112
+ expect(codeOf(await call("db", { op: "set", path: "notes/b", data: {}, ifVersion: 0 })) === null, "ifVersion 0 creates");
113
+ ok(await call("db", { op: "delete", path: "notes/a", ifVersion: 2 }), "delete");
114
+ const gone = ok(await call("db", { op: "get", path: "notes/a" }), "get");
115
+ expect(!gone.exists, "a deleted document is gone");
116
+ });
117
+ add("db: a query answers a collection's documents, filtered, ordered, limited", async (handlers) => {
118
+ const call = as(handlers, viewers.interact);
119
+ for (const [id, score] of [
120
+ ["a", 3],
121
+ ["b", 1],
122
+ ["c", 2],
123
+ ]) {
124
+ ok(await call("db", { op: "set", path: `scores/${id}`, data: { score } }), "set");
125
+ }
126
+ ok(await call("db", { op: "set", path: "scores/a/history/1", data: { score: 9 } }), "set");
127
+ const found = ok(await call("db", {
128
+ op: "query",
129
+ collection: "scores",
130
+ where: [["score", ">=", 2]],
131
+ orderBy: { field: "score", direction: "desc" },
132
+ limit: 5,
133
+ }), "query");
134
+ expect(JSON.stringify(found.docs.map((each) => each.id)) === '["a","c"]', `a query answers its collection's own documents, filtered and ordered: ${JSON.stringify(found.docs.map((each) => each.id))}`);
135
+ });
136
+ add("db: a batch is applied whole or not at all", async (handlers) => {
137
+ const call = as(handlers, viewers.interact);
138
+ ok(await call("db", { op: "set", path: "items/x", data: { n: 1 } }), "set");
139
+ const refused = await call("db", {
140
+ op: "batch",
141
+ writes: [
142
+ { op: "set", path: "items/y", data: { n: 1 } },
143
+ { op: "update", path: "items/x", data: { n: 2 }, ifVersion: 9 },
144
+ ],
145
+ });
146
+ expect(codeOf(refused) === "conflict", "a batch with a stale write: conflict");
147
+ const y = ok(await call("db", { op: "get", path: "items/y" }), "get");
148
+ expect(!y.exists, "nothing of a refused batch is written");
149
+ const done = ok(await call("db", {
150
+ op: "batch",
151
+ writes: [
152
+ { op: "set", path: "items/y", data: { n: 1 } },
153
+ { op: "update", path: "items/x", data: { n: 2 }, ifVersion: 1 },
154
+ ],
155
+ }), "batch");
156
+ expect(JSON.stringify(done.versions) === "[1,2]", "a batch answers each write's version");
157
+ });
158
+ add("db: a watch hears the document now and at each change", async (handlers) => {
159
+ const heard = [];
160
+ const controller = new AbortController();
161
+ const watching = as(handlers, viewers.view);
162
+ ok(await watching("db", { op: "watch", path: "notes/w" }, {
163
+ subscription: {
164
+ changed: (state) => heard.push(state),
165
+ signal: controller.signal,
166
+ },
167
+ }), "watch");
168
+ ok(await as(handlers, viewers.interact)("db", { op: "set", path: "notes/w", data: { n: 1 } }), "set");
169
+ await new Promise((resolve) => setTimeout(resolve, 50));
170
+ controller.abort();
171
+ ok(await as(handlers, viewers.interact)("db", {
172
+ op: "set",
173
+ path: "notes/w",
174
+ data: { n: 2 },
175
+ ifVersion: 1,
176
+ }), "set");
177
+ await new Promise((resolve) => setTimeout(resolve, 50));
178
+ expect(heard.length >= 1 && heard.some((each) => each.exists && each.data?.n === 1), "a watch hears a write");
179
+ expect(!heard.some((each) => each.data?.n === 2), "a watch ends with its signal");
180
+ });
181
+ add("db: a person's own data is theirs: data/users/me is them, another's is refused, even past the bridge", async (handlers) => {
182
+ const mine = as(handlers, viewers.interact);
183
+ ok(await mine("db", { op: "set", path: "data/users/me/prefs", data: { dark: true } }), "set own");
184
+ const own = ok(await mine("db", { op: "get", path: `data/users/${viewers.interact.id}/prefs` }), "get own");
185
+ expect(own.exists, "me is the viewer's own id");
186
+ const theirs = as(handlers, viewers.other);
187
+ const path = `data/users/${viewers.interact.id}/prefs`;
188
+ expect(codeOf(await theirs("db", { op: "get", path })) === "forbidden", "another person's data: forbidden");
189
+ const past = await direct(handlers, "db", { op: "get", path }, viewers.other);
190
+ expect(!past.ok, "the app's handler refuses another person's data itself");
191
+ const listed = await direct(handlers, "db", { op: "query", collection: `data/users/${viewers.interact.id}` }, viewers.other);
192
+ expect(!listed.ok, "and their collections");
193
+ });
194
+ add("db: a person's own paths come back as data/users/me, never their id", async (handlers) => {
195
+ const mine = as(handlers, viewers.interact);
196
+ ok(await mine("db", { op: "set", path: "data/users/me/prefs", data: { n: 1 } }), "set own");
197
+ const got = ok(await mine("db", { op: "get", path: "data/users/me/prefs" }), "get");
198
+ const listed = ok(await mine("db", { op: "query", collection: "data/users/me" }), "query");
199
+ const said = JSON.stringify([got, listed]);
200
+ expect(got.path === "data/users/me/prefs", `a snapshot says me: ${got.path}`);
201
+ expect(viewers.interact.id === undefined || !said.includes(viewers.interact.id), "no answer names the viewer's id");
202
+ });
203
+ add("db: the page's rules hold, at the bridge and in the app", async (handlers) => {
204
+ expect(codeOf(await as(handlers, viewers.interact)("db", { op: "set", path: "config/main", data: {} })) === "forbidden", "a rule's write level holds at the bridge");
205
+ const past = await direct(handlers, "db", { op: "set", path: "config/main", data: {} }, viewers.interact);
206
+ expect(!past.ok, "the app's handler applies the page's rules itself");
207
+ const view = await direct(handlers, "db", { op: "set", path: "notes/v", data: {} }, viewers.view);
208
+ expect(!view.ok, "a view-only person writes nothing, even past the bridge");
209
+ ok(await as(handlers, viewers.admin)("db", { op: "set", path: "config/main", data: {} }), "an admin writes it");
210
+ });
211
+ }
212
+ if (config.capabilities.artifact !== undefined) {
213
+ add("artifact: get answers the current version; a publish from it makes the next", async (handlers) => {
214
+ const call = as(handlers, viewers.admin);
215
+ const current = ok(await call("artifact", { op: "get" }), "get");
216
+ expect(typeof current.version === "string" && Array.isArray(current.files), "get: { version, files }");
217
+ const published = ok(await call("artifact", {
218
+ op: "publish",
219
+ base: current.version,
220
+ files: { "notes.txt": { text: "new" } },
221
+ label: "From the page",
222
+ }), "publish");
223
+ expect(published.version !== current.version, "a publish makes a new version");
224
+ const after = ok(await call("artifact", { op: "get" }), "get");
225
+ expect(after.version === published.version, "the new version is current");
226
+ expect(after.files.some((each) => each.path === "notes.txt"), "with the patch applied");
227
+ expect(current.files.every((file) => after.files.some((each) => each.path === file.path)), "and the base's other files kept");
228
+ });
229
+ add("artifact: a publish from a base that moved is a conflict; below admin, refused even past the bridge", async (handlers) => {
230
+ const call = as(handlers, viewers.admin);
231
+ const current = ok(await call("artifact", { op: "get" }), "get");
232
+ ok(await call("artifact", {
233
+ op: "publish",
234
+ base: current.version,
235
+ files: { "a.txt": { text: "1" } },
236
+ }), "publish");
237
+ expect(codeOf(await call("artifact", {
238
+ op: "publish",
239
+ base: current.version,
240
+ files: { "a.txt": { text: "2" } },
241
+ })) === "conflict", "a stale base: conflict");
242
+ expect(codeOf(await as(handlers, viewers.interact)("artifact", {
243
+ op: "publish",
244
+ base: "x",
245
+ files: { "a.txt": { text: "3" } },
246
+ })) === "forbidden", "below admin: forbidden at the bridge");
247
+ const now = ok(await call("artifact", { op: "get" }), "get");
248
+ const past = await direct(handlers, "artifact", { op: "publish", base: now.version, files: { "a.txt": { text: "4" } } }, viewers.interact);
249
+ expect(!past.ok, "the app's handler refuses a publish below admin itself");
250
+ });
251
+ }
252
+ if (config.capabilities.artifact !== undefined) {
253
+ add("artifact: a publish whose merged files make no page is refused", async (handlers) => {
254
+ const call = as(handlers, viewers.admin);
255
+ const current = ok(await call("artifact", { op: "get" }), "get");
256
+ const refused = await call("artifact", {
257
+ op: "publish",
258
+ base: current.version,
259
+ files: { [current.entry]: null },
260
+ });
261
+ expect(!refused.ok, "a publish that removes the entry is refused (check the merged set)");
262
+ });
263
+ }
264
+ if (config.capabilities.assets !== undefined) {
265
+ add("assets: an upload is listed, served by its id, and removed", async (handlers) => {
266
+ const call = as(handlers, viewers.admin);
267
+ const bytes = "R0lGODlhAQABAAAAACw="; // a small GIF's start: its bytes, as base64
268
+ const asset = ok(await call("assets", { op: "upload", name: "pixel.gif", base64: bytes }), "upload");
269
+ expect(ASSET_ID.test(asset.id), "an asset's id is 32 lowercase hex characters");
270
+ expect(asset.url === assetUrl(asset.id), "its url is /_blob/<id>");
271
+ expect(asset.type === "image/gif" && asset.size === 14, "its type is the name's; its size the bytes'");
272
+ const listed = ok(await as(handlers, viewers.view)("assets", { op: "list" }), "list");
273
+ expect(listed.some((each) => each.id === asset.id), "the library lists it");
274
+ const store = options.assets?.(handlers);
275
+ if (store !== undefined) {
276
+ const stored = await store.get(asset.id, access);
277
+ expect(stored !== null && stored.size === 14, "the server's store has it");
278
+ const body = await stored?.read();
279
+ const length = body instanceof Uint8Array
280
+ ? body.length
281
+ : body === null || body === undefined
282
+ ? -1
283
+ : (await new Response(body).arrayBuffer()).byteLength;
284
+ expect(length === 14, "with its bytes");
285
+ }
286
+ ok(await call("assets", { op: "delete", id: asset.id }), "delete");
287
+ const after = ok(await call("assets", { op: "list" }), "list");
288
+ expect(!after.some((each) => each.id === asset.id), "a removed asset isn't listed");
289
+ if (store !== undefined) {
290
+ expect((await store.get(asset.id, access)) === null, "nor served");
291
+ }
292
+ });
293
+ add("assets: removing is the admins', even past the bridge", async (handlers) => {
294
+ const asset = ok(await as(handlers, viewers.admin)("assets", {
295
+ op: "upload",
296
+ name: "a.txt",
297
+ base64: "aGk=",
298
+ }), "upload");
299
+ expect(codeOf(await as(handlers, viewers.interact)("assets", { op: "delete", id: asset.id })) ===
300
+ "forbidden", "below admin: forbidden at the bridge");
301
+ const past = await direct(handlers, "assets", { op: "delete", id: asset.id }, viewers.view);
302
+ expect(!past.ok || past.value !== true, "the app's handler refuses a removal below admin itself");
303
+ });
304
+ }
305
+ if (config.capabilities.comments !== undefined) {
306
+ add("comments: content hears only whether the composer opened", async (handlers) => {
307
+ const opened = ok(await as(handlers, viewers.view)("comments", {
308
+ anchor: { name: "slide-3", label: "Slide 3" },
309
+ }), "open");
310
+ expect(typeof opened === "boolean", "comments.open answers a boolean");
311
+ });
312
+ }
313
+ return cases;
314
+ }
@@ -0,0 +1,3 @@
1
+ import type { Gate } from "../config/capabilities.ts";
2
+ /** How a capability's gates read to the author: one sentence each. */
3
+ export declare function gateWords(gates: readonly Gate[], effect: string): string;
@@ -0,0 +1,19 @@
1
+ /** How a capability's gates read to the author: one sentence each. */
2
+ export function gateWords(gates, effect) {
3
+ const sentences = [];
4
+ if (gates.includes("consent")) {
5
+ sentences.push("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).");
6
+ }
7
+ if (gates.includes("confirm")) {
8
+ sentences.push(`The app shows the person ${effect} first, and nothing happens unless they confirm.`);
9
+ }
10
+ if (gates.includes("user-activation")) {
11
+ sentences.push("Call it from a click (it needs one).");
12
+ }
13
+ for (const gate of gates) {
14
+ if (typeof gate === "object") {
15
+ sentences.push(`At most ${gate.rateLimit.perMinute} a minute.`);
16
+ }
17
+ }
18
+ return sentences.join(" ");
19
+ }
@@ -14,6 +14,8 @@ export type GuideTopic = BuiltInTopic | (string & {});
14
14
  export declare const ANY_HTTPS_SITE = "any https site";
15
15
  /** The copy of Plotly's map shapes (topojson) to give it, on jsDelivr (P078). */
16
16
  export declare const PLOTLY_TOPOJSON_URL = "https://cdn.jsdelivr.net/npm/plotly.js@3.4.0/dist/topojson/";
17
+ /** The built-in topics a config has: the capabilities topic only with a runtime (P085). */
18
+ export declare function builtInTopics(config: PortholeConfig): readonly BuiltInTopic[];
17
19
  /** The manual for `topics`, in the order asked (all built-in topics by default). */
18
20
  export declare function generateGuide(config: PortholeConfig, topics?: readonly GuideTopic[]): string;
19
21
  /** The description of the host's show tool, for the agent's tool list. */
@@ -7,6 +7,8 @@ import { shellPlan } from "../shell/plan.js";
7
7
  import { themeDefault } from "../theme/variables.js";
8
8
  import { GUIDE_EXAMPLES } from "./examples.js";
9
9
  import { manualLimits, sizeWords } from "./limits.js";
10
+ import { gateWords } from "./gates.js";
11
+ import { capabilitiesTopic, runtimeEntries, runtimeToolWords } from "./runtime.js";
10
12
  const VARIABLE = /--[a-z0-9]+(?:-[a-z0-9]+)*/gu;
11
13
  function context(config) {
12
14
  const variables = Object.keys(config.theme.variables);
@@ -62,7 +64,7 @@ function files(config) {
62
64
  }
63
65
  const limits = fileLimits(config.limits);
64
66
  const downloads = config.capabilities.downloadFile !== undefined;
65
- return lines("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.", '- 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))).', `- 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 downloadFile" : ""}. A missing path shows your 404.html, if you publish one.`, "- 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.", '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.', `- 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.`);
67
+ return lines("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.", '- 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))).', `- 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.`, "- 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.", '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.', `- 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.`);
66
68
  }
67
69
  /** What content may load, in prose, from the same origins the CSP lists. */
68
70
  function network(config) {
@@ -73,7 +75,7 @@ function network(config) {
73
75
  if (open.length === 0) {
74
76
  // A live widget's data comes from the app alone (P079), and its scripts from Porthole's copies.
75
77
  const data = declaredCapabilities(config).includes("readData")
76
- ? " Your data comes only from the app (readData)."
78
+ ? ` Your data comes only from the app (${config.runtime === undefined ? "readData" : "data.read"}).`
77
79
  : "";
78
80
  return servesLibraries(config)
79
81
  ? `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}`
@@ -224,25 +226,6 @@ function chart(c) {
224
226
  ? `\nBars in HTML, under a title like the line chart's:\n${GUIDE_EXAMPLES.bars}`
225
227
  : null);
226
228
  }
227
- /** How a capability's gates read to the author: one sentence each. */
228
- function gateWords(gates, effect) {
229
- const sentences = [];
230
- if (gates.includes("consent")) {
231
- sentences.push("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).");
232
- }
233
- if (gates.includes("confirm")) {
234
- sentences.push(`The app shows the person ${effect} first, and nothing happens unless they confirm.`);
235
- }
236
- if (gates.includes("user-activation")) {
237
- sentences.push("Call it from a click (it needs one).");
238
- }
239
- for (const gate of gates) {
240
- if (typeof gate === "object") {
241
- sentences.push(`At most ${gate.rateLimit.perMinute} a minute.`);
242
- }
243
- }
244
- return sentences.join(" ");
245
- }
246
229
  /**
247
230
  * What a data refusal tells content (P080): the codes and the sentence, for the author to draw. With
248
231
  * the shell's globals they are the error's own fields; without, the JSON-RPC error's data.
@@ -275,15 +258,28 @@ const ENTRIES = {
275
258
  annotate: (c) => `- Comments: the person may point at parts of the ${c.noun} to comment on them. Give headings and the parts that matter stable ids (id="revenue"), so comments stay on them when the ${c.noun} is written again.`,
276
259
  reportError: (c) => `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
277
260
  resize: () => "",
261
+ // The runtime's own: taught as porthole.use's methods (runtimeEntries), never alone.
262
+ user: () => "",
263
+ comments: () => "",
264
+ artifact: () => "",
265
+ assets: () => "",
266
+ db: () => "",
278
267
  };
268
+ /** The shell's own capabilities, which content never calls by name: taught as they are. */
269
+ const SHELL_OWN = ["annotate", "reportError", "resize"];
279
270
  function interactive(c) {
280
271
  const { config, noun } = c;
281
- const entries = declaredCapabilities(config)
282
- .map((name) => {
283
- const own = config.capabilities[name]?.guide;
284
- return own === undefined ? ENTRIES[name](c, effectiveGates(config, name)) : `- ${own}`;
285
- })
286
- .filter((entry) => entry !== "");
272
+ // Under the capability runtime (P085), what content calls is porthole.use's methods.
273
+ const runtime = config.runtime !== undefined;
274
+ const entries = [
275
+ ...(runtime ? runtimeEntries(config) : []),
276
+ ...declaredCapabilities(config)
277
+ .filter((name) => !runtime || SHELL_OWN.includes(name) || config.capabilities[name]?.guide !== undefined)
278
+ .map((name) => {
279
+ const own = config.capabilities[name]?.guide;
280
+ return own === undefined ? ENTRIES[name](c, effectiveGates(config, name)) : `- ${own}`;
281
+ }),
282
+ ].filter((entry) => entry !== "");
287
283
  const stated = manualLimits(config, "");
288
284
  const stored = stated.find((limit) => limit.id === "storage");
289
285
  const state = stored === undefined ? null : `- ${stored.text}`;
@@ -300,17 +296,23 @@ const TOPICS = {
300
296
  widget,
301
297
  chart,
302
298
  interactive,
299
+ capabilities: (c) => capabilitiesTopic(c.config, c.noun),
303
300
  };
301
+ /** The built-in topics a config has: the capabilities topic only with a runtime (P085). */
302
+ export function builtInTopics(config) {
303
+ return BUILT_IN_TOPICS.filter((topic) => topic !== "capabilities" || config.runtime !== undefined);
304
+ }
304
305
  /** The manual for `topics`, in the order asked (all built-in topics by default). */
305
306
  export function generateGuide(config, topics) {
306
307
  const c = context(config);
307
308
  const own = config.guide.topics ?? {};
308
- return (topics ?? BUILT_IN_TOPICS)
309
+ return (topics ?? builtInTopics(config))
309
310
  .map((topic) => {
310
- if (Object.hasOwn(TOPICS, topic)) {
311
+ // A built-in topic the config has; a 0.6 config's own `capabilities` stays its own.
312
+ if (Object.hasOwn(TOPICS, topic) && builtInTopics(config).includes(topic)) {
311
313
  return TOPICS[topic](c);
312
314
  }
313
- const text = own[topic];
315
+ const text = Object.hasOwn(own, topic) ? own[topic] : undefined;
314
316
  if (text === undefined) {
315
317
  throw new RangeError(`No guide topic ${JSON.stringify(topic)}`);
316
318
  }
@@ -340,7 +342,7 @@ export function generateToolDescription(config) {
340
342
  : origins.length === 0
341
343
  ? `loading only ${fromAnywhere}`
342
344
  : `loading only from ${origins.join(", ")}${fromAnywhere === "" ? "" : `, and ${fromAnywhere}`}`;
343
- const globals = declaredCapabilities(config).flatMap((name) => {
345
+ const globals = (config.runtime === undefined ? declaredCapabilities(config) : []).flatMap((name) => {
344
346
  const spec = capabilitySpec(name);
345
347
  if (spec.global === undefined || !c.global(spec.global)) {
346
348
  return [];
@@ -367,5 +369,5 @@ export function generateToolDescription(config) {
367
369
  const theme = config.theme.documents === "never"
368
370
  ? "always in light (the app doesn't theme it)"
369
371
  : "in the person's light or dark theme through CSS variables";
370
- return `${what} ${where}, ${theme}, ${net}. ${globals.join(" ")}${read} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu, " ");
372
+ return `${what} ${where}, ${theme}, ${net}. ${globals.join(" ")} ${runtimeToolWords(config)}${read} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu, " ");
371
373
  }
@@ -114,15 +114,15 @@ export function manualLimits(config, network) {
114
114
  add("print", "window.print() does nothing.");
115
115
  }
116
116
  if (!tokens.includes("allow-downloads")) {
117
- add("downloads", `Downloads don't work: <a download>, data: and blob: links, saves from script.${declared.has("downloadFile") ? " To give the person a file, ask the app (ui/download-file; with the App SDK, app.downloadFile)." : ""}`);
117
+ add("downloads", `Downloads don't work: <a download>, data: and blob: links, saves from script.${!declared.has("downloadFile") ? "" : config.runtime !== undefined ? " To give the person a file: downloads.save (topic capabilities)." : " To give the person a file, ask the app (ui/download-file; with the App SDK, app.downloadFile)."}`);
118
118
  }
119
119
  if (!tokens.includes("allow-forms")) {
120
120
  add("forms", 'Forms never submit, and some browsers fire no submit event: use them as UI, give buttons type="button" and handle their click.');
121
121
  }
122
- add("link-schemes", `mailto:, tel: and sms: links open nothing: show the address or number as text${globals.has("copyText") ? " (with a copy button)" : ""}.`);
122
+ add("link-schemes", `mailto:, tel: and sms: links open nothing: show the address or number as text${globals.has("copyText") || (config.runtime !== undefined && declared.has("copyText")) ? " (with a copy button)" : ""}.`);
123
123
  if (!tokens.includes("allow-popups")) {
124
124
  add("windows", globals.has("openLink") || declared.has("openLink")
125
- ? "window.open and target=_blank open no window (window.open returns null or throws): links open in a new tab through the app (openLink; a click on <a href> does it)."
125
+ ? `window.open and target=_blank open no window (window.open returns null or throws): links open in a new tab through the app (${config.runtime === undefined ? "openLink" : "links.open"}; a click on <a href> does it).`
126
126
  : "Links to other pages, window.open and target=_blank open nothing (window.open returns null or throws).");
127
127
  }
128
128
  add("devices", "Camera, microphone, location and sharing are denied without asking (they reject, or aren't there); file inputs and FileReader work.");
@@ -131,7 +131,7 @@ export function manualLimits(config, network) {
131
131
  add("address", config.isolation === "opaque"
132
132
  ? `The ${it}'s address is about:srcdoc: it has no query string or hash to read.`
133
133
  : `The ${it}'s address is its own (with Porthole's one-time ticket), never the app's: read no parameters from it.`);
134
- add("shell", `document.write and document.open throw; nested frames (iframe, object, embed) are removed; full screen and the clipboard are closed${globals.has("copyText") ? " (copy buttons call copyText)" : ""}.`);
134
+ add("shell", `document.write and document.open throw; nested frames (iframe, object, embed) are removed; full screen and the clipboard are closed${globals.has("copyText") ? " (copy buttons call copyText)" : config.runtime !== undefined && declared.has("copyText") ? " (copy buttons call clipboard.copy)" : ""}.`);
135
135
  add("storage", config.isolation === "opaque"
136
136
  ? `State isn't saved: localStorage works but lasts only while the ${it} is on screen, and a reload or another device starts fresh. Keep what matters in the ${it}'s code.`
137
137
  : config.storage?.scope !== undefined
@@ -0,0 +1,13 @@
1
+ import { type CapabilityName } from "../config/capabilities.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
3
+ /** The prefix of the manual's line for a host function under the runtime (the agreement test's). */
4
+ export declare function runtimeEntryPrefix(serves: CapabilityName): string | null;
5
+ /**
6
+ * The interactive topic's lines under the runtime: one per host function the config serves to
7
+ * pages, as `porthole.use`'s methods, each with its level, whether it is declared, and its gates.
8
+ */
9
+ export declare function runtimeEntries(config: PortholeConfig): string[];
10
+ /** The tool description's words on the runtime. */
11
+ export declare function runtimeToolWords(config: PortholeConfig): string;
12
+ /** The capabilities topic: the call contract, declaring, levels, state, and each one's types. */
13
+ export declare function capabilitiesTopic(config: PortholeConfig, noun: string): string;