@serene-pub/sdk 0.6.0-pr-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 (187) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +17 -0
  3. package/README.md +368 -0
  4. package/dist/actions.d.ts +572 -0
  5. package/dist/actions.js +829 -0
  6. package/dist/annexFields.d.ts +234 -0
  7. package/dist/annexFields.js +413 -0
  8. package/dist/announce.d.ts +464 -0
  9. package/dist/announce.js +426 -0
  10. package/dist/attributes.d.ts +670 -0
  11. package/dist/attributes.js +904 -0
  12. package/dist/bands.d.ts +125 -0
  13. package/dist/bands.js +256 -0
  14. package/dist/builder.d.ts +683 -0
  15. package/dist/builder.js +677 -0
  16. package/dist/candidates.d.ts +109 -0
  17. package/dist/candidates.js +118 -0
  18. package/dist/capabilities.d.ts +744 -0
  19. package/dist/capabilities.js +679 -0
  20. package/dist/channels.d.ts +106 -0
  21. package/dist/channels.js +129 -0
  22. package/dist/clauses.d.ts +40 -0
  23. package/dist/clauses.js +43 -0
  24. package/dist/component.d.ts +33 -0
  25. package/dist/component.js +27 -0
  26. package/dist/componentBuild.d.ts +48 -0
  27. package/dist/componentBuild.js +84 -0
  28. package/dist/componentClient.d.ts +100 -0
  29. package/dist/componentClient.js +13 -0
  30. package/dist/componentImports.d.ts +51 -0
  31. package/dist/componentImports.js +106 -0
  32. package/dist/componentModule.d.ts +8 -0
  33. package/dist/componentModule.js +270 -0
  34. package/dist/componentWire.d.ts +130 -0
  35. package/dist/componentWire.js +280 -0
  36. package/dist/config.d.ts +295 -0
  37. package/dist/config.js +231 -0
  38. package/dist/connections.d.ts +89 -0
  39. package/dist/connections.js +131 -0
  40. package/dist/declarations.d.ts +290 -0
  41. package/dist/declarations.js +794 -0
  42. package/dist/descriptors.d.ts +1774 -0
  43. package/dist/descriptors.js +1329 -0
  44. package/dist/dev.d.ts +136 -0
  45. package/dist/dev.js +161 -0
  46. package/dist/document.d.ts +202 -0
  47. package/dist/document.js +312 -0
  48. package/dist/engines.d.ts +117 -0
  49. package/dist/engines.js +203 -0
  50. package/dist/eventMapLaws.d.ts +63 -0
  51. package/dist/eventMapLaws.js +128 -0
  52. package/dist/events.d.ts +554 -0
  53. package/dist/events.js +633 -0
  54. package/dist/executor.d.ts +771 -0
  55. package/dist/executor.js +1829 -0
  56. package/dist/extension.d.ts +448 -0
  57. package/dist/extension.js +315 -0
  58. package/dist/facets.d.ts +53 -0
  59. package/dist/facets.js +60 -0
  60. package/dist/foldedSections.d.ts +74 -0
  61. package/dist/foldedSections.js +161 -0
  62. package/dist/genres.d.ts +507 -0
  63. package/dist/genres.js +633 -0
  64. package/dist/guardedConnection.d.ts +138 -0
  65. package/dist/guardedConnection.js +341 -0
  66. package/dist/handlebarsReach.d.ts +122 -0
  67. package/dist/handlebarsReach.js +222 -0
  68. package/dist/hash.d.ts +146 -0
  69. package/dist/hash.js +166 -0
  70. package/dist/hookGrants.d.ts +47 -0
  71. package/dist/hookGrants.js +68 -0
  72. package/dist/hooks.d.ts +290 -0
  73. package/dist/hooks.js +113 -0
  74. package/dist/hostElements.d.ts +447 -0
  75. package/dist/hostElements.js +702 -0
  76. package/dist/i18n.d.ts +94 -0
  77. package/dist/i18n.js +123 -0
  78. package/dist/identity.d.ts +93 -0
  79. package/dist/identity.js +135 -0
  80. package/dist/index.d.ts +85 -0
  81. package/dist/index.js +176 -0
  82. package/dist/layout.d.ts +194 -0
  83. package/dist/layout.js +40 -0
  84. package/dist/media.d.ts +202 -0
  85. package/dist/media.js +70 -0
  86. package/dist/messageBlocks.d.ts +487 -0
  87. package/dist/messageBlocks.js +683 -0
  88. package/dist/migration.d.ts +128 -0
  89. package/dist/migration.js +261 -0
  90. package/dist/names.d.ts +78 -0
  91. package/dist/names.js +136 -0
  92. package/dist/nodeInput.d.ts +399 -0
  93. package/dist/nodeInput.js +178 -0
  94. package/dist/participants.d.ts +291 -0
  95. package/dist/participants.js +252 -0
  96. package/dist/personGate.d.ts +62 -0
  97. package/dist/personGate.js +77 -0
  98. package/dist/pick.d.ts +84 -0
  99. package/dist/pick.js +103 -0
  100. package/dist/pluginHarness.d.ts +235 -0
  101. package/dist/pluginHarness.js +558 -0
  102. package/dist/pluginPermissions.d.ts +25 -0
  103. package/dist/pluginPermissions.js +97 -0
  104. package/dist/pluginRuleRef.d.ts +13 -0
  105. package/dist/pluginRuleRef.js +10 -0
  106. package/dist/predicates.d.ts +182 -0
  107. package/dist/predicates.js +249 -0
  108. package/dist/preview.d.ts +120 -0
  109. package/dist/preview.js +82 -0
  110. package/dist/promptBlocks.d.ts +130 -0
  111. package/dist/promptBlocks.js +197 -0
  112. package/dist/rankingDecisions.d.ts +60 -0
  113. package/dist/rankingDecisions.js +48 -0
  114. package/dist/receipt.d.ts +313 -0
  115. package/dist/receipt.js +60 -0
  116. package/dist/receiverRules.d.ts +24 -0
  117. package/dist/receiverRules.js +94 -0
  118. package/dist/refs.d.ts +117 -0
  119. package/dist/refs.js +137 -0
  120. package/dist/registry.d.ts +230 -0
  121. package/dist/registry.js +273 -0
  122. package/dist/review.d.ts +108 -0
  123. package/dist/review.js +97 -0
  124. package/dist/sampling.d.ts +152 -0
  125. package/dist/sampling.js +712 -0
  126. package/dist/scope.d.ts +65 -0
  127. package/dist/scope.js +128 -0
  128. package/dist/scripts.d.ts +243 -0
  129. package/dist/scripts.js +326 -0
  130. package/dist/sessionLayout.d.ts +339 -0
  131. package/dist/sessionLayout.js +503 -0
  132. package/dist/sessionSettings.d.ts +70 -0
  133. package/dist/sessionSettings.js +2 -0
  134. package/dist/settings.d.ts +501 -0
  135. package/dist/settings.js +604 -0
  136. package/dist/settingsSlot.d.ts +108 -0
  137. package/dist/settingsSlot.js +166 -0
  138. package/dist/shapes.d.ts +373 -0
  139. package/dist/shapes.js +408 -0
  140. package/dist/sheets.d.ts +165 -0
  141. package/dist/sheets.js +251 -0
  142. package/dist/statShapes.d.ts +96 -0
  143. package/dist/statShapes.js +112 -0
  144. package/dist/status.d.ts +103 -0
  145. package/dist/status.js +125 -0
  146. package/dist/storage.d.ts +145 -0
  147. package/dist/storage.js +33 -0
  148. package/dist/storyTime.d.ts +308 -0
  149. package/dist/storyTime.js +560 -0
  150. package/dist/surfaces.d.ts +501 -0
  151. package/dist/surfaces.js +292 -0
  152. package/dist/template.d.ts +312 -0
  153. package/dist/template.js +554 -0
  154. package/dist/templateCheck.d.ts +60 -0
  155. package/dist/templateCheck.js +516 -0
  156. package/dist/templateFit.d.ts +157 -0
  157. package/dist/templateFit.js +349 -0
  158. package/dist/templateIds.d.ts +138 -0
  159. package/dist/templateIds.js +144 -0
  160. package/dist/templateScopeAt.d.ts +131 -0
  161. package/dist/templateScopeAt.js +354 -0
  162. package/dist/testing.d.ts +177 -0
  163. package/dist/testing.js +383 -0
  164. package/dist/tokenizers.d.ts +113 -0
  165. package/dist/tokenizers.js +184 -0
  166. package/dist/turnLock.d.ts +96 -0
  167. package/dist/turnLock.js +79 -0
  168. package/dist/turnOrder.d.ts +143 -0
  169. package/dist/turnOrder.js +128 -0
  170. package/dist/validate.d.ts +74 -0
  171. package/dist/validate.js +1399 -0
  172. package/dist/values.d.ts +212 -0
  173. package/dist/values.js +390 -0
  174. package/dist/variables.d.ts +493 -0
  175. package/dist/variables.js +662 -0
  176. package/dist/verdicts.d.ts +275 -0
  177. package/dist/verdicts.js +348 -0
  178. package/dist/widgetDecls.d.ts +88 -0
  179. package/dist/widgetDecls.js +119 -0
  180. package/dist/widgets.d.ts +1527 -0
  181. package/dist/widgets.js +208 -0
  182. package/dist/wire.d.ts +126 -0
  183. package/dist/wire.js +140 -0
  184. package/dist/worldinfo.d.ts +150 -0
  185. package/dist/worldinfo.js +212 -0
  186. package/host-elements.d.ts +914 -0
  187. package/package.json +67 -0
@@ -0,0 +1,558 @@
1
+ /**
2
+ * The **plugin sandbox's context, in the author's harness** (plans 29 §14 D-3).
3
+ *
4
+ * The SDK's executor builds a node's context itself — `{ signal, progress,
5
+ * status, log, countTokens }`, plus `read` for a Query, `call` for an Oracle and
6
+ * `commit` for an Outlet. That is the context a **core** handler runs against,
7
+ * and it is *not* the one a **plugin's** handler ever sees. At install a
8
+ * plugin's node handlers do not go through that path at all: the app's
9
+ * `pipelines/runtime/pluginBindings.ts` calls `RuntimeManager.callHook`, which
10
+ * runs the hook inside the plugin's sandbox against a context the sandbox
11
+ * builds — `{ random, now, log, storage, fetch, signal }` — and commits its rows
12
+ * afterwards.
13
+ *
14
+ * Two packages paid for that gap before it was written down:
15
+ *
16
+ * - **Twenty Questions shipped a dead Query.** Its `ctx.read` worked in the
17
+ * harness, because the executor endows `read` for every Query whoever wrote
18
+ * it. No sandbox endows it, so the query would have read nothing at install.
19
+ * - **Battleship had to write its own fake store.** Nothing in the harness
20
+ * endows `ctx.storage`, so a package whose whole point is that one handler
21
+ * reads back what another wrote could not run its own handlers without
22
+ * hand-wrapping every binding.
23
+ *
24
+ * So this module endows the *sandbox's* surface, and endows **only** that: a
25
+ * plugin Query's `ctx.read` is `undefined` here exactly as it is at install, and
26
+ * a test written against it fails the way the install would. The executor's own
27
+ * conveniences — `progress`, `status`, `countTokens`, `iteration`, `scripts` —
28
+ * are absent for the same reason: no sandbox has ever defined them.
29
+ *
30
+ * ⚠ **Not the real sandbox.** No opaque origin, no worker, no QuickJS, no
31
+ * membrane; the handler runs in this process with ordinary references. What is
32
+ * reproduced is the *shape* — which members exist, which are withheld, what a
33
+ * refusal says, and where the randomness and the clock come from — because that
34
+ * is what a handler can be written against and get wrong.
35
+ */
36
+ import { getDefinition } from './descriptors.js';
37
+ import { err, ok } from './executor.js';
38
+ // ── The grant table (plans 29 R-3) ──────────────────────────────────────────
39
+ // Lives in `hookGrants.ts`, the one copy the sandboxes, the harness and the
40
+ // guide all read (K1c); re-exported here so the harness's API is unchanged.
41
+ import { hookCtxGrants } from './hookGrants.js';
42
+ export { HOOK_CTX_KINDS, hookCtxGrants, hookCtxKeysFor, isHookCtxKind } from './hookGrants.js';
43
+ /** A node kind, as a descriptor spells it, read as the hook ctx kind it dispatches under. */
44
+ const CTX_KIND_OF_NODE = {
45
+ task: 'task',
46
+ query: 'query',
47
+ oracle: 'oracle',
48
+ outlet: 'outlet',
49
+ };
50
+ // ── Randomness and the clock ────────────────────────────────────────────────
51
+ /**
52
+ * The sandbox's RNG — xfnv1a over the seed label, then mulberry32.
53
+ *
54
+ * ⚠ **Not `seededRandom`.** The executor's RNG (executor.ts) is a different
55
+ * algorithm over a different seed, and the two produce different streams from
56
+ * the same word. That is a fact about the two codebases, not a design: a plugin
57
+ * handler's rolls come from the *sandbox's* stream, so a golden over a handler
58
+ * that rolls is only reproducible against this one. Kept byte-for-byte in step
59
+ * with `buildProgram` in the app's `QuickJsSandbox.ts` / `SesWorkerSandbox.ts`.
60
+ * @experimental
61
+ */
62
+ export function pluginSeededRandom(label) {
63
+ let h = 1779033703 ^ label.length;
64
+ for (let i = 0; i < label.length; i++) {
65
+ h = Math.imul(h ^ label.charCodeAt(i), 3432918353);
66
+ h = (h << 13) | (h >>> 19);
67
+ }
68
+ h = Math.imul(h ^ (h >>> 16), 2246822507);
69
+ h = Math.imul(h ^ (h >>> 13), 3266489909);
70
+ let a = (h ^= h >>> 16) >>> 0;
71
+ return () => {
72
+ a |= 0;
73
+ a = (a + 0x6d2b79f5) | 0;
74
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
75
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
76
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
77
+ };
78
+ }
79
+ /**
80
+ * djb2 over the serialized input — the app's per-call address, so the seed
81
+ * label a harness composes is the label an install composes (`pluginBindings.ts`).
82
+ * @experimental
83
+ */
84
+ export function inputDigest(v) {
85
+ let s;
86
+ try {
87
+ s = JSON.stringify(v) ?? '';
88
+ }
89
+ catch {
90
+ s = '';
91
+ }
92
+ let h = 5381;
93
+ for (let i = 0; i < s.length; i++)
94
+ h = ((h << 5) + h + s.charCodeAt(i)) | 0;
95
+ return (h >>> 0).toString(36);
96
+ }
97
+ /**
98
+ * The seed label a plugin node handler's RNG is derived from, as the app
99
+ * composes it: the run seed, the pin, and a digest of the exact input — so
100
+ * replays roll the same and two same-typed nodes in one run (or one node under
101
+ * `each`) get distinct streams without depending on completion order.
102
+ * @experimental
103
+ */
104
+ export const nodeSeedLabel = (seed, pin, input) => `${seed}:node:${pin}:${inputDigest(input)}`;
105
+ // ── ctx.log, as the prelude formats it ──────────────────────────────────────
106
+ const LOG_DETAIL_MAX = 2000;
107
+ const isLogLevel = (v) => v === 'debug' || v === 'info' || v === 'warn' || v === 'error';
108
+ /**
109
+ * One argument, rendered the way the sandbox prelude's `__fmtLog` renders it:
110
+ * a string reads bare, anything else keeps its quotes and braces, and a value
111
+ * JSON has no form for says so in words rather than vanishing.
112
+ *
113
+ * ⚠ One divergence from the prelude, stated rather than hidden: a circular
114
+ * value renders as `[unserializable]` here where the prelude walks the object
115
+ * and writes `[circular]` at the offending edge. Both refuse to throw and both
116
+ * keep the line; only the wording of that one case differs.
117
+ */
118
+ function renderLogArg(v, bare) {
119
+ if (bare && typeof v === 'string')
120
+ return v;
121
+ if (v === undefined)
122
+ return 'undefined';
123
+ const t = typeof v;
124
+ if (t === 'function')
125
+ return '[function]';
126
+ if (t === 'bigint')
127
+ return `${String(v)}n`;
128
+ if (t === 'symbol')
129
+ return String(v);
130
+ if (t === 'number' && !Number.isFinite(v))
131
+ return String(v);
132
+ let out;
133
+ try {
134
+ out = JSON.stringify(v, (_k, val) => val instanceof Error ? { name: val.name, message: val.message } : val);
135
+ }
136
+ catch {
137
+ out = undefined;
138
+ }
139
+ if (out === undefined)
140
+ out = '[unserializable]';
141
+ return out.length > LOG_DETAIL_MAX
142
+ ? `${out.slice(0, LOG_DETAIL_MAX)}...(+${out.length - LOG_DETAIL_MAX} more chars)`
143
+ : out;
144
+ }
145
+ /** The prelude's `__fmtLog`: `[level] message detail…`, or `[log] …`. @experimental */
146
+ export function formatHookLog(args) {
147
+ if (args.length > 1 && isLogLevel(args[0]))
148
+ return (`[${args[0]}] ` +
149
+ [renderLogArg(args[1], true), ...args.slice(2).map((a) => renderLogArg(a, false))].join(' '));
150
+ if (!args.length)
151
+ return '[log]';
152
+ return `[log] ${args.map((a) => renderLogArg(a, true)).join(' ')}`;
153
+ }
154
+ // ── The in-memory ExtensionStorage ──────────────────────────────────────────
155
+ /**
156
+ * The row half of the grant, as a fraction of it — mirrors `rowQuotaFor` in the
157
+ * app's `storageHost.ts`, which is the arithmetic the sandbox actually applies.
158
+ * Rows live in the database and files on disk; one budget is what an author can
159
+ * reason about, and the sub-cap is what stops a plugin putting megabytes in the
160
+ * database.
161
+ * @experimental
162
+ */
163
+ export function rowQuotaFor(quotaBytes) {
164
+ if (!Number.isFinite(quotaBytes) || quotaBytes <= 0)
165
+ return 64 * 1024;
166
+ return Math.min(Math.floor(quotaBytes), Math.max(64 * 1024, Math.min(1024 * 1024, Math.floor(quotaBytes / 8))));
167
+ }
168
+ /** The grant a sandbox falls back to when the manifest declares none. @experimental */
169
+ export const DEFAULT_STORAGE_QUOTA_BYTES = 10 * 1024 * 1024;
170
+ /**
171
+ * The clock this harness pins when a caller names none.
172
+ *
173
+ * Deliberately the same instant as `EXAMPLE_CLOCK` in `testing.ts`, so a
174
+ * handler run inside an executed example and the same handler run in a unit
175
+ * test report the same `ctx.now()` — a golden that moved between the two would
176
+ * be a golden nobody keeps. Defined here rather than imported because
177
+ * `testing.ts` re-exports this module, and a test pins that the two agree.
178
+ * @experimental
179
+ */
180
+ export const HARNESS_CLOCK = 1_700_000_000_000;
181
+ const utf8 = (s) => new TextEncoder().encode(s).length;
182
+ /**
183
+ * An in-memory `ExtensionStorage` — the half the SDK's harness cannot otherwise
184
+ * supply, with the refusals install actually makes.
185
+ *
186
+ * Faithful in the ways a handler can depend on: `get` answers `undefined` for a
187
+ * key nobody wrote; a row costs its key as well as its value; a write past the
188
+ * row budget or the whole grant comes back as `err` rather than throwing, and
189
+ * comes back **whole** so a handler that prunes and retries can; a key that is
190
+ * not a key, and a value JSON cannot carry, throw with the sandbox's sentence.
191
+ *
192
+ * ⚠ Not faithful about: transactions (install commits a call's rows together,
193
+ * this writes as it goes), the database, and the bytes a row costs on disk.
194
+ * What it does reproduce is the one property a package like Battleship exists
195
+ * to demonstrate — a row one handler writes is a row the next handler reads.
196
+ *
197
+ * **Isolation is structural.** One call is one namespace; two plugins get two
198
+ * calls and neither can name the other's keys, because there is no shared map
199
+ * to name them in.
200
+ * @experimental
201
+ */
202
+ export function memoryStorage(opts = {}) {
203
+ const quotaBytes = opts.quotaBytes ?? DEFAULT_STORAGE_QUOTA_BYTES;
204
+ const rowQuotaBytes = opts.rowQuotaBytes ?? rowQuotaFor(quotaBytes);
205
+ const now = opts.now ?? (() => HARNESS_CLOCK);
206
+ const stamp = () => new Date(Math.floor(now())).toISOString();
207
+ const rows = new Map();
208
+ const files = new Map();
209
+ let writes = 0;
210
+ const jsonOf = (v) => {
211
+ let s;
212
+ try {
213
+ s = JSON.stringify(v === undefined ? null : v);
214
+ }
215
+ catch {
216
+ s = undefined;
217
+ }
218
+ if (typeof s !== 'string')
219
+ throw new Error('storage: a row value must be JSON-serializable');
220
+ return s;
221
+ };
222
+ const rowKey = (key) => {
223
+ if (typeof key !== 'string' || key.length === 0)
224
+ throw new Error('storage: a row key is required');
225
+ if (key.length > 512)
226
+ throw new Error('storage: a row key may not exceed 512 characters');
227
+ return key;
228
+ };
229
+ const rowSize = (key, json) => utf8(key) + utf8(json);
230
+ const rowTotal = () => [...rows.values()].reduce((n, r) => n + r.bytes, 0);
231
+ const fileTotal = () => [...files.values()].reduce((n, f) => n + f.bytes.byteLength, 0);
232
+ const usageFrom = (rowBytes, fileBytes) => ({
233
+ quotaBytes,
234
+ usedBytes: rowBytes + fileBytes,
235
+ availableBytes: Math.max(0, quotaBytes - rowBytes - fileBytes),
236
+ rowBytes,
237
+ fileBytes,
238
+ });
239
+ const usage = () => usageFrom(rowTotal(), fileTotal());
240
+ const receipt = (deltaBytes) => ok({ deltaBytes, usage: usage() });
241
+ /** A relative path, jailed the way the host jails one: `..` is refused, never normalised. */
242
+ const filePath = (rel) => {
243
+ if (typeof rel !== 'string' || rel.length === 0)
244
+ throw new Error('storage: a path is required');
245
+ const parts = rel.split('/').filter((p) => p !== '' && p !== '.');
246
+ if (rel.startsWith('/') || parts.some((p) => p === '..'))
247
+ throw new Error('storage: path escapes the extension directory');
248
+ return parts.join('/');
249
+ };
250
+ const fileEntry = (path, f) => ({
251
+ path,
252
+ bytes: f.bytes.byteLength,
253
+ updatedAt: f.updatedAt,
254
+ });
255
+ const extensionFiles = {
256
+ list: async (prefix) => [...files.entries()]
257
+ .filter(([p]) => !prefix || p.startsWith(prefix))
258
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
259
+ .map(([p, f]) => fileEntry(p, f)),
260
+ stat: async (path) => {
261
+ const p = filePath(path);
262
+ const f = files.get(p);
263
+ return f ? fileEntry(p, f) : null;
264
+ },
265
+ read: async (path) => {
266
+ const f = files.get(filePath(path));
267
+ return f ? ok(new Uint8Array(f.bytes)) : err('storage: not found');
268
+ },
269
+ write: async (path, bytes) => {
270
+ const p = filePath(path);
271
+ const incoming = bytes?.byteLength ?? 0;
272
+ const existing = files.get(p)?.bytes.byteLength ?? 0;
273
+ if (rowTotal() + fileTotal() - existing + incoming > quotaBytes)
274
+ return err('storage: quota exceeded');
275
+ files.set(p, { bytes: new Uint8Array(bytes ?? []), updatedAt: stamp() });
276
+ return ok({ deltaBytes: incoming - existing, usage: usage() });
277
+ },
278
+ delete: async (path) => {
279
+ const p = filePath(path);
280
+ const freed = files.get(p)?.bytes.byteLength ?? 0;
281
+ files.delete(p);
282
+ return receipt(-freed);
283
+ },
284
+ deleteAll: async (prefix) => {
285
+ const doomed = [...files.keys()].filter((p) => !prefix || p.startsWith(prefix));
286
+ for (const p of doomed)
287
+ files.delete(p);
288
+ return ok({ removed: doomed.length, usage: usage() });
289
+ },
290
+ };
291
+ const store = {
292
+ get writes() {
293
+ return writes;
294
+ },
295
+ snapshot: () => Object.fromEntries([...rows.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([k, r]) => [k, r.value])),
296
+ usage: async () => usage(),
297
+ get: async (key) => rows.get(rowKey(key))?.value,
298
+ keys: async (prefix) => {
299
+ const p = prefix ?? '';
300
+ return [...rows.keys()].filter((k) => k.startsWith(p)).sort();
301
+ },
302
+ query: async (q = {}) => {
303
+ const p = q.prefix ?? '';
304
+ const since = q.since == null ? NaN : Date.parse(q.since);
305
+ const until = q.until == null ? NaN : Date.parse(q.until);
306
+ const want = Math.floor(Number(q.limit));
307
+ const limit = Math.max(1, Math.min(200, Number.isFinite(want) && want > 0 ? want : 50));
308
+ const order = q.order === 'oldest' || q.order === 'key' ? q.order : 'newest';
309
+ const all = [];
310
+ for (const [key, r] of rows) {
311
+ if (!key.startsWith(p))
312
+ continue;
313
+ const t = Date.parse(r.updatedAt);
314
+ if (!Number.isNaN(since) && !(t >= since))
315
+ continue;
316
+ if (!Number.isNaN(until) && !(t < until))
317
+ continue;
318
+ all.push({ key, value: r.value, bytes: r.bytes, updatedAt: r.updatedAt });
319
+ }
320
+ all.sort((a, b) => {
321
+ if (order !== 'key') {
322
+ const ta = Date.parse(a.updatedAt);
323
+ const tb = Date.parse(b.updatedAt);
324
+ if (ta !== tb)
325
+ return order === 'oldest' ? ta - tb : tb - ta;
326
+ }
327
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
328
+ });
329
+ // An offset cursor. One it cannot read throws rather than silently
330
+ // restarting at zero, which is how a pager becomes an infinite loop.
331
+ let start = 0;
332
+ if (q.cursor != null) {
333
+ const c = String(q.cursor);
334
+ if (!/^o:[0-9]+$/.test(c))
335
+ throw new Error('storage: unreadable cursor');
336
+ start = parseInt(c.slice(2), 10);
337
+ }
338
+ const page = { rows: all.slice(start, start + limit) };
339
+ if (start + limit < all.length)
340
+ page.nextCursor = `o:${start + limit}`;
341
+ return page;
342
+ },
343
+ put: async (key, value) => {
344
+ writes++;
345
+ const k = rowKey(key);
346
+ const json = jsonOf(value);
347
+ const size = rowSize(k, json);
348
+ const prev = rows.get(k);
349
+ const delta = size - (prev?.bytes ?? 0);
350
+ const before = rowTotal();
351
+ // Two ceilings, checked in the order the sandbox checks them, so a
352
+ // handler that publishes the refusal publishes the same sentence.
353
+ if (before + delta > rowQuotaBytes)
354
+ return err('storage: the row budget is full');
355
+ const fileBytes = fileTotal();
356
+ if (before + fileBytes + delta > quotaBytes)
357
+ return err('storage: quota exceeded');
358
+ // Re-parsed, not stored by reference: at install the value crosses a
359
+ // JSON boundary, so a handler mutating the object it put must not be
360
+ // able to change what the store holds.
361
+ rows.set(k, { value: JSON.parse(json), bytes: size, updatedAt: stamp() });
362
+ return ok({ deltaBytes: delta, usage: usageFrom(before + delta, fileBytes) });
363
+ },
364
+ delete: async (key) => {
365
+ const k = rowKey(key);
366
+ const prev = rows.get(k);
367
+ if (!prev)
368
+ return receipt(0);
369
+ rows.delete(k);
370
+ return receipt(-prev.bytes);
371
+ },
372
+ deleteAll: async (prefix) => {
373
+ const p = prefix ?? '';
374
+ const doomed = [...rows.keys()].filter((k) => k.startsWith(p));
375
+ for (const k of doomed)
376
+ rows.delete(k);
377
+ return ok({ removed: doomed.length, usage: usage() });
378
+ },
379
+ files: extensionFiles,
380
+ };
381
+ for (const [key, value] of Object.entries(opts.seed ?? {})) {
382
+ const json = jsonOf(value);
383
+ rows.set(rowKey(key), { value: JSON.parse(json), bytes: rowSize(key, json), updatedAt: stamp() });
384
+ }
385
+ return store;
386
+ }
387
+ // ── ctx.fetch, with its refusals ────────────────────────────────────────────
388
+ /**
389
+ * Does an allowlist entry cover this host and port? The authoring grammar is
390
+ * `host`, `*.suffix` or `*`, each with an optional `:port`; a bare host or
391
+ * wildcard reaches only the default web ports. Mirrors `matchAllow` in the
392
+ * app's `fetchHost.ts`.
393
+ */
394
+ function matchAllow(allow, reqHost, reqPort) {
395
+ const host = String(reqHost).toLowerCase();
396
+ for (const entry of allow) {
397
+ const raw = String(entry ?? '').toLowerCase();
398
+ if (!raw)
399
+ continue;
400
+ let entryHost = raw;
401
+ let entryPort = null;
402
+ // A trailing ":<digits>" is a port; skip the split for IPv6 (which has
403
+ // its own colons) so "::1" is not mis-parsed as host ":" + port "1".
404
+ const ci = raw.lastIndexOf(':');
405
+ if (ci > 0 && /^\d+$/.test(raw.slice(ci + 1)) && raw.slice(0, ci).indexOf(':') < 0) {
406
+ entryHost = raw.slice(0, ci);
407
+ entryPort = Number(raw.slice(ci + 1));
408
+ }
409
+ let hostOk;
410
+ if (entryHost === '*')
411
+ hostOk = true;
412
+ else if (entryHost.startsWith('*.')) {
413
+ // "*.example.com" matches any sub-domain, but NOT the apex.
414
+ const suffix = entryHost.slice(1);
415
+ hostOk = host.length > suffix.length && host.slice(-suffix.length) === suffix;
416
+ }
417
+ else
418
+ hostOk = host === entryHost;
419
+ if (!hostOk)
420
+ continue;
421
+ if (entryPort !== null) {
422
+ if (reqPort === entryPort)
423
+ return entryHost;
424
+ }
425
+ else if (entryHost === 'localhost' || isIpLiteral(entryHost)) {
426
+ // A deliberate internal grant — any port on that literal target.
427
+ return entryHost;
428
+ }
429
+ else if (reqPort === 80 || reqPort === 443) {
430
+ // A bare host/wildcard grant reaches only the default web ports.
431
+ return entryHost;
432
+ }
433
+ }
434
+ return null;
435
+ }
436
+ const isIpLiteral = (h) => /^\d{1,3}(\.\d{1,3}){3}$/.test(h) || h.includes(':');
437
+ /**
438
+ * Build the context a plugin's handler runs against at install.
439
+ *
440
+ * The one-liner `examples/fixtures.ts` in a plugin repo should not have to
441
+ * write: pass it to a handler and the handler sees what the sandbox gives it,
442
+ * including the absences.
443
+ * @experimental
444
+ */
445
+ export function pluginHandlerContext(opts) {
446
+ const base = opts.kind ? hookCtxGrants(opts.kind) : { storage: true, fetch: true };
447
+ const grants = {
448
+ storage: opts.grants?.storage ?? base.storage,
449
+ fetch: opts.grants?.fetch ?? base.fetch,
450
+ };
451
+ const nowMs = Math.floor(opts.now ?? HARNESS_CLOCK);
452
+ const random = pluginSeededRandom(opts.seed ?? `${opts.pluginId}:harness`);
453
+ const logs = opts.logs;
454
+ // Built in the sandbox's own order, because `hookCtxKeysFor` is what a test
455
+ // compares `Object.keys(ctx)` against and an order nobody decided would make
456
+ // that comparison an accident.
457
+ const ctx = {
458
+ random,
459
+ now: () => nowMs,
460
+ log: (...args) => void logs?.push(formatHookLog(args)),
461
+ signal: opts.signal ?? new AbortController().signal,
462
+ };
463
+ const members = ctx;
464
+ if (grants.storage)
465
+ insertBefore(members, 'signal', 'storage', opts.storage ?? memoryStorage());
466
+ if (grants.fetch)
467
+ insertBefore(members, 'signal', 'fetch', makeFetch(opts, ctx.signal));
468
+ return ctx;
469
+ }
470
+ /**
471
+ * Put a member in its sandbox position. `signal` is defined last in both
472
+ * backends' programs, so an endowment appended after it would give a context
473
+ * whose key order no install produces — and the key order is the thing a
474
+ * surface test reads.
475
+ */
476
+ function insertBefore(obj, before, key, value) {
477
+ const tail = obj[before];
478
+ delete obj[before];
479
+ obj[key] = value;
480
+ obj[before] = tail;
481
+ }
482
+ function makeFetch(opts, signal) {
483
+ const allow = opts.network ?? [];
484
+ return async (url, init) => {
485
+ // The refusal a plugin without the permission hears. Declared with no
486
+ // hosts — or with every host an admin denied — is the same grant as
487
+ // none, and it must hear "permission not granted" rather than "host not
488
+ // permitted", which would confirm it holds the permission and merely
489
+ // aimed badly.
490
+ if (!allow.length)
491
+ throw new Error('network: permission not granted');
492
+ // No request may START after ctx.signal fires — the host's rule, and the
493
+ // signal read here is the one the handler holds, not the one the caller
494
+ // may or may not have passed in.
495
+ if (signal.aborted)
496
+ throw new Error('fetch: the call was cancelled');
497
+ let u;
498
+ try {
499
+ u = new URL(url);
500
+ }
501
+ catch {
502
+ throw new Error('fetch: a url is required');
503
+ }
504
+ if (u.protocol !== 'http:' && u.protocol !== 'https:')
505
+ throw new Error('fetch: only http(s) is allowed');
506
+ const host = u.hostname.replace(/^\[|\]$/g, '').toLowerCase();
507
+ const port = u.port ? Number(u.port) : u.protocol === 'https:' ? 443 : 80;
508
+ if (matchAllow(allow, host, port) === null)
509
+ throw new Error(`fetch: host not permitted: ${u.host}`);
510
+ if (!opts.fetch)
511
+ throw new Error(`fetch: '${u.host}' is permitted, but this harness was given no answer for it — ` +
512
+ `pass fetch: (url, init) => ({ status, ok, headers, body }) to script the response ` +
513
+ `(nothing here reaches the network)`);
514
+ return await opts.fetch(url, init);
515
+ };
516
+ }
517
+ /**
518
+ * Project a plugin's handlers into executor bindings that run them against the
519
+ * **sandbox's** context — the harness's counterpart of the app's
520
+ * `pluginNodeBindings` (`pipelines/runtime/pluginBindings.ts`), which does the
521
+ * same projection over a real sandbox.
522
+ *
523
+ * The executor's own context reaches the handler in exactly one respect: its
524
+ * `signal`, because at install the host fires the sandbox's abort from the same
525
+ * place. Everything else it built — `read`, `call`, `commit`, `progress`,
526
+ * `status`, `countTokens` — is dropped, because no sandbox has ever endowed it.
527
+ * A plugin Query reaching for `ctx.read` therefore fails here exactly as it
528
+ * fails at install, which is the whole reason this exists (G13).
529
+ * @experimental
530
+ */
531
+ export function pluginNodeBindings(opts) {
532
+ const storage = opts.storage ?? memoryStorage();
533
+ const seed = opts.seed ?? 'seed:harness';
534
+ const bindings = {};
535
+ for (const [pin, handler] of Object.entries(opts.handlers)) {
536
+ const kind = opts.kinds?.[pin] ?? CTX_KIND_OF_NODE[getDefinition(pin)?.kind ?? ''];
537
+ const hook = async (input, execCtx = {}) => {
538
+ if (!kind)
539
+ return err(`${pin}: this harness cannot tell which hook ctx kind '${pin}' dispatches under, so it ` +
540
+ `cannot decide whether the handler gets ctx.storage or ctx.fetch (plans/29 R-3). ` +
541
+ `Register the definition before building the bindings, or name it in \`kinds\`.`);
542
+ return await handler(input, pluginHandlerContext({
543
+ pluginId: opts.pluginId,
544
+ kind,
545
+ seed: nodeSeedLabel(seed, pin, input),
546
+ storage,
547
+ now: opts.now,
548
+ signal: execCtx?.signal,
549
+ network: opts.network,
550
+ fetch: opts.fetch,
551
+ logs: opts.logs,
552
+ }));
553
+ };
554
+ bindings[pin] = hook;
555
+ }
556
+ return bindings;
557
+ }
558
+ //# sourceMappingURL=pluginHarness.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * What a plugin may do, by kind (K1, R50): one table, rendered from the grant
3
+ * table the sandboxes enforce (`hookCtxKeysFor`) and the rulings every door
4
+ * refuses on, so the guide cannot claim more or less than the code does.
5
+ *
6
+ * `guides/plugin-permissions.md` is this module's output (`renderPluginPermissionsGuide`),
7
+ * held to it by a test, and every refusal that stems from a row names the
8
+ * row's anchor (`pluginRuleRef`), each anchor held by a test to exist.
9
+ *
10
+ * ⚠ Not a **capability** — that is what a *connection* can do (`capabilities.ts`).
11
+ * These are a plugin's **permissions**: what its sandboxed code may do (canon).
12
+ */
13
+ import type { PluginRule } from './pluginRuleRef.js';
14
+ export { PLUGIN_PERMISSIONS_GUIDE, pluginRuleRef, type PluginRule } from './pluginRuleRef.js';
15
+ /** The rules a refusal can point at, each a heading in the guide. @experimental */
16
+ export declare const PLUGIN_RULES: Record<PluginRule, {
17
+ title: string;
18
+ ruling: string;
19
+ text: string;
20
+ }>;
21
+ /** Every anchor a refusal may point at — each a heading the guide renders. @experimental */
22
+ export declare const PLUGIN_RULE_ANCHORS: readonly string[];
23
+ /** The guide, rendered from the table. @internal */
24
+ export declare function renderPluginPermissionsGuide(): string;
25
+ //# sourceMappingURL=pluginPermissions.d.ts.map
@@ -0,0 +1,97 @@
1
+ /**
2
+ * What a plugin may do, by kind (K1, R50): one table, rendered from the grant
3
+ * table the sandboxes enforce (`hookCtxKeysFor`) and the rulings every door
4
+ * refuses on, so the guide cannot claim more or less than the code does.
5
+ *
6
+ * `guides/plugin-permissions.md` is this module's output (`renderPluginPermissionsGuide`),
7
+ * held to it by a test, and every refusal that stems from a row names the
8
+ * row's anchor (`pluginRuleRef`), each anchor held by a test to exist.
9
+ *
10
+ * ⚠ Not a **capability** — that is what a *connection* can do (`capabilities.ts`).
11
+ * These are a plugin's **permissions**: what its sandboxed code may do (canon).
12
+ */
13
+ import { HOOK_CTX_KINDS, hookCtxKeysFor } from './hookGrants.js';
14
+ export { PLUGIN_PERMISSIONS_GUIDE, pluginRuleRef } from './pluginRuleRef.js';
15
+ /** The rules a refusal can point at, each a heading in the guide. @experimental */
16
+ export const PLUGIN_RULES = {
17
+ connections: {
18
+ title: 'Plugins never touch a connection',
19
+ ruling: 'R53',
20
+ text: "A plugin's code never reads connection data or calls a model; model calls are core's nodes. " +
21
+ 'It may know only which capabilities are available. A node that uses a connection takes only ' +
22
+ "core's stand-ins: shape it with your own prompts or a config instead.",
23
+ },
24
+ 'private-nodes': {
25
+ title: 'A node is as public as its handler',
26
+ ruling: 'R62',
27
+ text: "`handler(definition, fn, { visibility: 'public' })` makes a node usable by any package's " +
28
+ 'pipeline, or by one a person makes; private is the default. A definition never says `public` ' +
29
+ "itself. A swap contribution must be public: it runs your node in another package's pipeline. " +
30
+ 'Refused at build, install, publish and run.',
31
+ },
32
+ secrets: {
33
+ title: 'Secrets are handles',
34
+ ruling: 'R63',
35
+ text: 'A `secret` setting reaches your code as a handle (`⟦secret:<key>:<nonce>⟧`), never its value; ' +
36
+ '`ctx.fetch` fills the value in for your declared hosts only, an echoed or quoted key comes back ' +
37
+ 'as the handle, and anything you return, throw, log or store is scrubbed of it. When your node ' +
38
+ "or tool runs in a pipeline another package owns, or one a person made, only the secrets you " +
39
+ 'mark `lend: true` go with it.',
40
+ },
41
+ events: {
42
+ title: 'Events are caused by writes',
43
+ ruling: 'F8',
44
+ text: 'No node emits an event or starts a pipeline. A package records its own declared event with the ' +
45
+ '`record-event` write, within the scope its entry declares, and everything in the session hears it.',
46
+ },
47
+ };
48
+ /** The anchor a kind's heading gets: `kind-oracle`. */
49
+ const kindAnchor = (kind) => `kind-${kind}`;
50
+ /** What each kind's hook is, in a line — the one prose half the grant table cannot say. */
51
+ const KIND_ROLE = {
52
+ task: 'A node that computes: data in, data out.',
53
+ query: "A node that reads. Yours reads your plugin's own storage; Serene Pub's data reaches it on its input ports, from core's queries.",
54
+ oracle: 'The one node kind that calls out: the network, through the hosts your plugin declares. Never a model: model calls are core\'s nodes.',
55
+ outlet: "A node that writes. Yours declares `effects: 'emit'`: it writes your own storage and passes values on, and core's outlets write to the session.",
56
+ 'chain-link': 'A link in a script chain: text in, text out.',
57
+ event: 'An event listener: runs when a session event happens.',
58
+ lifecycle: 'A lifecycle callback: runs at startup, enable, disable, update, uninstall or shutdown.',
59
+ };
60
+ /** Every anchor a refusal may point at — each a heading the guide renders. @experimental */
61
+ export const PLUGIN_RULE_ANCHORS = [
62
+ ...HOOK_CTX_KINDS.map(kindAnchor),
63
+ ...Object.keys(PLUGIN_RULES),
64
+ ];
65
+ const code = (keys) => keys.map((k) => `\`${k}\``);
66
+ /** The guide, rendered from the table. @internal */
67
+ export function renderPluginPermissionsGuide() {
68
+ const lines = [
69
+ '# What a plugin may do',
70
+ '',
71
+ "Your plugin's code runs in a sandbox, and what it may do depends on what kind of handler it is. " +
72
+ 'Each kind is handed a `ctx` with exactly these members and nothing else: `random`, `now`, `log` ' +
73
+ "and `signal` are every kind's, and storage and network are granted by kind. This page is generated " +
74
+ 'from the table the sandboxes enforce, and a refusal names the section below that explains it. ' +
75
+ 'For what each part of a plugin is for, see [What a plugin can do](extending.md).',
76
+ '',
77
+ '<!-- Generated from the SDK (`renderPluginPermissionsGuide`, sdk/src/pluginPermissions.ts). Do not edit by hand. -->',
78
+ '',
79
+ '| Kind | Its `ctx` | What it is |',
80
+ '|---|---|---|',
81
+ ...HOOK_CTX_KINDS.map((k) => `| [${k}](#${kindAnchor(k)}) | ${code(hookCtxKeysFor(k)).join(' · ')} | ${KIND_ROLE[k]} |`),
82
+ '',
83
+ ];
84
+ for (const k of HOOK_CTX_KINDS) {
85
+ const keys = hookCtxKeysFor(k);
86
+ lines.push(
87
+ // GitHub's slug of "Kind: oracle" is `kind-oracle`, the anchor.
88
+ `## Kind: ${k}`, '', KIND_ROLE[k], '', `- Handed: ${code(keys).join(', ')}.`, `- ${keys.includes('storage') ? "Storage: your plugin's own rows and files, when it asks for storage (`permissions.storage`)." : 'No storage.'}`, `- ${keys.includes('fetch') ? 'Network: only the hosts your plugin declares (`permissions.network.hosts`) and an admin left allowed.' : 'No network.'}`, '');
89
+ }
90
+ lines.push('## Rules for every kind', '');
91
+ // Each heading is its anchor in words — "Private nodes" slugs to
92
+ // `private-nodes` — with the rule itself as the first line.
93
+ for (const [anchor, rule] of Object.entries(PLUGIN_RULES))
94
+ lines.push(`### ${anchor[0].toUpperCase()}${anchor.slice(1).replace(/-/g, ' ')}`, '', `**${rule.title}.** ${rule.text}`, '');
95
+ return lines.join('\n');
96
+ }
97
+ //# sourceMappingURL=pluginPermissions.js.map