@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,383 @@
1
+ /**
2
+ * `@serene-pub/sdk/testing` — the harness a **plugin author** runs (03 §9, U11).
3
+ *
4
+ * Distinct from `src/conformance.ts`, which is what **SP Core** runs against its own
5
+ * executor. Two different audiences and two different questions:
6
+ *
7
+ * conformance.ts — "does this host obey the laws?"
8
+ * testing.ts — "does my hook behave, and did my change alter what gets sent?"
9
+ *
10
+ * The second question is the one that keeps a plugin working across SP releases, and it
11
+ * is answered by goldens: record a receipt now, compare later, and see the diff rather
12
+ * than a pass/fail. **"It still runs" is not the assertion anyone needs** — a plugin that
13
+ * runs and quietly changes the prompt is the failure mode that reaches users.
14
+ */
15
+ import { run } from './executor.js';
16
+ /**
17
+ * The plugin sandbox's context, in this harness (plans 29 §14 D-3) — the half
18
+ * the executor cannot supply, because a plugin's node handlers never run
19
+ * against the executor's context at install. Re-exported here so an author's
20
+ * one import is `@serene-pub/sdk/testing`.
21
+ */
22
+ export * from './pluginHarness.js';
23
+ /**
24
+ * Reduce a receipt to what a golden should hold.
25
+ *
26
+ * Timings, run ids and wall-clock are all excluded — a golden that fails because a run
27
+ * took 3ms instead of 2ms is a golden nobody keeps. What is kept is every decision and
28
+ * every payload, which is what actually changes when a plugin's behaviour changes.
29
+ * @experimental
30
+ */
31
+ export function toGolden(name, r) {
32
+ return {
33
+ name,
34
+ specId: r.specId,
35
+ specVersion: r.specVersion,
36
+ seed: r.seed,
37
+ outcome: r.outcome,
38
+ haltReason: r.haltReason,
39
+ nodes: r.nodes.map((n) => ({
40
+ nodeKey: n.nodeKey,
41
+ kind: n.kind,
42
+ result: n.result,
43
+ input: n.input,
44
+ output: n.output,
45
+ })),
46
+ emitted: r.emitted.map((e) => ({ event: e.event, cause: e.cause })),
47
+ wire: r.preview?.context.rendered,
48
+ };
49
+ }
50
+ /** A structural diff, deepest-path-first, so the first line names the actual change. @experimental */
51
+ export function diffGolden(before, after) {
52
+ const out = [];
53
+ const walk = (a, b, path) => {
54
+ if (JSON.stringify(a) === JSON.stringify(b))
55
+ return;
56
+ const both = a && b && typeof a === 'object' && typeof b === 'object';
57
+ if (!both)
58
+ return void out.push({ path, before: a, after: b });
59
+ const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
60
+ let pushed = false;
61
+ for (const k of keys) {
62
+ const before = out.length;
63
+ walk(a[k], b[k], path ? `${path}.${k}` : k);
64
+ if (out.length > before)
65
+ pushed = true;
66
+ }
67
+ if (!pushed)
68
+ out.push({ path, before: a, after: b });
69
+ };
70
+ walk(before, after, '');
71
+ return out;
72
+ }
73
+ /** @experimental */
74
+ export function renderDiff(d) {
75
+ if (!d.length)
76
+ return 'identical';
77
+ return d
78
+ .map((x) => ` ${x.path}\n before: ${JSON.stringify(x.before)}\n after: ${JSON.stringify(x.after)}`)
79
+ .join('\n');
80
+ }
81
+ /** @experimental */
82
+ export class GoldenMismatch extends Error {
83
+ name;
84
+ diff;
85
+ constructor(name, diff) {
86
+ super(`golden '${name}' changed:\n${renderDiff(diff)}`);
87
+ this.name = name;
88
+ this.diff = diff;
89
+ }
90
+ }
91
+ /** Record if absent, compare if present. The whole workflow in one call. @experimental */
92
+ export function checkGolden(name, r, stored) {
93
+ const golden = toGolden(name, r);
94
+ if (!stored)
95
+ return { golden, recorded: true };
96
+ const diff = diffGolden(stored, golden);
97
+ if (diff.length)
98
+ throw new GoldenMismatch(name, diff);
99
+ return { golden, recorded: false };
100
+ }
101
+ const must = (cond, why) => {
102
+ if (!cond)
103
+ throw new Error(why);
104
+ };
105
+ const isResult = (v) => !!v && typeof v === 'object' && ['ok', 'err', 'cancelled', 'halt'].includes(v.kind);
106
+ /**
107
+ * What a hook has to do to be a hook. Run these in your own tests — the executor assumes
108
+ * all of it, and a hook that breaks one of them fails in a way that is hard to attribute.
109
+ * @experimental
110
+ */
111
+ export const BINDING_PROBES = [
112
+ {
113
+ id: 'B1',
114
+ title: 'returns a discriminated result, never a bare value',
115
+ consequence: 'The executor cannot tell success from a halt, so a correct "not applicable" is recorded as an error and the run inspector stops being trustworthy.',
116
+ async check(hook, _d, ctx) {
117
+ const r = await hook(ctx.sampleInput, ctx.makeCtx());
118
+ must(isResult(r), `returned ${typeof r}; expected ok(…) / err(…) / halt(…) / cancelled(…)`);
119
+ },
120
+ },
121
+ {
122
+ id: 'B2',
123
+ title: 'a Task reaches for no services',
124
+ consequence: 'Purity is what makes replay exact (F11). A Task that reads the clock or the network produces a run nobody can reproduce, and the receipt becomes a story rather than a record.',
125
+ async check(hook, d, ctx) {
126
+ if (d.kind !== 'task')
127
+ return;
128
+ const surface = ctx.makeCtx();
129
+ must(!('read' in surface), 'a Task context must not carry `read`');
130
+ must(!('call' in surface), 'a Task context must not carry `call`');
131
+ must(!('commit' in surface), 'a Task context must not carry `commit`');
132
+ await hook(ctx.sampleInput, surface);
133
+ },
134
+ },
135
+ {
136
+ id: 'B3',
137
+ title: 'randomness comes only from the run seed',
138
+ consequence: 'A dice roll nobody can replay is a dice roll nobody can dispute — and the seeded version is the whole reason SP can explain a probability roll where the incumbent cannot.',
139
+ async check(hook, d, ctx) {
140
+ if (!d.declaresRandomness)
141
+ return;
142
+ const a = await hook(ctx.sampleInput, ctx.makeCtx({ random: seeded('probe') }));
143
+ const b = await hook(ctx.sampleInput, ctx.makeCtx({ random: seeded('probe') }));
144
+ must(JSON.stringify(a) === JSON.stringify(b), 'two invocations with the same seeded RNG produced different output — something is reaching for Math.random');
145
+ },
146
+ },
147
+ {
148
+ id: 'B4',
149
+ title: 'it settles rather than hanging',
150
+ consequence: '`runtime: node` abandons rather than kills (13 §7h), so a hook that never settles keeps burning CPU after the executor has moved on and eventually marks your plugin unhealthy.',
151
+ async check(hook, _d, ctx) {
152
+ const settled = await Promise.race([
153
+ Promise.resolve(hook(ctx.sampleInput, ctx.makeCtx())).then(() => true),
154
+ new Promise((res) => setTimeout(() => res(false), 250)),
155
+ ]);
156
+ must(settled, 'did not settle within 250ms in a probe with no I/O');
157
+ },
158
+ },
159
+ {
160
+ id: 'B5',
161
+ title: 'it honours the abort signal',
162
+ consequence: 'The signal is the only cooperative way an in-process hook can be stopped. Ignoring it means an admin killing a run watches it keep going.',
163
+ async check(hook, _d, ctx) {
164
+ const c = new AbortController();
165
+ c.abort();
166
+ const r = await hook(ctx.sampleInput, ctx.makeCtx({ signal: c.signal }));
167
+ must(isResult(r), 'an aborted invocation still has to return a result, not throw');
168
+ },
169
+ },
170
+ ];
171
+ function seeded(seed) {
172
+ let h = 2166136261;
173
+ for (let i = 0; i < seed.length; i++)
174
+ h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
175
+ return () => {
176
+ h = Math.imul(h ^ (h >>> 15), 2246822507);
177
+ h = Math.imul(h ^ (h >>> 13), 3266489909);
178
+ return ((h ^= h >>> 16) >>> 0) / 4294967296;
179
+ };
180
+ }
181
+ const PROBE_TIMEOUT_MS = 1000;
182
+ /**
183
+ * The timer is *not* unref'd and *is* cleared. A probe that awaits a hook which never
184
+ * settles has to lose to a timer the event loop is still holding — otherwise the loop
185
+ * drains, the await never resolves, and the author sees their test runner give up
186
+ * instead of seeing "your hook never returned".
187
+ */
188
+ function bounded(p) {
189
+ let timer;
190
+ return Promise.race([
191
+ p,
192
+ new Promise((_, rej) => {
193
+ timer = setTimeout(() => rej(new Error(`probe did not settle within ${PROBE_TIMEOUT_MS}ms — the hook never returned`)), PROBE_TIMEOUT_MS);
194
+ }),
195
+ ]).finally(() => clearTimeout(timer));
196
+ }
197
+ /** @experimental */
198
+ export async function probeBinding(hook, descriptor, ctx) {
199
+ const out = [];
200
+ for (const p of BINDING_PROBES) {
201
+ try {
202
+ // Every probe is bounded. A probe that awaits a hook which never settles would
203
+ // otherwise hang the author's whole test run — turning "your hook has a bug"
204
+ // into "the SDK's harness is broken", which is the wrong lesson to teach.
205
+ await bounded(Promise.resolve(p.check(hook, descriptor, ctx)));
206
+ out.push({ id: p.id, title: p.title, pass: true });
207
+ }
208
+ catch (e) {
209
+ out.push({ id: p.id, title: p.title, pass: false, error: e.message, consequence: p.consequence });
210
+ }
211
+ }
212
+ return out;
213
+ }
214
+ /** A context shaped like the executor's, per kind — so a probe tests the real surface. @experimental */
215
+ export const probeCtxFor = (kind, sampleInput = {}) => ({
216
+ sampleInput,
217
+ makeCtx: (over = {}) => {
218
+ const base = {
219
+ signal: new AbortController().signal,
220
+ progress: () => { },
221
+ log: () => { },
222
+ };
223
+ if (kind === 'query')
224
+ base.read = () => [];
225
+ if (kind === 'oracle') {
226
+ base.call = async (p) => p;
227
+ base.connectionMetadata = {};
228
+ base.sampling = {};
229
+ base.reportUsage = () => { };
230
+ base.reportSampling = () => { };
231
+ }
232
+ if (kind === 'outlet') {
233
+ base.commit = async (p) => ({ id: 'row:probe', ...p });
234
+ base.emit = () => { };
235
+ }
236
+ return { ...base, ...over };
237
+ },
238
+ });
239
+ // ── Executed examples ───────────────────────────────────────────────────────
240
+ /**
241
+ * The seed and the clock an executed example runs on.
242
+ *
243
+ * Fixed, and fixed *here* rather than per example: two runs of the same page
244
+ * have to produce the same bytes or the golden is noise, and a seed chosen by
245
+ * each example is a seed one of them forgets to choose. Everything a receipt
246
+ * records that moves on its own — run id, timestamps, durations — is either
247
+ * excluded by `toGolden` or never rendered by `renderRunSummary`.
248
+ *
249
+ * They live in the SDK rather than in the docs generator because the generator
250
+ * is not the only thing that runs an example any more: the browser playground
251
+ * runs the same module against the same seed, and a reader who compares what
252
+ * they just ran against the page has to be comparing the same run.
253
+ * @experimental
254
+ */
255
+ export const EXAMPLE_SEED = 'seed:example';
256
+ /** @experimental */
257
+ export const EXAMPLE_CLOCK = 1_700_000_000_000;
258
+ /** The context an executed example runs against. Seed and clock default to the fixed pair. @experimental */
259
+ export function makeExampleRunCtx(doc, opts = {}) {
260
+ const seed = opts.seed ?? EXAMPLE_SEED;
261
+ const now = opts.now ?? (() => EXAMPLE_CLOCK);
262
+ return { doc, seed, now, run: (runOpts) => run(doc, { ...runOpts, seed, now }) };
263
+ }
264
+ const plural = (n, noun) => `${n} ${noun}${n === 1 ? '' : 's'}`;
265
+ /** How much of a written text a summary line shows before it stops. */
266
+ const WROTE_LIMIT = 100;
267
+ /**
268
+ * Whether this outlet's published result is a write the host took (13 §7j-b).
269
+ *
270
+ * The verb on the line below is `wrote`, so it has to be earned. A write-effect
271
+ * outlet publishes a discriminated `WriteResult` and the executor stamps
272
+ * `committed` on it; an emit-class outlet publishes whatever its binding
273
+ * returned, and `pending` is a write still sitting in review.
274
+ */
275
+ const committed = (output) => !!output &&
276
+ typeof output === 'object' &&
277
+ output.status === 'committed';
278
+ /**
279
+ * What an outlet was handed to write, if anything readable.
280
+ *
281
+ * `text` first, because that is the port the writing outlets in the core
282
+ * catalog name. Then the first string-valued port, because an outlet is free
283
+ * to name its own — `audio`, `value` — and a summary that understood one word
284
+ * only would go quiet on exactly the outlets a plugin author wrote. A receipt
285
+ * carries a node's input, not its port declarations, so the input object is
286
+ * all there is to read here.
287
+ */
288
+ function wroteText(input) {
289
+ if (!input || typeof input !== 'object' || Array.isArray(input))
290
+ return undefined;
291
+ const ports = input;
292
+ const value = typeof ports.text === 'string'
293
+ ? ports.text
294
+ : Object.values(ports).find((v) => typeof v === 'string');
295
+ if (value === undefined)
296
+ return undefined;
297
+ // One line, whatever the text did: a summary is a block of plain text, and a
298
+ // reply with a paragraph break in it would otherwise break the column.
299
+ const flat = value.replace(/\s+/g, ' ').trim();
300
+ if (!flat)
301
+ return undefined;
302
+ return flat.length > WROTE_LIMIT ? `${flat.slice(0, WROTE_LIMIT)}…` : flat;
303
+ }
304
+ /**
305
+ * A receipt as a page shows it: what ran, in order, and how each step ended.
306
+ *
307
+ * Not `renderReceipt`, which is the run inspector's rendering and carries the
308
+ * run id, the elapsed times and the wall clock. Every one of those moves
309
+ * between two identical runs, and a page that changed on every build would
310
+ * teach a reader to ignore it. What is left is what the run DECIDED — which is
311
+ * the only part worth pinning.
312
+ * @experimental
313
+ */
314
+ export function renderRunSummary(r) {
315
+ const out = [];
316
+ out.push(`outcome ${r.outcome}${r.haltNodeKey ? ` · halted at ${r.haltNodeKey}` : ''}`);
317
+ if (r.haltReason)
318
+ out.push(` reason: ${r.haltReason}`);
319
+ for (const n of r.nodes) {
320
+ out.push(` ▸ ${n.nodeKey.padEnd(22)} ${n.kind.padEnd(8)} ${n.result}`);
321
+ if (n.reason)
322
+ out.push(` reason: ${n.reason}`);
323
+ if (n.recoveredAsEmpty)
324
+ out.push(` recovered as empty — the run continued without it`);
325
+ if (n.samplingIgnored?.length)
326
+ out.push(` ignored samplers: ${n.samplingIgnored.join(', ')}`);
327
+ }
328
+ // What actually reached the session. The node lines above say a write
329
+ // happened; these say what it was, which is the half a reader came for.
330
+ //
331
+ // Only outlets that committed. An emit-class outlet is not a write (F7 —
332
+ // there is exactly one of those), and a line for the streaming twin of the
333
+ // write beside it would print the same sentence twice; a dry run committed
334
+ // nothing at all and its line would name a row nobody has.
335
+ for (const n of r.nodes) {
336
+ if (n.kind !== 'outlet' || n.result !== 'ok' || n.dry || !committed(n.output))
337
+ continue;
338
+ const wrote = wroteText(n.input);
339
+ if (wrote !== undefined)
340
+ out.push(` ▸ ${n.nodeKey} wrote: “${wrote}”`);
341
+ }
342
+ for (const e of r.emitted)
343
+ out.push(` ▸ core emitted ${e.event} (cause: ${e.cause}) → ${plural(e.subscribers, 'subscriber')}`);
344
+ out.push(` consumption: ${plural(r.consumption.tokens, 'token')}, ` +
345
+ `${plural(r.consumption.nodeExecutions, 'node execution')}`);
346
+ return out.join('\n');
347
+ }
348
+ // ── Equivalence ─────────────────────────────────────────────────────────────
349
+ /**
350
+ * F26 as a one-liner an author can run: parallel and forced-sequential must produce the
351
+ * same result. If your hook has a hidden ordering dependency, this is where it shows up
352
+ * — not in a user's chat at 2am under load.
353
+ * @experimental
354
+ */
355
+ export async function assertEquivalent(doc, opts) {
356
+ const norm = (r) => r.nodes
357
+ .map((n) => `${n.nodeKey}:${n.result}:${JSON.stringify(n.output)}`)
358
+ .sort()
359
+ .join('\n');
360
+ const par = await run(doc, opts);
361
+ const seq = await run(doc, { ...opts, forceSequential: true });
362
+ if (norm(par) !== norm(seq)) {
363
+ throw new Error('forced-sequential execution produced a different result (F26). Something in this spec ' +
364
+ 'depends on completion order — usually a hook mutating shared state rather than returning it.');
365
+ }
366
+ }
367
+ /** Run the same spec twice on one seed and assert nothing moved (F11). @experimental */
368
+ export async function assertDeterministic(doc, opts) {
369
+ const a = await run(doc, opts);
370
+ const b = await run(doc, opts);
371
+ const diff = diffGolden(toGolden('a', a), toGolden('b', b));
372
+ if (diff.length)
373
+ throw new GoldenMismatch('determinism', diff);
374
+ }
375
+ /** @experimental */
376
+ export function renderProbes(results) {
377
+ const lines = results.map((r) => ` ${r.pass ? '✓' : '✗'} ${r.id} ${r.title}`);
378
+ for (const r of results.filter((x) => !x.pass)) {
379
+ lines.push('', `✗ ${r.id} — ${r.error}`, ` what this breaks: ${r.consequence}`);
380
+ }
381
+ return lines.join('\n');
382
+ }
383
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Which tokenizer a run budgets with — the ids, the resolution, and the one
3
+ * thing that makes the whole arrangement work: **loading is asynchronous,
4
+ * counting is not.**
5
+ *
6
+ * ## The problem this file exists to dissolve
7
+ *
8
+ * `RunOptions.countTokens` is `(v: unknown) => number`, strictly synchronous,
9
+ * because the allocation and wire-measurement loops decide what fits while
10
+ * walking candidates — a loop that awaited per candidate would be a different
11
+ * loop, and a much slower one, at exactly the moment somebody's context is
12
+ * biggest. A host's real tokenizers, meanwhile, are async: not because
13
+ * *counting* is async but because **loading** a 55 MB merge table is.
14
+ *
15
+ * So the two are separated. `loadTokenizer` is awaited **once**, before the run
16
+ * starts, and hands back a plain synchronous function. Nothing downstream of
17
+ * that point knows a tokenizer was ever loaded. The executor passes an *id*
18
+ * rather than a function, so which tokenizer a run used is a fact recorded in
19
+ * configuration rather than a closure a host happened to build.
20
+ *
21
+ * ## Why the data-bearing loaders are registered rather than imported here
22
+ *
23
+ * The SDK barrel has **no dependencies**, deliberately — nothing it reaches
24
+ * imports anything outside `src/`. (The one exception is its own entry point:
25
+ * `/template-check` parses with `handlebars` and `liquidjs`, typed templates
26
+ * Q5, and nothing on the barrel imports it.) Real tokenizers are the opposite of that: the four
27
+ * packages a host needs for the twelve ids below are ~69 MB on disk, and an
28
+ * author who installed `@serene-pub/sdk` to write one node type has no business
29
+ * downloading a BPE merge table. There is also a hard mechanical reason: this
30
+ * package is consumed by a host through a `file:` link, so a bare specifier
31
+ * written *here* resolves against **this** package's tree, not the host's, and
32
+ * would simply not be found.
33
+ *
34
+ * So the split runs along the line of what needs data:
35
+ *
36
+ * - The four **ratio** counters need no data and live here, defined below.
37
+ * They are the fallbacks a host gets for free.
38
+ * - The eight **data-bearing** ones are registered by the host with
39
+ * `defineTokenizer`, the same seam `defineWireFormat` already is: the SDK
40
+ * owns the id, the resolution, the caching and the degradation; the host
41
+ * owns the one `import()` that has to happen where the package actually is.
42
+ *
43
+ * A host that registers nothing still resolves every id it asks for — to the
44
+ * rough estimate, with a sentence saying so. Budgeting degrades; it never
45
+ * fails.
46
+ */
47
+ /**
48
+ * Counting, after loading. Takes `unknown` because a wire payload is not always
49
+ * a string and a counter must not be the thing that decides it should have been.
50
+ * @experimental
51
+ */
52
+ export type TokenCount = (value: unknown) => number;
53
+ /**
54
+ * One tokenizer a host can offer.
55
+ *
56
+ * `load` may be async and is awaited at most once per id per process — the
57
+ * result is what gets called sixty times while a context is allocated, so it
58
+ * must be resident by then rather than resolved per block.
59
+ * @experimental
60
+ */
61
+ export interface TokenizerDefinition {
62
+ /** The id core stores and passes — `connections.token_counter`'s vocabulary. */
63
+ id: string;
64
+ /** Resolve whatever data this needs and return the synchronous counter. */
65
+ load(): Promise<TokenCount> | TokenCount;
66
+ }
67
+ /** A tokenizer that is resident and ready to count. @experimental */
68
+ export interface LoadedTokenizer {
69
+ /** What was asked for. Kept even when it could not be honoured. */
70
+ requested: string;
71
+ /** What is actually counting — `ROUGH_TOKENIZER_ID` when the request degraded. */
72
+ id: string;
73
+ /** Synchronous, always. The awaiting already happened. */
74
+ count: TokenCount;
75
+ /**
76
+ * Set only when `requested` could not be honoured, and phrased for a
77
+ * receipt: a run whose budgeting quietly fell back to an estimate must say
78
+ * so, because the numbers are the whole point of the receipt.
79
+ */
80
+ degraded?: string;
81
+ }
82
+ /** What `count` is when nothing better could be resolved. @internal */
83
+ export declare const ROUGH_TOKENIZER_ID = "rough";
84
+ /** Every id this SDK will answer to, whether or not a loader is registered. @internal */
85
+ export declare const TOKENIZER_IDS: readonly string[];
86
+ /**
87
+ * Offer a tokenizer, or replace one.
88
+ *
89
+ * **Replaces rather than throwing on a duplicate**, unlike `defineWireFormat`.
90
+ * A wire format is authored once in a module that is imported once; a tokenizer
91
+ * loader is registered by a host whose dev server re-evaluates modules on every
92
+ * edit, and a registry that throws there poisons the process for the rest of the
93
+ * session. The trade is that a plugin can shadow a host's loader for an id —
94
+ * which is a real risk and a deliberate one: the alternative was worse, and a
95
+ * shadowing loader still cannot change what the id *means*, only how it loads.
96
+ * @experimental
97
+ */
98
+ export declare function defineTokenizer(t: TokenizerDefinition): TokenizerDefinition;
99
+ /** Every id that currently has a loader — the registered ones plus the built-ins. @internal */
100
+ export declare const registeredTokenizers: () => string[];
101
+ /**
102
+ * Resolve an id to something that can count, and never fail.
103
+ *
104
+ * The three ways this degrades are three different sentences on purpose. An
105
+ * absent id is not a problem at all (a host that never configured one gets the
106
+ * estimate silently); an unregistered id is a wiring gap worth naming; a loader
107
+ * that threw is an environment problem worth naming *with its own message*,
108
+ * because "gpt-tokenizer is not installed" and "this Android build cannot parse
109
+ * that regex" want different fixes.
110
+ * @internal
111
+ */
112
+ export declare function loadTokenizer(id: string | null | undefined): Promise<LoadedTokenizer>;
113
+ //# sourceMappingURL=tokenizers.d.ts.map
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Which tokenizer a run budgets with — the ids, the resolution, and the one
3
+ * thing that makes the whole arrangement work: **loading is asynchronous,
4
+ * counting is not.**
5
+ *
6
+ * ## The problem this file exists to dissolve
7
+ *
8
+ * `RunOptions.countTokens` is `(v: unknown) => number`, strictly synchronous,
9
+ * because the allocation and wire-measurement loops decide what fits while
10
+ * walking candidates — a loop that awaited per candidate would be a different
11
+ * loop, and a much slower one, at exactly the moment somebody's context is
12
+ * biggest. A host's real tokenizers, meanwhile, are async: not because
13
+ * *counting* is async but because **loading** a 55 MB merge table is.
14
+ *
15
+ * So the two are separated. `loadTokenizer` is awaited **once**, before the run
16
+ * starts, and hands back a plain synchronous function. Nothing downstream of
17
+ * that point knows a tokenizer was ever loaded. The executor passes an *id*
18
+ * rather than a function, so which tokenizer a run used is a fact recorded in
19
+ * configuration rather than a closure a host happened to build.
20
+ *
21
+ * ## Why the data-bearing loaders are registered rather than imported here
22
+ *
23
+ * The SDK barrel has **no dependencies**, deliberately — nothing it reaches
24
+ * imports anything outside `src/`. (The one exception is its own entry point:
25
+ * `/template-check` parses with `handlebars` and `liquidjs`, typed templates
26
+ * Q5, and nothing on the barrel imports it.) Real tokenizers are the opposite of that: the four
27
+ * packages a host needs for the twelve ids below are ~69 MB on disk, and an
28
+ * author who installed `@serene-pub/sdk` to write one node type has no business
29
+ * downloading a BPE merge table. There is also a hard mechanical reason: this
30
+ * package is consumed by a host through a `file:` link, so a bare specifier
31
+ * written *here* resolves against **this** package's tree, not the host's, and
32
+ * would simply not be found.
33
+ *
34
+ * So the split runs along the line of what needs data:
35
+ *
36
+ * - The four **ratio** counters need no data and live here, defined below.
37
+ * They are the fallbacks a host gets for free.
38
+ * - The eight **data-bearing** ones are registered by the host with
39
+ * `defineTokenizer`, the same seam `defineWireFormat` already is: the SDK
40
+ * owns the id, the resolution, the caching and the degradation; the host
41
+ * owns the one `import()` that has to happen where the package actually is.
42
+ *
43
+ * A host that registers nothing still resolves every id it asks for — to the
44
+ * rough estimate, with a sentence saying so. Budgeting degrades; it never
45
+ * fails.
46
+ */
47
+ import { countableText, roughTokens } from './preview.js';
48
+ /** What `count` is when nothing better could be resolved. @internal */
49
+ export const ROUGH_TOKENIZER_ID = 'rough';
50
+ /**
51
+ * A counter that is nothing but a characters-per-token ratio.
52
+ *
53
+ * Four of the twelve ids are this and only this — a model family whose real
54
+ * tokenizer either is not distributable or is not worth 13 MB to approximate
55
+ * within a few percent. Written once here rather than four times, because a
56
+ * ratio copied is a ratio that drifts.
57
+ */
58
+ const ratio = (charsPerToken) => (value) => Math.ceil(countableText(value).length / charsPerToken);
59
+ /**
60
+ * The ids this SDK knows, and which of them it can satisfy unaided.
61
+ *
62
+ * ⚠ These four ratios are shared with a host's own estimator surface (Serene
63
+ * Pub's `TokenCounterManager`), and the two must agree: a person who picks
64
+ * "Estimate" in a connection form and a pipeline that budgets for that same
65
+ * connection are naming one thing. Nothing here can enforce that from inside
66
+ * the SDK — the host's suite is where that equality is asserted.
67
+ */
68
+ const definitions = new Map([
69
+ ['estimate', { id: 'estimate', load: () => ratio(3.4) }],
70
+ ['anthropic-claude', { id: 'anthropic-claude', load: () => ratio(3.6) }],
71
+ ['gemini', { id: 'gemini', load: () => ratio(4) }],
72
+ ['gemma', { id: 'gemma', load: () => ratio(3.5) }],
73
+ ]);
74
+ /**
75
+ * Ids the SDK names but cannot satisfy on its own.
76
+ *
77
+ * Declared rather than left implicit so that "nobody registered a loader for
78
+ * GPT-4o" and "GPT-4o is not a tokenizer this build has ever heard of" are two
79
+ * different sentences. They are two different problems — a host wiring bug and
80
+ * a typo in a column — and a single "unknown tokenizer" for both is how the
81
+ * first one goes uninvestigated for a release.
82
+ */
83
+ const HOST_PROVIDED = [
84
+ 'openai-gpt2',
85
+ 'openai-gpt3.5',
86
+ 'openai-gpt4',
87
+ 'openai-gpt4o',
88
+ 'llama',
89
+ 'llama3',
90
+ 'mistral',
91
+ 'cohere',
92
+ ];
93
+ /** Every id this SDK will answer to, whether or not a loader is registered. @internal */
94
+ export const TOKENIZER_IDS = [...definitions.keys(), ...HOST_PROVIDED];
95
+ /**
96
+ * In-flight and settled loads, keyed by id.
97
+ *
98
+ * The PROMISE is cached rather than its value, so sixty blocks arriving before
99
+ * the first load settles share one load instead of racing to build the same
100
+ * merge table sixty times. A rejected load is evicted (see `loadTokenizer`) —
101
+ * caching a failure forever would mean one transient import error degrades
102
+ * every run until the process restarts.
103
+ */
104
+ const loading = new Map();
105
+ /**
106
+ * Offer a tokenizer, or replace one.
107
+ *
108
+ * **Replaces rather than throwing on a duplicate**, unlike `defineWireFormat`.
109
+ * A wire format is authored once in a module that is imported once; a tokenizer
110
+ * loader is registered by a host whose dev server re-evaluates modules on every
111
+ * edit, and a registry that throws there poisons the process for the rest of the
112
+ * session. The trade is that a plugin can shadow a host's loader for an id —
113
+ * which is a real risk and a deliberate one: the alternative was worse, and a
114
+ * shadowing loader still cannot change what the id *means*, only how it loads.
115
+ * @experimental
116
+ */
117
+ export function defineTokenizer(t) {
118
+ definitions.set(t.id, t);
119
+ // A redefinition supersedes whatever the previous one had already loaded.
120
+ loading.delete(t.id);
121
+ return t;
122
+ }
123
+ /** Every id that currently has a loader — the registered ones plus the built-ins. @internal */
124
+ export const registeredTokenizers = () => [...definitions.keys()];
125
+ /**
126
+ * Resolve an id to something that can count, and never fail.
127
+ *
128
+ * The three ways this degrades are three different sentences on purpose. An
129
+ * absent id is not a problem at all (a host that never configured one gets the
130
+ * estimate silently); an unregistered id is a wiring gap worth naming; a loader
131
+ * that threw is an environment problem worth naming *with its own message*,
132
+ * because "gpt-tokenizer is not installed" and "this Android build cannot parse
133
+ * that regex" want different fixes.
134
+ * @internal
135
+ */
136
+ export async function loadTokenizer(id) {
137
+ const requested = typeof id === 'string' ? id.trim() : '';
138
+ // No id is not a degradation. It is a host that has not been asked to pick
139
+ // one, and the rough estimate is exactly what it has always used.
140
+ if (!requested)
141
+ return { requested, id: ROUGH_TOKENIZER_ID, count: roughTokens };
142
+ const def = definitions.get(requested);
143
+ if (!def) {
144
+ const known = TOKENIZER_IDS.includes(requested);
145
+ return {
146
+ requested,
147
+ id: ROUGH_TOKENIZER_ID,
148
+ count: roughTokens,
149
+ degraded: known
150
+ ? `no loader is registered for tokenizer '${requested}', so this run budgeted ` +
151
+ `with the rough estimate. The host registers data-bearing tokenizers with ` +
152
+ `defineTokenizer() — see @serene-pub/sdk/tokenizers.`
153
+ : `'${requested}' is not a tokenizer this build recognises, so this run budgeted ` +
154
+ `with the rough estimate. Known ids: ${TOKENIZER_IDS.join(', ')}.`,
155
+ };
156
+ }
157
+ try {
158
+ let pending = loading.get(requested);
159
+ if (!pending) {
160
+ // Wrapped in Promise.resolve so a synchronous `load` — every built-in
161
+ // ratio is one — takes the same path as an async import rather than a
162
+ // second one that could diverge.
163
+ pending = Promise.resolve().then(() => def.load());
164
+ loading.set(requested, pending);
165
+ }
166
+ const count = await pending;
167
+ if (typeof count !== 'function')
168
+ throw new Error(`its load() resolved to ${typeof count} rather than a counting function`);
169
+ return { requested, id: requested, count };
170
+ }
171
+ catch (e) {
172
+ // Evicted so the next run retries. A tokenizer that failed to load
173
+ // because a file was momentarily unreadable should not doom the process.
174
+ loading.delete(requested);
175
+ return {
176
+ requested,
177
+ id: ROUGH_TOKENIZER_ID,
178
+ count: roughTokens,
179
+ degraded: `tokenizer '${requested}' could not be loaded, so this run budgeted with the ` +
180
+ `rough estimate: ${e.message}`,
181
+ };
182
+ }
183
+ }
184
+ //# sourceMappingURL=tokenizers.js.map