ngx-json-render 0.9.2 → 0.9.5

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.
package/README.md CHANGED
@@ -109,28 +109,6 @@ export class App {
109
109
  vocabulary. Everything below is the other path — your own components, which is
110
110
  what the catalog API is for.
111
111
 
112
- ## ngx-json-render or Hashbrown?
113
-
114
- [Hashbrown](https://hashbrown.dev) is the other generative-UI library for
115
- Angular. Both let a model compose your components; they differ in what the
116
- model emits and in how much of the agent around it they provide. Compared
117
- against `@hashbrownai/angular` 0.6.1, as published on 2026-09-30:
118
-
119
- | | ngx-json-render | Hashbrown |
120
- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
121
- | What the model emits | A json-render spec, streamed as RFC 6902 patches — the format the React, Vue, Svelte and Solid renderers read, so a catalog and a spec move between frameworks unchanged | Hashbrown's own JSON, generated against a schema built from the components you expose; read by Hashbrown's Angular and React clients |
122
- | Server | Anything that streams text: the [AI SDK](https://ai-sdk.dev) in a few lines, or your own endpoint; `catalog.prompt()` writes the system prompt | An [AG-UI](https://docs.ag-ui.com) endpoint, built with Hashbrown's adapters (OpenAI, Anthropic, Google, Azure, Bedrock, Ollama) or your own mapping |
123
- | Angular | 20, 21 and 22, each tested in CI | 22 only since 0.6 (0.5 supported 20 and 21) |
124
- | Components | Your own, or 33 ready-made Angular Material ones ([`ngx-json-render-material`](https://www.npmjs.com/package/ngx-json-render-material)) | Your own (`exposeComponent`, UI kits) |
125
- | Beyond rendering | Rendering-focused: state and two-way bindings in the spec, actions, visibility, repeat, watch, confirmation dialogs | An agent toolkit: client-side tools, a QuickJS sandbox for model-written code, shared agent state, interrupts, streaming Markdown |
126
- | License | Apache-2.0 | MIT |
127
-
128
- Reach for Hashbrown when you want the agent loop — tools, a sandbox, AG-UI —
129
- from one library and are on Angular 22. Reach for this one when you want an
130
- open spec format that is not tied to Angular or to one vendor's client, a
131
- server you already have, Angular 20 or 21, or a UI that renders from a
132
- ready-made Material catalog before you have written a component.
133
-
134
112
  ## Quick start
135
113
 
136
114
  **1. Define a catalog** — the vocabulary the model (or your server) is allowed to use:
@@ -472,6 +450,117 @@ this package's, and both silent when you get them wrong:
472
450
  writes the chunks a server route would, reads the message a client would —
473
451
  and asserts both of these, so this section cannot quietly go stale.
474
452
 
453
+ ### From an AG-UI agent
454
+
455
+ [AG-UI](https://docs.ag-ui.com) is the event protocol CopilotKit, LangGraph and
456
+ others speak between an agent and its frontend. A json-render spec travels on
457
+ it as an **activity** with `activityType: "json-render-spec"`
458
+ (`JSON_RENDER_ACTIVITY_TYPE`): `ACTIVITY_SNAPSHOT` carries a whole spec in
459
+ `content`, and `ACTIVITY_DELTA` carries RFC 6902 patches against it in `patch`
460
+ — the same patches a JSONL stream is made of. `ngx-json-render/ag-ui` reads
461
+ that, and needs nothing from `@ag-ui/*` at runtime: it accepts any agent and
462
+ event of the right shape.
463
+
464
+ With an `@ag-ui/client` agent, `injectAgentUI` gives the signals `injectUIStream`
465
+ gives. The app keeps running the agent; the hook only listens, so it sees every
466
+ run whoever starts it, and checks each spec when the run ends:
467
+
468
+ ```ts
469
+ import { Component } from '@angular/core';
470
+ import { HttpAgent } from '@ag-ui/client';
471
+ import { JsonRenderer } from 'ngx-json-render';
472
+ import { injectAgentUI } from 'ngx-json-render/ag-ui';
473
+ import { catalog } from './catalog';
474
+
475
+ @Component({
476
+ imports: [JsonRenderer],
477
+ template: `
478
+ <json-render [spec]="ui.spec()" [loading]="ui.isStreaming()" />
479
+ <button (click)="ask('show me revenue for the quarter')">Ask</button>
480
+ `,
481
+ })
482
+ export class AgentPage {
483
+ readonly agent = new HttpAgent({ url: '/api/agent' });
484
+ readonly ui = injectAgentUI({ agent: this.agent, catalog, validate: 'warn' });
485
+
486
+ ask(text: string) {
487
+ this.agent.addMessage({ id: crypto.randomUUID(), role: 'user', content: text });
488
+ this.agent.runAgent();
489
+ }
490
+ }
491
+ ```
492
+
493
+ `ui.surfaces()` lists every spec the agent has built, keyed by the activity's
494
+ `messageId`, for a run that opens more than one; `ui.spec()` is the latest.
495
+ Elements a delta does not touch keep their identity, so the renderer skips
496
+ them. Without the hook, `applyAgUiEvent(surfaces, event)` is the same fold as a
497
+ pure function.
498
+
499
+ **In a CopilotKit Angular app**, register the ready-made activity renderer.
500
+ It draws the spec with the registry and catalog from `provideJsonRender`:
501
+
502
+ ```ts
503
+ import { provideJsonRender } from 'ngx-json-render';
504
+ import { jsonRenderActivityRenderer } from 'ngx-json-render/ag-ui';
505
+
506
+ providers: [
507
+ provideJsonRender({ registry }),
508
+ provideCopilotKit({
509
+ runtimeUrl: '/api/copilotkit',
510
+ renderActivityMessages: [jsonRenderActivityRenderer()],
511
+ }),
512
+ ];
513
+ ```
514
+
515
+ **On the server**, the model's output — prose with ` ```spec ` fenced JSONL,
516
+ as `catalog.prompt({ mode: 'inline' })` asks for — splits into text-message
517
+ events and activity deltas with `createMixedStreamParser` from
518
+ `@json-render/core`, and `EventEncoder` from `@ag-ui/encoder` writes the
519
+ server-sent events:
520
+
521
+ ```ts
522
+ // server.ts — an AG-UI endpoint (Express)
523
+ import { EventType, type BaseEvent, type RunAgentInput } from '@ag-ui/core';
524
+ import { EventEncoder } from '@ag-ui/encoder';
525
+ import { createMixedStreamParser } from '@json-render/core';
526
+
527
+ app.post('/api/agent', async (req, res) => {
528
+ const { threadId, runId, messages } = req.body as RunAgentInput;
529
+ const encoder = new EventEncoder({ accept: req.headers.accept });
530
+ const send = (event: BaseEvent) => res.write(encoder.encode(event));
531
+ res.setHeader('Content-Type', encoder.getContentType());
532
+
533
+ const textId = crypto.randomUUID();
534
+ const uiId = crypto.randomUUID();
535
+ send({ type: EventType.RUN_STARTED, threadId, runId } as BaseEvent);
536
+ send({ type: EventType.TEXT_MESSAGE_START, messageId: textId, role: 'assistant' } as BaseEvent);
537
+ send({ type: EventType.ACTIVITY_SNAPSHOT, messageId: uiId, activityType: 'json-render-spec',
538
+ content: { root: '', elements: {} } } as BaseEvent);
539
+
540
+ const parser = createMixedStreamParser({
541
+ onText: (line) => send({ type: EventType.TEXT_MESSAGE_CONTENT, messageId: textId,
542
+ delta: line + '\n' } as BaseEvent),
543
+ onPatch: (patch) => send({ type: EventType.ACTIVITY_DELTA, messageId: uiId,
544
+ activityType: 'json-render-spec', patch: [patch] } as BaseEvent),
545
+ });
546
+ const result = streamText({
547
+ model: anthropic('claude-sonnet-5'),
548
+ system: catalog.prompt({ mode: 'inline' }),
549
+ messages: toModelMessages(messages), // AG-UI user/assistant messages → your model's format
550
+ });
551
+ for await (const chunk of result.textStream) parser.push(chunk);
552
+ parser.flush();
553
+
554
+ send({ type: EventType.TEXT_MESSAGE_END, messageId: textId } as BaseEvent);
555
+ send({ type: EventType.RUN_FINISHED, threadId, runId } as BaseEvent);
556
+ res.end();
557
+ });
558
+ ```
559
+
560
+ `projects/ngx-json-render/ag-ui/src/ag-ui.spec.ts` runs a real `HttpAgent`
561
+ against a replayed server-sent stream, through AG-UI's own decoder and event
562
+ checks, and renders the result.
563
+
475
564
  ### Supplying the transport
476
565
 
477
566
  By default the request goes through the global `fetch`. Pass your own to add
@@ -645,7 +734,37 @@ export class App {
645
734
 
646
735
  The spec renders while the model is still writing the tool call, from the host's `toolinputpartial` notifications; pass `streamPartialInput: false` to wait for the result. `mcp.sendMessage(text, data)` posts a user message to the chat, so a button can continue the conversation, and `mcp.callServerTool(name, args)` replaces the spec with another tool's result. The connection closes with the injector that created it.
647
736
 
648
- The server side is upstream's `@json-render/mcp`, which serves the view as a single HTML resource. [`projects/mcp-app`](https://github.com/shteynu/ngx-json-render/tree/main/projects/mcp-app) is a complete example with the Material catalog: the view, the build that inlines it into one page, and a server that works around two `createMcpApp` problems.
737
+ ### The server
738
+
739
+ `ngx-json-render/mcp/server` is the other half: an MCP server with one `render-ui` tool for your catalog, and the view as its `ui://` resource. It needs no Angular, so it runs in plain Node or on an edge function, and it takes the same two optional peers.
740
+
741
+ ```ts
742
+ import { readFileSync } from 'node:fs';
743
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
744
+ import { createRenderUiServer } from 'ngx-json-render/mcp/server';
745
+ import { catalog } from './catalog'; // defineCatalog(schema, …) from ngx-json-render/schema
746
+
747
+ const server = createRenderUiServer({
748
+ catalog,
749
+ html: readFileSync('dist/view.html', 'utf8'), // the view above, built into one page
750
+ name: 'my-app',
751
+ version: '1.0.0',
752
+ });
753
+ await server.connect(new StdioServerTransport());
754
+ ```
755
+
756
+ Over HTTP, `handleRenderUiRequest(options, request)` takes a web `Request` and returns a `Response`. It serves each request statelessly with a fresh server, as a serverless or edge function needs, and answers CORS for browser-based clients such as MCP Inspector.
757
+
758
+ What it does on top of upstream's `createMcpApp` from `@json-render/mcp`, whose tool and resource it registers the same way:
759
+
760
+ - **A description Claude reads whole.** `createMcpApp` describes the tool with `catalog.prompt()`, about 26 000 characters, and Claude cuts a tool description off after roughly 2 000, before the first component. `renderUiDescription(catalog)` stays under that limit (`DESCRIPTION_LIMIT`) and leaves the components to the input schema.
761
+ - **An input schema that keeps the spec whole.** `catalog.zodSchema()` has no `state`, `on` or `watch`, so the MCP SDK strips them from the arguments before the tool sees them, and it types no props. `specInputSchema(catalog)` declares them and gives each component its own props, with dynamic values allowed and unknown props rejected, and checks each action's params.
762
+ - **Errors the model can fix.** A spec with a missing child or root, or a `$template` that reads a repeat item as `${$item/field}`, goes back as a tool error that says what to write instead (`specProblems`).
763
+ - **The structured result ChatGPT asks for:** the spec as `structuredContent`, with an output schema (`specOutputSchema`).
764
+
765
+ Options: `name`, `version`, `toolName` (default `render-ui`), `title`, `description`, `csp` (the origins the view may load from and connect to; left out, the host allows none) and `widgetDomain` (the view's origin for ChatGPT's plugin directory). If your catalog has a `sendMessage` action, the description tells the model how to use it; the view's handler for it calls `mcp.sendMessage()`.
766
+
767
+ [`projects/mcp-app`](https://github.com/shteynu/ngx-json-render/tree/main/projects/mcp-app) is a complete example with the Material catalog: the view, the build that inlines it into one page, and this server, the one behind `https://ngx-json-render.vercel.app/mcp`.
649
768
 
650
769
  ## Devtools
651
770
 
@@ -1087,8 +1206,12 @@ Schema alone (`ngx-json-render/schema`): `schema`, `AngularSchema`, `AngularSpec
1087
1206
 
1088
1207
  MCP Apps (`ngx-json-render/mcp`): `injectJsonRenderApp`, `parseSpecFromToolResult`, `messageText`, and the types `JsonRenderApp`, `JsonRenderAppOptions`. Needs the optional peers `@modelcontextprotocol/ext-apps` and `@modelcontextprotocol/sdk`.
1089
1208
 
1209
+ MCP App server (`ngx-json-render/mcp/server`): `createRenderUiServer`, `handleRenderUiRequest`, `renderUiDescription`, `specInputSchema`, `specOutputSchema`, `specProblems`, `DESCRIPTION_LIMIT`, and the types `RenderUiServerOptions`, `RenderUiDescriptionOptions`. No Angular; the same optional peers.
1210
+
1090
1211
  Router (`ngx-json-render/router`): `injectRouterNavigate`, and the type `RouterNavigateOptions`. Needs the optional peer `@angular/router`, which an Angular app on the router already has.
1091
1212
 
1213
+ AG-UI (`ngx-json-render/ag-ui`): `injectAgentUI`, `applyAgUiEvent`, `surfacesFromMessages`, `isJsonRenderSpec`, `JsonRenderActivity` (`<json-render-activity>`), `jsonRenderActivityRenderer`, `JSON_RENDER_ACTIVITY_TYPE`, and the types `AgUiAgent`, `AgUiEvent`, `AgUiMessage`, `AgUiSubscriber`, `AgUiSurface`, `AgentUIOptions`, `AgentUIReturn`, `JsonRenderActivityRendererConfig`, `JsonRenderActivityRendererOptions`. No peer: any agent and event of the right shape will do.
1214
+
1092
1215
  Devtools (`ngx-json-render/devtools`): `JsonRenderDevtools` (`<json-render-devtools>`), and the types `DevtoolsEvent`, `PanelPosition`. Needs the optional peer `@json-render/devtools`.
1093
1216
 
1094
1217
  Testing (`ngx-json-render/testing`): `renderSpec`, `renderComponent`, `recordedTransport`, `specStream`, `usageLine`.
@@ -0,0 +1,308 @@
1
+ import { applyPatch, checkSpec, formatSpecCheckIssues, JsonRenderer } from 'ngx-json-render';
2
+ import * as i0 from '@angular/core';
3
+ import { signal, inject, DestroyRef, computed, input, Component } from '@angular/core';
4
+
5
+ /**
6
+ * The `activityType` a json-render spec travels under.
7
+ *
8
+ * An agent sends the spec as an AG-UI activity: `ACTIVITY_SNAPSHOT` carries a
9
+ * whole spec in `content`, and `ACTIVITY_DELTA` carries RFC 6902 patches
10
+ * against it in `patch` — the same patches a json-render JSONL stream is made
11
+ * of. CopilotKit carries A2UI the same way, under `"a2ui-surface"`.
12
+ *
13
+ * The name says both the format and what `content` holds — a `Spec`, the
14
+ * object upstream calls a spec in its AI SDK part type `data-spec` — so a
15
+ * renderer for another framework can match it without reading these docs.
16
+ */
17
+ const JSON_RENDER_ACTIVITY_TYPE = 'json-render-spec';
18
+ const EMPTY_SPEC = { root: '', elements: {} };
19
+ function isRecord(value) {
20
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
21
+ }
22
+ /**
23
+ * Whether activity content has the shape of a spec. Only the shape: what the
24
+ * elements say is the renderer's and the finished-spec check's business.
25
+ */
26
+ function isJsonRenderSpec(content) {
27
+ return (isRecord(content) &&
28
+ typeof content['root'] === 'string' &&
29
+ isRecord(content['elements']));
30
+ }
31
+ function isPatch(value) {
32
+ return (isRecord(value) &&
33
+ typeof value['op'] === 'string' &&
34
+ typeof value['path'] === 'string');
35
+ }
36
+ function upsert(surfaces, messageId, spec) {
37
+ const index = surfaces.findIndex((s) => s.messageId === messageId);
38
+ if (index === -1)
39
+ return [...surfaces, { messageId, spec }];
40
+ const next = [...surfaces];
41
+ next[index] = { messageId, spec };
42
+ return next;
43
+ }
44
+ /**
45
+ * The surfaces an AG-UI message list holds, in message order.
46
+ *
47
+ * Used for `MESSAGES_SNAPSHOT` and to pick up the history an agent already
48
+ * has when a hook attaches to it.
49
+ */
50
+ function surfacesFromMessages(messages, activityType = JSON_RENDER_ACTIVITY_TYPE) {
51
+ const surfaces = [];
52
+ for (const message of messages) {
53
+ const m = message;
54
+ if (m.role === 'activity' &&
55
+ m['activityType'] === activityType &&
56
+ isJsonRenderSpec(m['content'])) {
57
+ surfaces.push({ messageId: m.id, spec: m['content'] });
58
+ }
59
+ }
60
+ return surfaces;
61
+ }
62
+ /**
63
+ * Fold one AG-UI event into the surfaces built so far.
64
+ *
65
+ * Returns the same array when the event does not concern json-render, so a
66
+ * signal holding the result only notifies on a real change. A delta applies
67
+ * through the same immutable patch engine as a JSONL stream: elements it does
68
+ * not touch keep their identity, and the renderer skips them.
69
+ *
70
+ * Two leniencies, both in the direction of rendering what arrived:
71
+ * - a delta for a surface no snapshot has opened starts from an empty spec,
72
+ * so an agent can stream patches the way a JSONL endpoint does;
73
+ * - a malformed patch op is dropped rather than failing the surface.
74
+ */
75
+ function applyAgUiEvent(surfaces, event, activityType = JSON_RENDER_ACTIVITY_TYPE) {
76
+ const e = event;
77
+ switch (e.type) {
78
+ case 'ACTIVITY_SNAPSHOT': {
79
+ const messageId = e['messageId'];
80
+ if (typeof messageId !== 'string' || e['activityType'] !== activityType) {
81
+ return surfaces;
82
+ }
83
+ const content = e['content'];
84
+ if (!isJsonRenderSpec(content))
85
+ return surfaces;
86
+ // `replace: false` means "only if new": the client already has a
87
+ // version of this surface it should keep.
88
+ if (e['replace'] === false &&
89
+ surfaces.some((s) => s.messageId === messageId)) {
90
+ return surfaces;
91
+ }
92
+ return upsert(surfaces, messageId, content);
93
+ }
94
+ case 'ACTIVITY_DELTA': {
95
+ const messageId = e['messageId'];
96
+ const patch = e['patch'];
97
+ if (typeof messageId !== 'string' ||
98
+ e['activityType'] !== activityType ||
99
+ !Array.isArray(patch)) {
100
+ return surfaces;
101
+ }
102
+ const current = surfaces.find((s) => s.messageId === messageId)?.spec ?? EMPTY_SPEC;
103
+ let spec = current;
104
+ for (const op of patch) {
105
+ if (isPatch(op))
106
+ spec = applyPatch(spec, op);
107
+ }
108
+ return spec === current ? surfaces : upsert(surfaces, messageId, spec);
109
+ }
110
+ case 'MESSAGES_SNAPSHOT': {
111
+ const messages = e['messages'];
112
+ if (!Array.isArray(messages))
113
+ return surfaces;
114
+ // AG-UI's rule: a snapshot that carries any activity message carries
115
+ // all of them, and one that carries none leaves the client's alone.
116
+ const carriesActivities = messages.some((m) => isRecord(m) && m['role'] === 'activity');
117
+ if (!carriesActivities)
118
+ return surfaces;
119
+ return surfacesFromMessages(messages, activityType);
120
+ }
121
+ default:
122
+ return surfaces;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Render what an AG-UI agent streams. Subscribes to the agent, folds every
128
+ * json-render activity it emits into signals, and checks each surface when
129
+ * the run ends — the same contract as `injectUIStream`, with the agent in
130
+ * place of the endpoint.
131
+ *
132
+ * The app keeps running the agent itself (`agent.runAgent()`, CopilotKit, a
133
+ * reconnect); the hook only listens, so it sees every run, whoever starts it.
134
+ * It starts from whatever surfaces are already in the agent's messages and
135
+ * unsubscribes on destroy.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * export class AgentPage {
140
+ * readonly agent = new HttpAgent({ url: '/api/agent' });
141
+ * readonly ui = injectAgentUI({ agent: this.agent, catalog });
142
+ * ask(text: string) {
143
+ * this.agent.addMessage({ id: crypto.randomUUID(), role: 'user', content: text });
144
+ * this.agent.runAgent();
145
+ * }
146
+ * }
147
+ * // template:
148
+ * // <json-render [spec]="ui.spec()" [registry]="registry" [loading]="ui.isStreaming()" />
149
+ * ```
150
+ */
151
+ function injectAgentUI(options) {
152
+ const activityType = options.activityType ?? JSON_RENDER_ACTIVITY_TYPE;
153
+ const validate = options.validate ?? 'off';
154
+ const checkOptions = {
155
+ limits: options.renderLimits ?? null,
156
+ catalog: options.catalog ?? null,
157
+ };
158
+ const surfaces = signal(surfacesFromMessages(options.agent.messages ?? [], activityType), ...(ngDevMode ? [{ debugName: "surfaces" }] : /* istanbul ignore next */ []));
159
+ const isStreaming = signal(false, ...(ngDevMode ? [{ debugName: "isStreaming" }] : /* istanbul ignore next */ []));
160
+ const error = signal(null, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
161
+ const issues = signal([], ...(ngDevMode ? [{ debugName: "issues" }] : /* istanbul ignore next */ []));
162
+ // Per run: which surfaces it changed, and whether it already failed.
163
+ let touched = new Set();
164
+ let failed = false;
165
+ const fail = (err) => {
166
+ failed = true;
167
+ error.set(err);
168
+ options.onError?.(err);
169
+ };
170
+ const finish = () => {
171
+ const found = [];
172
+ let next = surfaces();
173
+ for (const messageId of touched) {
174
+ const surface = next.find((s) => s.messageId === messageId);
175
+ if (!surface)
176
+ continue; // a later MESSAGES_SNAPSHOT dropped it
177
+ const check = checkSpec(surface.spec, validate, checkOptions);
178
+ found.push(...check.issues);
179
+ if (check.spec && check.spec !== surface.spec) {
180
+ const fixed = check.spec;
181
+ next = next.map((s) => s.messageId === messageId ? { messageId, spec: fixed } : s);
182
+ }
183
+ if (check.blocked || (validate === 'strict' && check.hasErrors)) {
184
+ fail(new Error(`Generated spec failed validation:\n${formatSpecCheckIssues(check.issues)}`));
185
+ continue;
186
+ }
187
+ options.onComplete?.(check.spec ?? surface.spec, messageId);
188
+ }
189
+ surfaces.set(next);
190
+ issues.set(found);
191
+ };
192
+ const subscription = options.agent.subscribe({
193
+ onRunInitialized() {
194
+ touched = new Set();
195
+ failed = false;
196
+ isStreaming.set(true);
197
+ error.set(null);
198
+ issues.set([]);
199
+ },
200
+ onEvent({ event }) {
201
+ const before = surfaces();
202
+ const after = applyAgUiEvent(before, event, activityType);
203
+ if (after === before)
204
+ return;
205
+ for (const surface of after) {
206
+ if (!before.includes(surface))
207
+ touched.add(surface.messageId);
208
+ }
209
+ surfaces.set(after);
210
+ },
211
+ onRunErrorEvent({ event }) {
212
+ fail(new Error(event.message));
213
+ },
214
+ onRunFailed({ error: err }) {
215
+ // A RUN_ERROR event already reported this run; the client then fails
216
+ // the run with the same message.
217
+ if (!failed)
218
+ fail(err instanceof Error ? err : new Error(String(err)));
219
+ },
220
+ onRunFinalized() {
221
+ if (!failed)
222
+ finish();
223
+ isStreaming.set(false);
224
+ },
225
+ });
226
+ inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
227
+ const spec = computed(() => surfaces().at(-1)?.spec ?? null, ...(ngDevMode ? [{ debugName: "spec" }] : /* istanbul ignore next */ []));
228
+ return {
229
+ surfaces: surfaces.asReadonly(),
230
+ spec,
231
+ isStreaming: isStreaming.asReadonly(),
232
+ error: error.asReadonly(),
233
+ issues: issues.asReadonly(),
234
+ };
235
+ }
236
+
237
+ /**
238
+ * Renders one json-render activity message. It takes the inputs every AG-UI
239
+ * activity renderer is given — CopilotKit Angular's `ActivityRenderer`
240
+ * contract — and draws `content` with `<json-render>`, which takes its
241
+ * registry, catalog and handlers from the nearest `provideJsonRender`.
242
+ *
243
+ * Register it with {@link jsonRenderActivityRenderer} rather than by hand.
244
+ */
245
+ class JsonRenderActivity {
246
+ activityType = input(JSON_RENDER_ACTIVITY_TYPE, ...(ngDevMode ? [{ debugName: "activityType" }] : /* istanbul ignore next */ []));
247
+ content = input.required(...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
248
+ /** The AG-UI activity message; unused, accepted for the contract. */
249
+ message = input(...(ngDevMode ? [undefined, { debugName: "message" }] : /* istanbul ignore next */ []));
250
+ /** The agent that produced it; unused, accepted for the contract. */
251
+ agent = input(...(ngDevMode ? [undefined, { debugName: "agent" }] : /* istanbul ignore next */ []));
252
+ spec = computed(() => {
253
+ const content = this.content();
254
+ return isJsonRenderSpec(content) ? content : null;
255
+ }, ...(ngDevMode ? [{ debugName: "spec" }] : /* istanbul ignore next */ []));
256
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: JsonRenderActivity, deps: [], target: i0.ɵɵFactoryTarget.Component });
257
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "21.2.25", type: JsonRenderActivity, isStandalone: true, selector: "json-render-activity", inputs: { activityType: { classPropertyName: "activityType", publicName: "activityType", isSignal: true, isRequired: false, transformFunction: null }, content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: true, transformFunction: null }, message: { classPropertyName: "message", publicName: "message", isSignal: true, isRequired: false, transformFunction: null }, agent: { classPropertyName: "agent", publicName: "agent", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0, template: `<json-render [spec]="spec()" />`, isInline: true, dependencies: [{ kind: "component", type: JsonRenderer, selector: "json-render", inputs: ["spec", "registry", "loading", "fallback", "validate", "renderLimits", "catalog", "state", "store", "handlers", "onAction", "navigate", "validationFunctions", "functions", "directives"], outputs: ["stateChange"] }] });
258
+ }
259
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.25", ngImport: i0, type: JsonRenderActivity, decorators: [{
260
+ type: Component,
261
+ args: [{
262
+ selector: 'json-render-activity',
263
+ imports: [JsonRenderer],
264
+ template: `<json-render [spec]="spec()" />`,
265
+ }]
266
+ }], propDecorators: { activityType: [{ type: i0.Input, args: [{ isSignal: true, alias: "activityType", required: false }] }], content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: true }] }], message: [{ type: i0.Input, args: [{ isSignal: true, alias: "message", required: false }] }], agent: [{ type: i0.Input, args: [{ isSignal: true, alias: "agent", required: false }] }] } });
267
+ /**
268
+ * Teach a CopilotKit Angular app to render json-render activities:
269
+ *
270
+ * ```ts
271
+ * providers: [
272
+ * provideJsonRender({ registry }),
273
+ * provideCopilotKit({
274
+ * runtimeUrl: '/api/copilotkit',
275
+ * renderActivityMessages: [jsonRenderActivityRenderer()],
276
+ * }),
277
+ * ]
278
+ * ```
279
+ *
280
+ * Content that is not a spec is rejected by the config's schema, so CopilotKit
281
+ * skips the message with a warning instead of mounting an empty renderer.
282
+ */
283
+ function jsonRenderActivityRenderer(options = {}) {
284
+ return {
285
+ activityType: options.activityType ?? JSON_RENDER_ACTIVITY_TYPE,
286
+ ...(options.agentId !== undefined ? { agentId: options.agentId } : {}),
287
+ content: {
288
+ safeParse: (content) => isJsonRenderSpec(content)
289
+ ? { success: true, data: content }
290
+ : {
291
+ success: false,
292
+ error: new Error('Activity content is not a json-render spec: expected { root: string, elements: object }.'),
293
+ },
294
+ },
295
+ component: options.component ?? JsonRenderActivity,
296
+ };
297
+ }
298
+
299
+ /*
300
+ * Public API Surface of ngx-json-render/ag-ui
301
+ */
302
+
303
+ /**
304
+ * Generated bundle index. Do not edit.
305
+ */
306
+
307
+ export { JSON_RENDER_ACTIVITY_TYPE, JsonRenderActivity, applyAgUiEvent, injectAgentUI, isJsonRenderSpec, jsonRenderActivityRenderer, surfacesFromMessages };
308
+ //# sourceMappingURL=ngx-json-render-ag-ui.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ngx-json-render-ag-ui.mjs","sources":["../../../projects/ngx-json-render/ag-ui/src/events.ts","../../../projects/ngx-json-render/ag-ui/src/agent-ui.ts","../../../projects/ngx-json-render/ag-ui/src/json-render-activity.ts","../../../projects/ngx-json-render/ag-ui/src/public-api.ts","../../../projects/ngx-json-render/ag-ui/src/ngx-json-render-ag-ui.ts"],"sourcesContent":["import type { JsonPatch, Spec } from '@json-render/core';\nimport { applyPatch } from 'ngx-json-render';\n\n/**\n * The `activityType` a json-render spec travels under.\n *\n * An agent sends the spec as an AG-UI activity: `ACTIVITY_SNAPSHOT` carries a\n * whole spec in `content`, and `ACTIVITY_DELTA` carries RFC 6902 patches\n * against it in `patch` — the same patches a json-render JSONL stream is made\n * of. CopilotKit carries A2UI the same way, under `\"a2ui-surface\"`.\n *\n * The name says both the format and what `content` holds — a `Spec`, the\n * object upstream calls a spec in its AI SDK part type `data-spec` — so a\n * renderer for another framework can match it without reading these docs.\n */\nexport const JSON_RENDER_ACTIVITY_TYPE = 'json-render-spec';\n\n/**\n * The part of an AG-UI event this entry point reads.\n *\n * Structural on purpose: `@ag-ui/core`'s `EventType` is a string enum, so its\n * events fit a `string` here, and nothing below needs the package at runtime\n * or pins its version.\n */\nexport interface AgUiEvent {\n readonly type: string;\n}\n\n/** The part of an AG-UI message this entry point reads. */\nexport interface AgUiMessage {\n readonly id: string;\n readonly role: string;\n}\n\n/** One spec an agent is building, keyed by its activity message. */\nexport interface AgUiSurface {\n /** The activity's `messageId`; one run can build several surfaces. */\n readonly messageId: string;\n readonly spec: Spec;\n}\n\nconst EMPTY_SPEC: Spec = { root: '', elements: {} };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Whether activity content has the shape of a spec. Only the shape: what the\n * elements say is the renderer's and the finished-spec check's business.\n */\nexport function isJsonRenderSpec(content: unknown): content is Spec {\n return (\n isRecord(content) &&\n typeof content['root'] === 'string' &&\n isRecord(content['elements'])\n );\n}\n\nfunction isPatch(value: unknown): value is JsonPatch {\n return (\n isRecord(value) &&\n typeof value['op'] === 'string' &&\n typeof value['path'] === 'string'\n );\n}\n\nfunction upsert(\n surfaces: readonly AgUiSurface[],\n messageId: string,\n spec: Spec,\n): readonly AgUiSurface[] {\n const index = surfaces.findIndex((s) => s.messageId === messageId);\n if (index === -1) return [...surfaces, { messageId, spec }];\n const next = [...surfaces];\n next[index] = { messageId, spec };\n return next;\n}\n\n/**\n * The surfaces an AG-UI message list holds, in message order.\n *\n * Used for `MESSAGES_SNAPSHOT` and to pick up the history an agent already\n * has when a hook attaches to it.\n */\nexport function surfacesFromMessages(\n messages: readonly AgUiMessage[],\n activityType: string = JSON_RENDER_ACTIVITY_TYPE,\n): readonly AgUiSurface[] {\n const surfaces: AgUiSurface[] = [];\n for (const message of messages) {\n const m = message as AgUiMessage & Record<string, unknown>;\n if (\n m.role === 'activity' &&\n m['activityType'] === activityType &&\n isJsonRenderSpec(m['content'])\n ) {\n surfaces.push({ messageId: m.id, spec: m['content'] });\n }\n }\n return surfaces;\n}\n\n/**\n * Fold one AG-UI event into the surfaces built so far.\n *\n * Returns the same array when the event does not concern json-render, so a\n * signal holding the result only notifies on a real change. A delta applies\n * through the same immutable patch engine as a JSONL stream: elements it does\n * not touch keep their identity, and the renderer skips them.\n *\n * Two leniencies, both in the direction of rendering what arrived:\n * - a delta for a surface no snapshot has opened starts from an empty spec,\n * so an agent can stream patches the way a JSONL endpoint does;\n * - a malformed patch op is dropped rather than failing the surface.\n */\nexport function applyAgUiEvent(\n surfaces: readonly AgUiSurface[],\n event: AgUiEvent,\n activityType: string = JSON_RENDER_ACTIVITY_TYPE,\n): readonly AgUiSurface[] {\n const e = event as AgUiEvent & Record<string, unknown>;\n switch (e.type) {\n case 'ACTIVITY_SNAPSHOT': {\n const messageId = e['messageId'];\n if (typeof messageId !== 'string' || e['activityType'] !== activityType) {\n return surfaces;\n }\n const content = e['content'];\n if (!isJsonRenderSpec(content)) return surfaces;\n // `replace: false` means \"only if new\": the client already has a\n // version of this surface it should keep.\n if (\n e['replace'] === false &&\n surfaces.some((s) => s.messageId === messageId)\n ) {\n return surfaces;\n }\n return upsert(surfaces, messageId, content);\n }\n case 'ACTIVITY_DELTA': {\n const messageId = e['messageId'];\n const patch = e['patch'];\n if (\n typeof messageId !== 'string' ||\n e['activityType'] !== activityType ||\n !Array.isArray(patch)\n ) {\n return surfaces;\n }\n const current =\n surfaces.find((s) => s.messageId === messageId)?.spec ?? EMPTY_SPEC;\n let spec = current;\n for (const op of patch) {\n if (isPatch(op)) spec = applyPatch(spec, op);\n }\n return spec === current ? surfaces : upsert(surfaces, messageId, spec);\n }\n case 'MESSAGES_SNAPSHOT': {\n const messages = e['messages'];\n if (!Array.isArray(messages)) return surfaces;\n // AG-UI's rule: a snapshot that carries any activity message carries\n // all of them, and one that carries none leaves the client's alone.\n const carriesActivities = messages.some(\n (m) => isRecord(m) && m['role'] === 'activity',\n );\n if (!carriesActivities) return surfaces;\n return surfacesFromMessages(messages as AgUiMessage[], activityType);\n }\n default:\n return surfaces;\n }\n}\n","import {\n DestroyRef,\n type Signal,\n computed,\n inject,\n signal,\n} from '@angular/core';\nimport type { Spec } from '@json-render/core';\nimport {\n type RenderLimits,\n type SpecCatalog,\n type SpecCheckIssue,\n type SpecValidationMode,\n checkSpec,\n formatSpecCheckIssues,\n} from 'ngx-json-render';\nimport {\n type AgUiEvent,\n type AgUiMessage,\n type AgUiSurface,\n JSON_RENDER_ACTIVITY_TYPE,\n applyAgUiEvent,\n surfacesFromMessages,\n} from './events';\n\n/**\n * The callbacks of an AG-UI subscriber this entry point uses — a subset of\n * `@ag-ui/client`'s `AgentSubscriber`.\n */\nexport interface AgUiSubscriber {\n onRunInitialized?(): void;\n onEvent?(params: { event: AgUiEvent }): void;\n onRunErrorEvent?(params: { event: { message: string } }): void;\n onRunFailed?(params: { error: Error }): void;\n onRunFinalized?(): void;\n}\n\n/**\n * What {@link injectAgentUI} needs of an agent. Any `@ag-ui/client` agent —\n * `HttpAgent`, a subclass of `AbstractAgent`, the agent CopilotKit hands out —\n * already has this shape.\n */\nexport interface AgUiAgent {\n readonly messages?: readonly AgUiMessage[];\n subscribe(subscriber: AgUiSubscriber): { unsubscribe(): void };\n}\n\n/** Options for {@link injectAgentUI}. */\nexport interface AgentUIOptions {\n /** The agent whose runs build the UI. The app runs it; the hook listens. */\n agent: AgUiAgent;\n /** Defaults to {@link JSON_RENDER_ACTIVITY_TYPE}. */\n activityType?: string;\n /**\n * Called once per surface a run touched, after the finished-spec check.\n * Skipped for a run that failed, and for a surface the check rejected.\n */\n onComplete?: (spec: Spec, messageId: string) => void;\n /** Called when a run fails or a finished surface fails the check. */\n onError?: (error: Error) => void;\n /** As for `injectUIStream`: checked once per surface, when the run ends. */\n validate?: SpecValidationMode;\n /** As for `injectUIStream`; enforced whatever `validate` is. */\n renderLimits?: RenderLimits | null;\n /** As for `injectUIStream`: lets `validate` check types and props. */\n catalog?: SpecCatalog | null;\n}\n\n/** Return type of {@link injectAgentUI}. */\nexport interface AgentUIReturn {\n /** Every json-render surface the agent has built, in order of appearance. */\n readonly surfaces: Signal<readonly AgUiSurface[]>;\n /** The most recently opened surface's spec — the one most apps render. */\n readonly spec: Signal<Spec | null>;\n /** Whether a run of the agent is in progress. */\n readonly isStreaming: Signal<boolean>;\n /** The last run's error, if any. */\n readonly error: Signal<Error | null>;\n /** What the check found in the surfaces the last run finished. */\n readonly issues: Signal<readonly SpecCheckIssue[]>;\n}\n\n/**\n * Render what an AG-UI agent streams. Subscribes to the agent, folds every\n * json-render activity it emits into signals, and checks each surface when\n * the run ends — the same contract as `injectUIStream`, with the agent in\n * place of the endpoint.\n *\n * The app keeps running the agent itself (`agent.runAgent()`, CopilotKit, a\n * reconnect); the hook only listens, so it sees every run, whoever starts it.\n * It starts from whatever surfaces are already in the agent's messages and\n * unsubscribes on destroy.\n *\n * @example\n * ```ts\n * export class AgentPage {\n * readonly agent = new HttpAgent({ url: '/api/agent' });\n * readonly ui = injectAgentUI({ agent: this.agent, catalog });\n * ask(text: string) {\n * this.agent.addMessage({ id: crypto.randomUUID(), role: 'user', content: text });\n * this.agent.runAgent();\n * }\n * }\n * // template:\n * // <json-render [spec]=\"ui.spec()\" [registry]=\"registry\" [loading]=\"ui.isStreaming()\" />\n * ```\n */\nexport function injectAgentUI(options: AgentUIOptions): AgentUIReturn {\n const activityType = options.activityType ?? JSON_RENDER_ACTIVITY_TYPE;\n const validate = options.validate ?? 'off';\n const checkOptions = {\n limits: options.renderLimits ?? null,\n catalog: options.catalog ?? null,\n };\n\n const surfaces = signal<readonly AgUiSurface[]>(\n surfacesFromMessages(options.agent.messages ?? [], activityType),\n );\n const isStreaming = signal(false);\n const error = signal<Error | null>(null);\n const issues = signal<readonly SpecCheckIssue[]>([]);\n\n // Per run: which surfaces it changed, and whether it already failed.\n let touched = new Set<string>();\n let failed = false;\n\n const fail = (err: Error) => {\n failed = true;\n error.set(err);\n options.onError?.(err);\n };\n\n const finish = () => {\n const found: SpecCheckIssue[] = [];\n let next = surfaces();\n for (const messageId of touched) {\n const surface = next.find((s) => s.messageId === messageId);\n if (!surface) continue; // a later MESSAGES_SNAPSHOT dropped it\n const check = checkSpec(surface.spec, validate, checkOptions);\n found.push(...check.issues);\n if (check.spec && check.spec !== surface.spec) {\n const fixed = check.spec;\n next = next.map((s) =>\n s.messageId === messageId ? { messageId, spec: fixed } : s,\n );\n }\n if (check.blocked || (validate === 'strict' && check.hasErrors)) {\n fail(\n new Error(\n `Generated spec failed validation:\\n${formatSpecCheckIssues(check.issues)}`,\n ),\n );\n continue;\n }\n options.onComplete?.(check.spec ?? surface.spec, messageId);\n }\n surfaces.set(next);\n issues.set(found);\n };\n\n const subscription = options.agent.subscribe({\n onRunInitialized() {\n touched = new Set();\n failed = false;\n isStreaming.set(true);\n error.set(null);\n issues.set([]);\n },\n onEvent({ event }) {\n const before = surfaces();\n const after = applyAgUiEvent(before, event, activityType);\n if (after === before) return;\n for (const surface of after) {\n if (!before.includes(surface)) touched.add(surface.messageId);\n }\n surfaces.set(after);\n },\n onRunErrorEvent({ event }) {\n fail(new Error(event.message));\n },\n onRunFailed({ error: err }) {\n // A RUN_ERROR event already reported this run; the client then fails\n // the run with the same message.\n if (!failed) fail(err instanceof Error ? err : new Error(String(err)));\n },\n onRunFinalized() {\n if (!failed) finish();\n isStreaming.set(false);\n },\n });\n\n inject(DestroyRef).onDestroy(() => subscription.unsubscribe());\n\n const spec = computed(() => surfaces().at(-1)?.spec ?? null);\n\n return {\n surfaces: surfaces.asReadonly(),\n spec,\n isStreaming: isStreaming.asReadonly(),\n error: error.asReadonly(),\n issues: issues.asReadonly(),\n };\n}\n","import { Component, type Type, computed, input } from '@angular/core';\nimport type { Spec } from '@json-render/core';\nimport { JsonRenderer } from 'ngx-json-render';\nimport { JSON_RENDER_ACTIVITY_TYPE, isJsonRenderSpec } from './events';\n\n/**\n * Renders one json-render activity message. It takes the inputs every AG-UI\n * activity renderer is given — CopilotKit Angular's `ActivityRenderer`\n * contract — and draws `content` with `<json-render>`, which takes its\n * registry, catalog and handlers from the nearest `provideJsonRender`.\n *\n * Register it with {@link jsonRenderActivityRenderer} rather than by hand.\n */\n@Component({\n selector: 'json-render-activity',\n imports: [JsonRenderer],\n template: `<json-render [spec]=\"spec()\" />`,\n})\nexport class JsonRenderActivity {\n readonly activityType = input<string>(JSON_RENDER_ACTIVITY_TYPE);\n readonly content = input.required<unknown>();\n /** The AG-UI activity message; unused, accepted for the contract. */\n readonly message = input<unknown>();\n /** The agent that produced it; unused, accepted for the contract. */\n readonly agent = input<unknown>();\n\n protected readonly spec = computed<Spec | null>(() => {\n const content = this.content();\n return isJsonRenderSpec(content) ? content : null;\n });\n}\n\n/** Options for {@link jsonRenderActivityRenderer}. */\nexport interface JsonRenderActivityRendererOptions {\n /** Defaults to {@link JSON_RENDER_ACTIVITY_TYPE}. */\n activityType?: string;\n /** Limit the renderer to one agent's activities. */\n agentId?: string;\n /** A component of your own in place of {@link JsonRenderActivity}. */\n component?: Type<unknown>;\n}\n\n/**\n * An activity renderer config in the shape CopilotKit Angular's\n * `renderActivityMessages` takes, matched structurally so this package does\n * not depend on CopilotKit.\n */\nexport interface JsonRenderActivityRendererConfig {\n activityType: string;\n agentId?: string;\n content: {\n safeParse(\n content: unknown,\n ): { success: true; data: Spec } | { success: false; error?: unknown };\n };\n component: Type<any>;\n}\n\n/**\n * Teach a CopilotKit Angular app to render json-render activities:\n *\n * ```ts\n * providers: [\n * provideJsonRender({ registry }),\n * provideCopilotKit({\n * runtimeUrl: '/api/copilotkit',\n * renderActivityMessages: [jsonRenderActivityRenderer()],\n * }),\n * ]\n * ```\n *\n * Content that is not a spec is rejected by the config's schema, so CopilotKit\n * skips the message with a warning instead of mounting an empty renderer.\n */\nexport function jsonRenderActivityRenderer(\n options: JsonRenderActivityRendererOptions = {},\n): JsonRenderActivityRendererConfig {\n return {\n activityType: options.activityType ?? JSON_RENDER_ACTIVITY_TYPE,\n ...(options.agentId !== undefined ? { agentId: options.agentId } : {}),\n content: {\n safeParse: (content) =>\n isJsonRenderSpec(content)\n ? { success: true, data: content }\n : {\n success: false,\n error: new Error(\n 'Activity content is not a json-render spec: expected { root: string, elements: object }.',\n ),\n },\n },\n component: options.component ?? JsonRenderActivity,\n };\n}\n","/*\n * Public API Surface of ngx-json-render/ag-ui\n */\n\nexport {\n JSON_RENDER_ACTIVITY_TYPE,\n applyAgUiEvent,\n isJsonRenderSpec,\n surfacesFromMessages,\n type AgUiEvent,\n type AgUiMessage,\n type AgUiSurface,\n} from './events';\nexport {\n injectAgentUI,\n type AgUiAgent,\n type AgUiSubscriber,\n type AgentUIOptions,\n type AgentUIReturn,\n} from './agent-ui';\nexport {\n JsonRenderActivity,\n jsonRenderActivityRenderer,\n type JsonRenderActivityRendererConfig,\n type JsonRenderActivityRendererOptions,\n} from './json-render-activity';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;AAGA;;;;;;;;;;;AAWG;AACI,MAAM,yBAAyB,GAAG;AA0BzC,MAAM,UAAU,GAAS,EAAE,IAAI,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE;AAEnD,SAAS,QAAQ,CAAC,KAAc,EAAA;AAC9B,IAAA,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;AAC7E;AAEA;;;AAGG;AACG,SAAU,gBAAgB,CAAC,OAAgB,EAAA;AAC/C,IAAA,QACE,QAAQ,CAAC,OAAO,CAAC;AACjB,QAAA,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,QAAQ;AACnC,QAAA,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAEjC;AAEA,SAAS,OAAO,CAAC,KAAc,EAAA;AAC7B,IAAA,QACE,QAAQ,CAAC,KAAK,CAAC;AACf,QAAA,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,QAAQ;AAC/B,QAAA,OAAO,KAAK,CAAC,MAAM,CAAC,KAAK,QAAQ;AAErC;AAEA,SAAS,MAAM,CACb,QAAgC,EAChC,SAAiB,EACjB,IAAU,EAAA;AAEV,IAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,KAA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