@adia-ai/a2ui-mcp 0.1.3 → 0.2.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.
@@ -0,0 +1,436 @@
1
+ /**
2
+ * Synthesis tools — chunk-based composition + multi-turn refinement.
3
+ *
4
+ * Extracts the 4 tools that share the LLM bridge + state-cache +
5
+ * issue-reporter + chunk-refiner stack: `compose_from_chunks`,
6
+ * `refine_composition`, `get_state`, `report_issue`.
7
+ *
8
+ * Spec: docs/specs/genui-multiturn-architecture.md (Phase A).
9
+ */
10
+
11
+ import { z } from 'zod';
12
+
13
+ import { composeFromIntent as composeFromChunksImpl } from '../../compose/strategies/zettel/chunk-synthesizer.js';
14
+ import { composeFromPlan, validatePlan } from '../../compose/strategies/zettel/chunk-composer.js';
15
+ import { createAdapter as createLLMAdapter } from '../../compose/llm/llm-bridge.js';
16
+ import {
17
+ getStateCache,
18
+ mintStateId,
19
+ mintNextStateId,
20
+ } from '../../compose/strategies/zettel/state-cache.js';
21
+ import {
22
+ reportIssue as reportIssueImpl,
23
+ autoReport,
24
+ createIssueAccumulator,
25
+ } from '../../compose/strategies/zettel/issue-reporter.js';
26
+ import {
27
+ refineFromIntent,
28
+ applyOps,
29
+ opsToA2UI,
30
+ validateOps,
31
+ } from '../../compose/strategies/zettel/chunk-refiner.js';
32
+
33
+ const stateCache = getStateCache();
34
+
35
+ const ENGINE_VERSION_INFO = {
36
+ mcp: '0.2.0',
37
+ corpus: '0.2.0',
38
+ engine: 'zettel',
39
+ llm_adapter: 'anthropic',
40
+ model: process.env.ANTHROPIC_MODEL || 'claude-opus-4-7',
41
+ };
42
+
43
+ export { stateCache, ENGINE_VERSION_INFO, autoReport, reportIssueImpl };
44
+
45
+ export function registerSynthesisTools(server) {
46
+ server.tool(
47
+ 'compose_from_chunks',
48
+ `Compose a UI page from training chunks — retrieval-first, synthesis-fallback.
49
+
50
+ Mix-and-match composition for intents that don't have a 1:1 chunk match. Workflow:
51
+ 1. Pure-retrieval tier: if \`search_chunks\` returns a strong direct match, return
52
+ that chunk's HTML immediately (no LLM call).
53
+ 2. Synthesis tier: when retrieval is weak, the LLM picks a page-kind chunk and
54
+ binds block/panel chunks to its named slots. Output validated against the
55
+ chunk catalog (slot names exist, bound chunks exist, kinds match).
56
+
57
+ Returns the composed HTML string + a binding plan describing which chunks plug
58
+ where. Useful when the prompt is novel ("dashboard with KPI grid + funnel +
59
+ country list") and no exact chunk has all those parts together — the LLM mixes
60
+ and matches from the corpus.
61
+
62
+ Two-call mode also available via \`plan\` parameter — pass a pre-baked binding
63
+ plan to skip the LLM call and just materialize HTML.`,
64
+ {
65
+ intent: z.string().optional().describe('Natural-language description of what to build (uses LLM synthesis)'),
66
+ plan: z.object({
67
+ page: z.string(),
68
+ slot_bindings: z.record(z.union([z.string(), z.array(z.string())])),
69
+ }).optional().describe('Pre-baked binding plan (skips LLM, materializes directly)'),
70
+ max_attempts: z.number().int().min(1).max(5).default(2).describe('LLM retry budget for synthesis'),
71
+ },
72
+ async ({ intent, plan, max_attempts }) => {
73
+ if (plan) {
74
+ const validation = validatePlan(plan);
75
+ if (!validation.ok) {
76
+ return {
77
+ isError: true,
78
+ content: [{ type: 'text', text: JSON.stringify({ error: 'invalid plan', errors: validation.errors }, null, 2) }],
79
+ };
80
+ }
81
+ const result = composeFromPlan(plan);
82
+ const state_id = mintStateId(intent || plan.page || 'plan', 1);
83
+ stateCache.set(state_id, {
84
+ state_id,
85
+ intent: intent || `(plan) ${plan.page}`,
86
+ plan: result.plan,
87
+ html: result.html,
88
+ source: 'plan',
89
+ ops_history: [],
90
+ parent_state_id: null,
91
+ created_at: new Date().toISOString(),
92
+ });
93
+ return {
94
+ content: [{ type: 'text', text: JSON.stringify({
95
+ state_id,
96
+ html: result.html,
97
+ plan: result.plan,
98
+ warnings: result.warnings,
99
+ source: 'plan',
100
+ }, null, 2) }],
101
+ };
102
+ }
103
+
104
+ if (!intent) {
105
+ return {
106
+ isError: true,
107
+ content: [{ type: 'text', text: JSON.stringify({ error: 'must provide either intent or plan' }, null, 2) }],
108
+ };
109
+ }
110
+
111
+ try {
112
+ const llmAdapter = await createLLMAdapter();
113
+ const result = await composeFromChunksImpl({
114
+ intent,
115
+ llmAdapter,
116
+ maxAttempts: max_attempts,
117
+ });
118
+ const state_id = mintStateId(intent, 1);
119
+ stateCache.set(state_id, {
120
+ state_id,
121
+ intent,
122
+ plan: result.plan,
123
+ html: result.html,
124
+ source: result.source,
125
+ score: result.score,
126
+ ops_history: [],
127
+ parent_state_id: null,
128
+ warnings: result.warnings,
129
+ synthesis: result.synthesis,
130
+ scopeDrift: result.scopeDrift,
131
+ created_at: new Date().toISOString(),
132
+ });
133
+
134
+ // Scope-drift auto-fire: composed HTML envelope exceeded the bound-
135
+ // chunk envelope by > SCOPE_DRIFT_RATIO. Fires a `scope-drift` issue
136
+ // (writes both .json and high-res .md) so post-mortem review can
137
+ // catch the canvas-drift regression class without manual reporting.
138
+ if (result.scopeDrift?.drift) {
139
+ await autoReport(
140
+ 'scope-drift',
141
+ {
142
+ intent,
143
+ state_id,
144
+ scopeDrift: result.scopeDrift,
145
+ tags: ['canvas-drift'],
146
+ trace: 'full',
147
+ },
148
+ { cache: stateCache, versionInfo: ENGINE_VERSION_INFO }
149
+ );
150
+ }
151
+
152
+ return {
153
+ content: [{ type: 'text', text: JSON.stringify({
154
+ state_id,
155
+ html: result.html,
156
+ plan: result.plan,
157
+ source: result.source,
158
+ score: result.score,
159
+ warnings: result.warnings,
160
+ scopeDrift: result.scopeDrift,
161
+ synthesis: result.synthesis ? { attempts: result.synthesis.attempts } : undefined,
162
+ }, null, 2) }],
163
+ };
164
+ } catch (e) {
165
+ return {
166
+ isError: true,
167
+ content: [{ type: 'text', text: JSON.stringify({ error: e.message }, null, 2) }],
168
+ };
169
+ }
170
+ },
171
+ );
172
+
173
+ // ── Multi-turn refinement (Phase A) ─────────────────────────────────
174
+ // Spec: docs/specs/genui-multiturn-architecture.md §3.
175
+
176
+ server.tool(
177
+ 'refine_composition',
178
+ `Refine an existing chunk-composed UI based on a natural-language intent or an explicit op-list.
179
+
180
+ Use when the user wants to modify an *existing* UI. Triggers on "change", "update", "modify", "add to", "remove from", "this", "it", "the X". Requires \`state_id\` from a prior \`compose_from_chunks\` call.
181
+
182
+ Two modes:
183
+ - **Intent-driven** — pass \`intent\`. Engine runs two-pass synthesis (locator pass identifies which slots to modify; modifier pass emits chunk-plan ops). Validator-driven retry on op-validation failure.
184
+ - **Explicit ops** — pass \`ops\` directly. Skips the LLM entirely; engine applies + materializes.
185
+
186
+ Returns a new \`state_id\` (versioned chain from the parent), the A2UI op-list applied, the post-op HTML, and a delta summary. Failed ops are reported in \`ops_failed\` with reasons.
187
+
188
+ For *fresh creation* use \`compose_from_chunks\`, not this tool.`,
189
+ {
190
+ state_id: z.string().describe('State id from a prior compose_from_chunks or refine_composition call'),
191
+ intent: z.string().optional().describe('Natural-language description of what to change (e.g. "add a country list to page-content")'),
192
+ ops: z.array(z.any()).optional().describe('Pre-computed chunk-plan ops to apply directly (skips the LLM)'),
193
+ max_attempts: z.number().int().min(1).max(5).default(2).describe('Validator retry budget for synthesis'),
194
+ },
195
+ async ({ state_id, intent, ops, max_attempts }) => {
196
+ const priorState = stateCache.get(state_id);
197
+ if (!priorState) {
198
+ await autoReport(
199
+ 'cache-miss-on-known-state',
200
+ { state_id, tool: 'refine_composition' },
201
+ { cache: stateCache, versionInfo: ENGINE_VERSION_INFO }
202
+ );
203
+ return {
204
+ isError: true,
205
+ content: [{ type: 'text', text: JSON.stringify({
206
+ error: 'state_id not found in cache',
207
+ hint: 'state cache is in-memory and bounded; re-run compose_from_chunks to mint a fresh state_id',
208
+ state_id,
209
+ }, null, 2) }],
210
+ };
211
+ }
212
+
213
+ if (!intent && !ops) {
214
+ return {
215
+ isError: true,
216
+ content: [{ type: 'text', text: JSON.stringify({ error: 'must provide either intent or ops' }, null, 2) }],
217
+ };
218
+ }
219
+
220
+ const issueAccumulator = createIssueAccumulator();
221
+ const issueCtx = { cache: stateCache, versionInfo: ENGINE_VERSION_INFO };
222
+ const startedAt = Date.now();
223
+
224
+ try {
225
+ let resolvedOps;
226
+ let delta_summary = '';
227
+ let synthesis = null;
228
+ let warnings = [];
229
+
230
+ if (ops && Array.isArray(ops)) {
231
+ // Explicit ops path — validate then apply
232
+ const validation = validateOps(ops, priorState);
233
+ if (!validation.ok) {
234
+ await issueAccumulator.flush(issueCtx);
235
+ return {
236
+ isError: true,
237
+ content: [{ type: 'text', text: JSON.stringify({
238
+ error: 'ops failed validation',
239
+ errors: validation.errors,
240
+ }, null, 2) }],
241
+ };
242
+ }
243
+ resolvedOps = ops;
244
+ delta_summary = `applied ${ops.length} explicit op(s)`;
245
+ } else {
246
+ // Intent path — two-pass synthesis with stub-friendly LLM bridge
247
+ const llmAdapter = await createLLMAdapter();
248
+ const refined = await refineFromIntent({
249
+ priorState,
250
+ intent,
251
+ llmAdapter,
252
+ maxAttempts: max_attempts,
253
+ issueAccumulator,
254
+ });
255
+ resolvedOps = refined.ops;
256
+ delta_summary = refined.delta_summary || '';
257
+ synthesis = refined.synthesis;
258
+ warnings = refined.warnings;
259
+
260
+ if (resolvedOps.length === 0) {
261
+ // Synthesizer gave up. Auto-fires already accumulated.
262
+ await issueAccumulator.flush(issueCtx);
263
+ const childId = mintNextStateId(state_id, (priorState.version || 1) + 1);
264
+ return {
265
+ content: [{ type: 'text', text: JSON.stringify({
266
+ state_id: childId,
267
+ ops_applied: [],
268
+ ops_failed: [],
269
+ delta_summary: '',
270
+ warnings,
271
+ synthesis: synthesis ? { attempts: synthesis.attempts, targeted: synthesis.targeted } : null,
272
+ html: priorState.html,
273
+ }, null, 2) }],
274
+ };
275
+ }
276
+ }
277
+
278
+ const applied = await applyOps({ priorState, ops: resolvedOps });
279
+
280
+ if (applied.ops_failed.length > 0) {
281
+ issueAccumulator.add('ops-failed-after-apply', {
282
+ state_id,
283
+ tool: 'refine_composition',
284
+ intent,
285
+ });
286
+ }
287
+
288
+ const a2uiMessages = opsToA2UI(applied.ops_applied, applied.newState);
289
+
290
+ const parentVersion = priorState.version || 1;
291
+ const newVersion = parentVersion + 1;
292
+ const newStateId = mintNextStateId(state_id, newVersion);
293
+
294
+ stateCache.set(newStateId, {
295
+ state_id: newStateId,
296
+ intent: intent || `(ops) ${priorState.intent}`,
297
+ plan: applied.newState.plan,
298
+ html: applied.newState.html,
299
+ source: 'refinement',
300
+ version: newVersion,
301
+ ops_history: [...(priorState.ops_history || []), ...a2uiMessages],
302
+ parent_state_id: state_id,
303
+ warnings: applied.newState.warnings,
304
+ delta_summary,
305
+ synthesis,
306
+ created_at: new Date().toISOString(),
307
+ duration_ms: Date.now() - startedAt,
308
+ });
309
+
310
+ await issueAccumulator.flush(issueCtx);
311
+
312
+ return {
313
+ content: [{ type: 'text', text: JSON.stringify({
314
+ state_id: newStateId,
315
+ ops_applied: a2uiMessages,
316
+ ops_failed: applied.ops_failed,
317
+ delta_summary,
318
+ warnings: [...warnings, ...(applied.newState.warnings || [])],
319
+ synthesis: synthesis ? { attempts: synthesis.attempts, targeted: synthesis.targeted, locatedTargets: synthesis.locatedTargets } : null,
320
+ html: applied.newState.html,
321
+ }, null, 2) }],
322
+ };
323
+ } catch (e) {
324
+ await issueAccumulator.flush(issueCtx);
325
+ return {
326
+ isError: true,
327
+ content: [{ type: 'text', text: JSON.stringify({ error: e.message }, null, 2) }],
328
+ };
329
+ }
330
+ },
331
+ );
332
+
333
+ server.tool(
334
+ 'get_state',
335
+ `Inspect a cached composition state by state_id.
336
+
337
+ Returns the full cache entry including the materialized HTML, the chunk binding plan, the chronological ops history (every refinement applied to this state's lineage), and the parent state_id (chain-back to the originating compose_from_chunks call).
338
+
339
+ Useful for debugging refinement sequences, replaying a state's history, or verifying that a state_id is still cached before issuing a refine_composition call.
340
+
341
+ Auto-fires a low-severity \`cache-miss-on-known-state\` issue when the state_id is not in the cache (the cache is bounded LRU; long-paused conversations may evict their state).`,
342
+ {
343
+ state_id: z.string().describe('State id from a prior compose_from_chunks or refine_composition call'),
344
+ },
345
+ async ({ state_id }) => {
346
+ const entry = stateCache.peek(state_id);
347
+ if (!entry) {
348
+ await autoReport(
349
+ 'cache-miss-on-known-state',
350
+ { state_id, tool: 'get_state' },
351
+ { cache: stateCache, versionInfo: ENGINE_VERSION_INFO }
352
+ );
353
+ return {
354
+ isError: true,
355
+ content: [{ type: 'text', text: JSON.stringify({
356
+ error: 'state_id not found in cache',
357
+ state_id,
358
+ }, null, 2) }],
359
+ };
360
+ }
361
+ return {
362
+ content: [{ type: 'text', text: JSON.stringify({
363
+ state_id: entry.state_id,
364
+ intent: entry.intent,
365
+ plan: entry.plan,
366
+ html: entry.html,
367
+ source: entry.source,
368
+ version: entry.version || 1,
369
+ parent_state_id: entry.parent_state_id || null,
370
+ ops_history: entry.ops_history || [],
371
+ warnings: entry.warnings || [],
372
+ created_at: entry.created_at,
373
+ }, null, 2) }],
374
+ };
375
+ },
376
+ );
377
+
378
+ server.tool(
379
+ 'report_issue',
380
+ `File a structured issue ticket — writes BOTH a machine-readable JSON file AND a human-readable Markdown report containing the full session trace (intent, retrieval log, LLM prompts, every attempt's raw response, composer plan, generated HTML preview, component count, warnings, environment).
381
+
382
+ When to call (any of these is a trigger):
383
+ (a) USER PHRASES — call immediately when the user says any of:
384
+ "file a ticket", "log a ticket", "save a ticket",
385
+ "report this as a bug", "report this issue", "log this issue",
386
+ "save the trace", "capture the session", "save the session for review",
387
+ "create a session ticket", "this is broken — debug it",
388
+ "download the trace", "export this for review",
389
+ "track this regression", "open a ticket for this".
390
+ (b) USER COMPLAINS the output is broken / wrong / missing.
391
+ (c) YOU CANNOT satisfy the user's intent after retrying.
392
+ (d) YOU DETECT a mismatch between requested and produced output you can't fix.
393
+
394
+ ALWAYS pass \`state_id\` from the most-recent compose_from_chunks or refine_composition call when one exists. The default \`trace: "full"\` then writes the high-resolution Markdown ticket. (Pass \`trace: "summary"\` for compact tickets, or \`trace: "none"\` to suppress the trace entirely.)
395
+
396
+ Do NOT call this for ordinary clarification or for output the user has not yet seen.
397
+
398
+ The tool returns BOTH paths in its response: \`path\` (.json) and \`markdown_path\` (.md). Surface BOTH to the user so they can navigate / download either:
399
+
400
+ 📋 Logged ticket \`{issue_id}\` (\`{severity}\` · owner: {suggested_owner})
401
+ • Trace report: \`{markdown_path}\` ← human-readable, scan this first
402
+ • Raw JSON: \`{path}\` ← machine-readable
403
+
404
+ Issue files land under \`.brain/audit-history/issues/\` (immutable; resolution lands in a sidecar file). Severity taxonomy matches the project's coherence-audit vocabulary: blocker = contract violation; drift = quality erosion; nit = cosmetic.`,
405
+ {
406
+ type: z.enum(['bug', 'training-gap', 'protocol-gap', 'ux-feedback']).describe('Issue category'),
407
+ severity: z.enum(['blocker', 'drift', 'nit']).describe('Severity tier'),
408
+ title: z.string().max(80).describe('One-line title (≤ 80 chars)'),
409
+ body: z.string().describe('Markdown body — observed vs expected, repro steps'),
410
+ state_id: z.string().optional().describe('State id from a prior tool call; auto-attaches the trace'),
411
+ trace: z.enum(['full', 'summary', 'none']).optional().describe('Trace depth — DEFAULT: "full" when state_id is provided (writes both .json + .md ticket with retrieval log, LLM prompts/attempts, plan, HTML preview). Use "summary" for compact tickets; "none" to suppress trace entirely.'),
412
+ suggested_owner: z.enum(['synthesis', 'retrieval', 'validator', 'chunk-corpus', 'mcp-protocol', 'unknown']).optional().describe('Best-guess owner for triage'),
413
+ tags: z.array(z.string()).optional().describe('Free-form tags for filtering'),
414
+ },
415
+ async ({ type, severity, title, body, state_id, trace, suggested_owner, tags }) => {
416
+ try {
417
+ const result = await reportIssueImpl(
418
+ { type, severity, title, body, state_id, trace, suggested_owner, tags },
419
+ {
420
+ cache: stateCache,
421
+ versionInfo: ENGINE_VERSION_INFO,
422
+ reporter: 'llm',
423
+ }
424
+ );
425
+ return {
426
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
427
+ };
428
+ } catch (e) {
429
+ return {
430
+ isError: true,
431
+ content: [{ type: 'text', text: JSON.stringify({ error: e.message }, null, 2) }],
432
+ };
433
+ }
434
+ },
435
+ );
436
+ }
@@ -1,20 +0,0 @@
1
- {"id":"intent-001","kind":"compose","category":"data-display","intent":"kpi grid with 4 stat cards: users, revenue, sessions, churn","expected_components":["Card","Stat","Grid"],"expected_chunk":"kpi-grid-4-card"}
2
- {"id":"intent-002","kind":"compose","category":"forms","intent":"sign-in form with email + password + 'forgot password' link","expected_components":["Card","Input","Button","Field"],"expected_chunk":"auth-sign-in"}
3
- {"id":"intent-003","kind":"compose","category":"layout","intent":"settings page with three tabs (general, integrations, billing)","expected_components":["Tabs","Tab","Card","Section"],"expected_chunk":"settings-tabs-3"}
4
- {"id":"intent-004","kind":"compose","category":"data","intent":"data table of users with role badge + last-active timestamp","expected_components":["Table","Badge"],"expected_chunk":"users-table"}
5
- {"id":"intent-005","kind":"compose","category":"data-viz","intent":"conversion funnel chart over 6 stages, with drop-off labels","expected_components":["Chart","Card","ChartLegend"],"expected_chunk":"conversion-funnel"}
6
- {"id":"intent-006","kind":"compose","category":"agent","intent":"agent activity feed with reasoning steps + final artifact","expected_components":["AgentTrace","AgentReasoning","AgentArtifact"],"expected_chunk":"agent-activity-feed"}
7
- {"id":"intent-007","kind":"compose","category":"layout","intent":"split-pane editor: code on the left, preview on the right","expected_components":["EditorShell","Pane","Code"],"expected_chunk":"editor-split"}
8
- {"id":"intent-008","kind":"compose","category":"overlay","intent":"command palette modal with grouped results (recent, suggestions)","expected_components":["Command","Modal"],"expected_chunk":"command-grouped"}
9
- {"id":"intent-009","kind":"compose","category":"forms","intent":"registration step 2 of 5 — profile setup with 4 fields","expected_components":["Card","StepProgress","Field","Input"],"expected_chunk":"reg-step-shell"}
10
- {"id":"intent-010","kind":"compose","category":"layout","intent":"404 error page with breadcrumb + back-to-home link","expected_components":["Card","Breadcrumb","Button"],"expected_chunk":"error-404"}
11
- {"id":"intent-011","kind":"refine","category":"data-display","intent":"dashboard for project metrics","refine":"add a date-range filter at the top","expected_components":["Card","Stat","Select"],"expected_chunk":"project-dashboard"}
12
- {"id":"intent-012","kind":"refine","category":"display","intent":"user profile card","refine":"make the email editable inline","expected_components":["Card","Avatar","Input"],"expected_chunk":"user-profile-card"}
13
- {"id":"intent-013","kind":"refine","category":"data","intent":"kanban board with 3 columns","refine":"add a count badge to each column header","expected_components":["Card","Badge","Header"],"expected_chunk":"kanban-3col"}
14
- {"id":"intent-014","kind":"refine","category":"chat","intent":"chat surface with streaming reply","refine":"add a stop button while streaming","expected_components":["ChatShell","Button","ChatInput"],"expected_chunk":"chat-streaming"}
15
- {"id":"intent-015","kind":"refine","category":"forms","intent":"sign-up form with email + password","refine":"add password strength meter","expected_components":["Card","Input","Progress"],"expected_chunk":"auth-sign-up"}
16
- {"id":"intent-016","kind":"refine","category":"settings","intent":"settings tab for notifications","refine":"split email + push into separate sections","expected_components":["Card","Section","Switch"],"expected_chunk":"settings-notifications"}
17
- {"id":"intent-017","kind":"refine","category":"data","intent":"table of orders","refine":"add a bulk-action toolbar above the table","expected_components":["Table","TableToolbar","Button"],"expected_chunk":"orders-table"}
18
- {"id":"intent-018","kind":"refine","category":"agent","intent":"agent reasoning panel","refine":"collapse intermediate steps by default, expandable","expected_components":["AgentReasoning","Accordion"],"expected_chunk":"agent-reasoning-collapsed"}
19
- {"id":"intent-019","kind":"refine","category":"overlay","intent":"modal confirming destructive action","refine":"require typing the resource name to confirm","expected_components":["Modal","Input","Button"],"expected_chunk":"destructive-confirm"}
20
- {"id":"intent-020","kind":"refine","category":"display","intent":"marketing landing hero","refine":"add a secondary 'see demo' CTA","expected_components":["Card","Heading","Button"],"expected_chunk":"marketing-hero"}