@aintela/chat 0.2.37 → 0.2.39

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.
@@ -26,22 +26,31 @@ import { Interaction } from '../../../../models/Interaction';
26
26
  */
27
27
  /** Default args shape when a registration omits its generic. */
28
28
  export type UiToolArgs = Record<string, unknown>;
29
- /** Context handed to every renderer. */
30
- export interface UiToolContext {
29
+ /**
30
+ * Context handed to every renderer.
31
+ *
32
+ * Generic over the tool's INPUT payload (`clientOutput`, i.e. the prefill / client data — the `In`
33
+ * param) and its ANSWER (`answer`'s value — the `Ans` param). Both default to `unknown`, so an
34
+ * un-parametrized registration behaves exactly as before; the codegen'd typed builder methods
35
+ * (e.g. `askUpdateProfile`) bind them so a host reads `ctx.clientOutput` and calls `ctx.answer` fully
36
+ * typed with no casts.
37
+ */
38
+ export interface UiToolContext<In = unknown, Ans = unknown> {
31
39
  /** Normalized tool name (`UI_` marker + `{Plugin}-`/`{Plugin}_` qualifier stripped). */
32
40
  name: string;
33
41
  /** This tool call's id — stable across the call's Composing→Executing→Done lifecycle. */
34
42
  callId: string;
35
- /** The tool RESULT, if any. May be an object or a (possibly double-encoded) JSON string. */
43
+ /** The tool RESULT, if any. May be an object or a (possibly double-encoded) JSON string. Kept
44
+ * `unknown`: this is what the tool RETURNED to the model, not necessarily the answer the user gave. */
36
45
  response: unknown;
37
46
  /**
38
- * The tool's CLIENT-ONLY output — the payload it wrote to its SDK `ToolClientOutput` sink,
39
- * already parsed. This is the preferred render source: it arrives correlated to THIS call (by
40
- * id) on the result event (so multiple UI calls never race), the LLM never saw it, and it
41
- * survives reload. `undefined` until the call has responded, or when the tool didn't opt in
42
- * (fall back to `args`). Replaces the old slot-id-correlated tool-event lookup over `parts`.
47
+ * The tool's CLIENT-ONLY output — the payload it wrote to its SDK client-data sink (`SetClientData`)
48
+ * or pushed as an ask-user prefill, already parsed. This is the preferred render source: it arrives
49
+ * correlated to THIS call (by id) on the result event (so multiple UI calls never race), the LLM never
50
+ * saw it, and it survives reload. `undefined` until the call has responded, or when the tool didn't opt
51
+ * in (fall back to `args`). Typed as `In` — the codegen binds it to the server descriptor's input shape.
43
52
  */
44
- clientOutput: unknown;
53
+ clientOutput: In;
45
54
  /** Sibling parts of the same interaction (e.g. present_tsx's compiled-JS event rides here). */
46
55
  parts: ReadonlyArray<InteractionPart>;
47
56
  /** The whole interaction this part belongs to. */
@@ -50,9 +59,16 @@ export interface UiToolContext {
50
59
  onGoing: boolean;
51
60
  /** True during historical replay / preview — actions must NOT re-fire side effects. */
52
61
  preview: boolean;
62
+ /**
63
+ * Submit the user's answer for this parked ask-user call, then let the library deliver it to the agent
64
+ * (via `answerHumanTool`, keyed by {@link callId}). A string is sent verbatim; anything else is
65
+ * JSON-serialized. Typed as `Ans` — the codegen binds it to the server descriptor's answer shape, so a
66
+ * host can't send the wrong payload. A no-op for render/action tools, which never park for an answer.
67
+ */
68
+ answer(value: Ans): void;
53
69
  }
54
70
  /** Context handed to actions — adds the host environment. */
55
- export interface UiToolActionContext extends UiToolContext {
71
+ export interface UiToolActionContext<In = unknown, Ans = unknown> extends UiToolContext<In, Ans> {
56
72
  /**
57
73
  * The host environment from `EnvironmentProvider` (e.g. `refreshDashboard`,
58
74
  * `createDashboardPad`). Empty `{}` when no provider is in scope or during
@@ -61,30 +77,33 @@ export interface UiToolActionContext extends UiToolContext {
61
77
  */
62
78
  env: Record<string, unknown>;
63
79
  }
64
- export type UiToolRenderFn<TArgs> = (args: TArgs, ctx: UiToolContext) => React.ReactNode;
65
- export type UiToolActionFn<TArgs> = (args: TArgs, ctx: UiToolActionContext) => void | Promise<void>;
80
+ export type UiToolRenderFn<TArgs, In = unknown> = (args: TArgs, ctx: UiToolContext<In>) => React.ReactNode;
81
+ export type UiToolActionFn<TArgs, In = unknown> = (args: TArgs, ctx: UiToolActionContext<In>) => void | Promise<void>;
66
82
  /**
67
83
  * The interactive face of an ASK-USER component — a human-in-the-loop prompt drawn in the docked
68
84
  * ask-user drawer (`AskUserSheet`) while the tool call is PARKED, keyed by the component NAME the
69
85
  * server stamps via `[KernelUIComponent]` (`functionDetails.askUserComponent`), not by the wire tool
70
86
  * name. Same `(args, ctx)` shape as a render tool.
71
87
  */
72
- export type UiToolAskUserQuestionFn<TArgs> = (args: TArgs, ctx: UiToolContext) => React.ReactNode;
88
+ export type UiToolAskUserQuestionFn<In = unknown, Ans = unknown, TArgs = UiToolArgs> = (args: TArgs, ctx: UiToolContext<In, Ans>) => React.ReactNode;
73
89
  /**
74
90
  * The ANSWERED face of an ask-user component — the locked summary drawn inline in the transcript once
75
91
  * the tool has responded. Receives the tool's response (also available as `ctx.response`), so a host
76
92
  * can render "you answered X" without re-deriving it from args.
77
93
  */
78
- export type UiToolAskUserResponseFn<TArgs> = (args: TArgs, ctx: UiToolContext, response: unknown) => React.ReactNode;
94
+ export type UiToolAskUserResponseFn<In = unknown, Ans = unknown, Res = unknown, TArgs = UiToolArgs> = (args: TArgs, ctx: UiToolContext<In, Ans>, response: Res) => React.ReactNode;
79
95
  /**
80
96
  * A host ask-user registration: the interactive `question` (required, drawn while parked) plus an
81
97
  * optional locked `response` summary (drawn inline once answered). Omit `response` to reuse `question`
82
98
  * in both states — the question component then owns its own answered/locked view (as the built-in
83
99
  * `AskUserPart`/`AskAuthPart` do).
100
+ *
101
+ * `TArgs` (defaulted, last so older parametrizations keep compiling) is the tool-CALL args shape —
102
+ * the codegen'd typed methods bind it to the generated `…Args` interface.
84
103
  */
85
- export interface UiToolAskUserRenderers<TArgs> {
86
- question: UiToolAskUserQuestionFn<TArgs>;
87
- response?: UiToolAskUserResponseFn<TArgs>;
104
+ export interface UiToolAskUserRenderers<In = unknown, Ans = unknown, Res = unknown, TArgs = UiToolArgs> {
105
+ question: UiToolAskUserQuestionFn<In, Ans, TArgs>;
106
+ response?: UiToolAskUserResponseFn<In, Ans, Res, TArgs>;
88
107
  }
89
108
  export interface UiToolRenderOptions<TArgs> {
90
109
  /** Runtime arg guard/coercion. Return `null` to render nothing (treated as invalid args). */
@@ -103,21 +122,21 @@ export interface UiToolActionOptions<TArgs> {
103
122
  export interface UiToolRenderEntry {
104
123
  kind: 'render';
105
124
  name: string;
106
- render: UiToolRenderFn<any>;
125
+ render: UiToolRenderFn<any, any>;
107
126
  parse?: (raw: unknown) => any;
108
127
  }
109
128
  export interface UiToolActionEntry {
110
129
  kind: 'action';
111
130
  name: string;
112
- run: UiToolActionFn<any>;
131
+ run: UiToolActionFn<any, any>;
113
132
  parse?: (raw: unknown) => any;
114
133
  status?: string | ((args: any, ctx: UiToolActionContext) => string | null);
115
134
  }
116
135
  export interface UiToolAskUserEntry {
117
136
  kind: 'askUser';
118
137
  name: string;
119
- question: UiToolAskUserQuestionFn<any>;
120
- response?: UiToolAskUserResponseFn<any>;
138
+ question: UiToolAskUserQuestionFn<any, any>;
139
+ response?: UiToolAskUserResponseFn<any, any, any>;
121
140
  parse?: (raw: unknown) => any;
122
141
  }
123
142
  export type UiToolEntry = UiToolRenderEntry | UiToolActionEntry | UiToolAskUserEntry;
@@ -135,8 +154,8 @@ export interface UiToolRegistry {
135
154
  names(): string[];
136
155
  }
137
156
  export interface UiToolRegistryBuilder {
138
- render<TArgs = UiToolArgs>(name: string, render: UiToolRenderFn<TArgs>, opts?: UiToolRenderOptions<TArgs>): UiToolRegistryBuilder;
139
- action<TArgs = UiToolArgs>(name: string, run: UiToolActionFn<TArgs>, opts?: UiToolActionOptions<TArgs>): UiToolRegistryBuilder;
157
+ render<TArgs = UiToolArgs, In = unknown>(name: string, render: UiToolRenderFn<TArgs, In>, opts?: UiToolRenderOptions<TArgs>): UiToolRegistryBuilder;
158
+ action<TArgs = UiToolArgs, In = unknown>(name: string, run: UiToolActionFn<TArgs, In>, opts?: UiToolActionOptions<TArgs>): UiToolRegistryBuilder;
140
159
  /**
141
160
  * Register an ASK-USER component drawn in the docked drawer (`AskUserSheet`). `componentName` must
142
161
  * match the server's `[KernelUIComponent("…")]` value (arrives as `functionDetails.askUserComponent`).
@@ -144,8 +163,13 @@ export interface UiToolRegistryBuilder {
144
163
  * when unregistered, so consumers only register their own components (e.g. `AskCreateAccount`).
145
164
  * Pass `{ question, response? }`: `question` is the interactive parked form, `response` the optional
146
165
  * locked summary shown once answered.
166
+ *
167
+ * Generic over `In` (the prefill / client-data shape read as `ctx.clientOutput`) and `Ans` (the shape
168
+ * passed to `ctx.answer`). Both default to `unknown`. The codegen'd typed methods (e.g.
169
+ * `askUpdateProfile`) are this method with those generics pre-bound — declaration-merged onto this
170
+ * interface so the fluent chain stays fully typed.
147
171
  */
148
- askUser<TArgs = UiToolArgs>(componentName: string, renderers: UiToolAskUserRenderers<TArgs>, opts?: UiToolRenderOptions<TArgs>): UiToolRegistryBuilder;
172
+ askUser<In = unknown, Ans = unknown, Res = unknown, TArgs = UiToolArgs>(componentName: string, renderers: UiToolAskUserRenderers<In, Ans, Res, TArgs>, opts?: UiToolRenderOptions<TArgs>): UiToolRegistryBuilder;
149
173
  build(): UiToolRegistry;
150
174
  }
151
175
  /**
@@ -18,7 +18,7 @@ export type { FriendlyState, FriendlyToolEntry } from './AiChat/ChatPane/friendl
18
18
  export { classifyPart, DEFAULT_PART_RENDERERS, TextPart, ThoughtPart, FunctionPart, WaitingPart, SuspendedPart, BoxedPart, UiToolDispatcher, } from './AiChat/ChatPane/parts';
19
19
  export type { PartKind, PartRendererProps, PartRenderer, PartRendererMap, } from './AiChat/ChatPane/parts';
20
20
  export { createUiToolRegistry, parseUiArgs, parseClientOutput } from './AiChat/ChatPane/parts';
21
- export type { UiToolRegistry, UiToolRegistryBuilder, UiToolContext, UiToolActionContext, UiToolArgs, UiToolRenderFn, UiToolActionFn, UiToolRenderOptions, UiToolActionOptions, UiToolEntry, UiToolRenderEntry, UiToolActionEntry, } from './AiChat/ChatPane/parts';
21
+ export type { UiToolRegistry, UiToolRegistryBuilder, UiToolContext, UiToolActionContext, UiToolArgs, UiToolRenderFn, UiToolActionFn, UiToolRenderOptions, UiToolActionOptions, UiToolEntry, UiToolRenderEntry, UiToolActionEntry, UiToolAskUserRenderers, UiToolAskUserQuestionFn, UiToolAskUserResponseFn, UiToolAskUserEntry, } from './AiChat/ChatPane/parts';
22
22
  export { useContainerWidth, useContainerRectangle } from '../hooks/useContainerWidth';
23
23
  export { default as Stopwatch } from './Stopwatch';
24
24
  export { default as LoadingDots } from './Library/LoadingDots';
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "@aintela/chat",
3
- "version": "0.2.37",
3
+ "version": "0.2.39",
4
4
  "type": "module",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
+ "bin": {
9
+ "aia-gen-uitools": "./scripts/gen-uitools.mjs"
10
+ },
8
11
  "main": "./dist/index.js",
9
12
  "types": "./dist/index.d.ts",
10
13
  "sideEffects": [
@@ -66,8 +69,12 @@
66
69
  },
67
70
  "files": [
68
71
  "dist",
72
+ "scripts/gen-uitools.mjs",
69
73
  "README.md"
70
74
  ],
75
+ "dependencies": {
76
+ "json-schema-to-typescript": "^15.0.0"
77
+ },
71
78
  "scripts": {
72
79
  "build": "vite build",
73
80
  "dev": "vite build --watch",
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env node
2
+ // aia-gen-uitools — turn the UI-tools manifest (per-tool args/input/answer/result JSON Schema,
3
+ // emitted by the server's `UiToolsManifest.PublishManifest(...)` executable) into TypeScript:
4
+ // • uiContracts.generated.ts — the args/input/answer/result interfaces (named after the C# contracts)
5
+ // • aiaUiTools.generated.ts — a typed registry builder adding one method per tool
6
+ // (askUpdateProfile, presentDataTable, …), each typed with its
7
+ // generated `…Args` interface + payload shapes.
8
+ //
9
+ // Shipped as the `aia-gen-uitools` bin of @aintela/chat — the library owns the generator; consumer
10
+ // apps only run it. Usage: aia-gen-uitools <manifest.json> <out-dir>
11
+ import { compile } from 'json-schema-to-typescript';
12
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+
15
+ const [, , manifestPath, outDir] = process.argv;
16
+ if (!manifestPath || !outDir) {
17
+ console.error('usage: aia-gen-uitools <manifest.json> <out-dir>');
18
+ process.exit(1);
19
+ }
20
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
21
+ mkdirSync(outDir, { recursive: true });
22
+
23
+ const PRIMITIVE = { string: 'string', integer: 'number', number: 'number', boolean: 'boolean' };
24
+
25
+ // A schema that's a bare scalar (e.g. the askauth token → `string`) becomes an inline TS primitive.
26
+ function primitiveOf(schema) {
27
+ if (!schema || schema.properties) return null;
28
+ const t = Array.isArray(schema.type) ? schema.type.find((x) => x !== 'null') : schema.type;
29
+ return PRIMITIVE[t] ?? null;
30
+ }
31
+
32
+ const opts = { bannerComment: '', additionalProperties: false, format: false };
33
+ const interfaces = new Map(); // declaration name -> its TS block (deduped ACROSS compiles)
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.
38
+ function splitDeclarations(ts) {
39
+ const starts = [...ts.matchAll(/^export (?:interface|type) (\w+)/gm)]
40
+ .map((m) => ({ name: m[1], start: m.index }));
41
+ return starts.map(({ name, start }, i) => ({
42
+ name,
43
+ text: ts.slice(start, i + 1 < starts.length ? starts[i + 1].start : ts.length).trim(),
44
+ }));
45
+ }
46
+
47
+ // Registers the schema's declarations (deduped by name) and returns the TS type to reference at
48
+ // the use site; `fallback` is used when the tool has no schema for that leg.
49
+ async function register(typeName, schema, fallback = 'void') {
50
+ if (!typeName || !schema) return fallback;
51
+ const prim = primitiveOf(schema);
52
+ 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
+ }
61
+ }
62
+ return typeName;
63
+ }
64
+
65
+ const rows = [];
66
+ for (const c of manifest.components) {
67
+ rows.push({
68
+ ...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),
73
+ });
74
+ }
75
+
76
+ // ---- uiContracts.generated.ts -------------------------------------------------
77
+ writeFileSync(
78
+ join(outDir, 'uiContracts.generated.ts'),
79
+ [
80
+ '// AUTO-GENERATED by aia-gen-uitools — do not edit. Source: the server UiToolsManifest.',
81
+ '/* eslint-disable */',
82
+ '',
83
+ ...[...interfaces.values()],
84
+ '',
85
+ ].join('\n'),
86
+ );
87
+
88
+ // ---- aiaUiTools.generated.ts --------------------------------------------------
89
+ // Import only the types the builder methods reference (sub-declarations stay in uiContracts).
90
+ const used = new Set();
91
+ for (const r of rows)
92
+ for (const t of [r.argsTs, r.inputTs, r.answerTs, r.resultTs]) if (t && interfaces.has(t)) used.add(t);
93
+ const named = [...used].sort();
94
+ const askRows = rows.filter((r) => r.kind === 'askUser' && r.clientMethod);
95
+ const renderRows = rows.filter((r) => r.kind === 'render' && r.clientMethod);
96
+
97
+ const declAsk = askRows.map(
98
+ (r) => ` ${r.clientMethod}(renderers: UiToolAskUserRenderers<${r.inputTs}, ${r.answerTs}, ${r.resultTs}, ${r.argsTs}>): AiaUiToolRegistryBuilder;`,
99
+ );
100
+ const declRender = renderRows.map(
101
+ (r) => ` ${r.clientMethod}(render: UiToolRenderFn<${r.argsTs}, ${r.inputTs}>): AiaUiToolRegistryBuilder;`,
102
+ );
103
+ const implAsk = askRows.map(
104
+ (r) => ` ${r.clientMethod}: (renderers: UiToolAskUserRenderers<${r.inputTs}, ${r.answerTs}, ${r.resultTs}, ${r.argsTs}>) => b.askUser('${r.component}', renderers),`,
105
+ );
106
+ const implRender = renderRows.map(
107
+ (r) => ` ${r.clientMethod}: (render: UiToolRenderFn<${r.argsTs}, ${r.inputTs}>) => b.render('${r.toolName}', render),`,
108
+ );
109
+
110
+ const importTypes = named.length ? `import type { ${named.join(', ')} } from './uiContracts.generated';\n` : '';
111
+
112
+ writeFileSync(
113
+ join(outDir, 'aiaUiTools.generated.ts'),
114
+ `// AUTO-GENERATED by aia-gen-uitools — do not edit. Source: the server UiToolsManifest.
115
+ /* eslint-disable */
116
+ import {
117
+ createUiToolRegistry,
118
+ type UiToolRegistry,
119
+ type UiToolRegistryBuilder,
120
+ type UiToolArgs,
121
+ type UiToolRenderFn,
122
+ type UiToolActionFn,
123
+ type UiToolRenderOptions,
124
+ type UiToolActionOptions,
125
+ type UiToolAskUserRenderers,
126
+ } from '@aintela/chat';
127
+ ${importTypes}
128
+ /**
129
+ * A builder with the typed per-tool methods (askUpdateProfile, …). It EXTENDS @aintela/chat's
130
+ * UiToolRegistryBuilder rather than declaration-merging onto it — merging would force the library's own
131
+ * builder implementation (compiled from source in dev via the alias) to declare these app-specific methods.
132
+ * The inherited builder methods are re-declared to return THIS builder, so the fluent chain keeps the typed
133
+ * methods no matter the call order. (Signatures mirror @aintela/chat's UiToolRegistryBuilder; regenerate if
134
+ * that surface changes.)
135
+ */
136
+ export interface AiaUiToolRegistryBuilder extends UiToolRegistryBuilder {
137
+ render<TArgs = UiToolArgs, In = unknown>(name: string, render: UiToolRenderFn<TArgs, In>, opts?: UiToolRenderOptions<TArgs>): AiaUiToolRegistryBuilder;
138
+ action<TArgs = UiToolArgs, In = unknown>(name: string, run: UiToolActionFn<TArgs, In>, opts?: UiToolActionOptions<TArgs>): AiaUiToolRegistryBuilder;
139
+ askUser<In = unknown, Ans = unknown, Res = unknown, TArgs = UiToolArgs>(componentName: string, renderers: UiToolAskUserRenderers<In, Ans, Res, TArgs>, opts?: UiToolRenderOptions<TArgs>): AiaUiToolRegistryBuilder;
140
+ build(): UiToolRegistry;
141
+ ${[...declAsk, ...declRender].join('\n')}
142
+ }
143
+
144
+ // Each method delegates to the public askUser/render, pre-binding the component/tool name. Object.assign
145
+ // onto the one builder instance the factory returns, so chaining is preserved at runtime.
146
+ export function createAiaUiToolRegistry(): AiaUiToolRegistryBuilder {
147
+ const b = createUiToolRegistry() as AiaUiToolRegistryBuilder;
148
+ return Object.assign(b, {
149
+ ${[...implAsk, ...implRender].join('\n')}
150
+ });
151
+ }
152
+ `,
153
+ );
154
+
155
+ console.log(`aia-gen-uitools — ${interfaces.size} interfaces + ${askRows.length + renderRows.length} builder methods → ${outDir}`);