plugin-build-visualization-block 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +21 -0
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/dist/client/59.6bac6ada1dacea82.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/385.1e235c5081822f07.js +10 -0
  8. package/dist/client-v2/59.cdb723e410dac32b.js +10 -0
  9. package/dist/client-v2/index.js +37 -1
  10. package/dist/externalVersion.js +12 -7
  11. package/dist/locale/en-US.json +77 -37
  12. package/dist/locale/vi-VN.json +58 -40
  13. package/dist/locale/zh-CN.json +79 -40
  14. package/dist/node_modules/zod/index.cjs +1 -1
  15. package/dist/node_modules/zod/package.json +1 -1
  16. package/dist/server/actions/build.js +8 -720
  17. package/dist/server/collections/workflow-runs.js +51 -0
  18. package/dist/server/pipeline/analyzer.js +18 -4
  19. package/dist/server/plugin.js +17 -20
  20. package/dist/server/tools/build-visualization-block.js +9 -26
  21. package/dist/server/workflow-domain.js +209 -0
  22. package/dist/server/workflow.js +466 -0
  23. package/dist/shared/blockSpec.js +1 -1
  24. package/dist/shared/workflow.js +58 -0
  25. package/package.json +14 -3
  26. package/server.d.ts +2 -2
  27. package/server.js +1 -1
  28. package/src/client/locale.ts +18 -18
  29. package/src/client/plugin.tsx +11 -0
  30. package/src/client/workflow.ts +28 -0
  31. package/src/client-v2/__tests__/buildApi.test.ts +68 -0
  32. package/src/client-v2/__tests__/modelOptions.test.ts +190 -0
  33. package/src/client-v2/__tests__/nativeModels.test.ts +77 -0
  34. package/src/client-v2/buildApi.ts +93 -0
  35. package/src/client-v2/components/AISelectors.tsx +85 -0
  36. package/src/client-v2/components/BuildForm.tsx +186 -0
  37. package/src/client-v2/components/CollectionMultiSelect.tsx +63 -0
  38. package/src/client-v2/components/NativePreview.tsx +53 -0
  39. package/src/client-v2/locale.ts +5 -0
  40. package/src/client-v2/modelOptions.ts +201 -0
  41. package/src/client-v2/models/BuildVisualizationBlockModel.tsx +95 -0
  42. package/src/client-v2/nativeBlock.ts +28 -0
  43. package/src/client-v2/pages/SettingsPage.tsx +77 -0
  44. package/src/client-v2/plugin.tsx +17 -4
  45. package/src/client-v2/workflow-fields.tsx +23 -0
  46. package/src/client-v2/workflow.ts +28 -0
  47. package/src/locale/en-US.json +77 -37
  48. package/src/locale/namespace.ts +6 -6
  49. package/src/locale/vi-VN.json +58 -40
  50. package/src/locale/zh-CN.json +79 -40
  51. package/src/server/__tests__/build-action.test.ts +121 -117
  52. package/src/server/__tests__/plugin.test.ts +19 -34
  53. package/src/server/actions/build.ts +268 -1318
  54. package/src/server/collections/workflow-runs.ts +30 -0
  55. package/src/server/pipeline/analyzer.ts +395 -368
  56. package/src/server/plugin.ts +26 -35
  57. package/src/server/tools/build-visualization-block.ts +18 -28
  58. package/src/server/workflow-domain.ts +235 -0
  59. package/src/server/workflow.ts +519 -0
  60. package/src/shared/blockSpec.ts +10 -1
  61. package/src/shared/workflow.ts +26 -0
  62. package/dist/client-v2/812.6b4f5e757b898c82.js +0 -10
@@ -1,368 +1,395 @@
1
- /**
2
- * AI Analyzer pipeline stage for `plugin-build-visualization-block`.
3
- *
4
- * This module is built incrementally:
5
- * - Task 4.1 (this file) implements the pure output-cleaning and JSON-extraction
6
- * helpers ported from `plugin-build-guide-block`'s `build.ts`:
7
- * `stripThink`, `stripFence`, `toPlainText`, and `extractJsonObject`.
8
- * - Task 4.2 adds the LLM provider invocation (prompt + `chatModel.invoke`).
9
- * - Task 4.3 adds `JSON.parse` + `blockSpecSchema.safeParse` and the fallback.
10
- *
11
- * The helpers below are intentionally pure string functions with no imports
12
- * from `@nocobase/*` or `zod`, so they can be unit-tested in isolation and
13
- * reused by the parse/fallback logic in task 4.3.
14
- */
15
-
16
- /**
17
- * Remove `<think>...</think>` reasoning blocks from model output.
18
- *
19
- * Handles an unclosed `<think>` tag (matches through end of string) and is
20
- * case-insensitive. Ported from `plugin-build-guide-block`'s `build.ts`.
21
- */
22
- export function stripThink(text: string): string {
23
- return text.replace(/<think>[\s\S]*?(?:<\/think>|$)/gi, '').trim();
24
- }
25
-
26
- /**
27
- * Strip a leading code fence (```json / ```markdown / ```md / ```html / ```)
28
- * and a trailing closing fence from model output. Ported from
29
- * `plugin-build-guide-block`'s `build.ts`.
30
- */
31
- export function stripFence(text: string): string {
32
- return text
33
- .replace(/^```(?:json|markdown|md|html)?\s*/i, '')
34
- .replace(/```\s*$/i, '')
35
- .trim();
36
- }
37
-
38
- /**
39
- * Coerce LangChain message content into plain text.
40
- *
41
- * Message content can be a plain string, an array of content parts (strings or
42
- * objects exposing `text`/`content`), or an object exposing `text`/`content`.
43
- * Anything else falls back to a JSON serialization. Ported from
44
- * `plugin-build-guide-block`'s `build.ts` (`toPlainText`), narrowed to avoid
45
- * `any`.
46
- */
47
- export function toPlainText(value: unknown): string {
48
- if (typeof value === 'string') {
49
- return value;
50
- }
51
- if (Array.isArray(value)) {
52
- return value
53
- .map((item) => {
54
- if (typeof item === 'string') {
55
- return item;
56
- }
57
- if (item && typeof item === 'object') {
58
- const part = item as { text?: unknown; content?: unknown };
59
- if (typeof part.text === 'string') {
60
- return part.text;
61
- }
62
- if (typeof part.content === 'string') {
63
- return part.content;
64
- }
65
- }
66
- return '';
67
- })
68
- .filter(Boolean)
69
- .join('\n');
70
- }
71
- if (value && typeof value === 'object') {
72
- const obj = value as { text?: unknown; content?: unknown };
73
- const text = obj.text ?? obj.content;
74
- if (typeof text === 'string') {
75
- return text;
76
- }
77
- }
78
- return JSON.stringify(value);
79
- }
80
-
81
- /**
82
- * Clean raw model output and extract the JSON object substring.
83
- *
84
- * Applies `stripThink` then `stripFence`, then returns the substring from the
85
- * first `{` to the last `}` (inclusive). When no balanced brace pair is found,
86
- * returns the cleaned text unchanged. Mirrors the brace-extraction logic in
87
- * `plugin-build-guide-block`'s `normalizePlan`.
88
- */
89
- export function extractJsonObject(text: string): string {
90
- const cleanText = stripFence(stripThink(text));
91
- const jsonStart = cleanText.indexOf('{');
92
- const jsonEnd = cleanText.lastIndexOf('}');
93
- return jsonStart >= 0 && jsonEnd > jsonStart ? cleanText.slice(jsonStart, jsonEnd + 1) : cleanText;
94
- }
95
-
96
- /*
97
- * Task 4.2: LLM provider acquisition + prompt construction + timed invocation.
98
- *
99
- * These exports are kept separate so task 4.3 can compose them (together with
100
- * the cleaning helpers above) into the full `analyze(...)` stage that adds
101
- * `JSON.parse` + `blockSpecSchema.safeParse` and the fallback.
102
- */
103
-
104
- import type { Application } from '@nocobase/server';
105
- import { HumanMessage, SystemMessage } from '@langchain/core/messages';
106
- import { BlockSpec, SchemaSummary, blockSpecSchema } from '../../shared/blockSpec';
107
- import { LLM_TIMEOUT_MS } from '../../shared/constants';
108
- import { buildFallbackSpec } from './fallback';
109
-
110
- /**
111
- * The messages sent to a chat model: a system message establishing the
112
- * JSON-only contract followed by a human message carrying the request.
113
- */
114
- export type AnalyzerMessage = SystemMessage | HumanMessage;
115
-
116
- /**
117
- * The minimal LLM provider surface this stage relies on. The AI plugin's
118
- * `getLLMService` returns a richer provider; we narrow to just the chat model
119
- * `invoke` call so our own code stays typed without depending on `any`.
120
- */
121
- export interface LLMProvider {
122
- chatModel: {
123
- invoke(messages: AnalyzerMessage[]): Promise<{ content: unknown }>;
124
- };
125
- }
126
-
127
- interface AIPluginLike {
128
- aiManager: {
129
- getLLMService(args: { llmService: string; model: string }): Promise<{ provider: LLMProvider }>;
130
- };
131
- }
132
-
133
- /**
134
- * Inputs to {@link buildAnalyzerMessages}.
135
- */
136
- export interface BuildAnalyzerMessagesParams {
137
- /** The user's natural-language requirement. */
138
- requirement: string;
139
- /** The introspected schema for the selected collections. */
140
- summary: SchemaSummary;
141
- }
142
-
143
- /**
144
- * Resolve the chat-model provider from the AI plugin.
145
- *
146
- * Ported from `plugin-build-guide-block`'s `build.ts`: looks up the `ai`
147
- * plugin, asks its `aiManager` for the configured LLM service, and returns the
148
- * provider. Throws when the AI plugin is not installed/available.
149
- */
150
- export async function getLLMProvider(app: Application, llmService: string, model: string): Promise<LLMProvider> {
151
- const aiPlugin = app.pm.get('ai') as AIPluginLike | undefined;
152
- if (!aiPlugin) {
153
- throw new Error('Plugin AI is not available');
154
- }
155
- const serviceData = await aiPlugin.aiManager.getLLMService({ llmService, model });
156
- return serviceData.provider;
157
- }
158
-
159
- /**
160
- * Produce a compact, token-friendly serialization of the schema summary. Only
161
- * the fields the model needs to choose collections/fields are included
162
- * (collection name + field name/type/interface + relation name/type/target).
163
- */
164
- function compactSummary(summary: SchemaSummary): unknown {
165
- return {
166
- dataSource: summary.dataSource,
167
- collections: summary.collections.map((collection) => ({
168
- name: collection.name,
169
- ...(collection.introspectionFailed ? { introspectionFailed: true } : {}),
170
- fields: collection.fields.map((field) => ({
171
- name: field.name,
172
- type: field.type,
173
- interface: field.interface,
174
- })),
175
- relations: collection.relations.map((relation) => ({
176
- name: relation.name,
177
- type: relation.type,
178
- target: relation.target,
179
- })),
180
- })),
181
- };
182
- }
183
-
184
- /**
185
- * The system prompt: establishes the assistant's role and the strict
186
- * JSON-only contract describing the {@link import('../../shared/blockSpec').BlockSpec}
187
- * shape the model must return.
188
- */
189
- const SYSTEM_PROMPT = `You are a NocoBase block designer. Given a natural-language requirement and a JSON description of the available collections (with their fields and relations), design exactly one block: a chart, a table, or a form.
190
-
191
- Return ONLY one JSON object. Do not include any prose, explanation, Markdown, or code fences. The JSON object must conform to this BlockSpec shape:
192
-
193
- {
194
- "version": 1,
195
- "blockType": "chart" | "table" | "form",
196
- "title": string,
197
- "primaryCollection": string, // a collection name from the provided schema; the block is bound to it
198
- "dataSource": string, // the provided dataSource
199
- // include exactly one of the following payloads, matching blockType:
200
- // when blockType === "chart":
201
- "charts": [
202
- {
203
- "key": string,
204
- "title": string,
205
- "chartType": string, // e.g. "ant-design-charts.pie", "ant-design-charts.column", "antd.statistic"
206
- "measures": [
207
- { "field": string, "aggregation": "count" | "sum" | "avg" | "max" | "min", "alias": string }
208
- ],
209
- "dimensions": [ { "field": string } ]
210
- }
211
- ],
212
- // when blockType === "table":
213
- "table": { "fields": [string] },
214
- // when blockType === "form":
215
- "form": { "fields": [string] }
216
- }
217
-
218
- Rules:
219
- - Use ONLY collections, fields, and relations that appear in the provided schema. Never invent field names.
220
- - "primaryCollection" must be one of the provided collection names.
221
- - "dataSource" must equal the provided dataSource.
222
- - Always set "version" to 1.
223
- - Choose the blockType that best satisfies the requirement and include only that type's payload.
224
- - Output the single JSON object and nothing else.`;
225
-
226
- /**
227
- * Build the `[SystemMessage, HumanMessage]` pair for the analyzer. The human
228
- * message carries the requirement and a compact JSON serialization of the
229
- * schema summary.
230
- */
231
- export function buildAnalyzerMessages(params: BuildAnalyzerMessagesParams): AnalyzerMessage[] {
232
- const { requirement, summary } = params;
233
- const schemaJson = JSON.stringify(compactSummary(summary));
234
- return [
235
- new SystemMessage(SYSTEM_PROMPT),
236
- new HumanMessage(`Requirement:
237
- ${requirement}
238
-
239
- Available schema (JSON):
240
- ${schemaJson}
241
-
242
- Return ONLY the BlockSpec JSON object.`),
243
- ];
244
- }
245
-
246
- /**
247
- * Invoke the chat model with a hard timeout of {@link LLM_TIMEOUT_MS}.
248
- *
249
- * Races the model call against a timer that rejects with a clear error, so a
250
- * hung provider can never block the build worker indefinitely. The raw model
251
- * output is cleaned (`stripThink`/`stripFence`) and reduced to the outermost
252
- * JSON object via {@link extractJsonObject}; parsing/validation/fallback are
253
- * handled by task 4.3.
254
- */
255
- export async function invokeLLM(provider: LLMProvider, messages: AnalyzerMessage[]): Promise<string> {
256
- let timer: ReturnType<typeof setTimeout> | undefined;
257
- const timeout = new Promise<never>((_resolve, reject) => {
258
- timer = setTimeout(() => reject(new Error(`LLM invocation timed out after ${LLM_TIMEOUT_MS}ms`)), LLM_TIMEOUT_MS);
259
- });
260
- try {
261
- const response = await Promise.race([provider.chatModel.invoke(messages), timeout]);
262
- return extractJsonObject(toPlainText(response.content));
263
- } finally {
264
- if (timer) {
265
- clearTimeout(timer);
266
- }
267
- }
268
- }
269
-
270
- /*
271
- * Task 4.3: full analyzer entry — compose provider acquisition + invocation
272
- * (task 4.2), output cleaning + JSON extraction (task 4.1), shape validation,
273
- * and the grounded fallback (task 4.4) into a single `analyze(...)` stage.
274
- */
275
-
276
- /**
277
- * The result of running the AI Analyzer stage.
278
- *
279
- * `spec` is always a usable {@link BlockSpec}: either the model's validated
280
- * output, or — when the model output cannot be parsed/validated or the LLM call
281
- * fails (timeout/transport) — the grounded fallback from
282
- * {@link buildFallbackSpec}. `usedFallback` records which path produced `spec`,
283
- * and `error` carries a concise human-readable reason for the fallback so the
284
- * caller (task 7.2) can persist it on the Build_Record. `analyze` performs no
285
- * DB writes itself.
286
- */
287
- export interface AnalyzeResult {
288
- spec: BlockSpec;
289
- usedFallback: boolean;
290
- error?: string;
291
- }
292
-
293
- /**
294
- * Inputs to {@link analyze}.
295
- */
296
- export interface AnalyzeParams {
297
- /** The user's natural-language requirement. */
298
- requirement: string;
299
- /** The introspected schema for the selected collections. */
300
- summary: SchemaSummary;
301
- /** The configured AI plugin LLM service name. */
302
- llmService: string;
303
- /** The model to invoke within that service. */
304
- model: string;
305
- }
306
-
307
- /**
308
- * Parse and shape-validate raw LLM output into a {@link BlockSpec}.
309
- *
310
- * Runs `JSON.parse` followed by `blockSpecSchema.safeParse`. On either failure
311
- * returns `{ ok: false, error }` with a concise message describing what went
312
- * wrong (Req 5.5); the caller turns that into a fallback. The input is expected
313
- * to already be the extracted JSON-object substring produced by
314
- * {@link invokeLLM} / {@link extractJsonObject}.
315
- */
316
- export function parseBlockSpec(raw: string): { ok: true; spec: BlockSpec } | { ok: false; error: string } {
317
- let parsed: unknown;
318
- try {
319
- parsed = JSON.parse(raw);
320
- } catch (err) {
321
- const reason = err instanceof Error ? err.message : String(err);
322
- return { ok: false, error: `Failed to parse LLM output as JSON: ${reason}` };
323
- }
324
-
325
- const result = blockSpecSchema.safeParse(parsed);
326
- if (!result.success) {
327
- const reason = result.error.issues
328
- .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)
329
- .join('; ');
330
- return { ok: false, error: `LLM output did not match BlockSpec shape: ${reason}` };
331
- }
332
-
333
- return { ok: true, spec: result.data as BlockSpec };
334
- }
335
-
336
- /**
337
- * Run the AI Analyzer stage: invoke the configured LLM with a prompt built from
338
- * the requirement + schema summary, then parse and shape-validate the output
339
- * into a {@link BlockSpec}.
340
- *
341
- * Failure handling (the result is always usable):
342
- * - parse/shape failure (Req 5.5) → grounded fallback with the parse error.
343
- * - LLM error / timeout / transport failure (Req 5.6) → grounded fallback with
344
- * the underlying error message.
345
- *
346
- * `analyze` never writes to the database; it returns `error` so the caller
347
- * (task 7.2) can record it on the Build_Record.
348
- */
349
- export async function analyze(app: Application, params: AnalyzeParams): Promise<AnalyzeResult> {
350
- const { requirement, summary, llmService, model } = params;
351
-
352
- let raw: string;
353
- try {
354
- const provider = await getLLMProvider(app, llmService, model);
355
- const messages = buildAnalyzerMessages({ requirement, summary });
356
- raw = await invokeLLM(provider, messages);
357
- } catch (err) {
358
- const error = err instanceof Error ? err.message : String(err);
359
- return { spec: buildFallbackSpec(summary), usedFallback: true, error };
360
- }
361
-
362
- const parsed = parseBlockSpec(raw);
363
- if (parsed.ok) {
364
- return { spec: parsed.spec, usedFallback: false };
365
- }
366
-
367
- return { spec: buildFallbackSpec(summary), usedFallback: true, error: parsed.error };
368
- }
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ /**
11
+ * AI Analyzer pipeline stage for `plugin-build-visualization-block`.
12
+ *
13
+ * This module is built incrementally:
14
+ * - Task 4.1 (this file) implements the pure output-cleaning and JSON-extraction
15
+ * helpers ported from `plugin-build-guide-block`'s `build.ts`:
16
+ * `stripThink`, `stripFence`, `toPlainText`, and `extractJsonObject`.
17
+ * - Task 4.2 adds the LLM provider invocation (prompt + `chatModel.invoke`).
18
+ * - Task 4.3 adds `JSON.parse` + `blockSpecSchema.safeParse` and the fallback.
19
+ *
20
+ * The helpers below are intentionally pure string functions with no imports
21
+ * from `@nocobase/*` or `zod`, so they can be unit-tested in isolation and
22
+ * reused by the parse/fallback logic in task 4.3.
23
+ */
24
+
25
+ /**
26
+ * Remove `<think>...</think>` reasoning blocks from model output.
27
+ *
28
+ * Handles an unclosed `<think>` tag (matches through end of string) and is
29
+ * case-insensitive. Ported from `plugin-build-guide-block`'s `build.ts`.
30
+ */
31
+ export function stripThink(text: string): string {
32
+ return text.replace(/<think>[\s\S]*?(?:<\/think>|$)/gi, '').trim();
33
+ }
34
+
35
+ /**
36
+ * Strip a leading code fence (```json / ```markdown / ```md / ```html / ```)
37
+ * and a trailing closing fence from model output. Ported from
38
+ * `plugin-build-guide-block`'s `build.ts`.
39
+ */
40
+ export function stripFence(text: string): string {
41
+ return text
42
+ .replace(/^```(?:json|markdown|md|html)?\s*/i, '')
43
+ .replace(/```\s*$/i, '')
44
+ .trim();
45
+ }
46
+
47
+ /**
48
+ * Coerce LangChain message content into plain text.
49
+ *
50
+ * Message content can be a plain string, an array of content parts (strings or
51
+ * objects exposing `text`/`content`), or an object exposing `text`/`content`.
52
+ * Anything else falls back to a JSON serialization. Ported from
53
+ * `plugin-build-guide-block`'s `build.ts` (`toPlainText`), narrowed to avoid
54
+ * `any`.
55
+ */
56
+ export function toPlainText(value: unknown): string {
57
+ if (typeof value === 'string') {
58
+ return value;
59
+ }
60
+ if (Array.isArray(value)) {
61
+ return value
62
+ .map((item) => {
63
+ if (typeof item === 'string') {
64
+ return item;
65
+ }
66
+ if (item && typeof item === 'object') {
67
+ const part = item as { text?: unknown; content?: unknown };
68
+ if (typeof part.text === 'string') {
69
+ return part.text;
70
+ }
71
+ if (typeof part.content === 'string') {
72
+ return part.content;
73
+ }
74
+ }
75
+ return '';
76
+ })
77
+ .filter(Boolean)
78
+ .join('\n');
79
+ }
80
+ if (value && typeof value === 'object') {
81
+ const obj = value as { text?: unknown; content?: unknown };
82
+ const text = obj.text ?? obj.content;
83
+ if (typeof text === 'string') {
84
+ return text;
85
+ }
86
+ }
87
+ return JSON.stringify(value);
88
+ }
89
+
90
+ /**
91
+ * Clean raw model output and extract the JSON object substring.
92
+ *
93
+ * Applies `stripThink` then `stripFence`, then returns the substring from the
94
+ * first `{` to the last `}` (inclusive). When no balanced brace pair is found,
95
+ * returns the cleaned text unchanged. Mirrors the brace-extraction logic in
96
+ * `plugin-build-guide-block`'s `normalizePlan`.
97
+ */
98
+ export function extractJsonObject(text: string): string {
99
+ const cleanText = stripFence(stripThink(text));
100
+ const jsonStart = cleanText.indexOf('{');
101
+ const jsonEnd = cleanText.lastIndexOf('}');
102
+ return jsonStart >= 0 && jsonEnd > jsonStart ? cleanText.slice(jsonStart, jsonEnd + 1) : cleanText;
103
+ }
104
+
105
+ /*
106
+ * Task 4.2: LLM provider acquisition + prompt construction + timed invocation.
107
+ *
108
+ * These exports are kept separate so task 4.3 can compose them (together with
109
+ * the cleaning helpers above) into the full `analyze(...)` stage that adds
110
+ * `JSON.parse` + `blockSpecSchema.safeParse` and the fallback.
111
+ */
112
+
113
+ import type { Application } from '@nocobase/server';
114
+ import { HumanMessage, SystemMessage } from '@langchain/core/messages';
115
+ import { BlockSpec, SchemaSummary, blockSpecSchema } from '../../shared/blockSpec';
116
+ import { LLM_TIMEOUT_MS } from '../../shared/constants';
117
+ import { buildFallbackSpec } from './fallback';
118
+
119
+ /**
120
+ * The messages sent to a chat model: a system message establishing the
121
+ * JSON-only contract followed by a human message carrying the request.
122
+ */
123
+ export type AnalyzerMessage = SystemMessage | HumanMessage;
124
+
125
+ /**
126
+ * The minimal LLM provider surface this stage relies on. The AI plugin's
127
+ * `getLLMService` returns a richer provider; we narrow to just the chat model
128
+ * `invoke` call so our own code stays typed without depending on `any`.
129
+ */
130
+ export interface LLMProvider {
131
+ chatModel: {
132
+ invoke(messages: AnalyzerMessage[], options?: { signal?: AbortSignal }): Promise<{ content: unknown }>;
133
+ };
134
+ }
135
+
136
+ interface AIPluginLike {
137
+ aiManager: {
138
+ getLLMService(args: { llmService: string; model: string }): Promise<{ provider: LLMProvider }>;
139
+ };
140
+ }
141
+
142
+ /**
143
+ * Inputs to {@link buildAnalyzerMessages}.
144
+ */
145
+ export interface BuildAnalyzerMessagesParams {
146
+ /** The user's natural-language requirement. */
147
+ requirement: string;
148
+ /** The introspected schema for the selected collections. */
149
+ summary: SchemaSummary;
150
+ }
151
+
152
+ /**
153
+ * Resolve the chat-model provider from the AI plugin.
154
+ *
155
+ * Ported from `plugin-build-guide-block`'s `build.ts`: looks up the `ai`
156
+ * plugin, asks its `aiManager` for the configured LLM service, and returns the
157
+ * provider. Throws when the AI plugin is not installed/available.
158
+ */
159
+ export async function getLLMProvider(app: Application, llmService: string, model: string): Promise<LLMProvider> {
160
+ const aiPlugin = app.pm.get('ai') as unknown as AIPluginLike | undefined;
161
+ if (!aiPlugin) {
162
+ throw new Error('Plugin AI is not available');
163
+ }
164
+ const serviceData = await aiPlugin.aiManager.getLLMService({ llmService, model });
165
+ return serviceData.provider;
166
+ }
167
+
168
+ /**
169
+ * Produce a compact, token-friendly serialization of the schema summary. Only
170
+ * the fields the model needs to choose collections/fields are included
171
+ * (collection name + field name/type/interface + relation name/type/target).
172
+ */
173
+ function compactSummary(summary: SchemaSummary): unknown {
174
+ return {
175
+ dataSource: summary.dataSource,
176
+ collections: summary.collections.map((collection) => ({
177
+ name: collection.name,
178
+ ...(collection.introspectionFailed ? { introspectionFailed: true } : {}),
179
+ fields: collection.fields.map((field) => ({
180
+ name: field.name,
181
+ type: field.type,
182
+ interface: field.interface,
183
+ })),
184
+ relations: collection.relations.map((relation) => ({
185
+ name: relation.name,
186
+ type: relation.type,
187
+ target: relation.target,
188
+ })),
189
+ })),
190
+ };
191
+ }
192
+
193
+ /**
194
+ * The system prompt: establishes the assistant's role and the strict
195
+ * JSON-only contract describing the {@link import('../../shared/blockSpec').BlockSpec}
196
+ * shape the model must return.
197
+ */
198
+ const SYSTEM_PROMPT = `You are a NocoBase block designer. Given a natural-language requirement and a JSON description of the available collections (with their fields and relations), design exactly one block: a chart, a table, or a form.
199
+
200
+ Return ONLY one JSON object. Do not include any prose, explanation, Markdown, or code fences. The JSON object must conform to this BlockSpec shape:
201
+
202
+ {
203
+ "version": 1,
204
+ "blockType": "chart" | "table" | "form",
205
+ "title": string,
206
+ "primaryCollection": string, // a collection name from the provided schema; the block is bound to it
207
+ "dataSource": string, // the provided dataSource
208
+ // include exactly one of the following payloads, matching blockType:
209
+ // when blockType === "chart":
210
+ "charts": [
211
+ {
212
+ "key": string,
213
+ "title": string,
214
+ "chartType": string, // e.g. "ant-design-charts.pie", "ant-design-charts.column", "antd.statistic"
215
+ "measures": [
216
+ { "field": string, "aggregation": "count" | "sum" | "avg" | "max" | "min", "alias": string }
217
+ ],
218
+ "dimensions": [ { "field": string } ]
219
+ }
220
+ ],
221
+ // when blockType === "table":
222
+ "table": { "fields": [string] },
223
+ // when blockType === "form":
224
+ "form": { "fields": [string] }
225
+ }
226
+
227
+ Rules:
228
+ - Use ONLY collections, fields, and relations that appear in the provided schema. Never invent field names.
229
+ - "primaryCollection" must be one of the provided collection names.
230
+ - "dataSource" must equal the provided dataSource.
231
+ - Always set "version" to 1.
232
+ - Choose the blockType that best satisfies the requirement and include only that type's payload.
233
+ - Output the single JSON object and nothing else.`;
234
+
235
+ /**
236
+ * Build the `[SystemMessage, HumanMessage]` pair for the analyzer. The human
237
+ * message carries the requirement and a compact JSON serialization of the
238
+ * schema summary.
239
+ */
240
+ export function buildAnalyzerMessages(params: BuildAnalyzerMessagesParams): AnalyzerMessage[] {
241
+ const { requirement, summary } = params;
242
+ const schemaJson = JSON.stringify(compactSummary(summary));
243
+ return [
244
+ new SystemMessage(SYSTEM_PROMPT),
245
+ new HumanMessage(`Requirement:
246
+ ${requirement}
247
+
248
+ Available schema (JSON):
249
+ ${schemaJson}
250
+
251
+ Return ONLY the BlockSpec JSON object.`),
252
+ ];
253
+ }
254
+
255
+ /**
256
+ * Invoke the chat model with a hard timeout of {@link LLM_TIMEOUT_MS}.
257
+ *
258
+ * Races the model call against a timer that rejects with a clear error, so a
259
+ * hung provider can never block the build worker indefinitely. The raw model
260
+ * output is cleaned (`stripThink`/`stripFence`) and reduced to the outermost
261
+ * JSON object via {@link extractJsonObject}; parsing/validation/fallback are
262
+ * handled by task 4.3.
263
+ */
264
+ export async function invokeLLM(
265
+ provider: LLMProvider,
266
+ messages: AnalyzerMessage[],
267
+ signal?: AbortSignal,
268
+ ): Promise<string> {
269
+ signal?.throwIfAborted();
270
+ let rejectAbort: (reason: unknown) => void;
271
+ const canceled = new Promise<never>((_resolve, reject) => {
272
+ rejectAbort = reject;
273
+ });
274
+ const onAbort = () => rejectAbort(signal.reason);
275
+ signal?.addEventListener('abort', onAbort, { once: true });
276
+ let timer: ReturnType<typeof setTimeout> | undefined;
277
+ const timeout = new Promise<never>((_resolve, reject) => {
278
+ timer = setTimeout(() => reject(new Error(`LLM invocation timed out after ${LLM_TIMEOUT_MS}ms`)), LLM_TIMEOUT_MS);
279
+ });
280
+ try {
281
+ const response = await Promise.race([
282
+ signal ? provider.chatModel.invoke(messages, { signal }) : provider.chatModel.invoke(messages),
283
+ timeout,
284
+ canceled,
285
+ ]);
286
+ return extractJsonObject(toPlainText(response.content));
287
+ } finally {
288
+ signal?.removeEventListener('abort', onAbort);
289
+ if (timer) {
290
+ clearTimeout(timer);
291
+ }
292
+ }
293
+ }
294
+
295
+ /*
296
+ * Task 4.3: full analyzer entry — compose provider acquisition + invocation
297
+ * (task 4.2), output cleaning + JSON extraction (task 4.1), shape validation,
298
+ * and the grounded fallback (task 4.4) into a single `analyze(...)` stage.
299
+ */
300
+
301
+ /**
302
+ * The result of running the AI Analyzer stage.
303
+ *
304
+ * `spec` is always a usable {@link BlockSpec}: either the model's validated
305
+ * output, or — when the model output cannot be parsed/validated or the LLM call
306
+ * fails (timeout/transport) — the grounded fallback from
307
+ * {@link buildFallbackSpec}. `usedFallback` records which path produced `spec`,
308
+ * and `error` carries a concise human-readable reason for the fallback so the
309
+ * caller (task 7.2) can persist it on the Build_Record. `analyze` performs no
310
+ * DB writes itself.
311
+ */
312
+ export interface AnalyzeResult {
313
+ spec: BlockSpec;
314
+ usedFallback: boolean;
315
+ error?: string;
316
+ }
317
+
318
+ /**
319
+ * Inputs to {@link analyze}.
320
+ */
321
+ export interface AnalyzeParams {
322
+ signal?: AbortSignal;
323
+ /** The user's natural-language requirement. */
324
+ requirement: string;
325
+ /** The introspected schema for the selected collections. */
326
+ summary: SchemaSummary;
327
+ /** The configured AI plugin LLM service name. */
328
+ llmService: string;
329
+ /** The model to invoke within that service. */
330
+ model: string;
331
+ }
332
+
333
+ /**
334
+ * Parse and shape-validate raw LLM output into a {@link BlockSpec}.
335
+ *
336
+ * Runs `JSON.parse` followed by `blockSpecSchema.safeParse`. On either failure
337
+ * returns `{ ok: false, error }` with a concise message describing what went
338
+ * wrong (Req 5.5); the caller turns that into a fallback. The input is expected
339
+ * to already be the extracted JSON-object substring produced by
340
+ * {@link invokeLLM} / {@link extractJsonObject}.
341
+ */
342
+ export function parseBlockSpec(raw: string): { ok: true; spec: BlockSpec } | { ok: false; error: string } {
343
+ let parsed: unknown;
344
+ try {
345
+ parsed = JSON.parse(raw);
346
+ } catch (err) {
347
+ const reason = err instanceof Error ? err.message : String(err);
348
+ return { ok: false, error: `Failed to parse LLM output as JSON: ${reason}` };
349
+ }
350
+
351
+ const result = blockSpecSchema.safeParse(parsed);
352
+ if (!result.success) {
353
+ const reason = result.error.issues
354
+ .map((issue) => `${issue.path.join('.') || '<root>'}: ${issue.message}`)
355
+ .join('; ');
356
+ return { ok: false, error: `LLM output did not match BlockSpec shape: ${reason}` };
357
+ }
358
+
359
+ return { ok: true, spec: result.data as BlockSpec };
360
+ }
361
+
362
+ /**
363
+ * Run the AI Analyzer stage: invoke the configured LLM with a prompt built from
364
+ * the requirement + schema summary, then parse and shape-validate the output
365
+ * into a {@link BlockSpec}.
366
+ *
367
+ * Failure handling (the result is always usable):
368
+ * - parse/shape failure (Req 5.5) → grounded fallback with the parse error.
369
+ * - LLM error / timeout / transport failure (Req 5.6) → grounded fallback with
370
+ * the underlying error message.
371
+ *
372
+ * `analyze` never writes to the database; it returns `error` so the caller
373
+ * (task 7.2) can record it on the Build_Record.
374
+ */
375
+ export async function analyze(app: Application, params: AnalyzeParams): Promise<AnalyzeResult> {
376
+ const { requirement, summary, llmService, model } = params;
377
+
378
+ let raw: string;
379
+ try {
380
+ const provider = await getLLMProvider(app, llmService, model);
381
+ const messages = buildAnalyzerMessages({ requirement, summary });
382
+ raw = await invokeLLM(provider, messages, params.signal);
383
+ } catch (err) {
384
+ params.signal?.throwIfAborted();
385
+ const error = err instanceof Error ? err.message : String(err);
386
+ return { spec: buildFallbackSpec(summary), usedFallback: true, error };
387
+ }
388
+
389
+ const parsed = parseBlockSpec(raw);
390
+ if (parsed.ok === true) {
391
+ return { spec: parsed.spec, usedFallback: false };
392
+ }
393
+
394
+ return { spec: buildFallbackSpec(summary), usedFallback: true, error: parsed.error };
395
+ }