plugin-build-visualization-block 0.1.5 → 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 +7 -704
  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 +15 -1031
  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
@@ -7,11 +7,9 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
 
10
- var __create = Object.create;
11
10
  var __defProp = Object.defineProperty;
12
11
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
12
  var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
13
  var __hasOwnProp = Object.prototype.hasOwnProperty;
16
14
  var __export = (target, all) => {
17
15
  for (var name in all)
@@ -25,655 +23,16 @@ var __copyProps = (to, from, except, desc) => {
25
23
  }
26
24
  return to;
27
25
  };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
27
  var build_exports = {};
38
28
  __export(build_exports, {
39
- WORKER_JOB_BUILD_VISUALIZATION_PROCESS: () => WORKER_JOB_BUILD_VISUALIZATION_PROCESS,
40
29
  build: () => build,
41
- enqueueBuild: () => enqueueBuild,
42
- failTimedOutBuilds: () => failTimedOutBuilds,
43
30
  getResult: () => getResult,
44
- processQueuedBuild: () => processQueuedBuild,
45
- recoverInterruptedBuilds: () => recoverInterruptedBuilds,
46
- registerBuildQueue: () => registerBuildQueue,
47
- retry: () => retry,
48
- startBuildQueueProcessor: () => startBuildQueueProcessor,
49
- unregisterBuildQueue: () => unregisterBuildQueue
31
+ retry: () => retry
50
32
  });
51
33
  module.exports = __toCommonJS(build_exports);
52
- var import_crypto = __toESM(require("crypto"));
34
+ var import_workflow_domain = require("../workflow-domain");
53
35
  var import_constants = require("../../shared/constants");
54
- var import_introspector = require("../pipeline/introspector");
55
- var import_analyzer = require("../pipeline/analyzer");
56
- var import_validator = require("../pipeline/validator");
57
- var import_generator = require("../pipeline/generator");
58
- var import_fallback = require("../pipeline/fallback");
59
- const WORKER_JOB_BUILD_VISUALIZATION_PROCESS = "build-visualization:process";
60
- const BUILD_VISUALIZATION_QUEUE_CHANNEL = "plugin-build-visualization-block.build";
61
- const BUILD_VISUALIZATION_WORKER_ALIASES = [
62
- BUILD_VISUALIZATION_QUEUE_CHANNEL,
63
- "plugin-build-visualization-block:build:queue"
64
- ];
65
- const BUILD_VISUALIZATION_QUEUE_WAKE_CHANNEL = "plugin-build-visualization-block.build.wake";
66
- const BUILD_VISUALIZATION_QUEUE_REDIS_CONNECTION = "plugin-build-visualization-block.build.queue";
67
- const BUILD_VISUALIZATION_QUEUE_CONCURRENCY = Math.max(
68
- 1,
69
- Number.parseInt(
70
- process.env.BUILD_VISUALIZATION_QUEUE_CONCURRENCY || process.env.BUILD_VISUALIZATION_MAX_CONCURRENCY || "1",
71
- 10
72
- ) || 1
73
- );
74
- const BUILD_VISUALIZATION_QUEUE_TIMEOUT_MS = Math.max(
75
- import_constants.BUILD_TIMEOUT_MS,
76
- Number.parseInt(process.env.BUILD_VISUALIZATION_QUEUE_TIMEOUT_MS || "", 10) || import_constants.BUILD_TIMEOUT_MS
77
- );
78
- const BUILD_VISUALIZATION_QUEUE_POLL_INTERVAL_MS = Math.max(
79
- 1e3,
80
- Number.parseInt(process.env.BUILD_VISUALIZATION_QUEUE_POLL_INTERVAL_MS || "", 10) || 5e3
81
- );
82
- const BUILD_RUN_LOCK_TTL_MS = Math.max(
83
- 6e4,
84
- Number.parseInt(process.env.BUILD_VISUALIZATION_RUN_LOCK_TTL_MS || "", 10) || 24 * 60 * 60 * 1e3
85
- );
86
- const BUILD_HEARTBEAT_INTERVAL_MS = Math.max(
87
- 5e3,
88
- Number.parseInt(process.env.BUILD_VISUALIZATION_HEARTBEAT_MS || "", 10) || 3e4
89
- );
90
- const BUILD_STALE_MS = Math.max(
91
- BUILD_HEARTBEAT_INTERVAL_MS * 2,
92
- Number.parseInt(process.env.BUILD_VISUALIZATION_STALE_MS || "", 10) || 12e4
93
- );
94
- function getPubSubManager(app) {
95
- return app.pubSubManager;
96
- }
97
- function getRedisConnectionManager(app) {
98
- return app.redisConnectionManager;
99
- }
100
- function getEventQueueInternals(app) {
101
- return app.eventQueue;
102
- }
103
- function getAppIdentity(app) {
104
- return app;
105
- }
106
- function getBuildModel(app) {
107
- return app.db.getModel(import_constants.COLLECTION_NAME);
108
- }
109
- const buildQueueStates = /* @__PURE__ */ new WeakMap();
110
- function getBuildQueueState(app) {
111
- let state = buildQueueStates.get(app);
112
- if (!state) {
113
- state = { timer: null, kickTimer: null, processing: false, wakeHandler: null };
114
- buildQueueStates.set(app, state);
115
- }
116
- return state;
117
- }
118
- class StaleBuildRunError extends Error {
119
- constructor(buildId, runId) {
120
- super(`Build run ${runId} for record ${buildId} is no longer current`);
121
- this.name = "StaleBuildRunError";
122
- }
123
- }
124
- function isBuildVisualizationWorker(app) {
125
- return app.serving(WORKER_JOB_BUILD_VISUALIZATION_PROCESS) || workerModeServesBuildVisualization();
126
- }
127
- function workerModeServesBuildVisualization() {
128
- const workerMode = process.env.WORKER_MODE || "";
129
- const workerModes = workerMode.split(",").map((mode) => mode.trim()).filter(Boolean);
130
- return workerModes.some((mode) => {
131
- if (mode === "*" || mode === "worker" || mode === "task" || mode === WORKER_JOB_BUILD_VISUALIZATION_PROCESS) {
132
- return true;
133
- }
134
- return BUILD_VISUALIZATION_WORKER_ALIASES.some((alias) => mode === alias || mode.endsWith(`:${alias}`));
135
- });
136
- }
137
- function getBuildWorkerId(app) {
138
- const identity = getAppIdentity(app);
139
- return [
140
- process.env.HOSTNAME || process.env.COMPUTERNAME || "worker",
141
- identity.name || "app",
142
- identity.instanceId || "0",
143
- process.pid
144
- ].join(":");
145
- }
146
- async function updateRecordForRun(app, run, values, optional = false) {
147
- const model = getBuildModel(app);
148
- const [affected] = await model.update(values, {
149
- where: {
150
- id: run.buildId,
151
- buildRunId: run.runId
152
- }
153
- });
154
- if (!affected && !optional) {
155
- throw new StaleBuildRunError(run.buildId, run.runId);
156
- }
157
- return affected > 0;
158
- }
159
- async function claimBuildRun(app, run, workerId) {
160
- const now = /* @__PURE__ */ new Date();
161
- const model = getBuildModel(app);
162
- const [affected] = await model.update(
163
- {
164
- buildPhase: "analyzing",
165
- buildStartedAt: now,
166
- buildHeartbeatAt: now,
167
- buildWorkerId: workerId
168
- },
169
- {
170
- where: {
171
- id: run.buildId,
172
- status: "building",
173
- buildPhase: "queued",
174
- buildRunId: run.runId
175
- }
176
- }
177
- );
178
- return affected > 0;
179
- }
180
- function startBuildHeartbeat(app, run) {
181
- const timer = setInterval(() => {
182
- updateRecordForRun(app, run, { buildHeartbeatAt: /* @__PURE__ */ new Date() }, true).catch((error) => {
183
- var _a, _b;
184
- (_b = (_a = app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `[plugin-build-visualization-block] Failed to update heartbeat for build ${run.runId}`, error);
185
- });
186
- }, BUILD_HEARTBEAT_INTERVAL_MS);
187
- return () => clearInterval(timer);
188
- }
189
- function getBuildQueueRedisKey(app) {
190
- const appName = getAppIdentity(app).name || process.env.APP_NAME || "main";
191
- return `${appName}:plugin-build-visualization-block:build:queue`;
192
- }
193
- async function getBuildQueueRedis(app) {
194
- var _a, _b;
195
- const manager = getRedisConnectionManager(app);
196
- if (!(manager == null ? void 0 : manager.getConnectionSync)) {
197
- return void 0;
198
- }
199
- try {
200
- const connectionString = process.env.QUEUE_ADAPTER_REDIS_URL || process.env.REDIS_URL;
201
- return await manager.getConnectionSync(
202
- BUILD_VISUALIZATION_QUEUE_REDIS_CONNECTION,
203
- connectionString ? { connectionString } : void 0
204
- );
205
- } catch (error) {
206
- (_b = (_a = app.log) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(
207
- _a,
208
- `[plugin-build-visualization-block] Redis queue unavailable; DB polling fallback active: ${error instanceof Error ? error.message : String(error)}`
209
- );
210
- return void 0;
211
- }
212
- }
213
- async function enqueueBuildToRedis(app, message) {
214
- var _a, _b, _c, _d;
215
- const redis = await getBuildQueueRedis(app);
216
- if (!redis) return false;
217
- try {
218
- await redis.sendCommand(["RPUSH", getBuildQueueRedisKey(app), JSON.stringify(message)]);
219
- (_b = (_a = app.log) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(
220
- _a,
221
- `[plugin-build-visualization-block] Enqueued build ${message.runId} for record "${message.buildId}" to Redis`
222
- );
223
- return true;
224
- } catch (error) {
225
- (_d = (_c = app.log) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(
226
- _c,
227
- `[plugin-build-visualization-block] Failed to enqueue build to Redis; DB polling fallback active`,
228
- error
229
- );
230
- return false;
231
- }
232
- }
233
- async function publishBuildQueueWake(app, message) {
234
- var _a, _b, _c, _d;
235
- try {
236
- await ((_b = (_a = getPubSubManager(app)) == null ? void 0 : _a.publish) == null ? void 0 : _b.call(
237
- _a,
238
- BUILD_VISUALIZATION_QUEUE_WAKE_CHANNEL,
239
- { buildId: message == null ? void 0 : message.buildId, runId: message == null ? void 0 : message.runId },
240
- { skipSelf: !isBuildVisualizationWorker(app) }
241
- ));
242
- } catch (error) {
243
- (_d = (_c = app.log) == null ? void 0 : _c.debug) == null ? void 0 : _d.call(
244
- _c,
245
- `[plugin-build-visualization-block] Wake publish skipped: ${error instanceof Error ? error.message : String(error)}`
246
- );
247
- }
248
- }
249
- async function drainRedisBuildQueue(app, count) {
250
- var _a, _b;
251
- const redis = await getBuildQueueRedis(app);
252
- if (!redis) return [];
253
- const key = getBuildQueueRedisKey(app);
254
- const messages = [];
255
- for (let i = 0; i < count; i += 1) {
256
- const raw = await redis.sendCommand(["LPOP", key]);
257
- if (!raw) break;
258
- try {
259
- messages.push(JSON.parse(String(raw)));
260
- } catch (error) {
261
- (_b = (_a = app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(
262
- _a,
263
- `[plugin-build-visualization-block] Dropped invalid Redis build message: ${error instanceof Error ? error.message : String(error)}`
264
- );
265
- }
266
- }
267
- return messages;
268
- }
269
- function clearLocalBuildMemoryQueue(app) {
270
- var _a, _b, _c, _d, _e, _f, _g;
271
- const eventQueue = getEventQueueInternals(app);
272
- const fullChannel = (_a = eventQueue.getFullChannel) == null ? void 0 : _a.call(eventQueue, BUILD_VISUALIZATION_QUEUE_CHANNEL);
273
- const { adapter } = eventQueue;
274
- const queue = fullChannel ? (_c = (_b = adapter == null ? void 0 : adapter.queues) == null ? void 0 : _b.get) == null ? void 0 : _c.call(_b, fullChannel) : void 0;
275
- if (!(queue == null ? void 0 : queue.length)) return;
276
- (_e = (_d = adapter == null ? void 0 : adapter.queues) == null ? void 0 : _d.set) == null ? void 0 : _e.call(_d, fullChannel, []);
277
- (_g = (_f = app.log) == null ? void 0 : _f.warn) == null ? void 0 : _g.call(
278
- _f,
279
- `[plugin-build-visualization-block] Cleared ${queue.length} stale local memory message(s) on non-worker node; queued DB builds will be picked up by workers`
280
- );
281
- }
282
- function startBuildQueueProcessor(app) {
283
- var _a, _b, _c, _d, _e, _f, _g, _h;
284
- const state = getBuildQueueState(app);
285
- if (!isBuildVisualizationWorker(app)) {
286
- (_b = (_a = app.log) == null ? void 0 : _a.debug) == null ? void 0 : _b.call(_a, "[plugin-build-visualization-block] Build queue processor disabled on non-worker node");
287
- return;
288
- }
289
- if (state.timer) return;
290
- state.wakeHandler = async () => {
291
- scheduleBuildQueueTick(app, 0);
292
- };
293
- const subscribe = (_d = (_c = getPubSubManager(app)) == null ? void 0 : _c.subscribe) == null ? void 0 : _d.call(_c, BUILD_VISUALIZATION_QUEUE_WAKE_CHANNEL, state.wakeHandler);
294
- if (subscribe instanceof Promise) {
295
- subscribe.catch((error) => {
296
- var _a2, _b2;
297
- (_b2 = (_a2 = app.log) == null ? void 0 : _a2.debug) == null ? void 0 : _b2.call(
298
- _a2,
299
- `[plugin-build-visualization-block] Wake subscribe skipped: ${error instanceof Error ? error.message : String(error)}`
300
- );
301
- });
302
- }
303
- state.timer = setInterval(() => scheduleBuildQueueTick(app, 0), BUILD_VISUALIZATION_QUEUE_POLL_INTERVAL_MS);
304
- (_f = (_e = state.timer).unref) == null ? void 0 : _f.call(_e);
305
- scheduleBuildQueueTick(app, 1e3);
306
- (_h = (_g = app.log) == null ? void 0 : _g.info) == null ? void 0 : _h.call(
307
- _g,
308
- `[plugin-build-visualization-block] Build queue processor started (interval ${BUILD_VISUALIZATION_QUEUE_POLL_INTERVAL_MS}ms)`
309
- );
310
- }
311
- function stopBuildVisualizationQueueProcessor(app) {
312
- var _a, _b;
313
- const state = getBuildQueueState(app);
314
- if (state.timer) {
315
- clearInterval(state.timer);
316
- state.timer = null;
317
- }
318
- if (state.kickTimer) {
319
- clearTimeout(state.kickTimer);
320
- state.kickTimer = null;
321
- }
322
- if (state.wakeHandler) {
323
- const unsubscribe = (_b = (_a = getPubSubManager(app)) == null ? void 0 : _a.unsubscribe) == null ? void 0 : _b.call(_a, BUILD_VISUALIZATION_QUEUE_WAKE_CHANNEL, state.wakeHandler);
324
- if (unsubscribe instanceof Promise) {
325
- unsubscribe.catch(() => void 0);
326
- }
327
- state.wakeHandler = null;
328
- }
329
- state.processing = false;
330
- }
331
- function scheduleBuildQueueTick(app, delayMs) {
332
- var _a, _b;
333
- const state = getBuildQueueState(app);
334
- if (state.kickTimer) return;
335
- state.kickTimer = setTimeout(() => {
336
- state.kickTimer = null;
337
- runBuildQueueTick(app).catch((error) => {
338
- var _a2, _b2;
339
- (_b2 = (_a2 = app.log) == null ? void 0 : _a2.error) == null ? void 0 : _b2.call(_a2, "[plugin-build-visualization-block] Build queue tick failed", error);
340
- });
341
- }, delayMs);
342
- (_b = (_a = state.kickTimer).unref) == null ? void 0 : _b.call(_a);
343
- }
344
- async function runBuildQueueTick(app) {
345
- const state = getBuildQueueState(app);
346
- if (state.processing || !isBuildVisualizationWorker(app)) return;
347
- state.processing = true;
348
- try {
349
- await failTimedOutBuilds(app);
350
- const redisMessages = await drainRedisBuildQueue(app, BUILD_VISUALIZATION_QUEUE_CONCURRENCY);
351
- await processBuildQueueMessages(app, redisMessages);
352
- const remaining = Math.max(1, BUILD_VISUALIZATION_QUEUE_CONCURRENCY - redisMessages.length);
353
- await processQueuedBuildsFromDb(app, remaining);
354
- } finally {
355
- state.processing = false;
356
- }
357
- }
358
- function createBuildQueueMessageFromRecord(record) {
359
- const runId = record.get("buildRunId");
360
- if (!runId) return null;
361
- const queuedAtRaw = record.get("buildQueuedAt");
362
- const createdById = record.get("createdById");
363
- return {
364
- buildId: String(record.get("id")),
365
- runId: String(runId),
366
- userId: typeof createdById === "number" || typeof createdById === "string" ? createdById : null,
367
- queuedAt: queuedAtRaw ? new Date(queuedAtRaw).toISOString() : (/* @__PURE__ */ new Date()).toISOString()
368
- };
369
- }
370
- async function processQueuedBuildsFromDb(app, count) {
371
- const repository = app.db.getRepository(import_constants.COLLECTION_NAME);
372
- const records = await repository.find({
373
- filter: {
374
- status: "building",
375
- buildPhase: "queued"
376
- },
377
- sort: ["buildQueuedAt"],
378
- limit: count
379
- });
380
- const messages = records.map((record) => createBuildQueueMessageFromRecord(record)).filter((message) => message !== null);
381
- await processBuildQueueMessages(app, messages);
382
- }
383
- async function processBuildQueueMessages(app, messages) {
384
- if (!messages.length) return;
385
- await Promise.all(messages.map((message) => processQueuedBuild(app, message)));
386
- }
387
- async function runBuild(app, db, run) {
388
- const repository = db.getRepository(import_constants.COLLECTION_NAME);
389
- const record = await repository.findById(run.buildId);
390
- if (!record) {
391
- throw new Error("Build record not found");
392
- }
393
- if (record.get("buildRunId") !== run.runId) {
394
- throw new StaleBuildRunError(run.buildId, run.runId);
395
- }
396
- const requirement = String(record.get("requirement") ?? "");
397
- const dataSource = String(record.get("dataSource") ?? "main");
398
- const llmService = record.get("llmService");
399
- const model = record.get("model");
400
- const rawCollections = record.get("collections");
401
- const collections = Array.isArray(rawCollections) ? rawCollections.filter((name) => typeof name === "string") : [];
402
- if (!llmService || !model) {
403
- throw new Error("LLM service or model is missing in the build configuration");
404
- }
405
- await updateRecordForRun(app, run, {
406
- status: "building",
407
- buildPhase: "analyzing",
408
- buildLog: "Analyzing collections and requirement",
409
- errorMessage: null,
410
- blockSpec: null,
411
- blockSchema: null,
412
- adjustments: null,
413
- usedFallback: false,
414
- buildHeartbeatAt: /* @__PURE__ */ new Date()
415
- });
416
- const summary = await (0, import_introspector.introspect)(app, { dataSource, collections });
417
- const analysis = await (0, import_analyzer.analyze)(app, { requirement, summary, llmService, model });
418
- let usedFallback = analysis.usedFallback;
419
- if (analysis.error) {
420
- await updateRecordForRun(
421
- app,
422
- run,
423
- {
424
- errorMessage: analysis.error,
425
- buildLog: `Analyzer fell back: ${analysis.error}`,
426
- usedFallback: true
427
- },
428
- true
429
- );
430
- }
431
- const validation = (0, import_validator.validate)(analysis.spec, summary);
432
- usedFallback = usedFallback || validation.usedFallback;
433
- const specForGeneration = validation.usedFallback ? (0, import_fallback.buildFallbackSpec)(summary) : validation.spec;
434
- await updateRecordForRun(app, run, {
435
- buildPhase: "generating",
436
- buildLog: "Generating block schema",
437
- buildHeartbeatAt: /* @__PURE__ */ new Date()
438
- });
439
- const result = (0, import_generator.generate)(specForGeneration, summary);
440
- if (!result.ok) {
441
- throw new Error(
442
- result.failedNode ? `Schema generation failed at "${result.failedNode}": ${result.error}` : `Schema generation failed: ${result.error}`
443
- );
444
- }
445
- usedFallback = usedFallback || result.usedFallback;
446
- await updateRecordForRun(app, run, {
447
- status: "completed",
448
- buildPhase: "completed",
449
- blockSpec: specForGeneration,
450
- blockSchema: result.schema,
451
- adjustments: validation.adjustments,
452
- usedFallback,
453
- buildLog: usedFallback ? "Build completed using the fallback specification" : "Build completed successfully",
454
- errorMessage: null,
455
- buildHeartbeatAt: /* @__PURE__ */ new Date()
456
- });
457
- }
458
- async function withBuildRunLock(app, buildId, fn) {
459
- return app.lockManager.runExclusive(`build-visualization:run:${buildId}`, fn, BUILD_RUN_LOCK_TTL_MS);
460
- }
461
- async function processQueuedBuild(app, message) {
462
- var _a, _b;
463
- const buildId = message == null ? void 0 : message.buildId;
464
- const runId = message == null ? void 0 : message.runId;
465
- if (!buildId || !runId) {
466
- (_b = (_a = app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[plugin-build-visualization-block] Build queue message missing buildId or runId");
467
- return;
468
- }
469
- await withBuildRunLock(app, buildId, async () => {
470
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
471
- const run = { buildId, runId };
472
- const workerId = getBuildWorkerId(app);
473
- const claimed = await claimBuildRun(app, run, workerId);
474
- if (!claimed) {
475
- (_b2 = (_a2 = app.log) == null ? void 0 : _a2.info) == null ? void 0 : _b2.call(
476
- _a2,
477
- `[plugin-build-visualization-block] Build ${runId} for record "${buildId}" was already claimed or stale`
478
- );
479
- return;
480
- }
481
- const repository = app.db.getRepository(import_constants.COLLECTION_NAME);
482
- const record = await repository.findById(buildId);
483
- if (!record) {
484
- (_d = (_c = app.log) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(_c, `[plugin-build-visualization-block] Build record "${buildId}" not found; skipping queued build`);
485
- return;
486
- }
487
- if (record.get("status") !== "building") {
488
- (_f = (_e = app.log) == null ? void 0 : _e.info) == null ? void 0 : _f.call(
489
- _e,
490
- `[plugin-build-visualization-block] Build record "${buildId}" is ${record.get(
491
- "status"
492
- )}; skipping queued build`
493
- );
494
- return;
495
- }
496
- const stopHeartbeat = startBuildHeartbeat(app, run);
497
- try {
498
- await runBuild(app, app.db, run);
499
- } catch (error) {
500
- if (error instanceof StaleBuildRunError) {
501
- (_h = (_g = app.log) == null ? void 0 : _g.info) == null ? void 0 : _h.call(_g, `[plugin-build-visualization-block] ${error.message}`);
502
- return;
503
- }
504
- (_j = (_i = app.log) == null ? void 0 : _i.error) == null ? void 0 : _j.call(_i, "[plugin-build-visualization-block] Build worker error", error);
505
- await markBuildError(app, buildId, runId, error);
506
- } finally {
507
- stopHeartbeat();
508
- }
509
- });
510
- }
511
- async function markBuildError(app, buildId, runId, error) {
512
- const errorMessage = error instanceof Error ? error.message : String(error);
513
- if (runId) {
514
- await updateRecordForRun(
515
- app,
516
- { buildId, runId },
517
- {
518
- status: "error",
519
- buildPhase: "failed",
520
- errorMessage,
521
- buildLog: errorMessage,
522
- buildHeartbeatAt: /* @__PURE__ */ new Date()
523
- },
524
- true
525
- );
526
- return;
527
- }
528
- await app.db.getRepository(import_constants.COLLECTION_NAME).update({
529
- filterByTk: buildId,
530
- values: {
531
- status: "error",
532
- buildPhase: "failed",
533
- errorMessage,
534
- buildLog: errorMessage
535
- }
536
- });
537
- }
538
- async function enqueueBuild(app, message) {
539
- var _a, _b;
540
- try {
541
- const queuedInRedis = await enqueueBuildToRedis(app, message);
542
- if (queuedInRedis) {
543
- await publishBuildQueueWake(app, message);
544
- return;
545
- }
546
- await publishBuildQueueWake(app, message);
547
- if (isBuildVisualizationWorker(app)) {
548
- await app.eventQueue.publish(BUILD_VISUALIZATION_QUEUE_CHANNEL, message, {
549
- timeout: BUILD_VISUALIZATION_QUEUE_TIMEOUT_MS,
550
- maxRetries: 0
551
- });
552
- return;
553
- }
554
- (_b = (_a = app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(
555
- _a,
556
- `[plugin-build-visualization-block] Redis queue is unavailable; build ${message.runId} for record "${message.buildId}" will remain queued until a worker DB poller picks it up`
557
- );
558
- } catch (error) {
559
- await markBuildError(app, message.buildId, message.runId, error);
560
- throw error;
561
- }
562
- }
563
- function registerBuildQueue(app) {
564
- app.eventQueue.subscribe(BUILD_VISUALIZATION_QUEUE_CHANNEL, {
565
- concurrency: BUILD_VISUALIZATION_QUEUE_CONCURRENCY,
566
- idle: () => isBuildVisualizationWorker(app),
567
- process: async (message) => {
568
- await processQueuedBuild(app, message);
569
- }
570
- });
571
- if (!isBuildVisualizationWorker(app)) {
572
- app.on("afterStart", () => clearLocalBuildMemoryQueue(app));
573
- }
574
- }
575
- function unregisterBuildQueue(app) {
576
- app.eventQueue.unsubscribe(BUILD_VISUALIZATION_QUEUE_CHANNEL);
577
- stopBuildVisualizationQueueProcessor(app);
578
- }
579
- async function recoverInterruptedBuilds(app) {
580
- var _a, _b;
581
- const repository = app.db.getRepository(import_constants.COLLECTION_NAME);
582
- const model = getBuildModel(app);
583
- const staleBefore = new Date(Date.now() - BUILD_STALE_MS);
584
- const records = await repository.find({
585
- filter: {
586
- status: "building",
587
- $or: [{ buildHeartbeatAt: null }, { buildHeartbeatAt: { $lt: staleBefore } }]
588
- }
589
- });
590
- let requeued = 0;
591
- for (const record of records) {
592
- const buildId = String(record.get("id"));
593
- const previousRunId = record.get("buildRunId") || null;
594
- const runId = String(previousRunId || import_crypto.default.randomUUID());
595
- const [affected] = await model.update(
596
- {
597
- buildPhase: "queued",
598
- buildLog: "Build re-queued after worker restart",
599
- buildRunId: runId,
600
- buildQueuedAt: /* @__PURE__ */ new Date(),
601
- buildStartedAt: null,
602
- buildHeartbeatAt: null,
603
- buildWorkerId: null
604
- },
605
- {
606
- where: {
607
- id: buildId,
608
- status: "building",
609
- buildRunId: previousRunId
610
- }
611
- }
612
- );
613
- if (!affected) {
614
- continue;
615
- }
616
- await enqueueBuild(app, {
617
- buildId,
618
- runId,
619
- userId: null,
620
- queuedAt: (/* @__PURE__ */ new Date()).toISOString()
621
- });
622
- requeued += 1;
623
- }
624
- if (requeued) {
625
- (_b = (_a = app.log) == null ? void 0 : _a.info) == null ? void 0 : _b.call(_a, `[plugin-build-visualization-block] Re-queued ${requeued} interrupted build(s)`);
626
- }
627
- }
628
- async function failTimedOutBuilds(app) {
629
- var _a, _b;
630
- const repository = app.db.getRepository(import_constants.COLLECTION_NAME);
631
- const model = getBuildModel(app);
632
- const now = Date.now();
633
- const timeoutBefore = new Date(now - import_constants.BUILD_TIMEOUT_MS);
634
- const staleBefore = new Date(now - BUILD_STALE_MS);
635
- const records = await repository.find({
636
- filter: {
637
- status: "building",
638
- $or: [
639
- { buildStartedAt: { $lt: timeoutBefore } },
640
- { $and: [{ buildStartedAt: null }, { buildQueuedAt: { $lt: timeoutBefore } }] }
641
- ]
642
- }
643
- });
644
- let failed = 0;
645
- for (const record of records) {
646
- const heartbeatRaw = record.get("buildHeartbeatAt");
647
- const heartbeatStale = !heartbeatRaw || new Date(heartbeatRaw).getTime() < staleBefore.getTime();
648
- if (!heartbeatStale) {
649
- continue;
650
- }
651
- const buildId = String(record.get("id"));
652
- const previousRunId = record.get("buildRunId") ?? null;
653
- const [affected] = await model.update(
654
- {
655
- status: "error",
656
- buildPhase: "failed",
657
- errorMessage: "Build timed out",
658
- buildLog: "Build timed out",
659
- buildHeartbeatAt: /* @__PURE__ */ new Date()
660
- },
661
- {
662
- where: {
663
- id: buildId,
664
- status: "building",
665
- buildRunId: previousRunId
666
- }
667
- }
668
- );
669
- if (affected) {
670
- failed += 1;
671
- }
672
- }
673
- if (failed) {
674
- (_b = (_a = app.log) == null ? void 0 : _a.info) == null ? void 0 : _b.call(_a, `[plugin-build-visualization-block] Failed ${failed} timed-out build(s)`);
675
- }
676
- }
677
36
  function getCurrentRoles(ctx) {
678
37
  var _a;
679
38
  const roles = (_a = ctx.state) == null ? void 0 : _a.currentRoles;
@@ -779,30 +138,9 @@ async function build(ctx, next) {
779
138
  const values = params.values ?? {};
780
139
  const input = validateInput(ctx, values);
781
140
  assertCollectionPermissions(ctx, input.collections);
782
- const runId = import_crypto.default.randomUUID();
783
- const userId = ((_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id) ?? null;
784
- const repository = ctx.db.getRepository(import_constants.COLLECTION_NAME);
785
- const record = await repository.create({
786
- values: {
787
- requirement: input.requirement,
788
- collections: input.collections,
789
- dataSource: input.dataSource,
790
- primaryCollection: input.primaryCollection,
791
- llmService: input.llmService,
792
- model: input.model,
793
- status: "building",
794
- buildPhase: "queued",
795
- buildRunId: runId,
796
- buildQueuedAt: /* @__PURE__ */ new Date(),
797
- createdById: userId
798
- }
799
- });
800
- const buildId = String(record.get("id"));
801
- await enqueueBuild(ctx.app, {
802
- buildId,
803
- runId,
804
- userId,
805
- queuedAt: (/* @__PURE__ */ new Date()).toISOString()
141
+ const record = await (0, import_workflow_domain.requestBuild)((0, import_workflow_domain.getWorkflowService)(ctx.app), {
142
+ ...input,
143
+ createdById: ((_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id) ?? null
806
144
  });
807
145
  ctx.body = {
808
146
  id: record.get("id"),
@@ -822,7 +160,6 @@ function getFilterByTk(ctx) {
822
160
  ctx.throw(400, t(ctx, "A build id is required"));
823
161
  }
824
162
  async function retry(ctx, next) {
825
- var _a, _b;
826
163
  const filterByTk = getFilterByTk(ctx);
827
164
  const repository = ctx.db.getRepository(import_constants.COLLECTION_NAME);
828
165
  const record = await repository.findById(filterByTk);
@@ -830,33 +167,7 @@ async function retry(ctx, next) {
830
167
  ctx.throw(404, t(ctx, "Build record not found"));
831
168
  }
832
169
  assertBuildRecordAccess(ctx, record);
833
- const runId = import_crypto.default.randomUUID();
834
- const userId = ((_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id) ?? null;
835
- await repository.update({
836
- filterByTk,
837
- values: {
838
- status: "building",
839
- buildPhase: "queued",
840
- buildRunId: runId,
841
- buildQueuedAt: /* @__PURE__ */ new Date(),
842
- buildLog: "Build re-queued via retry",
843
- errorMessage: null,
844
- blockSchema: null,
845
- blockSpec: null,
846
- adjustments: null,
847
- usedFallback: false,
848
- buildStartedAt: null,
849
- buildHeartbeatAt: null,
850
- buildWorkerId: null
851
- }
852
- });
853
- const buildId = String(record.get("id"));
854
- await enqueueBuild(ctx.app, {
855
- buildId,
856
- runId,
857
- userId,
858
- queuedAt: (/* @__PURE__ */ new Date()).toISOString()
859
- });
170
+ await (0, import_workflow_domain.requestBuild)((0, import_workflow_domain.getWorkflowService)(ctx.app), {}, filterByTk);
860
171
  ctx.body = {
861
172
  id: record.get("id"),
862
173
  status: "building",
@@ -886,15 +197,7 @@ async function getResult(ctx, next) {
886
197
  }
887
198
  // Annotate the CommonJS export names for ESM import in node:
888
199
  0 && (module.exports = {
889
- WORKER_JOB_BUILD_VISUALIZATION_PROCESS,
890
200
  build,
891
- enqueueBuild,
892
- failTimedOutBuilds,
893
201
  getResult,
894
- processQueuedBuild,
895
- recoverInterruptedBuilds,
896
- registerBuildQueue,
897
- retry,
898
- startBuildQueueProcessor,
899
- unregisterBuildQueue
202
+ retry
900
203
  });