@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,1829 @@
1
+ /**
2
+ * A minimal executor — enough to run a compiled document and produce a receipt.
3
+ *
4
+ * Not the real thing, but it enforces the laws the design says the executor owns:
5
+ * discriminated results including halt, per-run seed, timeouts that bound execution
6
+ * but never waiting, consumption budgets, per-kind injection, and core-emitted events.
7
+ */
8
+ import { JUNCTION_CLAUSE_PORTS, envoyConfigKeysOf } from './document.js';
9
+ import { AMBIENT_SCRIPT_EXTRAS, getDefinition, opensLiveRow, scriptPointsOf } from './descriptors.js';
10
+ import { packageEventById } from './events.js';
11
+ import { collectDataRefs, isSlotRef } from './refs.js';
12
+ import { resolveConfigSources, slotConnectionId, slotConnectionModelId, SLOT_VALUE, } from './config.js';
13
+ import { resolveSamplingValues } from './sampling.js';
14
+ import { hashPayload, isGated, resolvePosition, } from './review.js';
15
+ import { isSecret } from './settings.js';
16
+ // The verdicts the run hears (01 §13): F39 at `resolveInput`, R-2 at the
17
+ // node, R-20 at a status. `verdicts.ts` reads only leaf vocabulary.
18
+ import { i18nVerdict, provisionalVerdict, refusalText, settingsTravelVerdict } from './verdicts.js';
19
+ import { i18nText } from './i18n.js';
20
+ import { previewTarget, roughTokens } from './preview.js';
21
+ import { resolveClauseMode } from './clauses.js';
22
+ import { ITEM as ITEM_KEY } from './scope.js';
23
+ import { predicateHolds, readPath, truthy } from './predicates.js';
24
+ import { isAllocatedContext, measureWire } from './wire.js';
25
+ // ── The reference behind a resolved slot ────────────────────────────────────
26
+ /**
27
+ * The row a resolved ref slot's VALUES were read from.
28
+ *
29
+ * ## Why this exists
30
+ *
31
+ * `connection` and `sampling` are both ref slots, and `resolveSlot` returns two
32
+ * different KINDS of thing for them: a connection resolves to a *reference*
33
+ * (`{ id, kind, metadata }` — material is injected at call time), while sampling
34
+ * resolves to the config's *values*, deliberately without an id, because the
35
+ * nodes that read a sampling slot need the numbers. `core:task/context-budget@1`
36
+ * derives the token budget from `contextTokens`, and the summarize batch cutter
37
+ * fits a transcript into that same window.
38
+ *
39
+ * A host, however, does not send values — it sends a request built from a
40
+ * `sampling_configs` ROW, so what it needs from this slot is the row id. It read
41
+ * one off the connection slot's `{ id }` and found nothing on sampling's, which
42
+ * a host cannot distinguish from "this node picked nothing" — so a per-node pick
43
+ * moved the budget while the request went out on the capability default. The
44
+ * budget was computed against one window and the prompt sent against another.
45
+ *
46
+ * ## Why a symbol, and why `Symbol.for`
47
+ *
48
+ * The values object is read by nodes, hashed into a plugin node's RNG label,
49
+ * and written into the receipt. An ordinary key would show up in all three:
50
+ * `Object.keys`, `JSON.stringify` and `for…in` skip symbol keys, so this is
51
+ * invisible to every value reader while object spread — which copies own
52
+ * enumerable symbol properties — still carries it to the host.
53
+ *
54
+ * `Symbol.for` rather than `Symbol()` because the registry is process-wide: two
55
+ * copies of this module (a `dist` build and a source import, say) still agree on
56
+ * the key. A `Symbol()` would differ between them and the reference would vanish
57
+ * again, silently — which is the exact failure mode this whole mechanism exists
58
+ * to end.
59
+ *
60
+ * ⚠ **It does not survive serialization**, by construction. That is safe only
61
+ * because the one consumer — the host's `call` — runs in-process with the
62
+ * binding that forwards it. Plugin node bindings receive their input across a
63
+ * sandbox transport and get no `ctx.call`, so none of them can be on the reading
64
+ * end today. If a plugin node ever gains the ability to dispatch, this reference
65
+ * has to be re-projected at that transport rather than assumed to cross it.
66
+ * @experimental
67
+ */
68
+ export const SLOT_REF = Symbol.for('@serene-pub/sdk:slot-ref');
69
+ /**
70
+ * The row id carried alongside a resolved slot's values, if there is one.
71
+ *
72
+ * Absent means "this node named nothing" — never "the id was lost". Read through
73
+ * this rather than by indexing the symbol, so a host never has to know how the
74
+ * reference is attached.
75
+ * @internal
76
+ */
77
+ export function slotRef(value) {
78
+ if (!value || typeof value !== 'object')
79
+ return null;
80
+ const id = value[SLOT_REF];
81
+ return typeof id === 'string' || typeof id === 'number' ? id : null;
82
+ }
83
+ /** @public */
84
+ export const ok = (value) => ({ kind: 'ok', value });
85
+ /** @experimental */
86
+ export const err = (reason) => ({ kind: 'err', reason });
87
+ /** @public */
88
+ export const halt = (reason) => ({
89
+ kind: 'halt',
90
+ reason,
91
+ });
92
+ /** @experimental */
93
+ export const cancelled = (reason) => ({
94
+ kind: 'cancelled',
95
+ reason,
96
+ });
97
+ /**
98
+ * Values are scoped, not global.
99
+ *
100
+ * A single shared map cannot hold two iterations of a map at once, which is why the
101
+ * earlier draft forced every map sequential. A scope chain fixes that and is also what
102
+ * makes nested clauses correct: an iteration writes into its own scope and reads through
103
+ * to its parent, so two iterations never see each other's intermediate values.
104
+ */
105
+ class ValueScope {
106
+ parent;
107
+ own = new Map();
108
+ constructor(parent) {
109
+ this.parent = parent;
110
+ }
111
+ get(k) {
112
+ return this.own.has(k) ? this.own.get(k) : this.parent?.get(k);
113
+ }
114
+ has(k) {
115
+ return this.own.has(k) || !!this.parent?.has(k);
116
+ }
117
+ set(k, v) {
118
+ this.own.set(k, v);
119
+ }
120
+ child() {
121
+ return new ValueScope(this);
122
+ }
123
+ }
124
+ /** @experimental */
125
+ export const isCommitted = (w) => w.status === 'committed';
126
+ import { isStatusText, sameStatus } from './status.js';
127
+ /**
128
+ * An oracle handler, with `ctx.can()` narrowed to what its own definition declared.
129
+ *
130
+ * The one hop that matters. `pin` already carries the descriptor's literal type
131
+ * through, so reading `optional` off it here is enough — there is no need to
132
+ * thread capability generics through a catalog and a binding map, and every hop
133
+ * that does not exist is a hop that cannot silently widen to `string` and take
134
+ * the safety with it.
135
+ *
136
+ * ```ts
137
+ * providerBinding(C.generateText, async (input, ctx) => {
138
+ * ctx.can('json_schema') // ✅ declared optional on the connection slot
139
+ * ctx.can('grammar') // ❌ compile error — this node never declared it
140
+ * })
141
+ * ```
142
+ * @experimental
143
+ */
144
+ export function providerBinding(
145
+ // The PINNED form only. A `{descriptor: D} | D` union here looks more
146
+ // permissive and is strictly worse: inference across a union falls back to
147
+ // the constraint, `D['slots']` widens, and `can()` silently becomes `never`.
148
+ _type) {
149
+ // CURRIED on purpose. Passing the type and the callback to one call means the
150
+ // callback's `ctx` is contextually typed while `D` is still being inferred,
151
+ // so it resolves against the constraint rather than the argument and `can()`
152
+ // collapses to `never` — compiling fine, narrowing nothing. Splitting the
153
+ // calls forces `D` to settle first.
154
+ return (fn) => fn;
155
+ }
156
+ // ── Deterministic RNG from the run seed (F11) ───────────────────────────────
157
+ /** @internal */
158
+ export function seededRandom(seed) {
159
+ let h = 2166136261;
160
+ for (let i = 0; i < seed.length; i++)
161
+ h = Math.imul(h ^ seed.charCodeAt(i), 16777619);
162
+ return () => {
163
+ h = Math.imul(h ^ (h >>> 15), 2246822507);
164
+ h = Math.imul(h ^ (h >>> 13), 3266489909);
165
+ return ((h ^= h >>> 16) >>> 0) / 4294967296;
166
+ };
167
+ }
168
+ /** A site's extras: the slot's own, then the ambient set, each once. */
169
+ const withAmbientExtras = (own = []) => [
170
+ ...new Set([...own, ...AMBIENT_SCRIPT_EXTRAS]),
171
+ ];
172
+ const EMPTY_WORLD = {
173
+ overrides: [],
174
+ samplingConfigs: [],
175
+ connections: [],
176
+ activeConnection: {},
177
+ };
178
+ class BudgetExceeded extends Error {
179
+ }
180
+ /**
181
+ * The counter this run will use, resolved and loaded once.
182
+ *
183
+ * Two things are deliberate here.
184
+ *
185
+ * **The registry is reached through a dynamic import.** The barrel exports
186
+ * `run`, and the barrel is imported by browser code in at least one host, so a
187
+ * static import would drag the tokenizer registry — and everything a host's
188
+ * registered loaders reach through it — into every bundle that can see this
189
+ * function. Dynamic keeps `@serene-pub/sdk/tokenizers` a real split point.
190
+ *
191
+ * **Nothing here can throw.** Not the import, not the load, not an id nobody
192
+ * has heard of. A run whose budgeting fell back to an estimate is a run with a
193
+ * worse estimate; a run that failed because a merge table would not parse is a
194
+ * user with no reply. The note that comes back is how the difference stays
195
+ * visible.
196
+ */
197
+ async function resolveTokenizer(opts) {
198
+ if (opts.countTokens)
199
+ return { count: opts.countTokens };
200
+ if (!opts.tokenizer)
201
+ return { count: roughTokens };
202
+ try {
203
+ const { loadTokenizer } = await import('./tokenizers.js');
204
+ return await loadTokenizer(opts.tokenizer);
205
+ }
206
+ catch (e) {
207
+ return {
208
+ count: roughTokens,
209
+ degraded: `the tokenizer registry could not be loaded, so this run budgeted with the ` +
210
+ `rough estimate: ${e.message}`,
211
+ };
212
+ }
213
+ }
214
+ /** @experimental */
215
+ export async function run(doc, opts) {
216
+ const world = opts.world ?? EMPTY_WORLD;
217
+ const seed = opts.seed ?? 'seed:0';
218
+ const rng = seededRandom(seed);
219
+ const now = opts.now ?? (() => Date.now());
220
+ // Clauses are addressed alongside nodes so a clause can carry a setting of
221
+ // its own — its execution mode. Keys cannot collide: a clause id qualifies
222
+ // the nodes inside it (`drafting` contains `drafting.item.draft`), so the
223
+ // clause's own id is never also a node's.
224
+ const sources = resolveConfigSources(world, [
225
+ ...doc.nodes.map((n) => n.key),
226
+ ...doc.clauses.map((b) => b.id),
227
+ // An envoy's config (R-18 (2)) is addressed like a node's, at the
228
+ // synthetic key a `slot.prompts({ envoy })` compiled to; the host
229
+ // projects the genre's declaration there and the panel's deviations
230
+ // sit above it.
231
+ ...envoyConfigKeysOf(doc),
232
+ ]);
233
+ // Values and the layer each won at, from ONE walk: the executor reads the
234
+ // values, and each node's receipt row keeps the layers (`configLayers`).
235
+ const config = {};
236
+ const layers = {};
237
+ for (const [key, slots] of Object.entries(sources)) {
238
+ const values = {};
239
+ const won = {};
240
+ for (const [slot, paths] of Object.entries(slots)) {
241
+ values[slot] = {};
242
+ won[slot] = {};
243
+ for (const [path, resolved] of Object.entries(paths)) {
244
+ values[slot][path] = resolved.value;
245
+ won[slot][path] = resolved.scopeKind;
246
+ }
247
+ }
248
+ config[key] = values;
249
+ if (Object.keys(won).length)
250
+ layers[key] = won;
251
+ }
252
+ // The one await a tokenizer costs, taken BEFORE `startedAt` is stamped: a
253
+ // cold merge table is setup, not work, and charging the first run of a
254
+ // process for it would make elapsed times mean two different things
255
+ // depending on how recently the server restarted — the same reason
256
+ // `queuedMs` is recorded and excluded.
257
+ const tokenizer = await resolveTokenizer(opts);
258
+ const countTokens = tokenizer.count;
259
+ const receipt = {
260
+ runId: opts.runId ?? 'run:test',
261
+ specId: doc.id,
262
+ specVersion: doc.version,
263
+ schemaVersion: 1,
264
+ seed,
265
+ triggerSource: opts.triggerSource ?? 'input',
266
+ triggerRef: opts.triggerRef,
267
+ actorUserId: opts.actorUserId,
268
+ // Pinned at construction — before any node — and never touched again.
269
+ ...(opts.portrayals ? { portrayals: opts.portrayals } : {}),
270
+ ...(opts.meta && Object.keys(opts.meta).length ? { meta: { ...opts.meta } } : {}),
271
+ // Lineage likewise: a dispatched child names its parent and root
272
+ // here, before node 1; a root run has neither and stands at 0.
273
+ ...(opts.lineage
274
+ ? { parentRunId: opts.lineage.parentRunId, rootRunId: opts.lineage.rootRunId }
275
+ : {}),
276
+ depth: opts.lineage?.depth ?? 0,
277
+ queuedMs: opts.queuedMs,
278
+ startedAt: now(),
279
+ endedAt: 0,
280
+ outcome: 'ok',
281
+ nodes: [],
282
+ emitted: [],
283
+ consumption: { tokens: 0, nodeExecutions: 0 },
284
+ };
285
+ // Said out loud rather than left to be inferred from numbers that look
286
+ // plausible. A run that silently budgeted with an estimate when somebody had
287
+ // chosen a real tokenizer is the failure this whole option exists to end,
288
+ // and it would be invisible if the fallback were quiet.
289
+ if (tokenizer.degraded)
290
+ receipt.notes = [...(receipt.notes ?? []), tokenizer.degraded];
291
+ /** Set the moment any node with declared effects is invoked — gates compaction. */
292
+ let effectfulNodeRan = false;
293
+ /**
294
+ * The status the run is showing right now (R-19): the last one any node
295
+ * set. Ephemeral — it reaches the host through `onStatus` and lands on
296
+ * the receipt only as `lastStatus`, and only when the run did not end
297
+ * `ok` (R-21). Never on a node row (F34).
298
+ */
299
+ let lastStatus;
300
+ const previewAt = opts.preview
301
+ ? previewTarget(doc.nodes, typeof opts.preview === 'object' ? opts.preview.atNode : undefined)
302
+ : undefined;
303
+ // A preview performs no writes (R-21 (1)); an explicit `dry` says so for a
304
+ // run that goes to the end.
305
+ const dry = opts.dry ?? !!opts.preview;
306
+ /**
307
+ * The run's live row — see `RunFacts.liveRow`. Set by the most recent
308
+ * live-row outlet that committed, read by every oracle call after it, and
309
+ * reported once more at the end so the host can finalise it.
310
+ */
311
+ let liveRow;
312
+ /**
313
+ * Hoist what the panel needs into one place. Almost all of it is already recorded —
314
+ * Assemble's allocation record and the oracle's resolved input. The only figure
315
+ * that exists nowhere else is the count of the formed payload.
316
+ */
317
+ const buildPreview = (node, input, definitionId, targetedBy, wire, wireCtx) => {
318
+ const ctxValue = input.context ?? input.main ?? input;
319
+ const conn = input.connection;
320
+ const budgetNode = doc.nodes.find((n) => n.definitionId === 'core:task/context-budget');
321
+ const budgetValue = budgetNode ? values.get(budgetNode.key) : undefined;
322
+ // Prefer the allocated blocks, which carry the trail. Fall back to sniffing an
323
+ // allocation array only for specs core has not migrated yet.
324
+ const allocatedSource = wireCtx ??
325
+ Object.values(input).find(isAllocatedContext);
326
+ const legacyAlloc = ctxValue?.alloc ?? ctxValue?.allocation;
327
+ const allocation = allocatedSource?.allocation ?? legacyAlloc;
328
+ const blocks = allocatedSource
329
+ ? allocatedSource.blocks.map((b) => ({
330
+ id: b.id,
331
+ sourceKey: b.sourceKey,
332
+ role: b.role,
333
+ weight: b.weight,
334
+ priority: b.priority,
335
+ included: b.included,
336
+ tokens: b.tokens,
337
+ why: b.why,
338
+ reason: b.why?.[b.why.length - 1],
339
+ }))
340
+ : (Array.isArray(legacyAlloc) ? legacyAlloc : []).map((a) => ({
341
+ sourceKey: a.sourceKey,
342
+ weight: a.weight,
343
+ priority: a.priority,
344
+ included: (a.included ?? 0) > 0,
345
+ tokens: countTokens(a.rendered ?? a.text ?? ''),
346
+ reason: a.reason ??
347
+ (a.available !== undefined &&
348
+ a.included !== undefined &&
349
+ a.available > a.included
350
+ ? `${a.available - a.included} of ${a.available} dropped — budget`
351
+ : undefined),
352
+ }));
353
+ const tokens = wire?.tokens ?? countTokens(ctxValue);
354
+ const available = budgetValue?.available ??
355
+ ctxValue?.budget ??
356
+ allocatedSource?.allocation.budget;
357
+ return {
358
+ atNode: node.key,
359
+ definitionId,
360
+ targetedBy,
361
+ connection: conn
362
+ ? {
363
+ id: conn.id,
364
+ kind: conn.kind,
365
+ contextLength: conn.metadata?.contextLength,
366
+ tokenizer: conn.metadata?.tokenizer,
367
+ }
368
+ : undefined,
369
+ budget: {
370
+ maxContext: budgetValue?.maxContext ?? conn?.metadata?.contextLength,
371
+ reserved: budgetValue?.reserved,
372
+ available,
373
+ },
374
+ context: {
375
+ rendered: redact(wire ? wire.payload : ctxValue),
376
+ tokens,
377
+ },
378
+ wire: wire
379
+ ? {
380
+ format: wire.format,
381
+ blockTokens: wire.blockTokens,
382
+ overheadTokens: wire.overheadTokens,
383
+ }
384
+ : undefined,
385
+ blocks,
386
+ totals: {
387
+ blocks: blocks.length,
388
+ included: blocks.filter((b) => b.included).length,
389
+ dropped: blocks.filter((b) => !b.included).length,
390
+ tokensIncluded: blocks.filter((b) => b.included).reduce((n, b) => n + b.tokens, 0),
391
+ tokensDropped: blocks.filter((b) => !b.included).reduce((n, b) => n + b.tokens, 0),
392
+ overBudgetBy: wire?.overBudgetBy ??
393
+ (typeof available === 'number' && tokens > available
394
+ ? tokens - available
395
+ : undefined),
396
+ },
397
+ allocation,
398
+ };
399
+ };
400
+ const values = new ValueScope();
401
+ values.set(doc.nodes[0]?.key ?? 'input', opts.input);
402
+ const reviews = [];
403
+ let seq = 0;
404
+ const budget = {
405
+ tokens: opts.budget?.tokens ?? Infinity,
406
+ nodes: opts.budget?.nodeExecutions ?? Infinity,
407
+ };
408
+ const spendTokens = (n) => {
409
+ receipt.consumption.tokens += n;
410
+ if (receipt.consumption.tokens > budget.tokens)
411
+ throw new BudgetExceeded('token budget exceeded');
412
+ };
413
+ const ordered = doc.nodes.slice().sort((a, b) => a.position - b.position);
414
+ const resolveInput = (node, scope, note) => {
415
+ const cfg = { ...node.config };
416
+ for (const { path, ref } of collectDataRefs(node.config)) {
417
+ setPath(cfg, path, readPort(scope.get(ref.node), ref.port));
418
+ }
419
+ for (const [k, v] of Object.entries(cfg)) {
420
+ if (!isSlotRef(v))
421
+ continue;
422
+ const ref = v;
423
+ // F39 — settings never travel; only data does (12 §2 P3). The
424
+ // substrate's `settings` is not a slot a reference may name:
425
+ // `SlotRef.slot` cannot spell it and `slot.*` never produces it, so
426
+ // one here is hand-crafted, and before this guard the generic
427
+ // fallthrough in `resolveSlot` handed the binding ANOTHER node's
428
+ // switches. It resolves to nothing, whoever it names — a node's
429
+ // own switches are read by the executor at the node and handed to
430
+ // no binding — and the row says so, because a silent `{}` is "it
431
+ // does nothing" with no error anywhere. `validate()` refuses the
432
+ // document with the same sentence: `core:verdict/settings-travel`
433
+ // owns it, and this is the run's door (01 §13). A reference naming
434
+ // no slot is not it — `validate()` refuses that shape; an
435
+ // unvalidated one falls through to `resolveSlot` as before.
436
+ const heard = settingsTravelVerdict.judge({
437
+ kind: 'reference',
438
+ node: node.key,
439
+ key: k,
440
+ slot: ref.slot,
441
+ target: node.resolvedRefs?.[k] ?? ref.ofNode ?? node.key,
442
+ });
443
+ if (!heard.ok) {
444
+ note?.(`${settingsTravelVerdict.law}: ${i18nText(heard.sentence)}; resolved to nothing — ` +
445
+ `${i18nText(heard.fix)}`);
446
+ cfg[k] = {};
447
+ continue;
448
+ }
449
+ cfg[k] = resolveSlot(node, ref);
450
+ }
451
+ return cfg;
452
+ };
453
+ /**
454
+ * Row-id equality across the string/number divide.
455
+ *
456
+ * The panel stores a pick as a number; `buildWorld` projects ids as strings.
457
+ * Neither is wrong on its own, and `===` between them is quietly always false.
458
+ */
459
+ const sameId = (a, b) => a != null && b != null && String(a) === String(b);
460
+ const resolveSlot = (node, ref) => {
461
+ const targetKey = node.resolvedRefs?.[Object.keys(node.config).find((k) => node.config[k] === ref) ?? ''] ??
462
+ ref.ofNode ??
463
+ node.key;
464
+ const slotName = ref.slot;
465
+ if (slotName === 'connection') {
466
+ const d = getDefinition(`${node.definitionId}@${node.definitionVersion}`);
467
+ const targetNode = doc.nodes.find((n) => n.key === targetKey) ?? node;
468
+ const td = getDefinition(`${targetNode.definitionId}@${targetNode.definitionVersion}`);
469
+ const kind = td?.shape ?? d?.shape;
470
+ const stored = config[targetKey]?.['connection']?.[SLOT_VALUE];
471
+ /**
472
+ * The pick, then the instance default — but the default answers only
473
+ * for a slot that names **nothing**.
474
+ *
475
+ * The distinction is the whole defect. A pick is a PAIR
476
+ * (`ConnectionSlotValue`), and this branch used to compare the stored
477
+ * value itself against a connection id: an object stringified to
478
+ * `[object Object]`, matched nothing, and `??` then handed the whole
479
+ * thing to `activeConnection` — so a slot that named a connection
480
+ * perfectly clearly ran against a different one. Reading the endpoint
481
+ * half first is only half the fix; the other half is that a slot which
482
+ * names something we cannot resolve must resolve to NOTHING. Falling
483
+ * back there is how "you picked the wrong server" becomes "your reply
484
+ * came from somewhere else", with no error either way.
485
+ *
486
+ * So: `stored == null` is the only door to the default. A value that
487
+ * names an unreadable endpoint, or one this world does not have,
488
+ * leaves as null — unconfigured, which a host can say out loud.
489
+ */
490
+ const pubDefault = kind ? world.activeConnection[kind] : undefined;
491
+ const chosenId = stored == null ? pubDefault : slotConnectionId(stored);
492
+ // Compared as strings, because the two sides genuinely differ in type:
493
+ // the panel commits a pick as a JSON number, and the world projects
494
+ // connection ids as strings. `===` between them is always false, and
495
+ // the miss used to fall through to `activeConnection` — which on most
496
+ // installs holds the very connection that was picked, so the bug
497
+ // looked fixed.
498
+ const conn = chosenId == null ? undefined : world.connections.find((c) => sameId(c.id, chosenId));
499
+ const modelId = slotConnectionModelId(stored);
500
+ const model = modelId == null
501
+ ? undefined
502
+ : world.models?.find((m) => sameId(m.id, modelId) && sameId(m.connectionId, conn?.id));
503
+ // metadata only — material is injected by the executor at call time (01 §10)
504
+ return conn
505
+ ? {
506
+ id: conn.id,
507
+ kind: conn.kind,
508
+ metadata: conn.metadata,
509
+ // The model half of the same pick, carried rather than
510
+ // dropped — a host reducing this back to an endpoint id is
511
+ // how a model chosen in a panel reached no request. Null
512
+ // when the slot named no model, the fallback included:
513
+ // `activeConnection` holds endpoint ids alone.
514
+ modelId,
515
+ contextWindow: model?.contextWindow ?? null,
516
+ }
517
+ : null;
518
+ }
519
+ if (slotName === 'sampling') {
520
+ /**
521
+ * The pick, then the instance default — the same two-step the
522
+ * `connection` branch above already takes, and `kind` is derived the
523
+ * same way so the two cannot disagree about which node's modality is
524
+ * being asked about.
525
+ *
526
+ * ⚠ The fallback was missing, and its absence was invisible because
527
+ * dispatch has one: a slot with no pick resolved to `{}` here while
528
+ * the call still went out against the instance default's window. A
529
+ * node that only forwards this (every oracle — the host reduces it
530
+ * back to a row id) could not tell. A node that READS it could: the
531
+ * summarize batch cutter has to fit a prompt into that window, and
532
+ * with `{}` it clamped against nothing on every install that had not
533
+ * picked a sampling config per step.
534
+ *
535
+ * A Task with no shape and no shaped target still gets no fallback —
536
+ * `core:task/context-budget@1` names its own `sampling` slot and is
537
+ * unaffected, because there is no modality to look a default up by.
538
+ */
539
+ const targetNode = doc.nodes.find((n) => n.key === targetKey) ?? node;
540
+ const kind = getDefinition(`${targetNode.definitionId}@${targetNode.definitionVersion}`)?.shape ??
541
+ getDefinition(`${node.definitionId}@${node.definitionVersion}`)?.shape;
542
+ // Split from the fallback below, because only this half is a PICK.
543
+ // The reference handed to the host is the pipeline config speaking
544
+ // (`pipelineConfig`, tier 2); the instance default is a tier the host
545
+ // reads for itself, from the same `connection_defaults` rows this
546
+ // projection comes from. Carrying the fallback down as though the
547
+ // pipeline had named it would relabel the tier a resolution reports
548
+ // while changing no value — a lie with no upside.
549
+ const picked = config[targetKey]?.['sampling']?.[SLOT_VALUE];
550
+ const refId = picked ?? (kind ? (world.activeSampling?.[kind] ?? undefined) : undefined);
551
+ const base = world.samplingConfigs.find((s) => sameId(s.id, refId));
552
+ const overrides = { ...(config[node.key]?.['sampling'] ?? {}) };
553
+ delete overrides[SLOT_VALUE];
554
+ // The config's switchboard applies here exactly as it does on the
555
+ // direct path: a sampler switched off must not reach the provider
556
+ // merely because a pipeline is what asked for it. A world carrying no
557
+ // `enabled` predates the distinction and is read as all-on.
558
+ const stored = !base
559
+ ? {}
560
+ : base.enabled
561
+ ? resolveSamplingValues({
562
+ shape: base.shape,
563
+ values: base.values,
564
+ enabled: base.enabled,
565
+ })
566
+ : base.values;
567
+ // Node overrides sit ABOVE the switchboard: a spec naming a value for
568
+ // this node is stating it outright, not toggling a stored one.
569
+ const values = { ...stored, ...overrides };
570
+ // The row these values came from, for the host that has to send a
571
+ // request built from a ROW rather than from numbers — see `SLOT_REF`.
572
+ //
573
+ // `base.id` and not `picked`: the id and the values then describe the
574
+ // same row BY CONSTRUCTION, which is the whole point. A pick naming a
575
+ // row this world does not carry resolves to no values, and attaching
576
+ // its id anyway would hand the host a window the budget above never
577
+ // saw — the same divergence, pointed the other way.
578
+ if (picked != null && base)
579
+ values[SLOT_REF] = base.id;
580
+ return values;
581
+ }
582
+ if (slotName === 'params') {
583
+ // A declared default is a promise the type makes; without this it was
584
+ // decoration. Nothing applied `default:` from a parameters schema, so
585
+ // a spec that did not override `budget` got `undefined` — which reads
586
+ // downstream as a budget of zero, excludes every block, and renders a
587
+ // context with its lore silently missing.
588
+ const paramsSchemaOf = (n) => (getDefinition(`${n.definitionId}@${n.definitionVersion}`)?.slots?.[slotName]?.schema ?? {});
589
+ const resolveAt = (n, schema, keep) => {
590
+ const out = {};
591
+ for (const [k, v] of Object.entries(schema))
592
+ if (keep(k) && v?.default !== undefined)
593
+ out[k] = v.default;
594
+ for (const [k, v] of Object.entries(config[n.key]?.[slotName] ?? {}))
595
+ if (keep(k))
596
+ out[k] = v;
597
+ return out;
598
+ };
599
+ const ownSchema = paramsSchemaOf(node);
600
+ if (targetKey === node.key)
601
+ return resolveAt(node, ownSchema, () => true);
602
+ /**
603
+ * A reference, and two addresses (R-7 P2, refined 2026-09-16 — see
604
+ * `FieldDecl.shared`). The referencing node's OWN declaration says
605
+ * which of its fields it holds in common with the owner: those
606
+ * resolve at the owner — the owner's declared default under the
607
+ * owner's stored value, because a shared setting is the owner's
608
+ * policy and filling a lane's gaps from the lane's own defaults
609
+ * would call the result the owner's. Every other field is the
610
+ * node's own — its share of the window, its ceiling — and resolves
611
+ * at its own address exactly as an unreferenced slot would, so one
612
+ * `slot.params({ node })` carries both halves and the spec names
613
+ * the owner once.
614
+ *
615
+ * The owner's schema is read for the shared half so a shared field
616
+ * the owner declares under a different default takes the owner's;
617
+ * a shared field the owner does not declare at all keeps the
618
+ * referencing node's default, so a reference to an owner of a
619
+ * different definition degrades to "own everywhere" rather than to
620
+ * `undefined`.
621
+ */
622
+ const targetNode = doc.nodes.find((n) => n.key === targetKey) ?? node;
623
+ const ownerSchema = paramsSchemaOf(targetNode);
624
+ const shared = new Set(Object.entries(ownSchema)
625
+ .filter(([, v]) => v?.shared === true)
626
+ .map(([k]) => k));
627
+ const own = resolveAt(node, ownSchema, (k) => !shared.has(k));
628
+ const fromOwner = resolveAt(targetNode, { ...Object.fromEntries([...shared].map((k) => [k, ownSchema[k]])), ...ownerSchema }, (k) => shared.has(k));
629
+ return { ...own, ...fromOwner };
630
+ }
631
+ // The generic slots (prompts, template) honour the reference target
632
+ // too: a shared prompts slot reads the *owner's* configured values, so
633
+ // one authored text serves every node that declared it shared (13 §12
634
+ // finding i). Without `ofNode` the target is the node itself, which is
635
+ // the behaviour every existing spec compiled against. `settings` never
636
+ // reaches here — `resolveInput` stops it first (F39).
637
+ return config[targetKey]?.[slotName] ?? {};
638
+ };
639
+ const invokeInner = async (node, scope, blockMode, iteration, iterationCount) => {
640
+ const d = getDefinition(`${node.definitionId}@${node.definitionVersion}`);
641
+ if (!d)
642
+ return err(`unknown type ${node.definitionId}@${node.definitionVersion}`);
643
+ // Declared, not bound (plans/29 R-2). `validate()` refuses the document;
644
+ // this is the same refusal for a document that reached the executor by
645
+ // another door — a stored version older than the flag — so it halts on
646
+ // the law rather than on "no binding registered" pointing at bindings.ts.
647
+ // `core:verdict/provisional` owns the sentence; this is its run door.
648
+ const placed = provisionalVerdict.judge({
649
+ kind: 'placement',
650
+ nodeKey: node.key,
651
+ definitionId: node.definitionId,
652
+ definitionVersion: node.definitionVersion,
653
+ provisional: d.provisional === true,
654
+ });
655
+ if (!placed.ok)
656
+ return err(refusalText(placed));
657
+ const hook = opts.bindings[`${node.definitionId}@${node.definitionVersion}`];
658
+ const started = now();
659
+ const nr = {
660
+ nodeKey: node.key,
661
+ seq: seq++,
662
+ kind: node.kind,
663
+ definitionId: `${node.definitionId}@${node.definitionVersion}`,
664
+ result: 'ok',
665
+ startedAt: started,
666
+ endedAt: started,
667
+ elapsedMs: 0,
668
+ blockMode,
669
+ iteration,
670
+ resolvedRefs: node.resolvedRefs,
671
+ ...(layers[node.key] ? { configLayers: layers[node.key] } : {}),
672
+ // Only a host that says what it seated can say "the pin ran".
673
+ ...(opts.swaps ? { swap: opts.swaps[node.key] ?? null } : {}),
674
+ notes: [],
675
+ };
676
+ receipt.consumption.nodeExecutions++;
677
+ if (receipt.consumption.nodeExecutions > budget.nodes)
678
+ throw new BudgetExceeded('node execution budget exceeded');
679
+ // ── Script chains (18 §4a) ────────────────────────────────────────────
680
+ // Substrate placement, like the review gate below — and deliberately
681
+ // *before* both the gate and the preview halt: a chain is configuration,
682
+ // so the payload a reviewer approves and the payload the preview shows
683
+ // are the payload the binding will actually receive. The binding never
684
+ // sees a chain and cannot decline one; declaring the hook is all a type
685
+ // does, and a host with no engine (`applyScripts` absent) runs every
686
+ // spec exactly as before. Declared above the input branch because an
687
+ // input node has a hook of its own — see there.
688
+ const scriptHooks = Object.entries(d.slots ?? {}).filter(([, sd]) => sd.kind === 'scripts');
689
+ const applyChainsAt = async (phase, bag) => {
690
+ if (!opts.applyScripts)
691
+ return bag;
692
+ let out = bag;
693
+ for (const [slotName, sdRaw] of scriptHooks) {
694
+ const sd = sdRaw;
695
+ if ((sd.phase ?? 'before') !== phase)
696
+ continue;
697
+ // An empty or absent chain still reaches the applier: the host
698
+ // may carry hook-level sources of its own — a connection's stop
699
+ // guards (18 §4b) apply whether or not the pipeline configured a
700
+ // chain, and the applier is the side that knows.
701
+ const chain = config[node.key]?.[slotName]?.[''];
702
+ const port = sd.port ?? 'main';
703
+ if (!(port in out))
704
+ continue;
705
+ const before = out[port];
706
+ try {
707
+ const outcome = await opts.applyScripts({
708
+ nodeKey: node.key,
709
+ definitionId: nr.definitionId,
710
+ slot: slotName,
711
+ phase,
712
+ port,
713
+ accepts: sd.accepts ?? [],
714
+ extras: withAmbientExtras(sd.extras),
715
+ }, chain, before);
716
+ if (outcome.applications.length)
717
+ nr.scripts = [...(nr.scripts ?? []), ...outcome.applications];
718
+ if (outcome.notes?.length)
719
+ nr.notes.push(...outcome.notes);
720
+ // Alias-preserving: a task publishing {main, messages} as one
721
+ // value keeps agreeing with itself after the rewrite — a
722
+ // downstream edge may pull either name.
723
+ out = { ...out, [port]: outcome.value };
724
+ for (const [k, v] of Object.entries(out))
725
+ if (k !== port && v === before)
726
+ out[k] = outcome.value;
727
+ }
728
+ catch (e) {
729
+ // Engine failure, absorbed like an optional node's failure
730
+ // (18 S2): the value passes through unchanged and the record
731
+ // is loud. A broken sandbox must never cost somebody their
732
+ // reply, and must never vanish either.
733
+ nr.scripts = [
734
+ ...(nr.scripts ?? []),
735
+ {
736
+ scriptId: -1,
737
+ name: '(engine)',
738
+ // The engine itself failed, before any link ran: there is
739
+ // no script kind to name, so the record says so.
740
+ scriptKind: '',
741
+ phase,
742
+ appliedBy: 'substrate',
743
+ result: 'err',
744
+ reason: e.message,
745
+ },
746
+ ];
747
+ }
748
+ }
749
+ return out;
750
+ };
751
+ if (node.kind === 'inlet') {
752
+ // An input has no invocation to wrap, but it can still declare a
753
+ // hook: phase `after`, over the value it publishes — which is what
754
+ // retrieval and the prompt see. The stored user message, written
755
+ // before the turn began, stays untouched by construction.
756
+ let published = opts.input;
757
+ if (scriptHooks.length &&
758
+ published &&
759
+ typeof published === 'object' &&
760
+ !Array.isArray(published))
761
+ published = await applyChainsAt('after', published);
762
+ scope.set(node.key, published);
763
+ nr.output = published;
764
+ nr.endedAt = now();
765
+ receipt.nodes.push(nr);
766
+ return ok(published);
767
+ }
768
+ if (!hook)
769
+ return err(`no binding registered for ${node.definitionId}@${node.definitionVersion}`);
770
+ let input = resolveInput(node, scope, (m) => nr.notes.push(m));
771
+ // ── Switched off ──────────────────────────────────────────────────────
772
+ //
773
+ // Only a node whose contract already says an empty result is fine may be
774
+ // turned off, which is exactly what `optional` declares. Reusing it
775
+ // rather than inventing a second flag means the question "is it safe to
776
+ // have nothing here" is answered once, by the author, in the place
777
+ // downstream nodes already read.
778
+ //
779
+ // Distinct from `toggleable`, which is for shape-transparent
780
+ // passthroughs — a source query is not a passthrough, and turning one
781
+ // off produces nothing rather than forwarding its input.
782
+ //
783
+ // Skipped before the binding runs, so a disabled source costs no query
784
+ // at all. That is the point: `share: 0` starves a source, this one does
785
+ // not ask for it.
786
+ //
787
+ // The address is the substrate's `settings` slot (R-9,
788
+ // `settingsSlot.ts`): declared on the registry row for every optional
789
+ // definition, read here as it always was.
790
+ if (d.optional === true && config[node.key]?.['settings']?.['enabled'] === false) {
791
+ nr.endedAt = now();
792
+ nr.elapsedMs = nr.endedAt - nr.startedAt;
793
+ nr.result = 'ok';
794
+ nr.notes.push('skipped: switched off');
795
+ receipt.nodes.push(nr);
796
+ return ok({});
797
+ }
798
+ if (scriptHooks.length)
799
+ input = await applyChainsAt('before', input);
800
+ // ── The review gate (01 §7) ───────────────────────────────────────────
801
+ // Substrate placement: after the input resolves, before the binding is invoked.
802
+ // Keys on declared effects, not on kind, so an effectful oracle gates too.
803
+ // `settings.review` is the substrate slot's second field (`settingsSlot.ts`).
804
+ if (isGated(d.effects)) {
805
+ const position = resolvePosition(d.reviewDefault, config[node.key]?.['settings']?.['review']);
806
+ // A dry run commits nothing (R-21 (1)), so there is nothing for a
807
+ // person to approve: the gate is recorded, never consulted. Without
808
+ // this a gated outlet BEFORE the preview halt — respond's
809
+ // `placeholder` — parked a card on every debounced token-count
810
+ // preview, so one turn showed several review prompts.
811
+ if (position !== 'off' && dry) {
812
+ nr.notes.push(`review '${position}': not asked — dry run`);
813
+ reviews.push({
814
+ nodeKey: node.key,
815
+ position,
816
+ action: 'approve',
817
+ originalHash: hashPayload(input),
818
+ by: 'system:dry-run',
819
+ });
820
+ }
821
+ else if (position !== 'off') {
822
+ const originalHash = hashPayload(input);
823
+ if (!opts.reviewer) {
824
+ nr.endedAt = now();
825
+ nr.result = 'err';
826
+ nr.reason = `review is '${position}' but no reviewer is available`;
827
+ receipt.nodes.push(nr);
828
+ return err(nr.reason);
829
+ }
830
+ const decision = await opts.reviewer({
831
+ nodeKey: node.key,
832
+ definitionId: nr.definitionId,
833
+ payload: input,
834
+ position,
835
+ });
836
+ const rec = {
837
+ nodeKey: node.key,
838
+ position,
839
+ action: decision.action,
840
+ originalHash,
841
+ by: decision.by,
842
+ at: decision.at,
843
+ };
844
+ if (decision.action === 'reject') {
845
+ reviews.push(rec);
846
+ nr.endedAt = now();
847
+ nr.result = 'halt';
848
+ nr.reason = 'rejected at review';
849
+ receipt.nodes.push(nr);
850
+ return halt('rejected at review');
851
+ }
852
+ if (decision.action === 'edit') {
853
+ // The binding receives the edited payload and cannot tell (F14).
854
+ input = decision.payload;
855
+ rec.editedHash = hashPayload(input);
856
+ }
857
+ reviews.push(rec);
858
+ }
859
+ else {
860
+ reviews.push({
861
+ nodeKey: node.key,
862
+ position,
863
+ action: 'approve',
864
+ originalHash: hashPayload(input),
865
+ });
866
+ }
867
+ }
868
+ // ── Wire formatting, at the pre-call substrate (16 §7) ────────────────
869
+ // Allocation happened upstream in Assemble; this is where blocks become the
870
+ // payload the connection actually wants. Once, here — never inside the
871
+ // allocation loop, and never a second time for the preview.
872
+ let wire;
873
+ // Kept because formatting replaces the port value — the panel still needs the blocks.
874
+ let wireCtx;
875
+ if (d.slots) {
876
+ const wireSlot = Object.entries(d.slots).find(([, sd]) => sd.kind === 'wire');
877
+ if (wireSlot) {
878
+ const [slotName, decl] = wireSlot;
879
+ const chosen = config[node.key]?.['wire'] ??
880
+ input[slotName] ??
881
+ decl.format;
882
+ const port = Object.entries(input).find(([, v]) => isAllocatedContext(v));
883
+ if (chosen && port) {
884
+ const portName = port[0];
885
+ const ctx = port[1];
886
+ wireCtx = ctx;
887
+ const available = input.budget?.available ?? ctx.allocation.budget;
888
+ try {
889
+ wire = measureWire(chosen, ctx, (t) => countTokens(t), available);
890
+ input = { ...input, [portName]: wire.payload };
891
+ nr.notes.push(`wire ${wire.format}: ${wire.blockTokens} block + ${wire.overheadTokens} scaffold = ${wire.tokens} tokens` +
892
+ (wire.overBudgetBy ? ` ⚠ OVER by ${wire.overBudgetBy}` : ''));
893
+ }
894
+ catch (e) {
895
+ nr.endedAt = now();
896
+ nr.result = 'err';
897
+ nr.reason = e.message;
898
+ receipt.nodes.push(nr);
899
+ return err(nr.reason);
900
+ }
901
+ // An over-budget payload is `err`, not a silent trim and not a retry:
902
+ // a retry would re-invoke Assemble, which is a back-edge the graph
903
+ // cannot show (F9, F25). It means declared overhead is wrong, and
904
+ // that should be loud (16 §7).
905
+ if (wire.overBudgetBy) {
906
+ nr.endedAt = now();
907
+ nr.result = 'err';
908
+ nr.reason =
909
+ `formatted payload is ${wire.tokens} tokens against ${available} available — ` +
910
+ `over by ${wire.overBudgetBy}. The estimate came from wire format '${wire.format}'`;
911
+ receipt.nodes.push(nr);
912
+ return err(nr.reason);
913
+ }
914
+ }
915
+ }
916
+ }
917
+ // ── The preview halt (debug mode) ─────────────────────────────────────
918
+ // Same substrate point as the review gate, and deliberately *before* it: there
919
+ // is nothing to review when nothing will be sent. The payload is formed and
920
+ // counted here, so the panel shows the real figure rather than a parallel
921
+ // estimate that drifts from what actually goes out.
922
+ if (previewAt && node.key === previewAt.key) {
923
+ receipt.preview = buildPreview(node, input, nr.definitionId, previewAt.targetedBy, wire, wireCtx);
924
+ nr.input = redact(input);
925
+ nr.endedAt = now();
926
+ nr.elapsedMs = nr.endedAt - nr.startedAt;
927
+ nr.result = 'halt';
928
+ nr.reason = `preview: stopped before ${node.key}, nothing sent`;
929
+ receipt.nodes.push(nr);
930
+ return halt(nr.reason);
931
+ }
932
+ nr.input = redact(input);
933
+ // Gates receipt compaction (13 §2): once anything effectful has been invoked,
934
+ // the run is worth recording in full whatever happens next.
935
+ if (d.effects && d.effects !== 'none')
936
+ effectfulNodeRan = true;
937
+ const timeoutMs = Math.min(d.timeoutMs ?? Infinity, opts.timeoutCeilingMs ?? Infinity);
938
+ nr.timeoutMsApplied = Number.isFinite(timeoutMs) ? timeoutMs : undefined;
939
+ const controller = new AbortController();
940
+ // F36: `wall` bounds the invocation; `idle` bounds the gap between
941
+ // pulses, and the pub's ceiling still bounds the whole.
942
+ const clock = nodeClock({
943
+ ms: timeoutMs,
944
+ kind: d.timeoutKind ?? 'wall',
945
+ ceilingMs: opts.timeoutCeilingMs ?? Infinity,
946
+ }, controller);
947
+ const base = {
948
+ signal: controller.signal,
949
+ pulse: clock.pulse,
950
+ progress: () => { }, // ephemeral, never recorded (F34)
951
+ // The status seam (R-19), on the same ephemeral footing: the host
952
+ // hears it, the receipt keeps only the last one on a run that
953
+ // did not end `ok`. A malformed text — no `i18n`, a map without
954
+ // `en`, a blank one — is a note and the status is dropped (R-20),
955
+ // never a failure: a status is advisory. The note quotes
956
+ // `core:verdict/i18n` — the run is one of R-20's doors (01 §13).
957
+ status: (text) => {
958
+ if (!isStatusText(text)) {
959
+ const heard = i18nVerdict.judge({
960
+ value: text?.i18n,
961
+ where: 'status.i18n',
962
+ required: true,
963
+ });
964
+ nr.notes.push(`status ignored: ${heard.ok ? 'a status is { i18n, vars? }' : refusalText(heard)}`);
965
+ return;
966
+ }
967
+ const changed = !sameStatus(lastStatus?.text, text);
968
+ lastStatus = { nodeKey: node.key, text };
969
+ if (!changed)
970
+ return;
971
+ try {
972
+ opts.onStatus?.(node.key, text);
973
+ }
974
+ catch {
975
+ // A status display must never take a run down.
976
+ }
977
+ },
978
+ log: (lvl, m) => nr.notes.push(`${lvl}: ${m}`),
979
+ countTokens,
980
+ };
981
+ if (d.declaresRandomness)
982
+ base.random = rng;
983
+ // Inside an `each` or a `loop`: which body this is, for a status that
984
+ // wants to count. `count` only where the clause knows its total.
985
+ if (iteration !== undefined)
986
+ base.iteration = {
987
+ index: iteration,
988
+ ...(iterationCount !== undefined ? { count: iterationCount } : {}),
989
+ };
990
+ // The interior-point broker (18 §4e): granted only when the descriptor
991
+ // declares points and the host supplied an engine — `ctx.scripts`
992
+ // simply does not exist otherwise, the `declaresRandomness` posture.
993
+ // The binding names a declared point and nothing else; the chain the
994
+ // user attached there (slot `scripts`, path = the point key) is what
995
+ // runs; applications land in the receipt marked `appliedBy: 'binding'`,
996
+ // so an interior letting user policy in stays visible from outside.
997
+ if (opts.applyScripts && d.scriptPoints?.length) {
998
+ const applyScripts = opts.applyScripts;
999
+ // The full shape, deprecated spellings folded — so `accepts` is
1000
+ // always the point's own (R-11), never a literal written here.
1001
+ const declared = scriptPointsOf(d);
1002
+ const apply = async (point, value) => {
1003
+ const known = declared.find((sp) => sp.key === point);
1004
+ if (!known)
1005
+ throw new Error(`'${point}' is not a script point '${nr.definitionId}' declares. ` +
1006
+ `Declared: ${declared.map((sp) => sp.key).join(', ')}. ` +
1007
+ `Points are part of the hashed contract — declare it on the descriptor.`);
1008
+ const outcome = await applyScripts({
1009
+ nodeKey: node.key,
1010
+ definitionId: nr.definitionId,
1011
+ slot: 'scripts',
1012
+ phase: 'before',
1013
+ port: point,
1014
+ accepts: [...known.accepts],
1015
+ // Interior points declare no extras of their own; what
1016
+ // every point is handed is the ambient set (R32).
1017
+ extras: withAmbientExtras(),
1018
+ origin: 'binding',
1019
+ }, config[node.key]?.['scripts']?.[point], value);
1020
+ if (outcome.applications.length)
1021
+ nr.scripts = [...(nr.scripts ?? []), ...outcome.applications];
1022
+ if (outcome.notes?.length)
1023
+ nr.notes.push(...outcome.notes);
1024
+ return outcome.value;
1025
+ };
1026
+ base.scripts = {
1027
+ apply,
1028
+ applyText: async (point, text) => {
1029
+ const out = await apply(point, text);
1030
+ return typeof out === 'string' ? out : text;
1031
+ },
1032
+ };
1033
+ }
1034
+ const nodeRef = {
1035
+ key: node.key,
1036
+ definitionId: node.definitionId,
1037
+ definitionVersion: node.definitionVersion,
1038
+ kind: node.kind,
1039
+ };
1040
+ const host = opts.host;
1041
+ let ctx = base;
1042
+ if (node.kind === 'query')
1043
+ ctx = {
1044
+ ...base,
1045
+ read: (table, q) => host?.read ? host.read(table, q, nodeRef) : [],
1046
+ };
1047
+ if (node.kind === 'oracle') {
1048
+ const conn = host?.connection?.(nodeRef);
1049
+ /**
1050
+ * What the bound connection can actually do.
1051
+ *
1052
+ * Narrowed to the ids this node DECLARED, not the connection's whole
1053
+ * set: a binding may only ask about what its own type said it might
1054
+ * use. Anything else would let a node quietly depend on a capability
1055
+ * it never advertised, which is the thing the declaration exists to
1056
+ * prevent — and the picker filters on those declarations, so a
1057
+ * dependency outside them was never checked at bind time either.
1058
+ */
1059
+ const d = getDefinition(`${node.definitionId}@${node.definitionVersion}`);
1060
+ const declared = new Set();
1061
+ for (const slot of Object.values(d?.slots ?? {}))
1062
+ for (const id of slot.optional ?? [])
1063
+ declared.add(id);
1064
+ const have = conn?.capabilities ?? {};
1065
+ ctx = {
1066
+ ...base,
1067
+ connectionMetadata: conn?.metadata ?? input.connection?.metadata ?? {},
1068
+ sampling: conn?.sampling ?? input.sampling ?? {},
1069
+ can: (id) => {
1070
+ if (!declared.has(id))
1071
+ return false;
1072
+ // `typeof` as well as `> 0`: this set comes off a JSON column
1073
+ // nothing type-checked, and a truthiness test alone would hand a
1074
+ // binding a string it would then compare numerically.
1075
+ const grade = have[id];
1076
+ return typeof grade === 'number' && grade > 0 ? grade : false;
1077
+ },
1078
+ call: async (p) => {
1079
+ // Recorded before dispatch, so an oracle that throws still leaves the
1080
+ // request in the receipt — the failing call is the one worth reading.
1081
+ nr.request = p;
1082
+ return host?.call
1083
+ ? await host.call(p, nodeRef, { liveRow, dry }, { signal: controller.signal, pulse: clock.pulse })
1084
+ : p;
1085
+ },
1086
+ reportUsage: (t) => {
1087
+ nr.tokens = (nr.tokens ?? 0) + t;
1088
+ spendTokens(t);
1089
+ },
1090
+ reportSampling: (applied, ignored) => {
1091
+ nr.samplingApplied = applied;
1092
+ nr.samplingIgnored = ignored;
1093
+ },
1094
+ reportCacheUsage: (usage) => {
1095
+ // Each field only if it was given: absent must survive as
1096
+ // absent all the way to the panel, or "this service does not
1097
+ // say" is reported as "nothing was reused".
1098
+ if (typeof usage?.prompt === 'number')
1099
+ nr.tokensPrompt = usage.prompt;
1100
+ if (typeof usage?.cached === 'number')
1101
+ nr.tokensCached = usage.cached;
1102
+ if (typeof usage?.cacheWrite === 'number')
1103
+ nr.tokensCacheWrite = usage.cacheWrite;
1104
+ },
1105
+ };
1106
+ }
1107
+ /**
1108
+ * The row this outlet committed, if it committed one — read off the
1109
+ * COMMIT rather than off what the binding chose to publish, because
1110
+ * the publish is the binding's business and the row is the host's.
1111
+ */
1112
+ let committedRow;
1113
+ let wroteNothing = false;
1114
+ if (node.kind === 'outlet') {
1115
+ ctx = {
1116
+ ...base,
1117
+ commit: async (p) => {
1118
+ // A recording names its event by literal (E1). A document that
1119
+ // reached the executor without publish's check could name a
1120
+ // core event — forging a `session-created` — or one nobody
1121
+ // declared; the executor refuses both itself.
1122
+ if (d.causesEventFrom) {
1123
+ const named = node.config[d.causesEventFrom];
1124
+ if (typeof named !== 'string' || named.startsWith('core:') || !packageEventById(named))
1125
+ throw new Error(`'${node.key}' records ${typeof named === 'string' ? `'${named}'` : 'no event'} — ` +
1126
+ `only an event a package declared may be recorded; core's are caused by core's writes`);
1127
+ }
1128
+ // A dry run's outlet reaches no host (R-21 (1)). The id is
1129
+ // synthetic and says so, so a downstream node — and a reader
1130
+ // of the receipt — can tell it from a row.
1131
+ const ids = dry
1132
+ ? (() => {
1133
+ nr.dry = true;
1134
+ nr.notes.push('dry: nothing committed');
1135
+ return { id: `dry:${node.key}` };
1136
+ })()
1137
+ : host?.commit
1138
+ ? await host.commit(p, nodeRef)
1139
+ : { id: `row:${node.key}`, ...p };
1140
+ const id = ids.id;
1141
+ if (typeof id === 'string' || typeof id === 'number')
1142
+ committedRow = id;
1143
+ // A host that looked and found nothing to write (an unchanged
1144
+ // annex) says so; the write caused no event (M3/W1).
1145
+ if (ids.written === false)
1146
+ wroteNothing = true;
1147
+ return ids;
1148
+ },
1149
+ emit: (handle, payload) => {
1150
+ nr.notes.push(dry ? `emit → ${handle} (dry)` : `emit → ${handle}`);
1151
+ if (!dry)
1152
+ host?.emit?.(handle, payload, nodeRef);
1153
+ },
1154
+ };
1155
+ }
1156
+ let res;
1157
+ try {
1158
+ res = await clock.race(Promise.resolve(hook(input, ctx)));
1159
+ }
1160
+ catch (e) {
1161
+ if (e instanceof BudgetExceeded)
1162
+ throw e;
1163
+ if (e instanceof NodeTimeout) {
1164
+ nr.timedOut = true;
1165
+ res = err(e.message);
1166
+ }
1167
+ else {
1168
+ res = err(e.message);
1169
+ }
1170
+ }
1171
+ nr.endedAt = now();
1172
+ nr.elapsedMs = nr.endedAt - nr.startedAt;
1173
+ nr.result = res.kind;
1174
+ // An optional node's failure is not the run's failure (see
1175
+ // `Descriptor.optional`). Recorded before it is absorbed: `result`
1176
+ // stays `err` and `reason` keeps the message, so the receipt reads as
1177
+ // "this failed and the run went on" rather than as a success.
1178
+ if (res.kind === 'err' && d.optional === true) {
1179
+ nr.reason = res.reason;
1180
+ nr.recoveredAsEmpty = true;
1181
+ res = ok({});
1182
+ }
1183
+ if (res.kind === 'ok') {
1184
+ // A gate-eligible outlet publishes the discriminated write result, so the
1185
+ // committed and pending cases are the same shape and a downstream type has
1186
+ // to handle both (13 §7j-b). There is no branch node to check `status` with
1187
+ // (F25), so the obligation belongs to the port shape, not to the spec.
1188
+ let published = res.value;
1189
+ // ── Script chains, after phase (18 §4a) — over what the binding
1190
+ // published, before it reaches the scope any downstream edge reads.
1191
+ if (scriptHooks.length &&
1192
+ published &&
1193
+ typeof published === 'object' &&
1194
+ !Array.isArray(published))
1195
+ published = await applyChainsAt('after', published);
1196
+ if (node.kind === 'outlet' && isGated(d.effects)) {
1197
+ // Wrap only if it is not already discriminated — but publish
1198
+ // either way. This used to skip publishing entirely when a
1199
+ // binding returned a `WriteResult` itself, so the binding doing
1200
+ // the *right* thing got the worse wiring: no `main`, and no
1201
+ // port typed `write-result@1` populated. Nothing caught it
1202
+ // because the only in-tree producer of `pending` was the
1203
+ // executor's own async-review branch, which called
1204
+ // `publishWriteResult` on its own; retiring that branch is what
1205
+ // surfaced this.
1206
+ const w = isWriteResult(published)
1207
+ ? published
1208
+ : {
1209
+ status: 'committed',
1210
+ ids: (published ?? {}),
1211
+ };
1212
+ published = publishWriteResult(w, d.ports.out);
1213
+ }
1214
+ // The run's live row (R-21 (2)): the row this outlet committed,
1215
+ // when the declaration says its row is the one a stream goes to.
1216
+ // A dry run's synthetic id counts — a downstream oracle in a dry
1217
+ // run still streams to nothing, and the host is told so by `dry`
1218
+ // rather than by the row's absence. Judged on the node's inputs,
1219
+ // not on what its binding chose to commit: a complete message from
1220
+ // the same outlet is an ordinary write, not the live row (F7, W1).
1221
+ if (d.liveRow && opensLiveRow(input) && committedRow !== undefined)
1222
+ liveRow = committedRow;
1223
+ scope.set(node.key, published);
1224
+ res = ok(published);
1225
+ nr.output = redact(published);
1226
+ }
1227
+ else if (res.kind === 'halt' || res.kind === 'err' || res.kind === 'cancelled') {
1228
+ nr.reason = res.reason;
1229
+ }
1230
+ // Core emits, not the node (01 §8 / F8). The event is the definition's,
1231
+ // or — for a recording — the one its literal names (E1).
1232
+ const caused = d.causesEvent ??
1233
+ (d.causesEventFrom && typeof node.config[d.causesEventFrom] === 'string'
1234
+ ? node.config[d.causesEventFrom]
1235
+ : undefined);
1236
+ if (res.kind === 'ok' && node.kind === 'outlet' && d.effects === 'write' && caused && !wroteNothing) {
1237
+ receipt.emitted.push({
1238
+ event: caused,
1239
+ cause: node.key,
1240
+ subscribers: opts.subscribers?.[caused] ?? 0,
1241
+ // Recorded, never dispatched: a dry run caused nothing, and a
1242
+ // reader of the receipt has to be able to tell that from a
1243
+ // write whose subscribers happened to be zero.
1244
+ ...(dry ? { dry: true } : {}),
1245
+ });
1246
+ }
1247
+ receipt.nodes.push(nr);
1248
+ return res;
1249
+ };
1250
+ /**
1251
+ * The invocation, observed. `onNode` fires at start and settle with node
1252
+ * identity and never a payload (F34) — an observer that throws is the
1253
+ * observer's problem, not the run's.
1254
+ */
1255
+ const invoke = async (node, scope, blockMode, iteration, iterationCount) => {
1256
+ const ev = (phase, result) => {
1257
+ try {
1258
+ opts.onNode?.({
1259
+ phase,
1260
+ nodeKey: node.key,
1261
+ definitionId: `${node.definitionId}@${node.definitionVersion}`,
1262
+ kind: node.kind,
1263
+ seq,
1264
+ declared: doc.nodes.length,
1265
+ iteration,
1266
+ ...(result ? { result } : {}),
1267
+ });
1268
+ }
1269
+ catch {
1270
+ // Progress display must never take a run down.
1271
+ }
1272
+ };
1273
+ ev('start');
1274
+ const res = await invokeInner(node, scope, blockMode, iteration, iterationCount);
1275
+ ev('end', res.kind);
1276
+ return res;
1277
+ };
1278
+ /** Admin kill (13 §3) — `cancelled`, not `err`, with the actor recorded. */
1279
+ const checkCancel = () => {
1280
+ const c = opts.cancelSignal?.();
1281
+ if (!c)
1282
+ return false;
1283
+ receipt.outcome = 'cancelled';
1284
+ receipt.cancelledBy = c.by;
1285
+ receipt.haltReason = c.reason;
1286
+ return true;
1287
+ };
1288
+ const writesOnLevel = (node) => node.kind === 'outlet' &&
1289
+ getDefinition(`${node.definitionId}@${node.definitionVersion}`)?.effects === 'write';
1290
+ /**
1291
+ * Run `run(0..n-1)` in parallel, handing chain *i* the parent's gate plus
1292
+ * "every chain before *i* has finished".
1293
+ */
1294
+ const parallelInOrder = async (items, gate, run) => {
1295
+ const finished = items.map(() => {
1296
+ let done;
1297
+ const p = new Promise((r) => (done = r));
1298
+ return { p, done };
1299
+ });
1300
+ return Promise.all(items.map((item, i) => run(item, i, [...gate, ...finished.slice(0, i).map((f) => f.p)]).finally(() => finished[i].done())));
1301
+ };
1302
+ const itemsAt = (level) => {
1303
+ const nodes = ordered
1304
+ .filter((n) => n.clauseId === level.clauseId && n.clauseChain === level.chain)
1305
+ .map((node) => ({
1306
+ sort: node.position,
1307
+ run: node,
1308
+ isClause: false,
1309
+ }));
1310
+ const clauses = doc.clauses
1311
+ .filter((b) => b.clauseId === level.clauseId && b.clauseChain === level.chain)
1312
+ .map((clause) => ({
1313
+ sort: clause.position,
1314
+ run: clause,
1315
+ isClause: true,
1316
+ }));
1317
+ return [...nodes, ...clauses].sort((a, b) => a.sort - b.sort);
1318
+ };
1319
+ const runLevel = async (level, scope, clauseMode, iteration, iterationCount, gate = []) => {
1320
+ let last = ok(null);
1321
+ for (const item of itemsAt(level)) {
1322
+ if (checkCancel())
1323
+ return cancelled('cancelled');
1324
+ if (!item.isClause && gate.length && writesOnLevel(item.run)) {
1325
+ await Promise.all(gate);
1326
+ if (checkCancel())
1327
+ return cancelled('cancelled');
1328
+ }
1329
+ last = item.isClause
1330
+ ? await runClause(item.run, scope, gate)
1331
+ : await invoke(item.run, scope, clauseMode, iteration, iterationCount);
1332
+ // A node that settled badly while the stop was pending settled
1333
+ // badly BECAUSE of the stop: an oracle whose call was aborted
1334
+ // returns `halt`, and reading that as the node's own decision would
1335
+ // file a person's Stop as the pipeline giving up. The stop is the
1336
+ // fact; the node's row keeps its own reason (13 §3).
1337
+ if (last.kind !== 'ok')
1338
+ return checkCancel() ? cancelled('cancelled') : last;
1339
+ }
1340
+ return last;
1341
+ };
1342
+ const runClause = async (clause, scope, gate = []) => {
1343
+ // `forceSequential` still wins over both: it is how a preview replays a
1344
+ // run deterministically, and a user setting must not be able to make a
1345
+ // preview nondeterministic.
1346
+ const mode = opts.forceSequential
1347
+ ? 'sequential'
1348
+ : resolveClauseMode(clause.mode, config[clause.id]?.['settings']?.['mode']);
1349
+ const collected = [];
1350
+ /**
1351
+ * The clause's own output, addressable by its id.
1352
+ *
1353
+ * `into` is the parent scope for every construct but the loop, which
1354
+ * publishes into its own scope first so the body can read it — see the
1355
+ * carry below. The union reads `collected` live, so one publish keeps
1356
+ * answering as iterations arrive.
1357
+ */
1358
+ const publish = (into = scope) => {
1359
+ const union = {
1360
+ branches: collected,
1361
+ get main() {
1362
+ return this.branches;
1363
+ },
1364
+ get values() {
1365
+ return this.branches
1366
+ .filter((b) => b.result.kind === 'ok')
1367
+ .map((b) => b.result.value);
1368
+ },
1369
+ get ok() {
1370
+ return collected.every((b) => b.result.kind === 'ok');
1371
+ },
1372
+ };
1373
+ into.set(clause.id, union);
1374
+ };
1375
+ if (clause.kind === 'gather') {
1376
+ // Chains share the scope: a sibling is addressable by its qualified key, and
1377
+ // keys are unique, so there is nothing to collide.
1378
+ const run = (chain, g = gate) => runLevel({ clauseId: clause.id, chain }, scope, mode, undefined, undefined, g);
1379
+ const results = mode === 'parallel'
1380
+ ? await parallelInOrder(clause.chains, gate, (chain, _i, g) => run(chain, g))
1381
+ : await sequential(clause.chains, (chain) => run(chain));
1382
+ clause.chains.forEach((chain, i) => collected.push({
1383
+ branchKey: chain,
1384
+ index: i,
1385
+ result: results[i],
1386
+ }));
1387
+ publish();
1388
+ return collected.find((b) => b.result.kind !== 'ok')?.result ?? ok(null);
1389
+ }
1390
+ if (clause.kind === 'each') {
1391
+ const items = resolveEachItems(clause.over, scope);
1392
+ if (clause.max !== undefined && items.length > clause.max) {
1393
+ return err(`each '${clause.id}' received ${items.length} items but declares max ${clause.max}`);
1394
+ }
1395
+ // Each iteration gets its own scope, so genuinely parallel maps are correct
1396
+ // rather than merely equivalent-if-you-squint.
1397
+ const run = async (item, i, g = gate) => {
1398
+ const child = scope.child();
1399
+ child.set(`${clause.id}.${ITEM_KEY}`, item);
1400
+ return runLevel({ clauseId: clause.id, chain: 'item' }, child, mode, i, items.length, g);
1401
+ };
1402
+ const results = mode === 'parallel'
1403
+ ? await parallelInOrder(items, gate, run)
1404
+ : await sequential(items.map((item, i) => ({ item, i })), ({ item, i }) => run(item, i));
1405
+ items.forEach((_, i) => collected.push({
1406
+ branchKey: `${clause.id}[${i}]`,
1407
+ index: i,
1408
+ result: results[i],
1409
+ }));
1410
+ publish();
1411
+ return collected.find((b) => b.result.kind !== 'ok')?.result ?? ok(null);
1412
+ }
1413
+ if (clause.kind === 'junction') {
1414
+ // ── route (20 §10) ───────────────────────────────────────────────
1415
+ // The decision is data a task computed; the routing is declaration.
1416
+ // Every predicate's evaluation is recorded — fired and skipped
1417
+ // alike — so "why did the lore branch not run" answers from rows.
1418
+ const value = resolvePredicate(clause.on, scope);
1419
+ const branches = clause.branches ?? {};
1420
+ // The predicate core is `predicates.ts` — the same `readPath` /
1421
+ // `predicateHolds` an action's enabled-when reads (U5e), so a
1422
+ // branch and a greyed button can never disagree about a value.
1423
+ const read = (path) => readPath(value, path);
1424
+ const describe = (p) => p.default
1425
+ ? 'default'
1426
+ : p.equals !== undefined
1427
+ ? `${p.path ?? 'value'} equals ${JSON.stringify(p.equals)}`
1428
+ : p.equalsPath !== undefined
1429
+ ? `${p.path ?? 'value'} equals the value at ${p.equalsPath}`
1430
+ : `${p.path ?? 'value'} truthy`;
1431
+ const fires = (p) => {
1432
+ if (p.default)
1433
+ return false; // resolved after the others
1434
+ // The routed value is handed in twice on purpose: once as the
1435
+ // subject (`read(p.path)`) and once as the **scope** an
1436
+ // `equalsPath` reads its other side from. One document, read
1437
+ // twice — which is what lets a branch ask *is the accused the
1438
+ // culprit?* about two ports of the same task, rather than only
1439
+ // *is the accused Vell?* against a literal the author typed.
1440
+ return predicateHolds(p, read(p.path), value);
1441
+ };
1442
+ const fired = new Map();
1443
+ for (const chain of clause.chains)
1444
+ fired.set(chain, fires(branches[chain] ?? {}));
1445
+ const anyFired = [...fired.values()].some(Boolean);
1446
+ for (const chain of clause.chains)
1447
+ if (branches[chain]?.default)
1448
+ fired.set(chain, !anyFired);
1449
+ receipt.notes = [
1450
+ ...(receipt.notes ?? []),
1451
+ ...clause.chains.map((chain) => `junction '${clause.id}': '${chain}' ${fired.get(chain) ? 'fired' : 'skipped'} (${describe(branches[chain] ?? {})})`),
1452
+ ];
1453
+ const firedChains = clause.chains.filter((c) => fired.get(c));
1454
+ const run = (chain, g = gate) => runLevel({ clauseId: clause.id, chain }, scope, mode, undefined, undefined, g);
1455
+ const results = new Map();
1456
+ if (mode === 'parallel') {
1457
+ const rs = await parallelInOrder(firedChains, gate, (chain, _i, g) => run(chain, g));
1458
+ firedChains.forEach((c, i) => results.set(c, rs[i]));
1459
+ }
1460
+ else {
1461
+ for (const c of firedChains) {
1462
+ if (checkCancel())
1463
+ return cancelled('cancelled');
1464
+ results.set(c, await run(c));
1465
+ }
1466
+ }
1467
+ clause.chains.forEach((chain, i) => collected.push({
1468
+ branchKey: chain,
1469
+ index: i,
1470
+ result: results.get(chain) ?? halt('not selected by route'),
1471
+ fired: !!fired.get(chain),
1472
+ }));
1473
+ // The union's ok/values read the *fired* branches: a skipped branch
1474
+ // is a stated outcome, never a failure and never a value.
1475
+ const union = {
1476
+ branches: collected,
1477
+ get main() {
1478
+ return this.branches;
1479
+ },
1480
+ get values() {
1481
+ return this.branches
1482
+ .filter((b) => b.fired && b.result.kind === 'ok')
1483
+ .map((b) => b.result.value);
1484
+ },
1485
+ ok: collected.every((b) => !b.fired || b.result.kind === 'ok'),
1486
+ };
1487
+ // A junction passes its result on (PLAN-turn-order §4.14, M4): the
1488
+ // fired branch's own ports — its last node's published value — are
1489
+ // readable under the clause's id, beside the four clause ports, so
1490
+ // `$.decide.order` needs no fold node. The first fired branch in
1491
+ // declaration order answers when several fire; `validate()` holds
1492
+ // every branch to publishing any port a spec reads this way.
1493
+ const answered = collected.find((b) => b.fired && b.result.kind === 'ok');
1494
+ const firedValue = answered ? answered.result.value : undefined;
1495
+ if (firedValue && typeof firedValue === 'object')
1496
+ for (const [port, v] of Object.entries(firedValue))
1497
+ if (!JUNCTION_CLAUSE_PORTS.has(port))
1498
+ union[port] = v;
1499
+ scope.set(clause.id, union);
1500
+ return collected.find((b) => b.fired && b.result.kind !== 'ok')?.result ?? ok(null);
1501
+ }
1502
+ // ── loop (01 §4a) ────────────────────────────────────────────────────
1503
+ // Do-while: run the body, then re-read the declared predicate. A tool loop
1504
+ // always wants one generate before it can know whether to stop.
1505
+ const max = clause.max ?? 0;
1506
+ /**
1507
+ * The carry: one scope for the whole loop, holding the clause's
1508
+ * accumulating output.
1509
+ *
1510
+ * A tool loop is only a loop if the next prompt can see the last
1511
+ * result, and the body cannot reference a node declared after it —
1512
+ * `makeScope` makes a back-edge unwritable (F9). What *is* declared
1513
+ * before the body is the clause itself, so `$.tools.values` reads the
1514
+ * iterations that have already finished. Each iteration still runs in
1515
+ * a child of this, so an iteration's node values stay private to it
1516
+ * and a loop remains the same construct as a parallel map (F26).
1517
+ */
1518
+ const carry = scope.child();
1519
+ publish(carry);
1520
+ let ran = 0;
1521
+ const stoppedOn = (stopped) => {
1522
+ receipt.loops = [
1523
+ ...(receipt.loops ?? []),
1524
+ { clauseId: clause.id, iterations: ran, stopped },
1525
+ ];
1526
+ publish();
1527
+ };
1528
+ for (let i = 0; i < max; i++) {
1529
+ if (checkCancel()) {
1530
+ stoppedOn('interrupted');
1531
+ return cancelled('cancelled');
1532
+ }
1533
+ const child = carry.child();
1534
+ const r = await runLevel({ clauseId: clause.id, chain: 'item' }, child, 'sequential', i, undefined, gate);
1535
+ ran++;
1536
+ collected.push({
1537
+ branchKey: `${clause.id}[${i}]`,
1538
+ index: i,
1539
+ result: r,
1540
+ });
1541
+ if (r.kind !== 'ok') {
1542
+ stoppedOn('interrupted');
1543
+ return r;
1544
+ }
1545
+ const again = clause.repeatWhile ? resolvePredicate(clause.repeatWhile, child) : false;
1546
+ if (!truthy(again)) {
1547
+ stoppedOn('predicate');
1548
+ return ok(null);
1549
+ }
1550
+ }
1551
+ stoppedOn('ceiling');
1552
+ // Reaching `max` is not an error — it is the bound doing its job, and the
1553
+ // receipt says so rather than leaving a truncated loop looking successful.
1554
+ receipt.notes = [
1555
+ ...(receipt.notes ?? []),
1556
+ `loop '${clause.id}' reached its declared max of ${max}`,
1557
+ ];
1558
+ return ok(null);
1559
+ };
1560
+ /** Set when the run ended by throwing; rethrown after the run-end hook. */
1561
+ let thrown;
1562
+ try {
1563
+ const outcome = await runLevel({ clauseId: undefined, chain: undefined }, values);
1564
+ if (outcome.kind === 'halt') {
1565
+ receipt.outcome = 'halt';
1566
+ receipt.haltReason = outcome.reason;
1567
+ receipt.haltNodeKey ??= receipt.nodes.find((n) => n.result === 'halt')?.nodeKey;
1568
+ }
1569
+ else if (outcome.kind !== 'ok') {
1570
+ receipt.outcome = outcome.kind;
1571
+ if (outcome.kind === 'err') {
1572
+ receipt.haltReason ??= outcome.reason;
1573
+ receipt.haltNodeKey ??= receipt.nodes.find((n) => n.result === 'err')?.nodeKey;
1574
+ }
1575
+ // Where a Stop landed (13 §3): the node whose settle the stop
1576
+ // converted — an oracle that halted on its abort — so the inspector
1577
+ // can say *Stopped at generate on request*. A stop that landed
1578
+ // between nodes names none: nothing was interrupted.
1579
+ if (outcome.kind === 'cancelled')
1580
+ receipt.haltNodeKey ??= [...receipt.nodes]
1581
+ .reverse()
1582
+ .find((n) => n.result !== 'ok' && !n.recoveredAsEmpty)?.nodeKey;
1583
+ }
1584
+ }
1585
+ catch (e) {
1586
+ receipt.outcome = 'err';
1587
+ receipt.haltReason = e?.message ?? String(e);
1588
+ // Anything but the budget is the host's failure and still propagates —
1589
+ // after the run-end hook below has had its say, which is the R-17
1590
+ // guarantee: a throw is one more way a run ends, not a way out of it.
1591
+ if (!(e instanceof BudgetExceeded))
1592
+ thrown = { error: e };
1593
+ }
1594
+ receipt.endedAt = now();
1595
+ receipt.reviews = reviews;
1596
+ // Receipts sort by execution order for rendering.
1597
+ receipt.nodes.sort((a, b) => a.seq - b.seq);
1598
+ // What it was doing when it died (R-21, "optional, taken"): the last
1599
+ // status, on a run that ended `halt`, `err` or `cancelled` — never on
1600
+ // `ok`, and never on a preview's halt, which is the pipeline stopping
1601
+ // where it was asked to rather than dying.
1602
+ if (lastStatus && receipt.outcome !== 'ok' && !receipt.preview)
1603
+ receipt.lastStatus = lastStatus;
1604
+ // ── Compact receipt (13 §2) ───────────────────────────────────────────────
1605
+ // The per-message multiplier is a hot event × every subscribed pipeline, where
1606
+ // most subscribers halt on the first node and that is success (01 §5). Those
1607
+ // runs keep their attribution and lose their payloads.
1608
+ // A preview is never compacted — the preview *is* the payload. Worth noting that the
1609
+ // trigger-source rule already gets this right on its own (a preview is `ui`), but
1610
+ // relying on that would be an accident rather than a decision.
1611
+ const compactDefault = receipt.triggerSource === 'event' && !receipt.preview;
1612
+ if ((opts.compactHaltReceipts ?? compactDefault) &&
1613
+ receipt.outcome === 'halt' &&
1614
+ !effectfulNodeRan) {
1615
+ receipt.compact = true;
1616
+ receipt.compactedNodeCount = receipt.nodes.length;
1617
+ receipt.nodes = [];
1618
+ receipt.reviews = [];
1619
+ }
1620
+ // The run-level guarantee (R-17): whatever ended the run — a verdict, the
1621
+ // budget, or a throw on its way out — the host hears about it once, with
1622
+ // the row it may have to finish. Absorbed if it throws — see
1623
+ // `RunOptions.onRunEnd`.
1624
+ if (opts.onRunEnd) {
1625
+ try {
1626
+ await opts.onRunEnd({
1627
+ kind: receipt.outcome,
1628
+ liveRow,
1629
+ dry,
1630
+ receipt,
1631
+ ...(thrown ? { error: thrown.error } : {}),
1632
+ });
1633
+ }
1634
+ catch (e) {
1635
+ receipt.notes = [
1636
+ ...(receipt.notes ?? []),
1637
+ `the host's run-end hook failed: ${e.message}`,
1638
+ ];
1639
+ }
1640
+ }
1641
+ if (thrown)
1642
+ throw thrown.error;
1643
+ return receipt;
1644
+ }
1645
+ /**
1646
+ * Every out port a gate-eligible outlet declares as `write-result@1` resolves to the
1647
+ * *same* discriminated value. A port named `messageId` therefore hands downstream the
1648
+ * result, not an id — which is the point: there may not be an id yet (13 §7j-b).
1649
+ */
1650
+ function publishWriteResult(w, out) {
1651
+ const published = { ...w, main: w };
1652
+ for (const [port, shape] of Object.entries(out ?? {})) {
1653
+ if (shape === 'core:shape/write-result@1')
1654
+ published[port] = w;
1655
+ }
1656
+ return published;
1657
+ }
1658
+ const isWriteResult = (v) => !!v &&
1659
+ typeof v === 'object' &&
1660
+ 'status' in v &&
1661
+ (v.status === 'committed' || v.status === 'pending');
1662
+ /**
1663
+ * A loop's `repeatWhile` is a **port reference**, resolved in the iteration's own scope.
1664
+ * Not an expression: a reference keeps the construct renderable ("repeats while
1665
+ * generate.hasToolCalls, max 8") and keeps a second expression language out of the design.
1666
+ */
1667
+ function resolvePredicate(ref, scope) {
1668
+ if (!ref || typeof ref !== 'object' || ref.__ref !== 'data')
1669
+ return ref;
1670
+ const r = ref;
1671
+ return readPort(scope.get(r.node), r.port);
1672
+ }
1673
+ /**
1674
+ * Read a port off an upstream value.
1675
+ *
1676
+ * `main` means **the whole value** when the producer declared no distinct `main` — which
1677
+ * is exactly the case for a map or loop item, where the "producer" is a raw list element
1678
+ * that never had ports at all. Without this, `$.$item` on a plain object silently
1679
+ * resolves to undefined, which is the least debuggable failure available.
1680
+ */
1681
+ function readPort(upstream, port) {
1682
+ if (!upstream || typeof upstream !== 'object')
1683
+ return upstream;
1684
+ if (port === 'main' && !(port in upstream))
1685
+ return upstream;
1686
+ return upstream[port];
1687
+ }
1688
+ /** `over` is either a literal list or a data ref into an upstream value. */
1689
+ function resolveEachItems(over, values) {
1690
+ if (Array.isArray(over))
1691
+ return over;
1692
+ if (over && typeof over === 'object' && over.__ref === 'data') {
1693
+ const r = over;
1694
+ const v = readPort(values.get(r.node), r.port);
1695
+ return Array.isArray(v) ? v : v === undefined || v === null ? [] : [v];
1696
+ }
1697
+ return [];
1698
+ }
1699
+ async function sequential(items, fn) {
1700
+ const out = [];
1701
+ for (const i of items)
1702
+ out.push(await fn(i));
1703
+ return out;
1704
+ }
1705
+ /** A node's own clock ran out (F36); the message is the receipt's reason. */
1706
+ class NodeTimeout extends Error {
1707
+ }
1708
+ /**
1709
+ * One invocation's clock (F36), by the definition's `timeoutKind`.
1710
+ *
1711
+ * - `wall` — `ms` from the start of the invocation to its end, whatever the
1712
+ * node does in between. `pulse` does nothing.
1713
+ * - `idle` — `ms` between signs of progress: every `pulse` restarts the
1714
+ * window, so a reply that streams for twenty minutes is fine and one that
1715
+ * goes silent for `ms` is not. The pub's ceiling, when finite, still
1716
+ * bounds the whole invocation, so no amount of pulsing runs a node forever.
1717
+ *
1718
+ * Real time only. Simulated waiting (`RunOptions.now`) never reaches it, and
1719
+ * neither does a review gate — those park outside any invocation.
1720
+ *
1721
+ * Either way the node's own signal aborts when the clock runs out, which is
1722
+ * what a host's in-flight request listens to (`CallHandles.signal`): a timeout
1723
+ * that let the request run on would leave a model server generating into
1724
+ * nothing, with the next request queued behind it.
1725
+ */
1726
+ function nodeClock(limit, controller) {
1727
+ const { ms, kind, ceilingMs } = limit;
1728
+ let window;
1729
+ let cap;
1730
+ let expire;
1731
+ const restart = () => {
1732
+ if (!expire || !Number.isFinite(ms))
1733
+ return;
1734
+ if (window !== undefined)
1735
+ clearTimeout(window);
1736
+ const fire = expire;
1737
+ window = setTimeout(() => fire(kind === 'idle'
1738
+ ? `timeout after ${ms}ms without progress`
1739
+ : `timeout after ${ms}ms`), ms);
1740
+ };
1741
+ return {
1742
+ pulse: () => {
1743
+ if (kind === 'idle')
1744
+ restart();
1745
+ },
1746
+ race(p) {
1747
+ const capped = kind === 'idle' && Number.isFinite(ceilingMs);
1748
+ if (!Number.isFinite(ms) && !capped)
1749
+ return p;
1750
+ return new Promise((resolve, reject) => {
1751
+ const settle = () => {
1752
+ expire = undefined;
1753
+ if (window !== undefined)
1754
+ clearTimeout(window);
1755
+ if (cap !== undefined)
1756
+ clearTimeout(cap);
1757
+ };
1758
+ expire = (reason) => {
1759
+ settle();
1760
+ controller.abort();
1761
+ reject(new NodeTimeout(reason));
1762
+ };
1763
+ restart();
1764
+ if (capped) {
1765
+ const fire = expire;
1766
+ cap = setTimeout(() => fire(`timeout after ${ceilingMs}ms (the pub's ceiling)`), ceilingMs);
1767
+ }
1768
+ p.then((v) => {
1769
+ settle();
1770
+ resolve(v);
1771
+ }, (e) => {
1772
+ settle();
1773
+ reject(e);
1774
+ });
1775
+ });
1776
+ },
1777
+ };
1778
+ }
1779
+ function setPath(obj, path, value) {
1780
+ let cur = obj;
1781
+ for (let i = 0; i < path.length - 1; i++) {
1782
+ const k = path[i];
1783
+ cur[k] = Array.isArray(cur[k]) ? [...cur[k]] : { ...(cur[k] ?? {}) };
1784
+ cur = cur[k];
1785
+ }
1786
+ cur[path[path.length - 1]] = value;
1787
+ }
1788
+ /** Vectors, material and secrets never enter a receipt (16 §1a, 01 §10, 13 §6). */
1789
+ function redact(v) {
1790
+ if (Array.isArray(v) && v.length > 8 && v.every((x) => typeof x === 'number')) {
1791
+ return { $vector: true, dims: v.length };
1792
+ }
1793
+ if (Array.isArray(v))
1794
+ return v.map(redact);
1795
+ // A secret-typed setting is redacted **by its type**, which is the entire reason
1796
+ // the field is typed rather than free-form: core can identify it without knowing
1797
+ // what the plugin called it (13 §6).
1798
+ if (isSecret(v))
1799
+ return '[secret]';
1800
+ if (v && typeof v === 'object') {
1801
+ const out = {};
1802
+ for (const [k, val] of Object.entries(v)) {
1803
+ if (k === 'material' || k === 'credentials') {
1804
+ out[k] = '[redacted]';
1805
+ continue;
1806
+ }
1807
+ out[k] = redact(val);
1808
+ }
1809
+ return out;
1810
+ }
1811
+ return v;
1812
+ }
1813
+ /** replay(receipt) — deterministic, never re-infers (F16). @experimental */
1814
+ export async function replay(doc, receipt, bindings) {
1815
+ const recorded = new Map(receipt.nodes.map((n) => [n.nodeKey, n.output]));
1816
+ const replayBindings = { ...bindings };
1817
+ for (const n of receipt.nodes) {
1818
+ if (n.kind !== 'oracle')
1819
+ continue;
1820
+ replayBindings[n.definitionId] = async () => ok(recorded.get(n.nodeKey));
1821
+ }
1822
+ return run(doc, {
1823
+ input: receipt.nodes[0]?.output,
1824
+ bindings: replayBindings,
1825
+ seed: receipt.seed,
1826
+ runId: receipt.runId + ':replay',
1827
+ });
1828
+ }
1829
+ //# sourceMappingURL=executor.js.map