@aintela/chat 0.4.0 → 0.4.2

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
@@ -77,6 +77,22 @@ manifest export and the generation:
77
77
  "gen:uitools": "dotnet run --project ../path/to/Server.UiToolsManifest -- src/agent/generated/uitools.manifest.json && aia-gen-uitools src/agent/generated/uitools.manifest.json src/agent/generated"
78
78
  ```
79
79
 
80
+ **Every C# contract becomes ONE interface, under its own name.** The manifest carries each object's C#
81
+ type name as a JSON-Schema `title` (`UiToolsManifest` stamps it), and the generator lifts each titled
82
+ type into `$defs` and references it from every payload that embeds it — so `RescheduleQuoteCardArgs`
83
+ gets `replacing?: RescheduleQuoteFlight[]`, and `RescheduleQuoteFlight` is declared once however many
84
+ tools carry one.
85
+
86
+ That matters because of what it replaced. JSON Schema keeps no record of the type a sub-object came
87
+ from, so a nested type could only be named after its POSITION — and the position of every array element
88
+ is the key `items`. Every nested list in every tool therefore emitted as one interface called `Items`,
89
+ and the second shape to claim the name was dropped in favour of the first with only a warning: a
90
+ reschedule-quote flight typechecked as an expense-report line, `tsc` accepted `expenseId` on a flight,
91
+ and nothing failed. Two different shapes claiming one name now **stops the run** and writes nothing,
92
+ naming both. A manifest published by an older server carries no titles; the generator then names a
93
+ hoisted element after its owner (`RescheduleQuoteCardArgsReplacingItem`) rather than after `items` —
94
+ correct, ugly, and a prompt to republish the manifest.
95
+
80
96
  ### `TurnAwareButton` — controls drawn inside a chat message
81
97
 
82
98
  A UI-tool component is rendered **while the agent is still streaming its turn** (a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aintela/chat",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -30,11 +30,216 @@ function primitiveOf(schema) {
30
30
  }
31
31
 
32
32
  const opts = { bannerComment: '', additionalProperties: false, format: false };
33
- const interfaces = new Map(); // declaration name -> its TS block (deduped ACROSS compiles)
33
+ const interfaces = new Map(); // declaration name -> { text, from } (deduped ACROSS compiles)
34
34
 
35
- // One compile() output holds the requested type PLUS every nested sub-schema hoisted into its own
36
- // named declaration. Split it so identical hoisted names from different tools (deep contracts share
37
- // sub-types) dedupe instead of colliding as duplicate identifiers in the generated file.
35
+ // ---- one declaration per named type -------------------------------------------
36
+ // json-schema-to-typescript gives a sub-schema its own declaration when something $refs it, and names
37
+ // that declaration after the LAST SEGMENT of the pointer — which for an array element is always the
38
+ // keyword `items`. So every repeated nested list, in every tool, emitted as one interface called
39
+ // `Items`, and the second shape to claim that name was dropped in favour of the first: a
40
+ // reschedule-quote flight typechecked as an expense-report line, and the only sign was a warning.
41
+ //
42
+ // The fix has two halves. The manifest now carries the C# type name as `title` on every object node
43
+ // (server side: UiToolsManifest.StampTitles) — the only record of that name a JSON Schema can keep.
44
+ // Here we act on it: every titled object is lifted into `$defs/<TypeName>` and referenced from each
45
+ // place it appears, so ONE C# contract is ONE exported interface under its real name, however many
46
+ // payloads embed it. Two DIFFERENT shapes claiming one name is then a genuine clash and stops the run
47
+ // (`reportCollisions`) instead of silently mistyping a payload.
48
+ const POINTER_SEGMENT_ALIAS = { items: 'item', additionalProperties: 'value', prefixItems: 'item' };
49
+ const POINTER_SEGMENT_SKIP = new Set(['properties', '$defs', 'definitions', 'allOf', 'anyOf', 'oneOf']);
50
+ const DEFS = '#/$defs/';
51
+
52
+ const pascal = (segment) => segment
53
+ .replace(/[^A-Za-z0-9]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))
54
+ .replace(/^(.)/, (c) => c.toUpperCase());
55
+
56
+ // '#/properties/replacing/items' -> ['properties', 'replacing', 'items'] (JSON-pointer unescaped)
57
+ const pointerSegments = (pointer) => pointer.slice(1).split('/').filter(Boolean)
58
+ .map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
59
+
60
+ const pointerOf = (segments) => '#' + segments
61
+ .map((s) => '/' + s.replace(/~/g, '~0').replace(/\//g, '~1')).join('');
62
+
63
+ const resolvePointer = (root, pointer) =>
64
+ pointerSegments(pointer).reduce((node, s) => (node == null ? node : node[s]), root);
65
+
66
+ // `null` is expressed as a member of `type`, and `"default": null` alongside it — both are facts about
67
+ // the SLOT a value sits in, not about the type, and a type is the same type in a nullable slot.
68
+ const withoutNullability = (node) => {
69
+ const type = Array.isArray(node.type) ? node.type.filter((t) => t !== 'null') : node.type;
70
+ const body = { ...node, ...(type === undefined ? {} : { type: type.length === 1 ? type[0] : type }) };
71
+ delete body.default;
72
+ return body;
73
+ };
74
+ const isNullable = (node) => Array.isArray(node.type) && node.type.includes('null');
75
+
76
+ // `{ anyOf: [X, { type: 'null' }] }` — how a nullable slot reads once its type is a $ref (a `type`
77
+ // member cannot say it alongside one). Same slot fact, so it unwraps the same way.
78
+ const withoutNullUnion = (node) => {
79
+ for (const keyword of ['anyOf', 'oneOf']) {
80
+ const branches = node[keyword];
81
+ if (!Array.isArray(branches) || branches.length !== 2) continue;
82
+ const value = branches.find((b) => b && b.type !== 'null');
83
+ if (value && branches.some((b) => b && b.type === 'null')) return value;
84
+ }
85
+ return node;
86
+ };
87
+
88
+ function eachRef(node, fn) {
89
+ if (Array.isArray(node)) { node.forEach((child) => eachRef(child, fn)); return; }
90
+ if (!node || typeof node !== 'object') return;
91
+ if (typeof node.$ref === 'string' && node.$ref.startsWith('#')) node.$ref = fn(node.$ref);
92
+ for (const [key, child] of Object.entries(node)) if (key !== '$ref') eachRef(child, fn);
93
+ }
94
+
95
+ function collectRefs(node, into = new Set()) {
96
+ eachRef(node, (ref) => { into.add(ref); return ref; });
97
+ return into;
98
+ }
99
+
100
+ // A manifest published by an OLDER server carries no titles. Name the sub-schemas that would be hoisted
101
+ // anyway (the $ref targets) after their owner rather than after their keyword, so `Items` can never
102
+ // recur: `#/properties/replacing/items` under RescheduleQuoteCardArgs becomes
103
+ // `RescheduleQuoteCardArgsReplacingItem`. Long and mechanical on purpose — a name like that reads as a
104
+ // prompt to republish the manifest from a current server, and it is never WRONG.
105
+ function nameUntitledRefTargets(schema, rootName) {
106
+ for (const pointer of collectRefs(schema)) {
107
+ const target = resolvePointer(schema, pointer);
108
+ if (!target || typeof target !== 'object' || target.title || !target.properties) continue;
109
+ target.title = rootName + pointerSegments(pointer)
110
+ .filter((s) => !POINTER_SEGMENT_SKIP.has(s))
111
+ .map((s) => pascal(POINTER_SEGMENT_ALIAS[s] ?? s))
112
+ .join('');
113
+ }
114
+ }
115
+
116
+ const collisions = [];
117
+
118
+ function hoistNamedTypes(schema, rootName, from) {
119
+ nameUntitledRefTargets(schema, rootName);
120
+
121
+ // A node carrying its own `description` is left where it is: a $ref's description migrates onto the
122
+ // DECLARATION, so lifting one would stamp a single parameter's prose on the shared type.
123
+ const nameable = (node) => !!node && typeof node === 'object' && typeof node.$ref !== 'string'
124
+ && !!node.title && !!node.properties && !node.description;
125
+
126
+ // Index every named node BEFORE anything moves, and repoint the schema builder's own $refs — it
127
+ // writes a type out once and points at that copy thereafter — at the `$defs` entry each target is
128
+ // about to become. Doing it up front is what makes the shape comparison below order-independent:
129
+ // the two spellings of one type reduce to the same key whichever is met first.
130
+ const named = new Map(); // original pointer -> title (the document root is never lifted)
131
+ (function index(node, segments) {
132
+ if (Array.isArray(node)) { node.forEach((c, i) => index(c, [...segments, String(i)])); return; }
133
+ if (!node || typeof node !== 'object' || typeof node.$ref === 'string') return;
134
+ if (segments.length > 0 && nameable(node)) named.set(pointerOf(segments), node.title);
135
+ for (const key of Object.keys(node)) if (key !== 'title') index(node[key], [...segments, key]);
136
+ })(schema, []);
137
+ eachRef(schema, (ref) => (named.has(ref) ? DEFS + named.get(ref) : ref));
138
+
139
+ // Every remaining pointer is written against the document AS PUBLISHED, so resolve against an
140
+ // untouched copy — lifting a type rewrites nodes out from under the pointers aimed at them.
141
+ const original = structuredClone(schema);
142
+
143
+ // A schema's identity, BY NAME: two nodes are the same type when they agree structurally and their
144
+ // named sub-types agree by name. Property order is an artefact of reflection and cannot count;
145
+ // a pointer counts as whatever it points at; a nullable slot holds the same type as a plain one.
146
+ const shapeOf = (raw, root = false, seen = new Set()) => {
147
+ if (Array.isArray(raw)) return `[${raw.map((n) => shapeOf(n, false, seen)).join(',')}]`;
148
+ if (!raw || typeof raw !== 'object') return JSON.stringify(raw);
149
+ const node = withoutNullUnion(raw);
150
+ if (node !== raw) return shapeOf(node, root, seen);
151
+ if (typeof node.$ref === 'string') {
152
+ if (node.$ref.startsWith(DEFS)) return `~named:${node.$ref.slice(DEFS.length)}`;
153
+ if (seen.has(node.$ref)) return '~cycle';
154
+ const target = resolvePointer(original, node.$ref);
155
+ return target ? shapeOf(target, false, new Set([...seen, node.$ref])) : `~dangling:${node.$ref}`;
156
+ }
157
+ if (!root && node.title) return `~named:${node.title}`;
158
+ const body = withoutNullability(node);
159
+ return `{${Object.keys(body).filter((k) => k !== 'title').sort()
160
+ .map((k) => `${JSON.stringify(k)}:${shapeOf(body[k], false, seen)}`).join(',')}}`;
161
+ };
162
+
163
+ // Rebuild a subtree so it stands on its own: every pointer at a named type becomes a `$defs`
164
+ // reference, and every other pointer is resolved and inlined. Without this a lifted body can end up
165
+ // pointing back at the place it was lifted from — which now IS the body — and dereferencing never
166
+ // terminates.
167
+ const materialize = (node, root = false, seen = new Set()) => {
168
+ if (Array.isArray(node)) return node.map((child) => materialize(child, false, seen));
169
+ if (!node || typeof node !== 'object') return node;
170
+ if (typeof node.$ref === 'string') {
171
+ if (node.$ref.startsWith(DEFS) || seen.has(node.$ref)) return { ...node };
172
+ const target = resolvePointer(original, node.$ref);
173
+ return target ? materialize(target, root, new Set([...seen, node.$ref])) : { ...node };
174
+ }
175
+ if (!root && nameable(node)) {
176
+ const ref = { $ref: DEFS + node.title };
177
+ return isNullable(node) ? { anyOf: [ref, { type: 'null' }] } : ref;
178
+ }
179
+ return Object.fromEntries(Object.entries(node)
180
+ .map(([key, child]) => [key, materialize(child, false, seen)]));
181
+ };
182
+
183
+ // Post-order, so a type nested inside another is already a reference by the time its owner is lifted.
184
+ const defs = new Map(); // title -> { body, shape, from }
185
+ const visit = (node, root) => {
186
+ if (Array.isArray(node)) return node.map((child) => visit(child, false));
187
+ if (!node || typeof node !== 'object' || typeof node.$ref === 'string') return node;
188
+
189
+ for (const key of Object.keys(node)) if (key !== 'title') node[key] = visit(node[key], false);
190
+ if (root || !nameable(node)) return node;
191
+
192
+ const body = withoutNullability(node);
193
+ const shape = shapeOf(body, true);
194
+ const existing = defs.get(node.title);
195
+ if (existing && existing.shape !== shape) {
196
+ collisions.push({ name: node.title, first: existing, second: { body, from } });
197
+ return node; // reported at the end of the run; nothing is written
198
+ }
199
+ if (!existing) defs.set(node.title, { body: materialize(body, true), shape, from });
200
+
201
+ const ref = { $ref: DEFS + node.title };
202
+ return isNullable(node) ? { anyOf: [ref, { type: 'null' }] } : ref;
203
+ };
204
+ visit(schema, true);
205
+ if (defs.size === 0) return schema;
206
+
207
+ // Whatever pointers are left aim INTO a subtree that has moved; materializing the document settles
208
+ // them the same way it settled the bodies, and leaves `$defs` as the only pointer target.
209
+ const hoisted = materialize(schema, true);
210
+ hoisted.$defs = { ...(schema.$defs ?? {}) };
211
+ for (const [title, def] of defs) hoisted.$defs[title] = def.body;
212
+ return hoisted;
213
+ }
214
+
215
+ // A C# `Dictionary<string, V>` reaches the schema as `additionalProperties`, which the schema builder
216
+ // writes as a TypeScript index signature — three lines of `{ [k: string]: V }` for what a TS reader
217
+ // spells `Record<string, V>`. Identical type, so this is only how it READS, but a payload carrying a
218
+ // dozen of them reads very differently for it.
219
+ //
220
+ // Done on the emitted TEXT, not by handing the builder a `tsType` override for the dictionary node:
221
+ // `tsType` replaces the node outright and the builder stops walking INTO it, so a named value type
222
+ // reached only through a dictionary (`faresByAgeGroup: Dictionary<string, Money>`) stops being emitted
223
+ // and the file references an interface it no longer declares.
224
+ //
225
+ // The leading `:` / `(` / `=` is what keeps an interface's OWN opening brace out of it — `export
226
+ // interface Foo {` must stay an interface with an index signature, not become `export interface
227
+ // FooRecord<…>`. A value spanning more than one line (a dictionary OF inline objects) doesn't match and
228
+ // keeps the index signature, which is correct if verbose; the loop is for a dictionary of dictionaries,
229
+ // where the inner rewrite is what makes the outer one match.
230
+ const INDEX_SIGNATURE = /([:(|&,=]\s*)\{\n\[k: string]: ([^\n{}]+)\n\}/g;
231
+
232
+ function asRecords(ts) {
233
+ for (let previous = null; previous !== ts;) {
234
+ previous = ts;
235
+ ts = ts.replace(INDEX_SIGNATURE, (_, lead, value) => `${lead}Record<string, ${value}>`);
236
+ }
237
+ return ts;
238
+ }
239
+
240
+ // One compile() output holds the requested type PLUS every named sub-schema hoisted into its own
241
+ // declaration. Split it so the same type reached through two different tools (deep contracts share
242
+ // sub-types) dedupes instead of colliding as duplicate identifiers in the generated file.
38
243
  function splitDeclarations(ts) {
39
244
  const starts = [...ts.matchAll(/^export (?:interface|type) (\w+)/gm)]
40
245
  .map((m) => ({ name: m[1], start: m.index }));
@@ -46,32 +251,52 @@ function splitDeclarations(ts) {
46
251
 
47
252
  // Registers the schema's declarations (deduped by name) and returns the TS type to reference at
48
253
  // the use site; `fallback` is used when the tool has no schema for that leg.
49
- async function register(typeName, schema, fallback = 'void') {
254
+ async function register(typeName, schema, fallback = 'void', from = typeName) {
50
255
  if (!typeName || !schema) return fallback;
51
256
  const prim = primitiveOf(schema);
52
257
  if (prim) return prim;
53
- if (!interfaces.has(typeName)) {
54
- const ts = await compile(schema, typeName, opts);
55
- for (const block of splitDeclarations(ts)) {
56
- const existing = interfaces.get(block.name);
57
- if (existing === undefined) interfaces.set(block.name, block.text);
58
- else if (existing !== block.text)
59
- console.warn(`aia-gen-uitools: type name '${block.name}' appears with differing shapes; keeping the first.`);
60
- }
258
+ const ts = asRecords(await compile(hoistNamedTypes(schema, typeName, from), typeName, opts));
259
+ // Compiled every time, not just the first: a second tool declaring the SAME name with a different
260
+ // shape is exactly the mistake worth catching, and skipping the compile is what used to hide it.
261
+ for (const block of splitDeclarations(ts)) {
262
+ const existing = interfaces.get(block.name);
263
+ if (existing === undefined) interfaces.set(block.name, { text: block.text, from });
264
+ else if (existing.text !== block.text)
265
+ collisions.push({ name: block.name, first: existing, second: { text: block.text, from } });
61
266
  }
62
267
  return typeName;
63
268
  }
64
269
 
270
+ const indent = (text) => text.split('\n').map((line) => ' ' + line).join('\n');
271
+ const show = (side) => indent(side.text ?? JSON.stringify(side.body, null, 2));
272
+
273
+ // Two contracts want one TypeScript name for two different shapes. Whichever we kept, the other payload
274
+ // would be typed as it — `tsc` would then accept the wrong fields and reject the right ones, which is
275
+ // not something to leave a caller to notice in a warning line.
276
+ function reportCollisions() {
277
+ if (collisions.length === 0) return;
278
+ for (const { name, first, second } of collisions)
279
+ console.error(
280
+ `aia-gen-uitools: '${name}' is claimed by two DIFFERENT shapes — one payload would be typed`
281
+ + ` as the other.\n from ${first.from}:\n${show(first)}\n from ${second.from}:\n${show(second)}`,
282
+ );
283
+ console.error('aia-gen-uitools: nothing written. Fix it at the source — give one of the C# contracts'
284
+ + " a distinct type name, or a distinct JSON-Schema 'title'.");
285
+ process.exit(1);
286
+ }
287
+
65
288
  const rows = [];
66
289
  for (const c of manifest.components) {
290
+ const where = (leg) => `${c.component} (${leg})`;
67
291
  rows.push({
68
292
  ...c,
69
- argsTs: await register(c.argsTypeName, c.args, 'UiToolArgs'),
70
- inputTs: await register(c.inputTypeName, c.input),
71
- answerTs: await register(c.answerTypeName, c.answer),
72
- resultTs: await register(c.resultTypeName, c.result),
293
+ argsTs: await register(c.argsTypeName, c.args, 'UiToolArgs', where('args')),
294
+ inputTs: await register(c.inputTypeName, c.input, 'void', where('input')),
295
+ answerTs: await register(c.answerTypeName, c.answer, 'void', where('answer')),
296
+ resultTs: await register(c.resultTypeName, c.result, 'void', where('result')),
73
297
  });
74
298
  }
299
+ reportCollisions();
75
300
 
76
301
  // ---- uiContracts.generated.ts -------------------------------------------------
77
302
  writeFileSync(
@@ -80,7 +305,7 @@ writeFileSync(
80
305
  '// AUTO-GENERATED by aia-gen-uitools — do not edit. Source: the server UiToolsManifest.',
81
306
  '/* eslint-disable */',
82
307
  '',
83
- ...[...interfaces.values()],
308
+ ...[...interfaces.values()].map((d) => d.text),
84
309
  '',
85
310
  ].join('\n'),
86
311
  );