@contractspec/lib.surface-runtime 0.3.0 → 0.3.3

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 (152) hide show
  1. package/dist/adapters/ai-sdk-stub.js +1 -6
  2. package/dist/adapters/blocknote-stub.js +3 -8
  3. package/dist/adapters/dnd-kit-adapter.js +6 -11
  4. package/dist/adapters/dnd-kit-stub.js +1 -6
  5. package/dist/adapters/floating-ui-stub.js +4 -9
  6. package/dist/adapters/index.js +7 -176
  7. package/dist/adapters/interfaces.js +0 -1
  8. package/dist/adapters/motion-stub.js +2 -7
  9. package/dist/adapters/resizable-panels-stub.js +7 -12
  10. package/dist/browser/adapters/ai-sdk-stub.js +1 -5
  11. package/dist/browser/adapters/blocknote-stub.js +3 -7
  12. package/dist/browser/adapters/dnd-kit-adapter.js +6 -10
  13. package/dist/browser/adapters/dnd-kit-stub.js +1 -5
  14. package/dist/browser/adapters/floating-ui-stub.js +4 -8
  15. package/dist/browser/adapters/index.js +7 -175
  16. package/dist/browser/adapters/motion-stub.js +2 -6
  17. package/dist/browser/adapters/resizable-panels-stub.js +5 -9
  18. package/dist/browser/evals/golden-harness.js +4 -825
  19. package/dist/browser/examples/pm-workbench.bundle.js +2 -316
  20. package/dist/browser/i18n/catalogs/en.js +1 -5
  21. package/dist/browser/i18n/catalogs/es.js +1 -5
  22. package/dist/browser/i18n/catalogs/fr.js +1 -5
  23. package/dist/browser/i18n/catalogs/index.js +3 -133
  24. package/dist/browser/i18n/index.js +3 -168
  25. package/dist/browser/i18n/keys.js +1 -5
  26. package/dist/browser/i18n/messages.js +6 -137
  27. package/dist/browser/index.js +4 -2470
  28. package/dist/browser/react/BundleProvider.js +12 -19
  29. package/dist/browser/react/BundleRenderer.js +15 -662
  30. package/dist/browser/react/OverlayConflictResolver.js +12 -180
  31. package/dist/browser/react/PatchProposalCard.js +9 -177
  32. package/dist/browser/react/RegionRenderer.js +14 -60
  33. package/dist/browser/react/SlotRenderer.js +15 -58
  34. package/dist/browser/react/WidgetPalette.js +6 -10
  35. package/dist/browser/react/index.js +14 -794
  36. package/dist/browser/runtime/apply-surface-patch.js +3 -208
  37. package/dist/browser/runtime/audit-events.js +8 -19
  38. package/dist/browser/runtime/build-context.js +2 -6
  39. package/dist/browser/runtime/extension-registry.js +3 -9
  40. package/dist/browser/runtime/field-renderer-registry.js +5 -11
  41. package/dist/browser/runtime/index.js +54 -1487
  42. package/dist/browser/runtime/overlay-alignment.js +8 -19
  43. package/dist/browser/runtime/overlay-signer.js +2 -7
  44. package/dist/browser/runtime/override-store.js +3 -9
  45. package/dist/browser/runtime/planner-prompt.js +2 -6
  46. package/dist/browser/runtime/planner-tools.js +3 -9
  47. package/dist/browser/runtime/policy-eval.js +3 -135
  48. package/dist/browser/runtime/preference-adapter.js +2 -62
  49. package/dist/browser/runtime/resolve-bundle.js +10 -447
  50. package/dist/browser/runtime/resolve-preferences.js +3 -7
  51. package/dist/browser/runtime/rollback.js +2 -325
  52. package/dist/browser/runtime/widget-registry.js +1 -5
  53. package/dist/browser/spec/define-module-bundle.js +2 -67
  54. package/dist/browser/spec/index.js +9 -317
  55. package/dist/browser/spec/validate-bundle.js +3 -8
  56. package/dist/browser/spec/validate-surface-patch.js +5 -11
  57. package/dist/browser/telemetry/index.js +4 -16
  58. package/dist/browser/telemetry/surface-metrics.js +7 -16
  59. package/dist/evals/golden-context.js +0 -1
  60. package/dist/evals/golden-harness.js +4 -826
  61. package/dist/examples/pm-workbench.bundle.js +2 -317
  62. package/dist/i18n/catalogs/en.js +1 -6
  63. package/dist/i18n/catalogs/es.js +1 -6
  64. package/dist/i18n/catalogs/fr.js +1 -6
  65. package/dist/i18n/catalogs/index.js +3 -134
  66. package/dist/i18n/index.js +3 -169
  67. package/dist/i18n/keys.js +1 -6
  68. package/dist/i18n/messages.js +6 -138
  69. package/dist/index.js +4 -2471
  70. package/dist/node/adapters/ai-sdk-stub.js +1 -5
  71. package/dist/node/adapters/blocknote-stub.js +3 -7
  72. package/dist/node/adapters/dnd-kit-adapter.js +6 -10
  73. package/dist/node/adapters/dnd-kit-stub.js +1 -5
  74. package/dist/node/adapters/floating-ui-stub.js +4 -8
  75. package/dist/node/adapters/index.js +7 -175
  76. package/dist/node/adapters/motion-stub.js +2 -6
  77. package/dist/node/adapters/resizable-panels-stub.js +5 -9
  78. package/dist/node/evals/golden-harness.js +4 -825
  79. package/dist/node/examples/pm-workbench.bundle.js +2 -316
  80. package/dist/node/i18n/catalogs/en.js +1 -5
  81. package/dist/node/i18n/catalogs/es.js +1 -5
  82. package/dist/node/i18n/catalogs/fr.js +1 -5
  83. package/dist/node/i18n/catalogs/index.js +3 -133
  84. package/dist/node/i18n/index.js +3 -168
  85. package/dist/node/i18n/keys.js +1 -5
  86. package/dist/node/i18n/messages.js +6 -137
  87. package/dist/node/index.js +4 -2470
  88. package/dist/node/react/BundleProvider.js +12 -19
  89. package/dist/node/react/BundleRenderer.js +15 -662
  90. package/dist/node/react/OverlayConflictResolver.js +12 -180
  91. package/dist/node/react/PatchProposalCard.js +9 -177
  92. package/dist/node/react/RegionRenderer.js +14 -60
  93. package/dist/node/react/SlotRenderer.js +15 -58
  94. package/dist/node/react/WidgetPalette.js +6 -10
  95. package/dist/node/react/index.js +14 -794
  96. package/dist/node/runtime/apply-surface-patch.js +3 -208
  97. package/dist/node/runtime/audit-events.js +8 -19
  98. package/dist/node/runtime/build-context.js +2 -6
  99. package/dist/node/runtime/extension-registry.js +3 -9
  100. package/dist/node/runtime/field-renderer-registry.js +5 -11
  101. package/dist/node/runtime/index.js +54 -1487
  102. package/dist/node/runtime/overlay-alignment.js +8 -19
  103. package/dist/node/runtime/overlay-signer.js +2 -7
  104. package/dist/node/runtime/override-store.js +3 -9
  105. package/dist/node/runtime/planner-prompt.js +2 -6
  106. package/dist/node/runtime/planner-tools.js +3 -9
  107. package/dist/node/runtime/policy-eval.js +3 -135
  108. package/dist/node/runtime/preference-adapter.js +2 -62
  109. package/dist/node/runtime/resolve-bundle.js +10 -447
  110. package/dist/node/runtime/resolve-preferences.js +3 -7
  111. package/dist/node/runtime/rollback.js +2 -325
  112. package/dist/node/runtime/widget-registry.js +1 -5
  113. package/dist/node/spec/define-module-bundle.js +2 -67
  114. package/dist/node/spec/index.js +9 -317
  115. package/dist/node/spec/validate-bundle.js +3 -8
  116. package/dist/node/spec/validate-surface-patch.js +5 -11
  117. package/dist/node/telemetry/index.js +4 -16
  118. package/dist/node/telemetry/surface-metrics.js +7 -16
  119. package/dist/react/BundleProvider.js +12 -20
  120. package/dist/react/BundleRenderer.js +15 -663
  121. package/dist/react/OverlayConflictResolver.js +12 -181
  122. package/dist/react/PatchProposalCard.js +9 -178
  123. package/dist/react/RegionRenderer.js +14 -61
  124. package/dist/react/SlotRenderer.js +15 -59
  125. package/dist/react/WidgetPalette.js +6 -11
  126. package/dist/react/index.js +14 -795
  127. package/dist/runtime/apply-surface-patch.js +3 -209
  128. package/dist/runtime/audit-events.js +8 -20
  129. package/dist/runtime/build-context.js +2 -7
  130. package/dist/runtime/extension-registry.js +3 -10
  131. package/dist/runtime/field-renderer-registry.js +9 -16
  132. package/dist/runtime/index.js +54 -1488
  133. package/dist/runtime/overlay-alignment.js +8 -20
  134. package/dist/runtime/overlay-signer.js +2 -8
  135. package/dist/runtime/override-store.js +3 -10
  136. package/dist/runtime/planner-prompt.js +11 -9
  137. package/dist/runtime/planner-tools.js +4 -11
  138. package/dist/runtime/policy-eval.js +3 -136
  139. package/dist/runtime/preference-adapter.js +2 -63
  140. package/dist/runtime/resolve-bundle.js +10 -448
  141. package/dist/runtime/resolve-preferences.js +3 -8
  142. package/dist/runtime/rollback.js +2 -326
  143. package/dist/runtime/widget-registry.js +1 -6
  144. package/dist/spec/define-module-bundle.js +2 -68
  145. package/dist/spec/index.js +9 -318
  146. package/dist/spec/types.js +0 -1
  147. package/dist/spec/validate-bundle.js +3 -9
  148. package/dist/spec/validate-surface-patch.js +5 -12
  149. package/dist/spec/verification-snapshot-types.js +0 -1
  150. package/dist/telemetry/index.js +4 -17
  151. package/dist/telemetry/surface-metrics.js +7 -17
  152. package/package.json +7 -7
@@ -1,1496 +1,63 @@
1
- // src/telemetry/surface-metrics.ts
2
- import {
3
- createCounter,
4
- createHistogram
5
- } from "@contractspec/lib.observability/metrics";
6
- var METER_NAME = "@contractspec/lib.surface-runtime";
7
- var resolutionDurationMs = createHistogram("bundle_surface_resolution_duration_ms", "Time to resolve bundle spec to surface plan in milliseconds", METER_NAME);
8
- var patchAcceptanceCounter = createCounter("bundle_surface_patch_acceptance_total", "Total AI patch proposals accepted by user", METER_NAME);
9
- var patchRejectionCounter = createCounter("bundle_surface_patch_rejection_total", "Total AI patch proposals rejected by user", METER_NAME);
10
- var policyDenialCounter = createCounter("bundle_surface_policy_denial_total", "Total policy denials (actions denied by policy)", METER_NAME);
11
- var surfaceFallbackCounter = createCounter("bundle_surface_fallback_total", "Total surface or layout fallbacks during resolution", METER_NAME);
12
- var missingRendererCounter = createCounter("bundle_surface_renderer_missing_total", "Total slots with no renderer for requested node kind", METER_NAME);
13
- // src/runtime/resolve-preferences.ts
14
- var DIMENSION_KEYS = [
15
- "guidance",
16
- "density",
17
- "dataDepth",
18
- "control",
19
- "media",
20
- "pace",
21
- "narrative"
22
- ];
23
- var SCOPE_ORDER = [
24
- "user",
25
- "workspace-user",
26
- "bundle",
27
- "surface",
28
- "entity",
29
- "session"
30
- ];
31
- function mergeByScope(layers, ctx) {
32
- const merged = { ...ctx.preferences };
33
- const sourceByDimension = {};
34
- for (const scope of SCOPE_ORDER) {
35
- const layer = layers[scope];
36
- if (!layer)
37
- continue;
38
- for (const dim of DIMENSION_KEYS) {
39
- const val = layer[dim];
40
- if (val !== undefined) {
41
- merged[dim] = val;
42
- sourceByDimension[dim] = scope;
43
- }
44
- }
45
- }
46
- for (const dim of DIMENSION_KEYS) {
47
- if (sourceByDimension[dim] === undefined) {
48
- sourceByDimension[dim] = "session";
49
- }
50
- }
51
- return { canonical: merged, sourceByDimension };
52
- }
53
- function resolveConstraints(_canonical, _ctx) {
54
- return { constrained: {}, notes: [] };
55
- }
56
- function resolvePreferenceProfile(ctx) {
57
- const layers = {
58
- session: ctx.preferences
59
- };
60
- const { canonical, sourceByDimension } = mergeByScope(layers, ctx);
61
- const { constrained, notes } = resolveConstraints(canonical, ctx);
62
- return {
63
- canonical,
64
- sourceByDimension,
65
- constrained,
66
- notes
67
- };
68
- }
69
-
70
- // src/spec/validate-surface-patch.ts
71
- var VALID_OPS = [
72
- "insert-node",
73
- "replace-node",
74
- "remove-node",
75
- "move-node",
76
- "resize-panel",
77
- "set-layout",
78
- "reveal-field",
79
- "hide-field",
80
- "promote-action",
81
- "set-focus"
82
- ];
83
- var VALID_NODE_KINDS = [
84
- "metric-strip",
85
- "data-view",
86
- "entity-card",
87
- "entity-header",
88
- "entity-summary",
89
- "entity-section",
90
- "entity-field",
91
- "entity-activity",
92
- "entity-relations",
93
- "entity-timeline",
94
- "entity-comments",
95
- "entity-attachments",
96
- "entity-view-switcher",
97
- "entity-automation-panel",
98
- "rich-doc",
99
- "chat-thread",
100
- "assistant-panel",
101
- "action-bar",
102
- "timeline",
103
- "board",
104
- "table",
105
- "calendar",
106
- "form",
107
- "chart",
108
- "relation-graph",
109
- "custom-widget"
110
- ];
111
- function validateSurfaceNode(node, path) {
112
- if (!node.nodeId || typeof node.nodeId !== "string") {
113
- throw new Error(`${path}: nodeId must be a non-empty string`);
114
- }
115
- if (!node.kind || !VALID_NODE_KINDS.includes(node.kind)) {
116
- throw new Error(`${path}: kind must be one of ${VALID_NODE_KINDS.join(", ")}`);
117
- }
118
- if (node.children) {
119
- for (let i = 0;i < node.children.length; i++) {
120
- const child = node.children[i];
121
- if (child)
122
- validateSurfaceNode(child, `${path}.children[${i}]`);
123
- }
124
- }
125
- }
126
- function validateSurfacePatchOp(op, index) {
127
- const path = `ops[${index}]`;
128
- if (!op || typeof op !== "object" || !("op" in op)) {
129
- throw new Error(`${path}: must be an object with op field`);
130
- }
131
- const opType = op.op;
132
- if (!VALID_OPS.includes(opType)) {
133
- throw new Error(`${path}: op must be one of ${VALID_OPS.join(", ")}`);
134
- }
135
- switch (op.op) {
136
- case "insert-node":
137
- if (!op.slotId || typeof op.slotId !== "string") {
138
- throw new Error(`${path}: insert-node requires slotId string`);
139
- }
140
- if (!op.node) {
141
- throw new Error(`${path}: insert-node requires node`);
142
- }
143
- validateSurfaceNode(op.node, `${path}.node`);
144
- if (op.index !== undefined && typeof op.index !== "number") {
145
- throw new Error(`${path}: insert-node index must be number if present`);
146
- }
147
- break;
148
- case "replace-node":
149
- if (!op.nodeId || typeof op.nodeId !== "string") {
150
- throw new Error(`${path}: replace-node requires nodeId string`);
151
- }
152
- if (!op.node) {
153
- throw new Error(`${path}: replace-node requires node`);
154
- }
155
- validateSurfaceNode(op.node, `${path}.node`);
156
- break;
157
- case "remove-node":
158
- if (!op.nodeId || typeof op.nodeId !== "string") {
159
- throw new Error(`${path}: remove-node requires nodeId string`);
160
- }
161
- break;
162
- case "move-node":
163
- if (!op.nodeId || typeof op.nodeId !== "string") {
164
- throw new Error(`${path}: move-node requires nodeId string`);
165
- }
166
- if (!op.toSlotId || typeof op.toSlotId !== "string") {
167
- throw new Error(`${path}: move-node requires toSlotId string`);
168
- }
169
- if (op.index !== undefined && typeof op.index !== "number") {
170
- throw new Error(`${path}: move-node index must be number if present`);
171
- }
172
- break;
173
- case "resize-panel":
174
- if (!op.persistKey || typeof op.persistKey !== "string") {
175
- throw new Error(`${path}: resize-panel requires persistKey string`);
176
- }
177
- if (!Array.isArray(op.sizes) || op.sizes.some((s) => typeof s !== "number")) {
178
- throw new Error(`${path}: resize-panel requires sizes number[]`);
179
- }
180
- break;
181
- case "set-layout":
182
- if (!op.layoutId || typeof op.layoutId !== "string") {
183
- throw new Error(`${path}: set-layout requires layoutId string`);
184
- }
185
- break;
186
- case "reveal-field":
187
- case "hide-field":
188
- if (!op.fieldId || typeof op.fieldId !== "string") {
189
- throw new Error(`${path}: ${op.op} requires fieldId string`);
190
- }
191
- break;
192
- case "promote-action": {
193
- if (!op.actionId || typeof op.actionId !== "string") {
194
- throw new Error(`${path}: promote-action requires actionId string`);
195
- }
196
- const validPlacements = ["header", "inline", "context", "assistant"];
197
- if (!op.placement || !validPlacements.includes(op.placement)) {
198
- throw new Error(`${path}: promote-action placement must be one of ${validPlacements.join(", ")}`);
199
- }
200
- break;
201
- }
202
- case "set-focus":
203
- if (!op.targetId || typeof op.targetId !== "string") {
204
- throw new Error(`${path}: set-focus requires targetId string`);
205
- }
206
- break;
207
- default:
208
- throw new Error(`${path}: unknown op "${opType}"`);
209
- }
210
- }
211
- function validateSurfacePatch(ops) {
212
- if (!Array.isArray(ops)) {
213
- throw new Error("Patch ops must be an array");
214
- }
215
- for (let i = 0;i < ops.length; i++) {
216
- const op = ops[i];
217
- if (op)
218
- validateSurfacePatchOp(op, i);
219
- }
220
- }
221
- function validateSurfaceNodeAgainstKinds(node, allowedKinds, path) {
222
- if (!allowedKinds.includes(node.kind)) {
223
- throw new Error(`${path}: kind "${node.kind}" not in allowed list [${allowedKinds.join(", ")}]`);
224
- }
225
- if (node.children) {
226
- for (let i = 0;i < node.children.length; i++) {
227
- const child = node.children[i];
228
- if (child)
229
- validateSurfaceNodeAgainstKinds(child, allowedKinds, `${path}.children[${i}]`);
230
- }
231
- }
232
- }
233
- function validatePatchProposal(ops, constraints) {
234
- if (!Array.isArray(ops)) {
235
- throw new Error("Patch ops must be an array");
236
- }
237
- const { allowedOps, allowedSlots, allowedNodeKinds } = constraints;
238
- for (let i = 0;i < ops.length; i++) {
239
- const op = ops[i];
240
- if (!op)
241
- continue;
242
- const path = `ops[${i}]`;
243
- if (!allowedOps.includes(op.op)) {
244
- throw new Error(`${path}: op "${op.op}" not in allowed list [${allowedOps.join(", ")}]`);
245
- }
246
- switch (op.op) {
247
- case "insert-node":
248
- if (!allowedSlots.includes(op.slotId)) {
249
- throw new Error(`${path}: slotId "${op.slotId}" not in allowed slots [${allowedSlots.join(", ")}]`);
250
- }
251
- if (op.node) {
252
- validateSurfaceNodeAgainstKinds(op.node, allowedNodeKinds, `${path}.node`);
253
- }
254
- break;
255
- case "move-node":
256
- if (!allowedSlots.includes(op.toSlotId)) {
257
- throw new Error(`${path}: toSlotId "${op.toSlotId}" not in allowed slots [${allowedSlots.join(", ")}]`);
258
- }
259
- break;
260
- case "replace-node":
261
- if (op.node) {
262
- validateSurfaceNodeAgainstKinds(op.node, allowedNodeKinds, `${path}.node`);
263
- }
264
- break;
265
- default:
266
- break;
267
- }
268
- }
269
- validateSurfacePatch(ops);
270
- }
271
-
272
- // src/runtime/apply-surface-patch.ts
273
- import { Logger } from "@contractspec/lib.observability";
274
- var logger = new Logger("@contractspec/lib.surface-runtime");
275
- function findNode(nodes, nodeId) {
276
- for (const n of nodes) {
277
- if (n.nodeId === nodeId)
278
- return n;
279
- if (n.children) {
280
- const found = findNode(n.children, nodeId);
281
- if (found)
282
- return found;
283
- }
284
- }
285
- return;
286
- }
287
- function collectNodeIds(nodes) {
288
- const ids = new Set;
289
- for (const n of nodes) {
290
- ids.add(n.nodeId);
291
- if (n.children)
292
- collectNodeIds(n.children).forEach((id) => ids.add(id));
293
- }
294
- return ids;
295
- }
296
- function validateOp(op, nodeIds) {
297
- if (op.op === "remove-node" || op.op === "replace-node" || op.op === "move-node") {
298
- if (!nodeIds.has(op.nodeId)) {
299
- throw new Error(`Patch op references unknown nodeId: ${op.nodeId}`);
300
- }
301
- }
302
- if (op.op === "insert-node" && !op.node?.nodeId) {
303
- throw new Error("insert-node requires node with nodeId");
304
- }
305
- }
306
- function produceInverse(op, plan) {
307
- switch (op.op) {
308
- case "insert-node":
309
- return op.node ? { op: "remove-node", nodeId: op.node.nodeId } : null;
310
- case "remove-node": {
311
- const node = findNode(plan.nodes, op.nodeId);
312
- return node ? { op: "insert-node", slotId: "primary", node } : null;
313
- }
314
- case "replace-node": {
315
- const prev = findNode(plan.nodes, op.nodeId);
316
- return prev ? { op: "replace-node", nodeId: op.nodeId, node: prev } : null;
317
- }
318
- case "set-layout":
319
- return { op: "set-layout", layoutId: plan.layoutId };
320
- case "reveal-field":
321
- return { op: "hide-field", fieldId: op.fieldId };
322
- case "hide-field":
323
- return { op: "reveal-field", fieldId: op.fieldId };
324
- case "move-node":
325
- case "resize-panel":
326
- case "set-focus":
327
- case "promote-action":
328
- return null;
329
- default:
330
- return null;
331
- }
332
- }
333
- function applySurfacePatch(plan, ops) {
334
- if (ops.length === 0)
335
- return { plan, inverseOps: [] };
336
- validateSurfacePatch(ops);
337
- const nodeIds = collectNodeIds(plan.nodes);
338
- for (const op of ops) {
339
- validateOp(op, nodeIds);
340
- }
341
- let nextNodes = [...plan.nodes];
342
- let nextLayoutId = plan.layoutId;
343
- const inverseOps = [];
344
- for (const op of ops) {
345
- const inv = produceInverse(op, {
346
- ...plan,
347
- nodes: nextNodes,
348
- layoutId: nextLayoutId
349
- });
350
- if (inv)
351
- inverseOps.unshift(inv);
352
- switch (op.op) {
353
- case "insert-node":
354
- if (op.node)
355
- nextNodes = [...nextNodes, op.node];
356
- break;
357
- case "remove-node":
358
- nextNodes = nextNodes.filter((n) => n.nodeId !== op.nodeId);
359
- break;
360
- case "replace-node": {
361
- const replace = (nodes) => nodes.map((n) => n.nodeId === op.nodeId ? op.node : { ...n, children: n.children ? replace(n.children) : undefined });
362
- nextNodes = replace(nextNodes);
363
- break;
364
- }
365
- case "set-layout":
366
- nextLayoutId = op.layoutId;
367
- break;
368
- case "move-node":
369
- case "resize-panel":
370
- case "set-focus":
371
- case "reveal-field":
372
- case "hide-field":
373
- case "promote-action":
374
- break;
375
- }
376
- }
377
- const result = {
378
- plan: { ...plan, nodes: nextNodes, layoutId: nextLayoutId },
379
- inverseOps
380
- };
381
- logger.info("bundle.surface.patch.applied", {
382
- bundleKey: plan.bundleKey,
383
- surfaceId: plan.surfaceId,
384
- opCount: ops.length,
385
- opTypes: [...new Set(ops.map((o) => o.op))]
386
- });
387
- return result;
388
- }
389
-
390
- // src/runtime/override-store.ts
391
- function buildOverrideTargetKey(bundleKey, surfaceId, routeId) {
392
- return routeId ? `${bundleKey}:${routeId}:${surfaceId}` : `${bundleKey}:${surfaceId}`;
393
- }
394
- function createOverrideStoreWithApprovalGate(store, options) {
395
- const { requireApprovalForWorkspacePatches = false, requestApproval } = options;
396
- return {
397
- list: store.list.bind(store),
398
- async save(scope, targetKey, patch, saveOptions) {
399
- if (requireApprovalForWorkspacePatches && scope === "workspace" && requestApproval) {
400
- const approved = await requestApproval({ scope, targetKey, patch });
401
- if (!approved) {
402
- throw new Error("Workspace overlay save rejected: approval required and not granted");
403
- }
404
- }
405
- return store.save(scope, targetKey, patch, saveOptions);
406
- },
407
- remove: store.remove.bind(store)
408
- };
409
- }
410
- function createInMemoryOverrideStore() {
411
- const overrides = new Map;
412
- function nextId() {
413
- return `ov_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
414
- }
415
- return {
416
- async list(scope, targetKey) {
417
- return Array.from(overrides.values()).filter((o) => o.scope === scope && o.targetKey === targetKey);
418
- },
419
- async save(scope, targetKey, patch, options) {
420
- const overrideId = options?.overrideId ?? nextId();
421
- const stored = {
422
- overrideId,
423
- scope,
424
- targetKey,
425
- patch,
426
- createdAt: new Date().toISOString(),
427
- createdBy: options?.createdBy
428
- };
429
- overrides.set(overrideId, stored);
430
- return overrideId;
431
- },
432
- async remove(overrideId) {
433
- overrides.delete(overrideId);
434
- }
435
- };
436
- }
437
-
438
- // src/runtime/resolve-bundle.ts
439
- import { traceAsync } from "@contractspec/lib.observability/tracing";
440
- import { Logger as Logger2 } from "@contractspec/lib.observability";
441
- var logger2 = new Logger2("@contractspec/lib.surface-runtime");
442
- function getOpTarget(op) {
443
- switch (op.op) {
444
- case "hide-field":
445
- case "reveal-field":
446
- return `field:${op.fieldId}`;
447
- case "remove-node":
448
- case "replace-node":
449
- case "move-node":
450
- return `node:${op.nodeId}`;
451
- case "insert-node":
452
- return op.slotId ? `slot:${op.slotId}` : null;
453
- default:
454
- return null;
455
- }
456
- }
457
- function matchRoute(pathPattern, route) {
458
- if (pathPattern === route)
459
- return true;
460
- const patternParts = pathPattern.split("/");
461
- const routeParts = route.split("/");
462
- if (patternParts.length !== routeParts.length)
463
- return false;
464
- for (let i = 0;i < patternParts.length; i++) {
465
- const p = patternParts[i];
466
- const r = routeParts[i];
467
- if (p?.startsWith(":"))
468
- continue;
469
- if (p !== r)
470
- return false;
471
- }
472
- return true;
473
- }
474
- function selectSurface(spec, ctx) {
475
- const route = spec.routes.find((r) => matchRoute(r.path, ctx.route)) ?? spec.routes[0];
476
- if (!route) {
477
- throw new Error("No routes declared in bundle spec.");
478
- }
479
- const fallbackRoute = !spec.routes.find((r) => matchRoute(r.path, ctx.route));
480
- let surface = spec.surfaces[route.defaultSurface];
481
- let fallback;
482
- if (!surface && route.candidateSurfaces?.length) {
483
- for (const sid of route.candidateSurfaces) {
484
- surface = spec.surfaces[sid];
485
- if (surface) {
486
- fallback = `surface=${sid}`;
487
- break;
488
- }
489
- }
490
- }
491
- if (!surface) {
492
- const overview = Object.values(spec.surfaces).find((s) => s.kind === "overview");
493
- if (overview) {
494
- surface = overview;
495
- fallback = "surface=overview";
496
- }
497
- }
498
- if (!surface) {
499
- throw new Error(`Default surface "${route.defaultSurface}" was not found.`);
500
- }
501
- return {
502
- surface,
503
- routeId: route.routeId,
504
- fallback: fallback ?? (fallbackRoute ? "route" : undefined)
505
- };
506
- }
507
- function selectLayout(surface, ctx, spec) {
508
- let preferredLayoutId;
509
- if (ctx.activeViewId && ctx.entity?.type && spec?.entities?.viewKinds) {
510
- const viewKind = spec.entities.viewKinds[ctx.activeViewId];
511
- const entityType = spec.entities.entityTypes[ctx.entity.type];
512
- if (viewKind?.defaultLayoutId && entityType?.supportedViews?.includes(ctx.activeViewId)) {
513
- preferredLayoutId = viewKind.defaultLayoutId;
514
- }
515
- }
516
- const matching = surface.layouts.filter((candidate) => candidate.when?.(ctx) ?? true);
517
- let layout;
518
- if (preferredLayoutId) {
519
- layout = matching.find((l) => l.layoutId === preferredLayoutId) ?? surface.layouts.find((l) => l.layoutId === preferredLayoutId) ?? matching[matching.length - 1] ?? surface.layouts[0];
520
- } else {
521
- layout = matching[matching.length - 1] ?? surface.layouts[0];
522
- }
523
- if (!layout) {
524
- throw new Error(`Surface "${surface.surfaceId}" has no layouts.`);
525
- }
526
- const layoutFallback = matching.length === 0 && surface.layouts.length > 0;
527
- return { layout, layoutFallback: layoutFallback || undefined };
528
- }
529
- function resolveDataRecipes(recipes, ctx) {
530
- const bindings = {};
531
- for (const r of recipes) {
532
- if (r.when?.(ctx) ?? true) {
533
- const key = r.hydrateInto ?? r.recipeId;
534
- bindings[key] = { recipeId: r.recipeId, source: r.source, _stub: true };
535
- }
536
- }
537
- return bindings;
538
- }
539
- function allowFromDecision(decision) {
540
- if (!decision)
541
- return true;
542
- return decision.effect === "allow" || decision.effect === "allow-session-only";
543
- }
544
- function generateResolutionId() {
545
- return `res_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
546
- }
547
- var OVERLAY_SCOPE_ORDER = [
548
- "system",
549
- "workspace",
550
- "team",
551
- "user",
552
- "session"
553
- ];
554
- function buildAdaptation(ctx) {
555
- const profile = resolvePreferenceProfile(ctx);
556
- const notes = [...profile.notes];
557
- const constrainedEntries = Object.entries(profile.constrained);
558
- if (constrainedEntries.length > 0) {
559
- notes.push(`constrained: ${constrainedEntries.map(([k, v]) => `${k}=${v}`).join(", ")}`);
560
- }
561
- return {
562
- appliedDimensions: profile.canonical,
563
- notes
564
- };
565
- }
566
- async function resolveBundle(spec, ctx, options) {
567
- return traceAsync("surface.resolveBundle", async (span) => {
568
- const start = performance.now();
569
- try {
570
- const plan = await resolveBundleInternal(spec, ctx, options);
571
- const durationMs = performance.now() - start;
572
- resolutionDurationMs.record(durationMs, {
573
- bundleKey: spec.meta.key,
574
- surfaceId: plan.surfaceId,
575
- fallback: plan.surfaceId === "_error" ? "error" : plan.audit.reasons.some((r) => r.startsWith("fallback=")) ? "yes" : "no"
576
- });
577
- span.setAttribute("bundle.key", spec.meta.key);
578
- span.setAttribute("surface.id", plan.surfaceId);
579
- span.setAttribute("resolution.duration_ms", durationMs);
580
- logger2.info("bundle.surface.resolved", {
581
- bundleKey: spec.meta.key,
582
- surfaceId: plan.surfaceId,
583
- layoutId: plan.layoutId,
584
- resolutionMs: Math.round(durationMs),
585
- fallback: plan.audit.reasons.some((r) => r.startsWith("fallback=")),
586
- nodeCount: plan.nodes.length
587
- });
588
- return plan;
589
- } catch (err) {
590
- const durationMs = performance.now() - start;
591
- resolutionDurationMs.record(durationMs, {
592
- bundleKey: spec.meta.key,
593
- surfaceId: "_error",
594
- fallback: "error"
595
- });
596
- return createErrorPlan(spec, ctx, err);
597
- }
598
- }, "@contractspec/lib.surface-runtime");
599
- }
600
- async function resolveBundleInternal(spec, ctx, options) {
601
- const {
602
- surface,
603
- routeId,
604
- fallback: surfaceFallback
605
- } = selectSurface(spec, ctx);
606
- const { layout, layoutFallback } = selectLayout(surface, ctx, spec);
607
- let bindings = resolveDataRecipes(surface.data, ctx);
608
- const redactBinding = options?.policy?.redactBinding;
609
- if (redactBinding) {
610
- const redacted = {};
611
- for (const [k, v] of Object.entries(bindings)) {
612
- redacted[k] = redactBinding(k, ctx) ?? v;
613
- }
614
- bindings = redacted;
615
- }
616
- let nodes = [];
617
- const evaluateNode = options?.policy?.evaluateNode;
618
- if (evaluateNode) {
619
- nodes = nodes.filter((n) => allowFromDecision(evaluateNode(n, ctx)));
620
- }
621
- const reasons = [
622
- `surface=${surface.surfaceId}`,
623
- `layout=${layout.layoutId}`,
624
- `density=${ctx.preferences.density}`,
625
- `narrative=${ctx.preferences.narrative}`
626
- ];
627
- if (surfaceFallback) {
628
- reasons.push(`fallback=${surfaceFallback}`);
629
- surfaceFallbackCounter.add(1, {
630
- bundleKey: spec.meta.key,
631
- type: "surface"
632
- });
633
- }
634
- if (layoutFallback) {
635
- reasons.push("fallback=layout");
636
- surfaceFallbackCounter.add(1, { bundleKey: spec.meta.key, type: "layout" });
637
- }
638
- const resolutionId = generateResolutionId();
639
- const plan = {
640
- bundleKey: spec.meta.key,
641
- surfaceId: surface.surfaceId,
642
- layoutId: layout.layoutId,
643
- layoutRoot: layout.root,
644
- nodes,
645
- actions: surface.actions ?? [],
646
- commands: surface.commands ?? [],
647
- bindings,
648
- adaptation: buildAdaptation(ctx),
649
- overlays: [],
650
- ai: {
651
- plannerId: spec.ai?.plannerId
652
- },
653
- audit: {
654
- resolutionId,
655
- createdAt: new Date().toISOString(),
656
- reasons
657
- },
658
- locale: ctx.locale
659
- };
660
- options?.audit?.emit({
661
- eventId: `evt_${resolutionId}`,
662
- at: new Date().toISOString(),
663
- actorId: ctx.actorId,
664
- source: "system",
665
- bundleKey: spec.meta.key,
666
- surfaceId: surface.surfaceId,
667
- eventType: "surface.resolved",
668
- payload: {
669
- resolutionId,
670
- layoutId: layout.layoutId,
671
- reasons,
672
- nodeCount: nodes.length
673
- }
674
- });
675
- let finalPlan = plan;
676
- if (options?.overlayMerge) {
677
- const { overrideStore, scopes = OVERLAY_SCOPE_ORDER } = options.overlayMerge;
678
- const targetKey = buildOverrideTargetKey(spec.meta.key, surface.surfaceId, routeId);
679
- const appliedOverlays = [];
680
- const conflicts = [];
681
- const seenTargets = new Map;
682
- const conflictKeys = new Set;
683
- for (const scope of scopes) {
684
- if (scope === "session")
685
- continue;
686
- const stored = await overrideStore.list(scope, targetKey);
687
- for (const ov of stored) {
688
- if (ov.patch.length === 0)
689
- continue;
690
- for (const op of ov.patch) {
691
- const opTarget = getOpTarget(op);
692
- if (opTarget) {
693
- const prev = seenTargets.get(opTarget);
694
- if (prev && prev.scope !== scope) {
695
- const ck = [opTarget, prev.scope, scope].sort().join(":");
696
- if (!conflictKeys.has(ck)) {
697
- conflictKeys.add(ck);
698
- conflicts.push({
699
- targetKey: opTarget,
700
- scopeA: prev.scope,
701
- scopeB: scope,
702
- overlayIdA: prev.overlayId,
703
- overlayIdB: ov.overrideId
704
- });
705
- }
706
- }
707
- seenTargets.set(opTarget, { scope, overlayId: ov.overrideId });
708
- }
709
- }
710
- try {
711
- const { plan: next } = applySurfacePatch(finalPlan, ov.patch);
712
- finalPlan = next;
713
- appliedOverlays.push({
714
- overlayId: ov.overrideId,
715
- scope,
716
- appliedOps: ov.patch.length
717
- });
718
- } catch (err) {
719
- logger2.warn("bundle.overlay.apply.failed", {
720
- overlayId: ov.overrideId,
721
- scope,
722
- error: err instanceof Error ? err.message : String(err)
723
- });
724
- }
725
- }
726
- }
727
- finalPlan = {
728
- ...finalPlan,
729
- overlays: appliedOverlays,
730
- overlayConflicts: conflicts.length > 0 ? conflicts : undefined
731
- };
732
- }
733
- return finalPlan;
734
- }
735
- function createErrorPlan(spec, ctx, err) {
736
- const message = err instanceof Error ? err.message : String(err);
737
- const errorLayoutRoot = {
738
- type: "stack",
739
- direction: "vertical",
740
- children: [{ type: "slot", slotId: "primary" }]
741
- };
742
- return {
743
- bundleKey: spec.meta.key,
744
- surfaceId: "_error",
745
- layoutId: "_error",
746
- layoutRoot: errorLayoutRoot,
747
- nodes: [],
748
- actions: [],
749
- commands: [],
750
- bindings: {},
751
- adaptation: {
752
- appliedDimensions: ctx.preferences,
753
- notes: [`resolution failed: ${message}`]
754
- },
755
- overlays: [],
756
- ai: {},
757
- audit: {
758
- resolutionId: generateResolutionId(),
759
- createdAt: new Date().toISOString(),
760
- reasons: ["fallback=error", `error=${message}`]
761
- },
762
- locale: ctx.locale
763
- };
764
- }
765
-
766
- // src/runtime/build-context.ts
767
- var DEFAULT_PREFERENCES = {
768
- guidance: "hints",
769
- density: "standard",
770
- dataDepth: "detailed",
771
- control: "standard",
772
- media: "text",
773
- pace: "balanced",
774
- narrative: "top-down"
775
- };
776
- function buildContext(params) {
777
- const {
778
- route,
779
- params: routeParams = {},
780
- query = {},
781
- tenantId = "default",
782
- workspaceId,
783
- actorId,
784
- device = "desktop",
785
- preferences: partialPrefs = {},
786
- capabilities = [],
787
- featureFlags = [],
788
- mode,
789
- locale,
790
- timezone,
791
- entity,
792
- conversation,
793
- activeViewId
794
- } = params;
795
- const preferences = {
796
- ...DEFAULT_PREFERENCES,
797
- ...partialPrefs
798
- };
799
- return {
800
- tenantId,
801
- workspaceId,
802
- actorId,
803
- route,
804
- params: routeParams,
805
- query,
806
- device,
807
- mode,
808
- locale,
809
- timezone,
810
- entity,
811
- conversation,
812
- activeViewId,
813
- preferences,
814
- capabilities,
815
- featureFlags
816
- };
817
- }
818
-
819
- // src/runtime/preference-adapter.ts
820
- var defaultPreferenceAdapter = {
821
- async resolve(ctx) {
822
- return resolvePreferenceProfile(ctx);
823
- },
824
- async savePreferencePatch(_args) {}
825
- };
826
-
827
- // src/runtime/planner-prompt.ts
828
- var SAFETY_INSTRUCTIONS = `
829
- ## Safety instructions (mandatory)
830
- - Do NOT emit JSX, HTML, or raw markup.
831
- - Do NOT invent node kinds; use only the allowed kinds listed above.
832
- - Do NOT call undeclared tools.
833
- - Prefer fewer high-confidence patches over many speculative ones.
834
- - Explain why a patch helps the user.
835
- `;
836
- function compilePlannerPrompt(input) {
837
- const {
838
- bundleMeta,
839
- surfaceId,
840
- allowedPatchOps,
841
- allowedSlots,
842
- allowedNodeKinds,
843
- actions,
844
- preferences,
845
- basePrompt,
846
- planSummary,
847
- entity
848
- } = input;
849
- const parts = [];
850
- parts.push(`# Bundle: ${bundleMeta.title} (${bundleMeta.key}@${bundleMeta.version})`);
851
- parts.push(`# Surface: ${surfaceId}`);
852
- parts.push("");
853
- if (basePrompt) {
854
- parts.push("## Base instructions");
855
- parts.push(basePrompt);
856
- parts.push("");
857
- }
858
- parts.push("## Allowed patch operations");
859
- parts.push(allowedPatchOps.join(", "));
860
- parts.push("");
861
- parts.push("## Allowed slots");
862
- parts.push(allowedSlots.join(", "));
863
- parts.push("");
864
- parts.push("## Allowed node kinds");
865
- parts.push(allowedNodeKinds.join(", "));
866
- parts.push("");
867
- if (actions.length > 0) {
868
- parts.push("## Visible actions");
869
- for (const a of actions) {
870
- parts.push(`- ${a.actionId}: ${a.title}`);
871
- }
872
- parts.push("");
873
- }
874
- parts.push("## Current preference profile");
875
- parts.push(`guidance=${preferences.guidance}, density=${preferences.density}, ` + `dataDepth=${preferences.dataDepth}, control=${preferences.control}, ` + `media=${preferences.media}, pace=${preferences.pace}, narrative=${preferences.narrative}`);
876
- parts.push("");
877
- if (planSummary) {
878
- parts.push("## Current plan summary");
879
- parts.push(planSummary);
880
- parts.push("");
881
- }
882
- if (entity) {
883
- parts.push("## Entity context");
884
- parts.push(`${entity.type}: ${entity.id}`);
885
- parts.push("");
886
- }
887
- parts.push(SAFETY_INSTRUCTIONS.trim());
888
- return parts.join(`
889
- `);
890
- }
891
-
892
- // src/runtime/planner-tools.ts
893
- var PROPOSE_PATCH_TOOL_SCHEMA = {
894
- type: "object",
895
- properties: {
896
- proposalId: { type: "string", description: "Unique proposal identifier" },
897
- ops: {
898
- type: "array",
899
- description: "Surface patch operations to propose",
900
- items: {
901
- type: "object",
902
- required: ["op"],
903
- properties: {
904
- op: {
905
- type: "string",
906
- enum: [
907
- "insert-node",
908
- "replace-node",
909
- "remove-node",
910
- "move-node",
911
- "resize-panel",
912
- "set-layout",
913
- "reveal-field",
914
- "hide-field",
915
- "promote-action",
916
- "set-focus"
917
- ]
918
- },
919
- slotId: { type: "string" },
920
- nodeId: { type: "string" },
921
- toSlotId: { type: "string" },
922
- index: { type: "number" },
923
- node: {
924
- type: "object",
925
- properties: {
926
- nodeId: { type: "string" },
927
- kind: { type: "string" },
928
- title: { type: "string" },
929
- props: { type: "object" },
930
- children: { type: "array" }
931
- }
932
- },
933
- persistKey: { type: "string" },
934
- sizes: { type: "array", items: { type: "number" } },
935
- layoutId: { type: "string" },
936
- fieldId: { type: "string" },
937
- actionId: { type: "string" },
938
- placement: {
939
- type: "string",
940
- enum: ["header", "inline", "context", "assistant"]
941
- },
942
- targetId: { type: "string" }
943
- }
944
- }
945
- }
946
- },
947
- required: ["proposalId", "ops"]
948
- };
949
- var proposePatchToolConfig = {
950
- name: "propose-patch",
951
- description: "Propose surface patches (layout changes, node insertions, etc.) for user approval. " + "Only use allowed ops, slots, and node kinds from the planner context.",
952
- schema: PROPOSE_PATCH_TOOL_SCHEMA,
953
- automationSafe: false,
954
- requiresApproval: true
955
- };
956
- function buildSurfacePatchProposal(proposalId, ops) {
957
- return {
958
- proposalId,
959
- source: "assistant",
960
- ops,
961
- approvalState: "proposed"
962
- };
963
- }
964
-
965
- // src/runtime/field-renderer-registry.ts
966
- var FALLBACK_FIELD_KIND = "text";
967
- var CORE_FIELD_KINDS = {
968
- text: {
969
- fieldKind: "text",
970
- viewer: "text-viewer",
971
- editor: "text-editor",
972
- summaryViewer: "text-summary",
973
- tableCell: "text-cell",
974
- filters: ["contains", "equals", "startsWith", "endsWith"],
975
- validators: ["required", "maxLength", "regex"]
976
- },
977
- number: {
978
- fieldKind: "number",
979
- viewer: "number-viewer",
980
- editor: "number-editor",
981
- summaryViewer: "number-summary",
982
- tableCell: "number-cell",
983
- filters: ["equals", "gt", "gte", "lt", "lte", "between"],
984
- validators: ["required", "min", "max", "integer"]
985
- },
986
- date: {
987
- fieldKind: "date",
988
- viewer: "date-viewer",
989
- editor: "date-editor",
990
- summaryViewer: "date-summary",
991
- tableCell: "date-cell",
992
- filters: ["equals", "before", "after", "between"],
993
- validators: ["required", "min", "max"]
994
- },
995
- select: {
996
- fieldKind: "select",
997
- viewer: "select-viewer",
998
- editor: "select-editor",
999
- summaryViewer: "select-summary",
1000
- tableCell: "select-cell",
1001
- filters: ["equals", "in"],
1002
- validators: ["required", "oneOf"]
1003
- },
1004
- checkbox: {
1005
- fieldKind: "checkbox",
1006
- viewer: "checkbox-viewer",
1007
- editor: "checkbox-editor",
1008
- summaryViewer: "checkbox-summary",
1009
- tableCell: "checkbox-cell",
1010
- filters: ["equals"],
1011
- validators: ["required"]
1012
- }
1013
- };
1014
- var STUB_FIELD_KINDS = {
1015
- relation: {
1016
- fieldKind: "relation",
1017
- viewer: "relation-viewer-stub",
1018
- summaryViewer: "relation-chip-stub",
1019
- tableCell: "relation-chip-stub"
1020
- },
1021
- rollup: {
1022
- fieldKind: "rollup",
1023
- viewer: "rollup-viewer-stub",
1024
- summaryViewer: "rollup-chip-stub",
1025
- tableCell: "rollup-cell-stub"
1026
- },
1027
- formula: {
1028
- fieldKind: "formula",
1029
- viewer: "formula-viewer-stub",
1030
- summaryViewer: "formula-summary-stub",
1031
- tableCell: "formula-cell-stub"
1032
- },
1033
- people: {
1034
- fieldKind: "people",
1035
- viewer: "people-viewer-stub",
1036
- editor: "people-picker-stub",
1037
- summaryViewer: "people-chip-stub",
1038
- tableCell: "people-cell-stub"
1039
- },
1040
- options: {
1041
- fieldKind: "options",
1042
- viewer: "options-viewer-stub",
1043
- editor: "options-editor-stub",
1044
- summaryViewer: "options-chip-stub",
1045
- tableCell: "options-cell-stub"
1046
- },
1047
- instance: {
1048
- fieldKind: "instance",
1049
- viewer: "instance-viewer-stub",
1050
- summaryViewer: "instance-chip-stub",
1051
- tableCell: "instance-cell-stub"
1052
- },
1053
- url: {
1054
- fieldKind: "url",
1055
- viewer: "url-viewer",
1056
- editor: "url-editor",
1057
- summaryViewer: "url-summary",
1058
- tableCell: "url-cell",
1059
- validators: ["required", "regex"]
1060
- }
1061
- };
1062
- function createFieldRendererRegistry() {
1063
- const all = { ...CORE_FIELD_KINDS, ...STUB_FIELD_KINDS };
1064
- const fallback = CORE_FIELD_KINDS[FALLBACK_FIELD_KIND];
1065
- if (!fallback) {
1066
- throw new Error(`Fallback field kind "${FALLBACK_FIELD_KIND}" not found`);
1067
- }
1068
- return {
1069
- get(kind) {
1070
- return all[kind];
1071
- },
1072
- has(kind) {
1073
- return kind in all;
1074
- },
1075
- getOrFallback(kind) {
1076
- return all[kind] ?? fallback;
1077
- }
1078
- };
1079
- }
1080
- function createMutableFieldRendererRegistry() {
1081
- const base = { ...CORE_FIELD_KINDS, ...STUB_FIELD_KINDS };
1082
- const custom = new Map;
1083
- const fallback = CORE_FIELD_KINDS[FALLBACK_FIELD_KIND];
1084
- if (!fallback) {
1085
- throw new Error(`Fallback field kind "${FALLBACK_FIELD_KIND}" not found`);
1086
- }
1087
- return {
1088
- get(kind) {
1089
- return custom.get(kind) ?? base[kind];
1090
- },
1091
- has(kind) {
1092
- return custom.has(kind) || kind in base;
1093
- },
1094
- getOrFallback(kind) {
1095
- return custom.get(kind) ?? base[kind] ?? fallback;
1096
- },
1097
- registerFieldRenderer(kind, entry) {
1098
- if (entry.fieldKind !== kind) {
1099
- throw new Error(`Field renderer entry fieldKind "${entry.fieldKind}" must match kind "${kind}"`);
1100
- }
1101
- custom.set(kind, entry);
1102
- }
1103
- };
1104
- }
1105
-
1106
- // src/runtime/widget-registry.ts
1107
- function validateTrust(trust) {
1108
- if (trust === "ephemeral-ai") {
1109
- throw new Error("Widgets cannot be registered with ephemeral-ai trust. Registration is a code/package concern.");
1110
- }
1111
- if (trust !== "core" && trust !== "workspace" && trust !== "signed-plugin") {
1112
- throw new Error(`Invalid widget trust: ${trust}`);
1113
- }
1114
- }
1115
- function createWidgetRegistry() {
1116
- const entries = new Map;
1117
- return {
1118
- register(entry) {
1119
- validateTrust(entry.trust);
1120
- if (entry.nodeKind !== "custom-widget") {
1121
- throw new Error(`Widget "${entry.widgetKey}" must have nodeKind "custom-widget"`);
1122
- }
1123
- entries.set(entry.widgetKey, entry);
1124
- },
1125
- get(widgetKey) {
1126
- return entries.get(widgetKey);
1127
- },
1128
- has(widgetKey) {
1129
- return entries.has(widgetKey);
1130
- },
1131
- list() {
1132
- return Array.from(entries.values());
1133
- },
1134
- listByTrust(trust) {
1135
- return Array.from(entries.values()).filter((e) => e.trust === trust);
1136
- }
1137
- };
1138
- }
1139
-
1140
- // src/runtime/extension-registry.ts
1141
- function createActionRegistry() {
1142
- const entries = new Map;
1143
- return {
1144
- register(entry) {
1145
- entries.set(entry.actionId, entry);
1146
- },
1147
- get(actionId) {
1148
- return entries.get(actionId);
1149
- },
1150
- has(actionId) {
1151
- return entries.has(actionId);
1152
- },
1153
- list() {
1154
- return Array.from(entries.values());
1155
- }
1156
- };
1157
- }
1158
- function createCommandRegistry() {
1159
- const entries = new Map;
1160
- return {
1161
- register(entry) {
1162
- entries.set(entry.commandId, entry);
1163
- },
1164
- get(commandId) {
1165
- return entries.get(commandId);
1166
- },
1167
- has(commandId) {
1168
- return entries.has(commandId);
1169
- },
1170
- list() {
1171
- return Array.from(entries.values());
1172
- }
1173
- };
1174
- }
1175
- function createBundleExtensionRegistry(options) {
1176
- const actionRegistry = options.actionRegistry ?? createActionRegistry();
1177
- const commandRegistry = options.commandRegistry ?? createCommandRegistry();
1178
- return {
1179
- registerWidget(entry) {
1180
- options.widgetRegistry.register(entry);
1181
- },
1182
- registerFieldRenderer(kind, entry) {
1183
- options.fieldRendererRegistry.registerFieldRenderer(kind, entry);
1184
- },
1185
- registerAction(entry) {
1186
- actionRegistry.register(entry);
1187
- },
1188
- registerCommand(entry) {
1189
- commandRegistry.register(entry);
1190
- }
1191
- };
1192
- }
1193
-
1194
- // src/runtime/overlay-alignment.ts
1195
- import { applyOverlayModifications } from "@contractspec/lib.overlay-engine/merger";
1196
- function toOverlayScopeContext(ctx) {
1197
- return {
1198
- tenantId: ctx.tenantId,
1199
- userId: ctx.actorId,
1200
- device: ctx.device,
1201
- tags: ctx.featureFlags
1202
- };
1203
- }
1204
- function toOverlayTargetRef(_ctx, target) {
1205
- return {
1206
- presentation: target.surfaceId ?? target.routeId,
1207
- bundleKey: target.bundleKey,
1208
- surfaceId: target.surfaceId,
1209
- routeId: target.routeId,
1210
- entityType: target.entityType
1211
- };
1212
- }
1213
- function toOverlayAppliesTo(ctx, target, scope) {
1214
- const scopeCtx = toOverlayScopeContext(ctx);
1215
- return {
1216
- ...scopeCtx,
1217
- ...target,
1218
- ...scope === "user" && ctx.actorId ? { userId: ctx.actorId } : {},
1219
- ...scope === "workspace" && ctx.workspaceId ? { tags: [...scopeCtx.tags ?? [], `workspace:${ctx.workspaceId}`] } : {}
1220
- };
1221
- }
1222
- function toOverlayRenderableField(field) {
1223
- return {
1224
- key: field.fieldId,
1225
- label: field.title,
1226
- visible: field.visible,
1227
- required: field.required,
1228
- order: 0
1229
- };
1230
- }
1231
- function fromOverlayRenderableField(overlay) {
1232
- return {
1233
- fieldId: overlay.key,
1234
- title: overlay.label ?? overlay.key,
1235
- visible: overlay.visible ?? true,
1236
- required: overlay.required ?? false
1237
- };
1238
- }
1239
- function toOverlayRenderable(fields) {
1240
- return {
1241
- fields: fields.map(toOverlayRenderableField)
1242
- };
1243
- }
1244
- function mergeOverlayResultIntoFields(fields, merged) {
1245
- const fieldMap = new Map(fields.map((f) => [f.fieldId, { ...f }]));
1246
- const result = [];
1247
- for (const overlay of merged.fields) {
1248
- const existing = fieldMap.get(overlay.key);
1249
- if (existing) {
1250
- result.push({
1251
- ...existing,
1252
- title: overlay.label ?? existing.title,
1253
- visible: overlay.visible ?? existing.visible,
1254
- required: overlay.required ?? existing.required
1255
- });
1256
- }
1257
- }
1258
- return result;
1259
- }
1260
- function applyEntityFieldOverlays(fields, overlays, options) {
1261
- if (!overlays.length)
1262
- return fields;
1263
- const target = toOverlayRenderable(fields);
1264
- const merged = applyOverlayModifications(target, overlays, options);
1265
- return mergeOverlayResultIntoFields(fields, merged);
1266
- }
1267
-
1268
- // src/runtime/overlay-signer.ts
1269
- import {
1270
- signOverlay,
1271
- verifyOverlaySignature
1272
- } from "@contractspec/lib.overlay-engine/signer";
1273
- function signWorkspaceOverlay(spec, privateKey, options) {
1274
- return signOverlay(spec, privateKey, options);
1275
- }
1276
- function verifyWorkspaceOverlay(overlay) {
1277
- return verifyOverlaySignature(overlay);
1278
- }
1279
-
1280
- // src/runtime/audit-events.ts
1281
- function generateEventId() {
1282
- return `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
1283
- }
1284
- function emitPatchProposed(audit, args) {
1285
- audit.emit({
1286
- eventId: generateEventId(),
1287
- at: new Date().toISOString(),
1288
- actorId: args.actorId,
1289
- source: args.proposal.source === "assistant" ? "assistant" : "user",
1290
- bundleKey: args.bundleKey,
1291
- surfaceId: args.surfaceId,
1292
- eventType: "patch.proposed",
1293
- payload: {
1294
- proposalId: args.proposal.proposalId,
1295
- source: args.proposal.source,
1296
- opsCount: args.proposal.ops.length
1297
- }
1298
- });
1299
- }
1300
- function emitPatchApproved(audit, args) {
1301
- audit.emit({
1302
- eventId: generateEventId(),
1303
- at: new Date().toISOString(),
1304
- actorId: args.actorId,
1305
- source: "user",
1306
- bundleKey: args.bundleKey,
1307
- surfaceId: args.surfaceId,
1308
- eventType: "patch.approved",
1309
- payload: {
1310
- proposalId: args.proposalId,
1311
- source: args.source,
1312
- opsCount: args.opsCount,
1313
- reason: args.reason
1314
- }
1315
- });
1316
- }
1317
- function emitPatchRejected(audit, args) {
1318
- audit.emit({
1319
- eventId: generateEventId(),
1320
- at: new Date().toISOString(),
1321
- actorId: args.actorId,
1322
- source: "user",
1323
- bundleKey: args.bundleKey,
1324
- surfaceId: args.surfaceId,
1325
- eventType: "patch.rejected",
1326
- payload: {
1327
- proposalId: args.proposalId,
1328
- source: args.source,
1329
- opsCount: args.opsCount,
1330
- reason: args.reason
1331
- }
1332
- });
1333
- }
1334
- function emitOverlaySaved(audit, args) {
1335
- audit.emit({
1336
- eventId: generateEventId(),
1337
- at: new Date().toISOString(),
1338
- actorId: args.actorId,
1339
- source: "user",
1340
- bundleKey: args.bundleKey,
1341
- eventType: "overlay.saved",
1342
- payload: {
1343
- overlayId: args.overlayId,
1344
- scope: args.scope,
1345
- opsCount: args.opsCount
1346
- }
1347
- });
1348
- }
1349
- function emitOverlayApplied(audit, args) {
1350
- audit.emit({
1351
- eventId: generateEventId(),
1352
- at: new Date().toISOString(),
1353
- source: "system",
1354
- bundleKey: args.bundleKey,
1355
- surfaceId: args.surfaceId,
1356
- eventType: "overlay.applied",
1357
- payload: {
1358
- overlayId: args.overlayId,
1359
- opsCount: args.opsCount
1360
- }
1361
- });
1362
- }
1363
- function emitOverlayFailed(audit, args) {
1364
- audit.emit({
1365
- eventId: generateEventId(),
1366
- at: new Date().toISOString(),
1367
- source: "system",
1368
- bundleKey: args.bundleKey,
1369
- surfaceId: args.surfaceId,
1370
- eventType: "overlay.failed",
1371
- payload: {
1372
- overlayId: args.overlayId,
1373
- error: args.error
1374
- }
1375
- });
1376
- }
1377
- function emitPolicyDenied(audit, args) {
1378
- audit.emit({
1379
- eventId: generateEventId(),
1380
- at: new Date().toISOString(),
1381
- actorId: args.actorId,
1382
- source: "policy",
1383
- bundleKey: args.bundleKey,
1384
- surfaceId: args.surfaceId,
1385
- eventType: "policy.denied",
1386
- payload: {
1387
- targetId: args.targetId,
1388
- reason: args.reason
1389
- }
1390
- });
1391
- }
1392
- function emitPolicyRedacted(audit, args) {
1393
- audit.emit({
1394
- eventId: generateEventId(),
1395
- at: new Date().toISOString(),
1396
- actorId: args.actorId,
1397
- source: "policy",
1398
- bundleKey: args.bundleKey,
1399
- surfaceId: args.surfaceId,
1400
- eventType: "policy.redacted",
1401
- payload: {
1402
- targetId: args.targetId,
1403
- redactions: args.redactions
1404
- }
1405
- });
1406
- }
1407
-
1408
- // src/runtime/rollback.ts
1409
- function rollbackSurfacePatches(plan, approvalStack, count = 1) {
1410
- if (count <= 0 || approvalStack.length === 0) {
1411
- return { plan, revertedCount: 0, remainingStack: approvalStack };
1412
- }
1413
- const toRevert = approvalStack.slice(-count);
1414
- const remaining = approvalStack.slice(0, -count);
1415
- const currentPlan = plan;
1416
- const allInverseOps = [];
1417
- for (const meta of toRevert) {
1418
- if (meta.inverseOps.length > 0) {
1419
- allInverseOps.push(...meta.inverseOps);
1420
- }
1421
- }
1422
- if (allInverseOps.length === 0) {
1423
- return { plan, revertedCount: 0, remainingStack: approvalStack };
1424
- }
1425
- const result = applySurfacePatch(currentPlan, allInverseOps);
1426
- return {
1427
- plan: result.plan,
1428
- revertedCount: toRevert.length,
1429
- remainingStack: remaining
1430
- };
1431
- }
1432
-
1433
- // src/runtime/policy-eval.ts
1434
- function evaluatePatchProposalPolicy(ops, ctx, policy) {
1435
- const evaluate = policy?.evaluatePatchProposal;
1436
- if (!evaluate)
1437
- return "allow";
1438
- return evaluate(ops, ctx);
1439
- }
1440
- function evaluateAndEmitPatchPolicy(ops, ctx, args) {
1441
- const effect = evaluatePatchProposalPolicy(ops, ctx, args.policy);
1442
- if (effect === "deny") {
1443
- if (args.audit) {
1444
- emitPolicyDenied(args.audit, {
1445
- bundleKey: args.bundleKey,
1446
- surfaceId: args.surfaceId,
1447
- targetId: args.targetId ?? "patch-proposal",
1448
- reason: "Policy denied patch proposal",
1449
- actorId: ctx.actorId
1450
- });
1451
- }
1452
- return false;
1453
- }
1454
- return true;
1455
- }
1
+ export { buildContext } from "./build-context";
2
+ export { resolvePreferenceProfile } from "./resolve-preferences";
3
+ export { defaultPreferenceAdapter } from "./preference-adapter";
4
+ export {
5
+ resolveBundle
6
+ } from "./resolve-bundle";
7
+ export {
8
+ applySurfacePatch
9
+ } from "./apply-surface-patch";
10
+ export {
11
+ compilePlannerPrompt
12
+ } from "./planner-prompt";
13
+ export {
14
+ proposePatchToolConfig,
15
+ PROPOSE_PATCH_TOOL_SCHEMA,
16
+ buildSurfacePatchProposal
17
+ } from "./planner-tools";
18
+ export {
19
+ createFieldRendererRegistry,
20
+ createMutableFieldRendererRegistry,
21
+ FALLBACK_FIELD_KIND
22
+ } from "./field-renderer-registry";
23
+ export {
24
+ createWidgetRegistry
25
+ } from "./widget-registry";
26
+ export {
27
+ createActionRegistry,
28
+ createCommandRegistry,
29
+ createBundleExtensionRegistry
30
+ } from "./extension-registry";
31
+ export {
32
+ createInMemoryOverrideStore,
33
+ createOverrideStoreWithApprovalGate,
34
+ buildOverrideTargetKey
35
+ } from "./override-store";
1456
36
  export {
1457
- verifyWorkspaceOverlay,
1458
- toOverlayTargetRef,
1459
37
  toOverlayScopeContext,
38
+ toOverlayTargetRef,
1460
39
  toOverlayRenderableField,
40
+ fromOverlayRenderableField,
1461
41
  toOverlayRenderable,
1462
- signWorkspaceOverlay,
1463
- rollbackSurfacePatches,
1464
- resolvePreferenceProfile,
1465
- resolveBundle,
1466
- proposePatchToolConfig,
1467
42
  mergeOverlayResultIntoFields,
1468
- fromOverlayRenderableField,
1469
- evaluatePatchProposalPolicy,
1470
- evaluateAndEmitPatchPolicy,
1471
- emitPolicyRedacted,
1472
- emitPolicyDenied,
1473
- emitPatchRejected,
43
+ applyEntityFieldOverlays
44
+ } from "./overlay-alignment";
45
+ export {
46
+ signWorkspaceOverlay,
47
+ verifyWorkspaceOverlay
48
+ } from "./overlay-signer";
49
+ export {
1474
50
  emitPatchProposed,
1475
51
  emitPatchApproved,
52
+ emitPatchRejected,
1476
53
  emitOverlaySaved,
1477
- emitOverlayFailed,
1478
54
  emitOverlayApplied,
1479
- defaultPreferenceAdapter,
1480
- createWidgetRegistry,
1481
- createOverrideStoreWithApprovalGate,
1482
- createMutableFieldRendererRegistry,
1483
- createInMemoryOverrideStore,
1484
- createFieldRendererRegistry,
1485
- createCommandRegistry,
1486
- createBundleExtensionRegistry,
1487
- createActionRegistry,
1488
- compilePlannerPrompt,
1489
- buildSurfacePatchProposal,
1490
- buildOverrideTargetKey,
1491
- buildContext,
1492
- applySurfacePatch,
1493
- applyEntityFieldOverlays,
1494
- PROPOSE_PATCH_TOOL_SCHEMA,
1495
- FALLBACK_FIELD_KIND
1496
- };
55
+ emitOverlayFailed,
56
+ emitPolicyDenied,
57
+ emitPolicyRedacted
58
+ } from "./audit-events";
59
+ export { rollbackSurfacePatches } from "./rollback";
60
+ export {
61
+ evaluatePatchProposalPolicy,
62
+ evaluateAndEmitPatchPolicy
63
+ } from "./policy-eval";