@ai-setting/roy-agent-core 1.4.12 → 1.4.13

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 (57) hide show
  1. package/dist/index.d.ts +7825 -0
  2. package/dist/index.js +13073 -19300
  3. package/dist/shared/chunk-0q6s9wm6.js +249 -0
  4. package/dist/shared/chunk-1aakcfp1.js +15 -0
  5. package/dist/shared/chunk-1d4rwms4.js +25 -0
  6. package/dist/shared/chunk-1pf5mfgd.js +82 -0
  7. package/dist/shared/chunk-1qwabsm0.js +154 -0
  8. package/dist/shared/chunk-25x2pdtp.js +107 -0
  9. package/dist/shared/chunk-2b5kbhx3.js +366 -0
  10. package/dist/shared/chunk-91bas8w5.js +20 -0
  11. package/dist/shared/chunk-9qzt1v1p.js +10 -0
  12. package/dist/shared/chunk-a9qmy3sc.js +296 -0
  13. package/dist/shared/chunk-g6j5n3gv.js +549 -0
  14. package/dist/shared/chunk-hs7tbmje.js +24 -0
  15. package/dist/shared/chunk-mf5xqbdh.js +14 -0
  16. package/dist/shared/chunk-q9j99fsm.js +368 -0
  17. package/dist/{env/workflow/engine/index.js → shared/chunk-rncy3rtd.js} +330 -1581
  18. package/dist/shared/chunk-t1rh6jtm.js +205 -0
  19. package/dist/{env/task/hooks/index.js → shared/chunk-wbkh7wat.js} +3 -18
  20. package/dist/shared/chunk-yqmx37vm.js +10 -0
  21. package/dist/shared/chunk-ze20rksg.js +102 -0
  22. package/package.json +7 -7
  23. package/dist/config/index.js +0 -1670
  24. package/dist/env/agent/index.js +0 -3035
  25. package/dist/env/commands/index.js +0 -1685
  26. package/dist/env/debug/formatters/index.js +0 -639
  27. package/dist/env/debug/index.js +0 -2300
  28. package/dist/env/hook/index.js +0 -273
  29. package/dist/env/index.js +0 -12591
  30. package/dist/env/llm/index.js +0 -2736
  31. package/dist/env/log-trace/index.js +0 -1779
  32. package/dist/env/mcp/index.js +0 -2173
  33. package/dist/env/mcp/tool/index.js +0 -1149
  34. package/dist/env/memory/built-in/index.js +0 -225
  35. package/dist/env/memory/index.js +0 -2171
  36. package/dist/env/memory/plugin/index.js +0 -1263
  37. package/dist/env/prompt/index.js +0 -2107
  38. package/dist/env/session/index.js +0 -3594
  39. package/dist/env/session/storage/index.js +0 -2049
  40. package/dist/env/skill/index.js +0 -1635
  41. package/dist/env/skill/tool/index.js +0 -114
  42. package/dist/env/task/delegate/index.js +0 -1844
  43. package/dist/env/task/index.js +0 -3578
  44. package/dist/env/task/plugins/index.js +0 -1626
  45. package/dist/env/task/storage/index.js +0 -1464
  46. package/dist/env/task/tools/index.js +0 -344
  47. package/dist/env/task/tools/operation/index.js +0 -270
  48. package/dist/env/tool/built-in/index.js +0 -1151
  49. package/dist/env/tool/index.js +0 -2284
  50. package/dist/env/workflow/decorators/index.js +0 -449
  51. package/dist/env/workflow/index.js +0 -6214
  52. package/dist/env/workflow/nodes/index.js +0 -650
  53. package/dist/env/workflow/service/index.js +0 -262
  54. package/dist/env/workflow/storage/index.js +0 -1236
  55. package/dist/env/workflow/tools/index.js +0 -1081
  56. package/dist/env/workflow/types/index.js +0 -479
  57. package/dist/env/workflow/utils/index.js +0 -1631
@@ -1,438 +1,28 @@
1
- // @bun
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- function __accessProp(key) {
7
- return this[key];
8
- }
9
- var __toCommonJS = (from) => {
10
- var entry = (__moduleCache ??= new WeakMap).get(from), desc;
11
- if (entry)
12
- return entry;
13
- entry = __defProp({}, "__esModule", { value: true });
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (var key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(entry, key))
17
- __defProp(entry, key, {
18
- get: __accessProp.bind(from, key),
19
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
20
- });
21
- }
22
- __moduleCache.set(from, entry);
23
- return entry;
24
- };
25
- var __moduleCache;
26
- var __returnValue = (v) => v;
27
- function __exportSetter(name, newValue) {
28
- this[name] = __returnValue.bind(null, newValue);
29
- }
30
- var __export = (target, all) => {
31
- for (var name in all)
32
- __defProp(target, name, {
33
- get: all[name],
34
- enumerable: true,
35
- configurable: true,
36
- set: __exportSetter.bind(all, name)
37
- });
38
- };
39
- var __legacyDecorateClassTS = function(decorators, target, key, desc) {
40
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
41
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
42
- r = Reflect.decorate(decorators, target, key, desc);
43
- else
44
- for (var i = decorators.length - 1;i >= 0; i--)
45
- if (d = decorators[i])
46
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
47
- return c > 3 && r && Object.defineProperty(target, key, r), r;
48
- };
49
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
50
- var __require = import.meta.require;
51
-
52
- // packages/core/src/env/workflow/types/workflow.ts
53
- import { z } from "zod";
54
- async function getYamlParser() {
55
- if (!yamlParser) {
56
- yamlParser = await import("yaml");
57
- }
58
- return yamlParser;
59
- }
60
- async function parseWorkflowFile(content, filename) {
61
- const isYaml = filename.endsWith(".yaml") || filename.endsWith(".yml");
62
- const isJson = filename.endsWith(".json");
63
- let definition;
64
- if (isYaml) {
65
- const yaml = await getYamlParser();
66
- definition = WorkflowDefinitionSchema.parse(yaml.parse(content));
67
- } else if (isJson) {
68
- definition = WorkflowDefinitionSchema.parse(JSON.parse(content));
69
- } else {
70
- try {
71
- definition = WorkflowDefinitionSchema.parse(JSON.parse(content));
72
- } catch {
73
- const yaml = await getYamlParser();
74
- definition = WorkflowDefinitionSchema.parse(yaml.parse(content));
75
- }
76
- }
77
- return {
78
- format: isYaml ? "yaml" : "json",
79
- definition
80
- };
81
- }
82
- function parseWorkflowFileSync(content, filename) {
83
- const isYaml = filename.endsWith(".yaml") || filename.endsWith(".yml");
84
- const isJson = filename.endsWith(".json");
85
- let definition;
86
- if (isJson) {
87
- definition = WorkflowDefinitionSchema.parse(JSON.parse(content));
88
- } else if (isYaml) {
89
- throw new Error("Synchronous YAML parsing not supported. Use parseWorkflowFile() instead.");
90
- } else {
91
- try {
92
- definition = WorkflowDefinitionSchema.parse(JSON.parse(content));
93
- } catch {
94
- throw new Error("Cannot auto-detect format. Please use .yaml, .yml, or .json extension.");
95
- }
96
- }
97
- return {
98
- format: isJson ? "json" : "yaml",
99
- definition
100
- };
101
- }
102
- var DependsOnSchema, RetryConfigSchema, NodeDefinitionSchema, WorkflowConfigSchema, OutputDefinitionSchema, WorkflowMetadataSchema, WorkflowDefinitionSchema, yamlParser = null;
103
- var init_workflow = __esm(() => {
104
- DependsOnSchema = z.array(z.string());
105
- RetryConfigSchema = z.object({
106
- max_attempts: z.number().min(1).default(1),
107
- backoff: z.enum(["fixed", "exponential"]).default("exponential"),
108
- initial_delay: z.number().min(0).default(1000)
109
- });
110
- NodeDefinitionSchema = z.object({
111
- id: z.string().min(1, "Node ID is required"),
112
- type: z.string().min(1, "Node type is required"),
113
- name: z.string().optional(),
114
- config: z.record(z.string(), z.unknown()).optional().default({}),
115
- depends_on: z.array(z.string()).optional(),
116
- condition: z.string().optional(),
117
- retry: RetryConfigSchema.optional(),
118
- timeout: z.number().optional()
119
- });
120
- WorkflowConfigSchema = z.object({
121
- parallel_limit: z.number().nullable().optional(),
122
- timeout: z.number().nullable().optional(),
123
- retry: RetryConfigSchema.optional(),
124
- debug: z.boolean().optional()
125
- });
126
- OutputDefinitionSchema = z.object({
127
- name: z.string(),
128
- source: z.string(),
129
- path: z.string()
130
- });
131
- WorkflowMetadataSchema = z.object({
132
- author: z.string().optional(),
133
- taskId: z.number().optional(),
134
- tags: z.array(z.string()).optional().default([]),
135
- created_at: z.string().optional(),
136
- updated_at: z.string().optional()
137
- });
138
- WorkflowDefinitionSchema = z.object({
139
- name: z.string().min(1, "Workflow name is required"),
140
- version: z.string().default("1.0"),
141
- description: z.string().optional(),
142
- config: WorkflowConfigSchema.optional().default({}),
143
- nodes: z.array(NodeDefinitionSchema).min(1, "At least one node is required"),
144
- entry: z.union([z.string(), z.array(z.string())]).default("__default_entry__"),
145
- outputs: z.array(OutputDefinitionSchema).optional().default([]),
146
- metadata: WorkflowMetadataSchema.optional().default({})
147
- });
148
- });
1
+ import {
2
+ AgentComponentAdapter,
3
+ AskUserError,
4
+ createNodeInterruptEvent,
5
+ init_agent_component_adapter,
6
+ init_workflow_hil
7
+ } from "./chunk-0q6s9wm6.js";
8
+ import {
9
+ createLogger,
10
+ getMaxOutput,
11
+ init_logger,
12
+ simplifyFilePath
13
+ } from "./chunk-a9qmy3sc.js";
14
+ import {
15
+ getTracerProvider,
16
+ init_tracer_provider
17
+ } from "./chunk-q9j99fsm.js";
18
+ import {
19
+ __esm,
20
+ __export,
21
+ __legacyDecorateClassTS,
22
+ __require
23
+ } from "./chunk-wbkh7wat.js";
149
24
 
150
- // packages/core/src/env/workflow/types/workflow-hil.ts
151
- function createNodeInterruptEvent(runId, nodeId, nodeType, query, agentSessionId) {
152
- return {
153
- type: "node.interrupt",
154
- run_id: runId,
155
- timestamp: Date.now(),
156
- node_id: nodeId,
157
- node_type: nodeType,
158
- query,
159
- ...agentSessionId ? { agent_session_id: agentSessionId } : {}
160
- };
161
- }
162
- function createWorkflowAskUserEvent(runId, sessionId, nodeId, nodeType, query) {
163
- return {
164
- type: "workflow.ask-user",
165
- run_id: runId,
166
- timestamp: Date.now(),
167
- session_id: sessionId,
168
- node_id: nodeId,
169
- node_type: nodeType,
170
- query
171
- };
172
- }
173
- var AskUserError;
174
- var init_workflow_hil = __esm(() => {
175
- AskUserError = class AskUserError extends Error {
176
- runId;
177
- sessionId;
178
- nodeId;
179
- nodeType;
180
- query;
181
- agentSessionId;
182
- timestamp;
183
- type = "ask-user";
184
- name = "AskUserError";
185
- constructor(runId, sessionId, nodeId, nodeType, query, agentSessionId, timestamp = Date.now()) {
186
- super(`[${nodeType}:${nodeId}] Ask user: ${query}`);
187
- this.runId = runId;
188
- this.sessionId = sessionId;
189
- this.nodeId = nodeId;
190
- this.nodeType = nodeType;
191
- this.query = query;
192
- this.agentSessionId = agentSessionId;
193
- this.timestamp = timestamp;
194
- }
195
- toEvent() {
196
- return {
197
- type: "workflow.ask-user",
198
- run_id: this.runId,
199
- timestamp: this.timestamp,
200
- session_id: this.sessionId,
201
- node_id: this.nodeId,
202
- node_type: this.nodeType,
203
- query: this.query
204
- };
205
- }
206
- };
207
- });
208
-
209
- // packages/core/src/env/workflow/types/workflow-message.ts
210
- import { z as z2 } from "zod";
211
- var WorkflowMessageRoleSchema;
212
- var init_workflow_message = __esm(() => {
213
- init_workflow_hil();
214
- WorkflowMessageRoleSchema = z2.enum([
215
- "workflow.node.call",
216
- "workflow.node.interrupt",
217
- "workflow.node.result",
218
- "workflow.node.resume"
219
- ]);
220
- });
221
-
222
- // packages/core/src/env/workflow/types/workflow-session.ts
223
- function isWorkflowSessionMetadata(metadata) {
224
- if (typeof metadata !== "object" || metadata === null || !("type" in metadata) || metadata.type !== "workflow") {
225
- return false;
226
- }
227
- const m = metadata;
228
- if (!m.workflowId || typeof m.workflowId !== "string") {
229
- return false;
230
- }
231
- if (!m.workflowName || typeof m.workflowName !== "string") {
232
- return false;
233
- }
234
- if (!m.status || typeof m.status !== "string") {
235
- return false;
236
- }
237
- const validStatuses = ["running", "paused", "completed", "failed", "stopped"];
238
- if (!validStatuses.includes(m.status)) {
239
- return false;
240
- }
241
- return true;
242
- }
243
- function getWorkflowSessionStatus(metadata) {
244
- return metadata.status || "running";
245
- }
246
- // packages/core/src/env/workflow/types/event.ts
247
- import { z as z3 } from "zod";
248
- function createWorkflowEvent(type, runId, data) {
249
- return {
250
- type,
251
- run_id: runId,
252
- timestamp: Date.now(),
253
- ...data
254
- };
255
- }
256
- var BaseEventSchema, WorkflowStartedEventSchema, WorkflowPausedEventSchema, WorkflowResumedEventSchema, WorkflowStoppedEventSchema, WorkflowCompletedEventSchema, WorkflowFailedEventSchema, WorkflowOutputEventSchema, NodeScheduledEventSchema, NodeStartedEventSchema, NodeProgressEventSchema, NodeCompletedEventSchema, NodeFailedEventSchema, NodeSkippedEventSchema, NodeDataEventSchema, NodeAddedEventSchema, NodeRemovedEventSchema, ControlPauseEventSchema, ControlResumeEventSchema, ControlStopEventSchema, NodeInterruptEventSchema, WorkflowAskUserEventSchema, WorkflowEventSchema;
257
- var init_event = __esm(() => {
258
- BaseEventSchema = z3.object({
259
- type: z3.string(),
260
- run_id: z3.string(),
261
- timestamp: z3.number()
262
- });
263
- WorkflowStartedEventSchema = BaseEventSchema.extend({
264
- type: z3.literal("workflow.started"),
265
- workflow_name: z3.string(),
266
- input: z3.record(z3.string(), z3.unknown()).optional()
267
- });
268
- WorkflowPausedEventSchema = BaseEventSchema.extend({
269
- type: z3.literal("workflow.paused")
270
- });
271
- WorkflowResumedEventSchema = BaseEventSchema.extend({
272
- type: z3.literal("workflow.resumed")
273
- });
274
- WorkflowStoppedEventSchema = BaseEventSchema.extend({
275
- type: z3.literal("workflow.stopped"),
276
- reason: z3.string()
277
- });
278
- WorkflowCompletedEventSchema = BaseEventSchema.extend({
279
- type: z3.literal("workflow.completed"),
280
- result: z3.record(z3.string(), z3.unknown()).optional(),
281
- duration_ms: z3.number()
282
- });
283
- WorkflowFailedEventSchema = BaseEventSchema.extend({
284
- type: z3.literal("workflow.failed"),
285
- error: z3.object({
286
- message: z3.string(),
287
- stack: z3.string().optional()
288
- }),
289
- failed_at: z3.string()
290
- });
291
- WorkflowOutputEventSchema = BaseEventSchema.extend({
292
- type: z3.literal("workflow.output"),
293
- output: z3.record(z3.string(), z3.unknown())
294
- });
295
- NodeScheduledEventSchema = BaseEventSchema.extend({
296
- type: z3.literal("node.scheduled"),
297
- node_id: z3.string()
298
- });
299
- NodeStartedEventSchema = BaseEventSchema.extend({
300
- type: z3.literal("node.started"),
301
- node_id: z3.string(),
302
- input: z3.any(),
303
- agentSessionId: z3.string().optional(),
304
- userResponse: z3.string().optional()
305
- });
306
- NodeProgressEventSchema = BaseEventSchema.extend({
307
- type: z3.literal("node.progress"),
308
- node_id: z3.string(),
309
- progress: z3.number(),
310
- message: z3.string().optional()
311
- });
312
- NodeCompletedEventSchema = BaseEventSchema.extend({
313
- type: z3.literal("node.completed"),
314
- node_id: z3.string(),
315
- output: z3.any(),
316
- duration_ms: z3.number()
317
- });
318
- NodeFailedEventSchema = BaseEventSchema.extend({
319
- type: z3.literal("node.failed"),
320
- node_id: z3.string(),
321
- error: z3.object({
322
- message: z3.string(),
323
- stack: z3.string().optional()
324
- })
325
- });
326
- NodeSkippedEventSchema = BaseEventSchema.extend({
327
- type: z3.literal("node.skipped"),
328
- node_id: z3.string(),
329
- reason: z3.string()
330
- });
331
- NodeDataEventSchema = BaseEventSchema.extend({
332
- type: z3.literal("node.data"),
333
- from_node: z3.string(),
334
- to_node: z3.string(),
335
- data: z3.any()
336
- });
337
- NodeAddedEventSchema = BaseEventSchema.extend({
338
- type: z3.literal("node.added"),
339
- node_id: z3.string(),
340
- node: z3.any()
341
- });
342
- NodeRemovedEventSchema = BaseEventSchema.extend({
343
- type: z3.literal("node.removed"),
344
- node_id: z3.string()
345
- });
346
- ControlPauseEventSchema = BaseEventSchema.extend({
347
- type: z3.literal("control.pause")
348
- });
349
- ControlResumeEventSchema = BaseEventSchema.extend({
350
- type: z3.literal("control.resume")
351
- });
352
- ControlStopEventSchema = BaseEventSchema.extend({
353
- type: z3.literal("control.stop")
354
- });
355
- NodeInterruptEventSchema = BaseEventSchema.extend({
356
- type: z3.literal("node.interrupt"),
357
- node_id: z3.string(),
358
- node_type: z3.string(),
359
- query: z3.string()
360
- });
361
- WorkflowAskUserEventSchema = BaseEventSchema.extend({
362
- type: z3.literal("workflow.ask-user"),
363
- session_id: z3.string(),
364
- node_id: z3.string(),
365
- node_type: z3.string(),
366
- query: z3.string()
367
- });
368
- WorkflowEventSchema = z3.union([
369
- WorkflowStartedEventSchema,
370
- WorkflowPausedEventSchema,
371
- WorkflowResumedEventSchema,
372
- WorkflowStoppedEventSchema,
373
- WorkflowCompletedEventSchema,
374
- WorkflowFailedEventSchema,
375
- WorkflowOutputEventSchema,
376
- NodeScheduledEventSchema,
377
- NodeStartedEventSchema,
378
- NodeProgressEventSchema,
379
- NodeCompletedEventSchema,
380
- NodeFailedEventSchema,
381
- NodeSkippedEventSchema,
382
- NodeDataEventSchema,
383
- NodeAddedEventSchema,
384
- NodeRemovedEventSchema,
385
- ControlPauseEventSchema,
386
- ControlResumeEventSchema,
387
- ControlStopEventSchema,
388
- NodeInterruptEventSchema,
389
- WorkflowAskUserEventSchema
390
- ]);
391
- });
392
-
393
- // packages/core/src/env/workflow/types/run.ts
394
- import { z as z4 } from "zod";
395
- function createNodeExecutionContext(params) {
396
- return {
397
- ...params,
398
- askUser: (query) => {
399
- throw new AskUserError(params.runId, params.sessionId, params.nodeId, "unknown", query);
400
- }
401
- };
402
- }
403
- var RunStatusSchema, NodeStatusSchema;
404
- var init_run = __esm(() => {
405
- init_workflow_message();
406
- RunStatusSchema = z4.enum([
407
- "idle",
408
- "running",
409
- "paused",
410
- "stopped",
411
- "completed",
412
- "failed"
413
- ]);
414
- NodeStatusSchema = z4.enum([
415
- "pending",
416
- "scheduled",
417
- "started",
418
- "running",
419
- "completed",
420
- "failed",
421
- "skipped"
422
- ]);
423
- });
424
-
425
- // packages/core/src/env/workflow/types/index.ts
426
- var init_types = __esm(() => {
427
- init_run();
428
- init_workflow();
429
- init_workflow_message();
430
- init_workflow_hil();
431
- init_event();
432
- init_run();
433
- });
434
-
435
- // packages/core/src/env/workflow/engine/event-bus.ts
25
+ // src/env/workflow/engine/event-bus.ts
436
26
  class EventBus {
437
27
  handlers = new Map;
438
28
  wildcardHandlers = new Set;
@@ -448,13 +38,13 @@ class EventBus {
448
38
  }
449
39
  once(eventType, handler) {
450
40
  let executed = false;
451
- const wrappedHandler = async (event2) => {
41
+ const wrappedHandler = async (event) => {
452
42
  if (executed) {
453
43
  return;
454
44
  }
455
45
  executed = true;
456
46
  try {
457
- await handler(event2);
47
+ await handler(event);
458
48
  } catch (error) {
459
49
  console.error("Event handler error:", error);
460
50
  }
@@ -477,26 +67,26 @@ class EventBus {
477
67
  this.wildcardHandlers.delete(handler);
478
68
  };
479
69
  }
480
- async publish(event2, waitForHandlers = false) {
481
- const handlers = this.handlers.get(event2.type);
70
+ async publish(event, waitForHandlers = false) {
71
+ const handlers = this.handlers.get(event.type);
482
72
  const handlerPromises = [];
483
73
  if (handlers) {
484
74
  for (const handler of handlers) {
485
- const promise = this.executeHandler(handler, event2);
75
+ const promise = this.executeHandler(handler, event);
486
76
  handlerPromises.push(promise);
487
77
  }
488
78
  }
489
79
  for (const handler of this.wildcardHandlers) {
490
- const promise = this.executeHandler(handler, event2);
80
+ const promise = this.executeHandler(handler, event);
491
81
  handlerPromises.push(promise);
492
82
  }
493
83
  if (waitForHandlers && handlerPromises.length > 0) {
494
84
  await Promise.allSettled(handlerPromises);
495
85
  }
496
86
  }
497
- async executeHandler(handler, event2) {
87
+ async executeHandler(handler, event) {
498
88
  try {
499
- await handler(event2);
89
+ await handler(event);
500
90
  } catch (error) {
501
91
  console.error("Event handler error:", error);
502
92
  }
@@ -518,20 +108,21 @@ class EventBus {
518
108
  };
519
109
  }
520
110
  }
111
+ var init_event_bus = () => {};
521
112
 
522
- // packages/core/src/env/workflow/engine/dag-manager.ts
113
+ // src/env/workflow/engine/dag-manager.ts
523
114
  class DAGManager {
524
115
  workflow;
525
116
  nodeMap;
526
117
  extendedDefinition = null;
527
118
  cachedAnalysis = null;
528
- constructor(workflow2) {
529
- if (!workflow2.nodes || workflow2.nodes.length === 0) {
119
+ constructor(workflow) {
120
+ if (!workflow.nodes || workflow.nodes.length === 0) {
530
121
  throw new Error("At least one node is required");
531
122
  }
532
- this.workflow = workflow2;
123
+ this.workflow = workflow;
533
124
  this.nodeMap = new Map;
534
- for (const node of workflow2.nodes) {
125
+ for (const node of workflow.nodes) {
535
126
  if (node.id === "") {
536
127
  throw new Error("Node ID cannot be empty");
537
128
  }
@@ -864,8 +455,9 @@ class DAGManager {
864
455
  return this.nodeMap.size;
865
456
  }
866
457
  }
458
+ var init_dag_manager = () => {};
867
459
 
868
- // packages/core/src/env/workflow/engine/scheduler.ts
460
+ // src/env/workflow/engine/scheduler.ts
869
461
  class Scheduler {
870
462
  dagManager;
871
463
  options;
@@ -1000,817 +592,273 @@ class Scheduler {
1000
592
  if (this.running.has(nodeId) || this.completed.has(nodeId) || this.failed.has(nodeId) || this.skipped.has(nodeId)) {
1001
593
  continue;
1002
594
  }
1003
- if (this.dagManager.areDependenciesMet(nodeId, allCompleted)) {
1004
- this.ready.add(nodeId);
1005
- }
1006
- }
1007
- }
1008
- getParallelLimit() {
1009
- return this.options.parallelLimit;
1010
- }
1011
- setParallelLimit(limit) {
1012
- this.options.parallelLimit = limit;
1013
- }
1014
- }
1015
-
1016
- // packages/core/src/env/log-trace/span-storage.ts
1017
- var exports_span_storage = {};
1018
- __export(exports_span_storage, {
1019
- SQLiteSpanStorage: () => SQLiteSpanStorage
1020
- });
1021
-
1022
- class SQLiteSpanStorage {
1023
- db = null;
1024
- dbPath;
1025
- initialized = false;
1026
- constructor(dbPath) {
1027
- if (!dbPath) {
1028
- throw new Error("SQLiteSpanStorage requires a valid dbPath parameter");
1029
- }
1030
- if (dbPath === ":memory:") {
1031
- throw new Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");
1032
- }
1033
- this.dbPath = dbPath;
1034
- }
1035
- async initialize() {
1036
- if (this.initialized)
1037
- return;
1038
- const { Database } = __require("bun:sqlite");
1039
- const fs = __require("fs");
1040
- const path = __require("path");
1041
- const dir = path.dirname(this.dbPath);
1042
- if (!fs.existsSync(dir)) {
1043
- fs.mkdirSync(dir, { recursive: true });
1044
- }
1045
- this.db = new Database(this.dbPath);
1046
- this.db.run("PRAGMA journal_mode=WAL");
1047
- this.db.run("PRAGMA busy_timeout=5000");
1048
- this.db.run("PRAGMA synchronous=NORMAL");
1049
- this.db.run(`
1050
- CREATE TABLE IF NOT EXISTS span (
1051
- span_id TEXT PRIMARY KEY,
1052
- trace_id TEXT NOT NULL,
1053
- parent_span_id TEXT,
1054
- name TEXT NOT NULL,
1055
- kind TEXT NOT NULL,
1056
- status TEXT NOT NULL,
1057
- start_time INTEGER NOT NULL,
1058
- end_time INTEGER,
1059
- attributes TEXT,
1060
- result TEXT,
1061
- error TEXT,
1062
- time_created INTEGER NOT NULL
1063
- )
1064
- `);
1065
- this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)");
1066
- this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)");
1067
- this.initialized = true;
1068
- }
1069
- save(span) {
1070
- if (!this.db)
1071
- return;
1072
- const stmt = this.db.prepare(`
1073
- INSERT OR REPLACE INTO span
1074
- (span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
1075
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1076
- `);
1077
- const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === "string" ? span.result : JSON.stringify(span.result) : null;
1078
- stmt.run(span.spanId, span.traceId, span.parentSpanId || null, span.name, span.kind, span.status, span.startTime, span.endTime || null, JSON.stringify(span.attributes), resultValue, span.error || null, Date.now());
1079
- }
1080
- saveBatch(spans) {
1081
- for (const span of spans) {
1082
- this.save(span);
1083
- }
1084
- }
1085
- findByTraceId(traceId) {
1086
- if (!this.db)
1087
- return [];
1088
- const rows = this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(traceId);
1089
- return this.buildTree(rows.map(this.rowToSpan));
1090
- }
1091
- findBySpanId(spanId) {
1092
- if (!this.db)
1093
- return;
1094
- const row = this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(spanId);
1095
- return row ? this.rowToSpan(row) : undefined;
1096
- }
1097
- listTraces(limit = 10) {
1098
- if (!this.db)
1099
- return [];
1100
- const rows = this.db.prepare(`
1101
- SELECT trace_id,
1102
- MIN(start_time) as start_time,
1103
- MAX(end_time) as end_time,
1104
- COUNT(*) as span_count
1105
- FROM span
1106
- GROUP BY trace_id
1107
- ORDER BY start_time DESC
1108
- LIMIT ?
1109
- `).all(limit);
1110
- return rows.map((row) => ({
1111
- traceId: row.trace_id,
1112
- rootSpanName: "unknown",
1113
- startTime: row.start_time,
1114
- endTime: row.end_time,
1115
- duration: row.end_time - row.start_time,
1116
- spanCount: row.span_count,
1117
- status: "ok"
1118
- }));
1119
- }
1120
- deleteByTraceId(traceId) {
1121
- if (this.db) {
1122
- this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(traceId);
1123
- }
1124
- }
1125
- close() {
1126
- if (this.db) {
1127
- this.db.close();
1128
- this.db = null;
1129
- }
1130
- }
1131
- rowToSpan(row) {
1132
- return {
1133
- traceId: row.trace_id,
1134
- spanId: row.span_id,
1135
- parentSpanId: row.parent_span_id,
1136
- name: row.name,
1137
- kind: row.kind,
1138
- status: row.status,
1139
- startTime: row.start_time,
1140
- endTime: row.end_time,
1141
- attributes: row.attributes ? JSON.parse(row.attributes) : {},
1142
- result: row.result || undefined,
1143
- error: row.error || undefined
1144
- };
1145
- }
1146
- buildTree(spans) {
1147
- const spanMap = new Map;
1148
- const roots = [];
1149
- for (const span of spans) {
1150
- spanMap.set(span.spanId, { ...span, children: [] });
1151
- }
1152
- for (const span of spanMap.values()) {
1153
- if (span.parentSpanId) {
1154
- const parent = spanMap.get(span.parentSpanId);
1155
- if (parent) {
1156
- parent.children.push(span);
1157
- } else {
1158
- roots.push(span);
1159
- }
1160
- } else {
1161
- roots.push(span);
1162
- }
1163
- }
1164
- return roots;
1165
- }
1166
- }
1167
-
1168
- // packages/core/src/env/log-trace/opentelemetry/propagation.ts
1169
- function padLeft(str, length) {
1170
- return str.padStart(length, "0");
1171
- }
1172
- function isValidHex(str) {
1173
- return /^[0-9a-f]+$/i.test(str);
1174
- }
1175
- function serialize(context2) {
1176
- const traceId = padLeft(context2.traceId.toLowerCase(), TRACE_ID_LENGTH);
1177
- const spanId = padLeft(context2.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);
1178
- const parts = [
1179
- TRACE_CONTEXT_VERSION,
1180
- traceId,
1181
- spanId,
1182
- TRACE_FLAGS_SAMPLED
1183
- ];
1184
- return parts.join("-");
1185
- }
1186
- function parse(traceparent) {
1187
- if (!traceparent || typeof traceparent !== "string") {
1188
- return;
1189
- }
1190
- const trimmed = traceparent.trim();
1191
- const parts = trimmed.split("-");
1192
- if (parts.length !== 4) {
1193
- return;
1194
- }
1195
- const [version, traceId, senderSpanId, flags] = parts;
1196
- if (version !== TRACE_CONTEXT_VERSION) {
1197
- if (version > TRACE_CONTEXT_VERSION) {
1198
- return;
1199
- }
1200
- }
1201
- if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {
1202
- return;
1203
- }
1204
- if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {
1205
- return;
1206
- }
1207
- if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {
1208
- return;
1209
- }
1210
- return {
1211
- traceId: traceId.toLowerCase(),
1212
- spanId: senderSpanId.toLowerCase()
1213
- };
1214
- }
1215
- var TRACE_CONTEXT_VERSION = "00", TRACE_FLAGS_SAMPLED = "01", TRACEPARENT_HEADER = "TRACEPARENT", TRACE_ID_LENGTH = 32, PARENT_SPAN_ID_LENGTH = 16, FLAGS_LENGTH = 2, propagation;
1216
- var init_propagation = __esm(() => {
1217
- propagation = {
1218
- inject(carrier, context2) {
1219
- carrier[TRACEPARENT_HEADER] = serialize(context2);
1220
- },
1221
- extract(carrier) {
1222
- const traceparent = carrier[TRACEPARENT_HEADER];
1223
- if (!traceparent) {
1224
- return;
1225
- }
1226
- return parse(traceparent);
1227
- },
1228
- getTraceparentHeader() {
1229
- return TRACEPARENT_HEADER;
1230
- }
1231
- };
1232
- });
1233
-
1234
- // packages/core/src/env/log-trace/types.ts
1235
- var SpanKind, SpanStatus;
1236
- var init_types2 = __esm(() => {
1237
- ((SpanKind2) => {
1238
- SpanKind2["CLIENT"] = "client";
1239
- SpanKind2["SERVER"] = "server";
1240
- SpanKind2["INTERNAL"] = "internal";
1241
- })(SpanKind ||= {});
1242
- ((SpanStatus2) => {
1243
- SpanStatus2["OK"] = "ok";
1244
- SpanStatus2["ERROR"] = "error";
1245
- })(SpanStatus ||= {});
1246
- });
1247
-
1248
- // packages/core/src/env/log-trace/opentelemetry/tracer-provider.ts
1249
- var exports_tracer_provider = {};
1250
- __export(exports_tracer_provider, {
1251
- resetTracerProvider: () => resetTracerProvider,
1252
- getTracerProvider: () => getTracerProvider,
1253
- OTelTracerProvider: () => OTelTracerProvider
1254
- });
1255
-
1256
- class OTelSpanImpl {
1257
- name;
1258
- kind;
1259
- spanContext;
1260
- attributes = {};
1261
- startTime;
1262
- endTime;
1263
- error;
1264
- storage;
1265
- parentSpanContext;
1266
- onEnd;
1267
- constructor(name, spanContext, storage, parentSpanContext, onEnd) {
1268
- this.name = name;
1269
- this.kind = "internal";
1270
- this.spanContext = spanContext;
1271
- this.parentSpanContext = parentSpanContext;
1272
- this.startTime = Date.now();
1273
- this.storage = storage;
1274
- this.onEnd = onEnd;
1275
- }
1276
- setAttribute(key, value) {
1277
- this.attributes[key] = value;
1278
- }
1279
- addEvent(name, attributes) {
1280
- const events = this.attributes._events || [];
1281
- events.push({ name, attributes });
1282
- this.attributes._events = events;
1283
- }
1284
- end(result, error) {
1285
- this.endTime = Date.now();
1286
- if (error) {
1287
- this.error = error.message;
1288
- }
1289
- this.storage.save({
1290
- traceId: this.spanContext.traceId,
1291
- spanId: this.spanContext.spanId,
1292
- parentSpanId: this.spanContext.parentSpanId,
1293
- name: this.name,
1294
- kind: this.kind,
1295
- status: error ? "error" /* ERROR */ : "ok" /* OK */,
1296
- startTime: this.startTime,
1297
- endTime: this.endTime,
1298
- attributes: this.attributes,
1299
- result,
1300
- error: this.error
1301
- });
1302
- this.onEnd?.();
1303
- }
1304
- }
1305
-
1306
- class OTelTracerImpl {
1307
- name;
1308
- version;
1309
- storage;
1310
- currentContext;
1311
- activeSpans = new Map;
1312
- onSpanEndCallback;
1313
- provider;
1314
- constructor(name, version, storage, provider) {
1315
- this.name = name;
1316
- this.version = version;
1317
- this.storage = storage;
1318
- this.provider = provider;
1319
- }
1320
- setOnSpanEndCallback(callback) {
1321
- this.onSpanEndCallback = callback;
1322
- }
1323
- getActiveSpanCount() {
1324
- return this.activeSpans.size;
1325
- }
1326
- startSpan(name, options) {
1327
- const parentFromOptions = options?.parent;
1328
- const hasExplicitParent = options && "parent" in options;
1329
- const globalContext = this.provider.getGlobalContext();
1330
- let effectiveParentContext;
1331
- if (hasExplicitParent) {
1332
- effectiveParentContext = parentFromOptions;
1333
- } else if (this.currentContext) {
1334
- effectiveParentContext = this.currentContext;
1335
- } else if (globalContext) {
1336
- effectiveParentContext = globalContext;
1337
- }
1338
- const traceId = effectiveParentContext?.traceId || this.generateTraceId();
1339
- const spanId = this.generateSpanId();
1340
- let parentSpanId;
1341
- if (hasExplicitParent && parentFromOptions) {
1342
- parentSpanId = parentFromOptions.parentSpanId || parentFromOptions.spanId;
1343
- } else if (this.currentContext) {
1344
- parentSpanId = this.currentContext.spanId;
1345
- } else if (globalContext) {
1346
- parentSpanId = globalContext.spanId;
1347
- }
1348
- const spanContext = {
1349
- traceId,
1350
- spanId,
1351
- parentSpanId
1352
- };
1353
- this.currentContext = {
1354
- traceId,
1355
- spanId,
1356
- parentSpanId
1357
- };
1358
- const span = new OTelSpanImpl(name, spanContext, this.storage, effectiveParentContext, () => this.handleSpanEnd(spanContext.spanId, effectiveParentContext?.spanId));
1359
- if (options?.attributes) {
1360
- for (const [key, value] of Object.entries(options.attributes)) {
1361
- span.setAttribute(key, value);
1362
- }
1363
- }
1364
- this.activeSpans.set(spanId, span);
1365
- return span;
1366
- }
1367
- injectToEnv(env) {
1368
- if (this.currentContext) {
1369
- propagation.inject(env, this.currentContext);
1370
- }
1371
- }
1372
- getCurrentContext() {
1373
- return this.currentContext;
1374
- }
1375
- setCurrentContext(context2) {
1376
- this.currentContext = context2;
1377
- }
1378
- endSpan(span) {
1379
- const spanContext = span.spanContext;
1380
- this.activeSpans.delete(spanContext.spanId);
1381
- const currentTraceId = this.currentContext?.traceId;
1382
- if (spanContext.parentSpanId) {
1383
- const parentSpan = this.activeSpans.get(spanContext.parentSpanId);
1384
- if (parentSpan) {
1385
- const parentContext = {
1386
- traceId: spanContext.traceId,
1387
- spanId: parentSpan.spanContext.spanId,
1388
- parentSpanId: parentSpan.spanContext.parentSpanId
1389
- };
1390
- this.currentContext = parentContext;
1391
- return parentContext;
1392
- }
1393
- if (currentTraceId) {
1394
- const parentContext = {
1395
- traceId: currentTraceId,
1396
- spanId: spanContext.parentSpanId,
1397
- parentSpanId: undefined
1398
- };
1399
- this.currentContext = parentContext;
1400
- return parentContext;
1401
- }
1402
- }
1403
- this.currentContext = undefined;
1404
- return;
1405
- }
1406
- generateTraceId() {
1407
- const timestamp = Date.now().toString(16).padStart(12, "0");
1408
- const random = Array.from({ length: 5 }, () => Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0")).join("");
1409
- return (timestamp + random).slice(0, 32).padStart(32, "0");
1410
- }
1411
- generateSpanId() {
1412
- return Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, "0");
1413
- }
1414
- handleSpanEnd(spanId, parentSpanId) {
1415
- this.activeSpans.delete(spanId);
1416
- const currentTraceId = this.currentContext?.traceId;
1417
- if (parentSpanId) {
1418
- const parentSpan = this.activeSpans.get(parentSpanId);
1419
- if (parentSpan) {
1420
- this.currentContext = {
1421
- traceId: parentSpan.spanContext.traceId,
1422
- spanId: parentSpan.spanContext.spanId,
1423
- parentSpanId: parentSpan.spanContext.parentSpanId
1424
- };
1425
- return;
1426
- }
1427
- if (currentTraceId) {
1428
- this.currentContext = {
1429
- traceId: currentTraceId,
1430
- spanId: parentSpanId,
1431
- parentSpanId: undefined
1432
- };
1433
- return;
1434
- }
1435
- }
1436
- this.currentContext = undefined;
1437
- }
1438
- }
1439
-
1440
- class OTelTracerProvider {
1441
- tracers = new Map;
1442
- storage;
1443
- initialized = false;
1444
- globalContext;
1445
- constructor(storage, dbPath) {
1446
- this.storage = storage || new SQLiteSpanStorage(dbPath || getDefaultDbPath());
1447
- }
1448
- async initialize() {
1449
- if (this.initialized)
1450
- return;
1451
- await this.storage.initialize();
1452
- this.initialized = true;
1453
- }
1454
- isInitialized() {
1455
- return this.initialized;
1456
- }
1457
- getGlobalContext() {
1458
- return this.globalContext;
1459
- }
1460
- setGlobalContext(context2) {
1461
- this.globalContext = context2;
1462
- }
1463
- getTracer(name, version) {
1464
- const key = `${name}@${version || "0.0.0"}`;
1465
- let tracer = this.tracers.get(key);
1466
- if (!tracer) {
1467
- tracer = new OTelTracerImpl(name, version, this.storage, this);
1468
- this.tracers.set(key, tracer);
1469
- if (this.initialized) {
1470
- this.restoreFromEnv(tracer);
1471
- }
1472
- }
1473
- return tracer;
1474
- }
1475
- restoreFromEnv(tracer) {
1476
- const extracted = propagation.extract(process.env);
1477
- if (extracted) {
1478
- tracer.setCurrentContext({
1479
- traceId: extracted.traceId,
1480
- spanId: extracted.spanId,
1481
- parentSpanId: undefined
1482
- });
1483
- }
1484
- }
1485
- shutdown() {
1486
- for (const tracer of this.tracers.values()) {}
1487
- this.tracers.clear();
1488
- this.storage.close();
1489
- this.initialized = false;
1490
- this.globalContext = undefined;
1491
- delete process.env["TRACEPARENT"];
1492
- delete process.env["TRACE_ID"];
1493
- delete process.env["LOG_TRACE_REQUEST_ID"];
1494
- }
1495
- getStorage() {
1496
- return this.storage;
1497
- }
1498
- }
1499
- function getTracerProvider() {
1500
- if (!providerInstance) {
1501
- providerInstance = new OTelTracerProvider;
1502
- }
1503
- return providerInstance;
1504
- }
1505
- function resetTracerProvider() {
1506
- if (providerInstance) {
1507
- providerInstance.shutdown();
1508
- providerInstance = null;
1509
- }
1510
- }
1511
- function getDefaultDbPath() {
1512
- const os = __require("os");
1513
- const path = __require("path");
1514
- const home = os.homedir();
1515
- const dataHome = process.env.XDG_DATA_HOME || path.join(home, ".local", "share");
1516
- return path.join(dataHome, "roy-agent", "traces.db");
1517
- }
1518
- var providerInstance = null;
1519
- var init_tracer_provider = __esm(() => {
1520
- init_propagation();
1521
- init_types2();
1522
- });
1523
-
1524
- // packages/core/src/env/log-trace/logger.ts
1525
- import { appendFileSync, existsSync, mkdirSync } from "fs";
1526
- import { join } from "path";
1527
- function simplifyFilePath(fullPath) {
1528
- let path = fullPath.replace(/\\/g, "/");
1529
- const bunfsMatch = path.match(/\/\$bunfs\/root\/(.+)$/);
1530
- if (bunfsMatch) {
1531
- const virtualPath = bunfsMatch[1];
1532
- const packagesMatch = virtualPath.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
1533
- if (packagesMatch) {
1534
- return packagesMatch[1];
1535
- }
1536
- return virtualPath;
1537
- }
1538
- const fileProtocolMatch = path.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);
1539
- if (fileProtocolMatch) {
1540
- const rootPkg = fileProtocolMatch[1].replace(/\+/g, "/");
1541
- const remaining = fileProtocolMatch[2];
1542
- const prefix = rootPkg;
1543
- const suffix = remaining.startsWith("src/") ? remaining : `src/${remaining}`;
1544
- return `${prefix}/${suffix}`;
1545
- }
1546
- const packagesRootMatch = path.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);
1547
- if (packagesRootMatch) {
1548
- return packagesRootMatch[1];
1549
- }
1550
- const rootMarkers = ["packages/core/src", "packages/core", "packages"];
1551
- for (const marker of rootMarkers) {
1552
- const idx = path.indexOf(marker);
1553
- if (idx !== -1) {
1554
- return path.substring(idx);
1555
- }
1556
- }
1557
- return path;
1558
- }
1559
- function getDefaultLogDir() {
1560
- const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1561
- try {
1562
- const xdg = __require("xdg-basedir");
1563
- if (xdg.xdgData) {
1564
- return join(xdg.xdgData, "roy-agent", "logs");
1565
- }
1566
- } catch {}
1567
- return join(home, ".local", "share", "roy-agent", "logs");
1568
- }
1569
- function isQuietMode() {
1570
- return quietMode;
1571
- }
1572
- function setQuietMode(enabled) {
1573
- quietMode = enabled;
1574
- }
1575
- function setConfigComponent(component) {
1576
- configComponentInstance = component;
1577
- }
1578
- function getLogLevel() {
1579
- if (configComponentInstance) {
1580
- const level = configComponentInstance.get("log_trace.logging.level");
1581
- if (level && ["debug", "info", "warn", "error"].includes(level)) {
1582
- return level;
1583
- }
1584
- }
1585
- const envLevel = process.env.LOG_LEVEL;
1586
- if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
1587
- return envLevel;
1588
- }
1589
- return "info";
1590
- }
1591
- function getCategoryLogLevel(category) {
1592
- if (configComponentInstance) {
1593
- const levels = configComponentInstance.get("log_trace.logging.levels");
1594
- if (levels && typeof levels === "object") {
1595
- const categoryLevel = levels[category];
1596
- if (categoryLevel && ["debug", "info", "warn", "error"].includes(categoryLevel)) {
1597
- return categoryLevel;
1598
- }
1599
- }
1600
- const directLevel = configComponentInstance.get(`log_trace.logging.levels.${category}`);
1601
- if (directLevel && ["debug", "info", "warn", "error"].includes(directLevel)) {
1602
- return directLevel;
1603
- }
1604
- }
1605
- const envKey = `LOG_LEVEL_${category.toUpperCase().replace(/:/g, "_")}`;
1606
- const envLevel = process.env[envKey];
1607
- if (envLevel && ["debug", "info", "warn", "error"].includes(envLevel)) {
1608
- return envLevel;
1609
- }
1610
- return getLogLevel();
1611
- }
1612
- function isAbsolutePath(path) {
1613
- if (path.startsWith("/")) {
1614
- return true;
1615
- }
1616
- if (/^[a-zA-Z]:[/\\]/.test(path)) {
1617
- return true;
1618
- }
1619
- return false;
1620
- }
1621
- function expandHomeDir(path) {
1622
- if (path.startsWith("~")) {
1623
- const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
1624
- return join(home, path.slice(1));
1625
- }
1626
- return path;
1627
- }
1628
- function getLogFile() {
1629
- if (configComponentInstance) {
1630
- const file = configComponentInstance.get("log_trace.logging.file");
1631
- if (file) {
1632
- return file;
1633
- }
1634
- }
1635
- return "app.log";
1636
- }
1637
- function getLogDir() {
1638
- if (configComponentInstance) {
1639
- const dir = configComponentInstance.get("log_trace.logging.dir");
1640
- if (dir) {
1641
- return dir;
1642
- }
1643
- }
1644
- return getDefaultLogDir();
1645
- }
1646
- function getMaxOutput() {
1647
- if (configComponentInstance) {
1648
- const maxOutput = configComponentInstance.get("log-trace.logging.maxOutput");
1649
- if (typeof maxOutput === "number") {
1650
- return maxOutput;
1651
- }
1652
- }
1653
- return;
1654
- }
1655
- function setLogDirOverride(dir) {
1656
- logDirOverride = dir;
1657
- }
1658
- function getLogDirOverride() {
1659
- return logDirOverride;
1660
- }
1661
-
1662
- class Logger {
1663
- prefix;
1664
- constructor(prefix) {
1665
- this.prefix = prefix;
1666
- }
1667
- shouldLog(level) {
1668
- const categoryLevel = getCategoryLogLevel(this.prefix);
1669
- return levelPriority[level] >= levelPriority[categoryLevel];
1670
- }
1671
- ensureLogDirectory(dir) {
1672
- if (!existsSync(dir)) {
1673
- try {
1674
- mkdirSync(dir, { recursive: true });
1675
- } catch (err) {
1676
- console.error("[Logger] Failed to create log directory:", dir, err);
1677
- }
1678
- }
1679
- }
1680
- getCallerLocation() {
1681
- const originalLimit = Error.stackTraceLimit;
1682
- Error.stackTraceLimit = 10;
1683
- const err = new Error;
1684
- Error.captureStackTrace(err, this.formatMessage);
1685
- const stack = err.stack?.split(`
1686
- `) || [];
1687
- Error.stackTraceLimit = originalLimit;
1688
- for (let i = 1;i < stack.length; i++) {
1689
- const line = stack[i];
1690
- if (line.includes("at ") && !line.includes("logger.ts") && !line.includes("formatMessage")) {
1691
- const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
1692
- if (match) {
1693
- const filePath = match[1];
1694
- const relativePath = this.getRelativePath(filePath);
1695
- return {
1696
- file: relativePath,
1697
- line: parseInt(match[2], 10)
1698
- };
1699
- }
1700
- }
1701
- }
1702
- return null;
1703
- }
1704
- getRelativePath(fullPath) {
1705
- return simplifyFilePath(fullPath);
1706
- }
1707
- formatMessage(level, message, data) {
1708
- const now = new Date;
1709
- const timestamp = now.toLocaleString("zh-CN", {
1710
- timeZone: "Asia/Shanghai",
1711
- year: "numeric",
1712
- month: "2-digit",
1713
- day: "2-digit",
1714
- hour: "2-digit",
1715
- minute: "2-digit",
1716
- second: "2-digit",
1717
- hour12: false
1718
- }).replace(/\//g, "-") + "." + String(now.getMilliseconds()).padStart(3, "0");
1719
- const prefix = this.prefix ? `[${this.prefix}]` : "";
1720
- let traceIdStr = "";
1721
- try {
1722
- const provider = getTracerProvider();
1723
- const tracer = provider.getTracer("roy-tracer");
1724
- const context2 = tracer.getCurrentContext();
1725
- if (context2?.traceId) {
1726
- traceIdStr = `[traceId=${context2.traceId}]`;
1727
- }
1728
- } catch {}
1729
- let locationStr = "";
1730
- if (data && typeof data === "object" && "callerLocation" in data) {
1731
- const logData = data;
1732
- locationStr = logData.callerLocation ? ` [${logData.callerLocation}]` : "";
1733
- const { callerLocation: _callerLocation, ...rest } = logData;
1734
- data = Object.keys(rest).length > 0 ? rest : undefined;
1735
- } else {
1736
- const location = this.getCallerLocation();
1737
- if (location) {
1738
- locationStr = ` [${location.file}:${location.line}]`;
1739
- }
1740
- }
1741
- let formatted = `${timestamp} [${level.toUpperCase()}]${traceIdStr}${locationStr}${prefix} ${message}`;
1742
- if (data !== undefined) {
1743
- if (typeof data === "object") {
1744
- formatted += " " + JSON.stringify(data).replace(/\n/g, "");
1745
- } else {
1746
- formatted += " " + String(data);
1747
- }
1748
- }
1749
- const maxOutput = getMaxOutput();
1750
- if (maxOutput && maxOutput > 0 && formatted.length > maxOutput) {
1751
- formatted = formatted.substring(0, maxOutput) + " [TRUNCATED]";
1752
- }
1753
- return formatted;
1754
- }
1755
- writeToFile(message) {
1756
- try {
1757
- const dir = getLogDir();
1758
- const filename = getLogFile();
1759
- const expandedDir = expandHomeDir(dir);
1760
- const resolvedDir = isAbsolutePath(expandedDir) ? expandedDir : join(process.cwd(), expandedDir);
1761
- this.ensureLogDirectory(resolvedDir);
1762
- const logFile = join(resolvedDir, filename);
1763
- appendFileSync(logFile, message + `
1764
- `, "utf-8");
1765
- } catch (err) {
1766
- console.error("[Logger] Failed to write to log file:", err);
1767
- }
1768
- }
1769
- log(level, message, data) {
1770
- if (!this.shouldLog(level))
1771
- return;
1772
- const formatted = this.formatMessage(level, message, data);
1773
- this.writeToFile(formatted);
1774
- if (!isQuietMode()) {
1775
- const consoleMethod = level === "error" ? console.error : level === "warn" ? console.warn : level === "info" ? console.log : console.debug;
1776
- consoleMethod(formatted);
595
+ if (this.dagManager.areDependenciesMet(nodeId, allCompleted)) {
596
+ this.ready.add(nodeId);
597
+ }
1777
598
  }
1778
599
  }
1779
- debug(message, data) {
1780
- this.log("debug", message, data);
1781
- }
1782
- info(message, data) {
1783
- this.log("info", message, data);
1784
- }
1785
- warn(message, data) {
1786
- this.log("warn", message, data);
1787
- }
1788
- error(message, data) {
1789
- this.log("error", message, data);
600
+ getParallelLimit() {
601
+ return this.options.parallelLimit;
1790
602
  }
1791
- }
1792
- function createLogger(prefix) {
1793
- if (!loggerCache.has(prefix)) {
1794
- loggerCache.set(prefix, new Logger(prefix));
603
+ setParallelLimit(limit) {
604
+ this.options.parallelLimit = limit;
1795
605
  }
1796
- return loggerCache.get(prefix);
1797
606
  }
1798
- function getLogLevels() {
1799
- return ["debug", "info", "warn", "error"];
1800
- }
1801
- var configComponentInstance = null, quietMode = false, logDirOverride, levelPriority, loggerCache;
1802
- var init_logger = __esm(() => {
1803
- init_tracer_provider();
1804
- levelPriority = {
1805
- debug: 0,
1806
- info: 1,
1807
- warn: 2,
1808
- error: 3
607
+ var init_scheduler = () => {};
608
+
609
+ // src/env/workflow/types/event.ts
610
+ import { z } from "zod";
611
+ function createWorkflowEvent(type, runId, data) {
612
+ return {
613
+ type,
614
+ run_id: runId,
615
+ timestamp: Date.now(),
616
+ ...data
1809
617
  };
1810
- loggerCache = new Map;
618
+ }
619
+ var BaseEventSchema, WorkflowStartedEventSchema, WorkflowPausedEventSchema, WorkflowResumedEventSchema, WorkflowStoppedEventSchema, WorkflowCompletedEventSchema, WorkflowFailedEventSchema, WorkflowOutputEventSchema, NodeScheduledEventSchema, NodeStartedEventSchema, NodeProgressEventSchema, NodeCompletedEventSchema, NodeFailedEventSchema, NodeSkippedEventSchema, NodeDataEventSchema, NodeAddedEventSchema, NodeRemovedEventSchema, ControlPauseEventSchema, ControlResumeEventSchema, ControlStopEventSchema, NodeInterruptEventSchema, WorkflowAskUserEventSchema, WorkflowEventSchema;
620
+ var init_event = __esm(() => {
621
+ BaseEventSchema = z.object({
622
+ type: z.string(),
623
+ run_id: z.string(),
624
+ timestamp: z.number()
625
+ });
626
+ WorkflowStartedEventSchema = BaseEventSchema.extend({
627
+ type: z.literal("workflow.started"),
628
+ workflow_name: z.string(),
629
+ input: z.record(z.string(), z.unknown()).optional()
630
+ });
631
+ WorkflowPausedEventSchema = BaseEventSchema.extend({
632
+ type: z.literal("workflow.paused")
633
+ });
634
+ WorkflowResumedEventSchema = BaseEventSchema.extend({
635
+ type: z.literal("workflow.resumed")
636
+ });
637
+ WorkflowStoppedEventSchema = BaseEventSchema.extend({
638
+ type: z.literal("workflow.stopped"),
639
+ reason: z.string()
640
+ });
641
+ WorkflowCompletedEventSchema = BaseEventSchema.extend({
642
+ type: z.literal("workflow.completed"),
643
+ result: z.record(z.string(), z.unknown()).optional(),
644
+ duration_ms: z.number()
645
+ });
646
+ WorkflowFailedEventSchema = BaseEventSchema.extend({
647
+ type: z.literal("workflow.failed"),
648
+ error: z.object({
649
+ message: z.string(),
650
+ stack: z.string().optional()
651
+ }),
652
+ failed_at: z.string()
653
+ });
654
+ WorkflowOutputEventSchema = BaseEventSchema.extend({
655
+ type: z.literal("workflow.output"),
656
+ output: z.record(z.string(), z.unknown())
657
+ });
658
+ NodeScheduledEventSchema = BaseEventSchema.extend({
659
+ type: z.literal("node.scheduled"),
660
+ node_id: z.string()
661
+ });
662
+ NodeStartedEventSchema = BaseEventSchema.extend({
663
+ type: z.literal("node.started"),
664
+ node_id: z.string(),
665
+ input: z.any(),
666
+ agentSessionId: z.string().optional(),
667
+ userResponse: z.string().optional()
668
+ });
669
+ NodeProgressEventSchema = BaseEventSchema.extend({
670
+ type: z.literal("node.progress"),
671
+ node_id: z.string(),
672
+ progress: z.number(),
673
+ message: z.string().optional()
674
+ });
675
+ NodeCompletedEventSchema = BaseEventSchema.extend({
676
+ type: z.literal("node.completed"),
677
+ node_id: z.string(),
678
+ output: z.any(),
679
+ duration_ms: z.number()
680
+ });
681
+ NodeFailedEventSchema = BaseEventSchema.extend({
682
+ type: z.literal("node.failed"),
683
+ node_id: z.string(),
684
+ error: z.object({
685
+ message: z.string(),
686
+ stack: z.string().optional()
687
+ })
688
+ });
689
+ NodeSkippedEventSchema = BaseEventSchema.extend({
690
+ type: z.literal("node.skipped"),
691
+ node_id: z.string(),
692
+ reason: z.string()
693
+ });
694
+ NodeDataEventSchema = BaseEventSchema.extend({
695
+ type: z.literal("node.data"),
696
+ from_node: z.string(),
697
+ to_node: z.string(),
698
+ data: z.any()
699
+ });
700
+ NodeAddedEventSchema = BaseEventSchema.extend({
701
+ type: z.literal("node.added"),
702
+ node_id: z.string(),
703
+ node: z.any()
704
+ });
705
+ NodeRemovedEventSchema = BaseEventSchema.extend({
706
+ type: z.literal("node.removed"),
707
+ node_id: z.string()
708
+ });
709
+ ControlPauseEventSchema = BaseEventSchema.extend({
710
+ type: z.literal("control.pause")
711
+ });
712
+ ControlResumeEventSchema = BaseEventSchema.extend({
713
+ type: z.literal("control.resume")
714
+ });
715
+ ControlStopEventSchema = BaseEventSchema.extend({
716
+ type: z.literal("control.stop")
717
+ });
718
+ NodeInterruptEventSchema = BaseEventSchema.extend({
719
+ type: z.literal("node.interrupt"),
720
+ node_id: z.string(),
721
+ node_type: z.string(),
722
+ query: z.string()
723
+ });
724
+ WorkflowAskUserEventSchema = BaseEventSchema.extend({
725
+ type: z.literal("workflow.ask-user"),
726
+ session_id: z.string(),
727
+ node_id: z.string(),
728
+ node_type: z.string(),
729
+ query: z.string()
730
+ });
731
+ WorkflowEventSchema = z.union([
732
+ WorkflowStartedEventSchema,
733
+ WorkflowPausedEventSchema,
734
+ WorkflowResumedEventSchema,
735
+ WorkflowStoppedEventSchema,
736
+ WorkflowCompletedEventSchema,
737
+ WorkflowFailedEventSchema,
738
+ WorkflowOutputEventSchema,
739
+ NodeScheduledEventSchema,
740
+ NodeStartedEventSchema,
741
+ NodeProgressEventSchema,
742
+ NodeCompletedEventSchema,
743
+ NodeFailedEventSchema,
744
+ NodeSkippedEventSchema,
745
+ NodeDataEventSchema,
746
+ NodeAddedEventSchema,
747
+ NodeRemovedEventSchema,
748
+ ControlPauseEventSchema,
749
+ ControlResumeEventSchema,
750
+ ControlStopEventSchema,
751
+ NodeInterruptEventSchema,
752
+ WorkflowAskUserEventSchema
753
+ ]);
754
+ });
755
+
756
+ // src/env/workflow/types/workflow.ts
757
+ import { z as z2 } from "zod";
758
+ var DependsOnSchema, RetryConfigSchema, NodeDefinitionSchema, WorkflowConfigSchema, OutputDefinitionSchema, WorkflowMetadataSchema, WorkflowDefinitionSchema;
759
+ var init_workflow = __esm(() => {
760
+ DependsOnSchema = z2.array(z2.string());
761
+ RetryConfigSchema = z2.object({
762
+ max_attempts: z2.number().min(1).default(1),
763
+ backoff: z2.enum(["fixed", "exponential"]).default("exponential"),
764
+ initial_delay: z2.number().min(0).default(1000)
765
+ });
766
+ NodeDefinitionSchema = z2.object({
767
+ id: z2.string().min(1, "Node ID is required"),
768
+ type: z2.string().min(1, "Node type is required"),
769
+ name: z2.string().optional(),
770
+ config: z2.record(z2.string(), z2.unknown()).optional().default({}),
771
+ depends_on: z2.array(z2.string()).optional(),
772
+ condition: z2.string().optional(),
773
+ retry: RetryConfigSchema.optional(),
774
+ timeout: z2.number().optional()
775
+ });
776
+ WorkflowConfigSchema = z2.object({
777
+ parallel_limit: z2.number().nullable().optional(),
778
+ timeout: z2.number().nullable().optional(),
779
+ retry: RetryConfigSchema.optional(),
780
+ debug: z2.boolean().optional()
781
+ });
782
+ OutputDefinitionSchema = z2.object({
783
+ name: z2.string(),
784
+ source: z2.string(),
785
+ path: z2.string()
786
+ });
787
+ WorkflowMetadataSchema = z2.object({
788
+ author: z2.string().optional(),
789
+ taskId: z2.number().optional(),
790
+ tags: z2.array(z2.string()).optional().default([]),
791
+ created_at: z2.string().optional(),
792
+ updated_at: z2.string().optional()
793
+ });
794
+ WorkflowDefinitionSchema = z2.object({
795
+ name: z2.string().min(1, "Workflow name is required"),
796
+ version: z2.string().default("1.0"),
797
+ description: z2.string().optional(),
798
+ config: WorkflowConfigSchema.optional().default({}),
799
+ nodes: z2.array(NodeDefinitionSchema).min(1, "At least one node is required"),
800
+ entry: z2.union([z2.string(), z2.array(z2.string())]).default("__default_entry__"),
801
+ outputs: z2.array(OutputDefinitionSchema).optional().default([]),
802
+ metadata: WorkflowMetadataSchema.optional().default({})
803
+ });
804
+ });
805
+
806
+ // src/env/workflow/types/workflow-message.ts
807
+ import { z as z3 } from "zod";
808
+ var WorkflowMessageRoleSchema;
809
+ var init_workflow_message = __esm(() => {
810
+ init_workflow_hil();
811
+ WorkflowMessageRoleSchema = z3.enum([
812
+ "workflow.node.call",
813
+ "workflow.node.interrupt",
814
+ "workflow.node.result",
815
+ "workflow.node.resume"
816
+ ]);
817
+ });
818
+
819
+ // src/env/workflow/types/workflow-session.ts
820
+ var init_workflow_session = () => {};
821
+
822
+ // src/env/workflow/types/context.ts
823
+ var init_context = () => {};
824
+
825
+ // src/env/workflow/types/run.ts
826
+ import { z as z4 } from "zod";
827
+ var RunStatusSchema, NodeStatusSchema;
828
+ var init_run = __esm(() => {
829
+ init_workflow_message();
830
+ RunStatusSchema = z4.enum([
831
+ "idle",
832
+ "running",
833
+ "paused",
834
+ "stopped",
835
+ "completed",
836
+ "failed"
837
+ ]);
838
+ NodeStatusSchema = z4.enum([
839
+ "pending",
840
+ "scheduled",
841
+ "started",
842
+ "running",
843
+ "completed",
844
+ "failed",
845
+ "skipped"
846
+ ]);
847
+ });
848
+
849
+ // src/env/workflow/types/index.ts
850
+ var init_types = __esm(() => {
851
+ init_run();
852
+ init_workflow();
853
+ init_workflow_message();
854
+ init_workflow_session();
855
+ init_context();
856
+ init_workflow_hil();
857
+ init_event();
858
+ init_run();
1811
859
  });
1812
860
 
1813
- // packages/core/src/env/log-trace/decorator.ts
861
+ // src/env/log-trace/decorator.ts
1814
862
  function Traced(options) {
1815
863
  return function(target, propertyKey, descriptor) {
1816
864
  const originalFn = descriptor.value;
@@ -1967,7 +1015,7 @@ var init_decorator = __esm(() => {
1967
1015
  init_logger();
1968
1016
  });
1969
1017
 
1970
- // packages/core/src/env/workflow/engine/executor.ts
1018
+ // src/env/workflow/engine/executor.ts
1971
1019
  var Executor;
1972
1020
  var init_executor = __esm(() => {
1973
1021
  init_event();
@@ -2241,22 +1289,22 @@ var init_executor = __esm(() => {
2241
1289
  }
2242
1290
  summarizeResult(nodeId, output, error, durationMs) {
2243
1291
  if (error) {
2244
- return `\u274C ${nodeId} failed: ${error}`;
1292
+ return `❌ ${nodeId} failed: ${error}`;
2245
1293
  }
2246
1294
  if (output === undefined || output === null) {
2247
- return `\u2705 ${nodeId} completed (${durationMs}ms)`;
1295
+ return `✅ ${nodeId} completed (${durationMs}ms)`;
2248
1296
  }
2249
1297
  if (typeof output === "object") {
2250
1298
  const keys = Object.keys(output);
2251
1299
  if (keys.length === 0) {
2252
- return `\u2705 ${nodeId} completed (${durationMs}ms)`;
1300
+ return `✅ ${nodeId} completed (${durationMs}ms)`;
2253
1301
  }
2254
1302
  const summary = keys.slice(0, 3).join(", ");
2255
- return `\u2705 ${nodeId}: ${summary} (${durationMs}ms)`;
1303
+ return `✅ ${nodeId}: ${summary} (${durationMs}ms)`;
2256
1304
  }
2257
1305
  const strOutput = String(output);
2258
1306
  const truncated = strOutput.length > 100 ? strOutput.substring(0, 100) + "..." : strOutput;
2259
- return `\u2705 ${nodeId}: ${truncated} (${durationMs}ms)`;
1307
+ return `✅ ${nodeId}: ${truncated} (${durationMs}ms)`;
2260
1308
  }
2261
1309
  async writeNodeResume(sessionId, response) {
2262
1310
  if (!this.sessionComponent)
@@ -2294,7 +1342,7 @@ var init_executor = __esm(() => {
2294
1342
  ], Executor.prototype, "writeNodeResume", null);
2295
1343
  });
2296
1344
 
2297
- // packages/core/src/env/workflow/nodes/tool-node.ts
1345
+ // src/env/workflow/nodes/tool-node.ts
2298
1346
  class ToolNode {
2299
1347
  definition;
2300
1348
  toolRegistry;
@@ -2556,8 +1604,9 @@ class ToolNode {
2556
1604
  return str.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t").replace(/"/g, "\\\"").replace(/`/g, "\\`").replace(/\$/g, "\\$");
2557
1605
  }
2558
1606
  }
1607
+ var init_tool_node = () => {};
2559
1608
 
2560
- // packages/core/src/env/workflow/nodes/skill-node.ts
1609
+ // src/env/workflow/nodes/skill-node.ts
2561
1610
  class SkillNode {
2562
1611
  definition;
2563
1612
  skillRegistry;
@@ -2754,8 +1803,9 @@ class SkillNode {
2754
1803
  return JSON.stringify(value);
2755
1804
  }
2756
1805
  }
1806
+ var init_skill_node = () => {};
2757
1807
 
2758
- // packages/core/src/env/workflow/nodes/agent-node.ts
1808
+ // src/env/workflow/nodes/agent-node.ts
2759
1809
  var AgentNode;
2760
1810
  var init_agent_node = __esm(() => {
2761
1811
  init_workflow_hil();
@@ -3011,208 +2061,7 @@ var init_agent_node = __esm(() => {
3011
2061
  ], AgentNode.prototype, "createAgentSubSession", null);
3012
2062
  });
3013
2063
 
3014
- // packages/core/src/env/workflow/nodes/agent-component-adapter.ts
3015
- var exports_agent_component_adapter = {};
3016
- __export(exports_agent_component_adapter, {
3017
- AgentComponentAdapter: () => AgentComponentAdapter
3018
- });
3019
-
3020
- class AgentComponentAdapter {
3021
- agentComponent;
3022
- options;
3023
- _sessionComponent;
3024
- agentSessionPrefix = "agent";
3025
- _currentAgentSessionId;
3026
- pendingSessions = new Map;
3027
- runSessionToAgentSessions = new Map;
3028
- constructor(agentComponent, options = {}, _sessionComponent) {
3029
- this.agentComponent = agentComponent;
3030
- this.options = options;
3031
- this._sessionComponent = _sessionComponent;
3032
- }
3033
- setSessionComponent(sessionComponent) {
3034
- this._sessionComponent = sessionComponent;
3035
- }
3036
- getCurrentAgentSessionId() {
3037
- return this._currentAgentSessionId;
3038
- }
3039
- registerAgent(name, config) {
3040
- this.agentComponent.registerAgent(name, {
3041
- type: config.type || "general",
3042
- model: config.model,
3043
- systemPrompt: config.systemPrompt,
3044
- maxIterations: config.maxIterations,
3045
- allowedTools: config.allowedTools,
3046
- deniedTools: config.deniedTools,
3047
- timeout: config.timeout,
3048
- maxErrorRetries: config.maxErrorRetries
3049
- });
3050
- if (config.sessionIdPrefix) {
3051
- this.agentSessionPrefixes.set(name, config.sessionIdPrefix);
3052
- }
3053
- }
3054
- async run(config, resumeOptions) {
3055
- const startTime = Date.now();
3056
- const nodeId = config.nodeId || "unknown";
3057
- const runId = config.runId || "unknown";
3058
- const workflowSessionId = config.workflowSessionId;
3059
- const existingAgentSessionId = config.agentSessionId;
3060
- const resumeAgentSessionId = resumeOptions?.agentSessionId;
3061
- const isResume = !!resumeOptions?.userResponse || !!existingAgentSessionId || !!resumeAgentSessionId;
3062
- let agentSessionId;
3063
- if (isResume && (this._currentAgentSessionId || existingAgentSessionId || resumeAgentSessionId)) {
3064
- agentSessionId = resumeAgentSessionId || existingAgentSessionId || this._currentAgentSessionId;
3065
- if (resumeOptions?.userResponse && this._sessionComponent && agentSessionId) {
3066
- try {
3067
- await this._sessionComponent.addMessage(agentSessionId, {
3068
- role: "user",
3069
- content: resumeOptions.userResponse,
3070
- metadata: {
3071
- type: "user_intent",
3072
- intent: "workflow.resume",
3073
- workflowNodeId: nodeId
3074
- }
3075
- });
3076
- } catch (error) {
3077
- console.warn(`Failed to add user response to agent session ${agentSessionId}:`, error);
3078
- }
3079
- }
3080
- } else {
3081
- if (this._sessionComponent) {
3082
- agentSessionId = `${this.agentSessionPrefix}_${runId}_${nodeId}_${Date.now()}`;
3083
- try {
3084
- await this._sessionComponent.create({
3085
- title: `Agent Session: ${config.type} (${agentSessionId})`,
3086
- metadata: {
3087
- type: "agent",
3088
- workflowRunId: runId,
3089
- workflowNodeId: nodeId
3090
- }
3091
- });
3092
- this._currentAgentSessionId = agentSessionId;
3093
- if (workflowSessionId) {
3094
- const mapping = this.runSessionToAgentSessions.get(workflowSessionId) || [];
3095
- mapping.push(agentSessionId);
3096
- this.runSessionToAgentSessions.set(workflowSessionId, mapping);
3097
- }
3098
- this.pendingSessions.set(agentSessionId, {
3099
- agentSessionId,
3100
- nodeId,
3101
- runId,
3102
- createdAt: Date.now()
3103
- });
3104
- } catch (error) {
3105
- console.warn(`Failed to create agent session ${agentSessionId}:`, error);
3106
- }
3107
- }
3108
- }
3109
- try {
3110
- const context2 = {};
3111
- if (config.options?.timeout) {
3112
- context2.abort = new AbortController;
3113
- }
3114
- if (agentSessionId) {
3115
- context2.sessionId = agentSessionId;
3116
- }
3117
- if (config.options?.allowedTools) {
3118
- context2.allowedTools = config.options.allowedTools;
3119
- }
3120
- if (config.options?.deniedTools) {
3121
- context2.deniedTools = config.options.deniedTools;
3122
- }
3123
- if (config.workflowHistory) {
3124
- context2.workflowHistory = config.workflowHistory;
3125
- }
3126
- const result = await this.agentComponent.run(config.type || "general", config.prompt, context2);
3127
- if (result.error?.startsWith("__ASK_USER_ERROR__:")) {
3128
- const jsonStr = result.error.substring("__ASK_USER_ERROR__:".length);
3129
- const errorInfo = JSON.parse(jsonStr);
3130
- throw new AskUserError(runId, errorInfo.sessionId, errorInfo.nodeId, errorInfo.nodeType || "agent", errorInfo.query);
3131
- }
3132
- const duration = Date.now() - startTime;
3133
- if (agentSessionId) {
3134
- this.pendingSessions.delete(agentSessionId);
3135
- }
3136
- const messages = result._messages || [];
3137
- return {
3138
- output: result.finalText || result.output,
3139
- metadata: {
3140
- duration,
3141
- iterations: result.iterations,
3142
- toolCalls: result.toolCalls?.length,
3143
- agentSessionId
3144
- },
3145
- messages
3146
- };
3147
- } catch (error) {
3148
- const isAskUserError = error instanceof Error && error.name === "AskUserError";
3149
- if (isAskUserError) {
3150
- throw error;
3151
- }
3152
- const duration = Date.now() - startTime;
3153
- const errorMessage = error instanceof Error ? error.message : String(error);
3154
- if (agentSessionId) {
3155
- this.pendingSessions.delete(agentSessionId);
3156
- }
3157
- return {
3158
- output: undefined,
3159
- metadata: {
3160
- duration,
3161
- error: errorMessage,
3162
- agentSessionId
3163
- }
3164
- };
3165
- } finally {
3166
- if (!isResume) {
3167
- this._currentAgentSessionId = undefined;
3168
- }
3169
- }
3170
- }
3171
- async resumeAgent(agentSessionId, userResponse, config) {
3172
- if (this._sessionComponent) {
3173
- try {
3174
- await this._sessionComponent.addMessage(agentSessionId, {
3175
- role: "user",
3176
- content: userResponse,
3177
- metadata: {
3178
- type: "user_intent",
3179
- intent: "workflow.resume"
3180
- }
3181
- });
3182
- this.pendingSessions.delete(agentSessionId);
3183
- this._currentAgentSessionId = agentSessionId;
3184
- } catch (error) {
3185
- console.warn(`Failed to add user response to agent session ${agentSessionId}:`, error);
3186
- }
3187
- }
3188
- config.agentSessionId = agentSessionId;
3189
- return this.run(config, { userResponse });
3190
- }
3191
- getPendingSession(agentSessionId) {
3192
- return this.pendingSessions.get(agentSessionId);
3193
- }
3194
- getPendingSessionsForRun(runId) {
3195
- return Array.from(this.pendingSessions.values()).filter((session) => session.runId === runId);
3196
- }
3197
- getAgentSessionsForWorkflowSession(workflowSessionId) {
3198
- return this.runSessionToAgentSessions.get(workflowSessionId) || [];
3199
- }
3200
- hasAgent(name) {
3201
- return this.agentComponent.getAgent(name) !== undefined;
3202
- }
3203
- listAgents() {
3204
- return this.agentComponent.listAgents().map((a) => a.name);
3205
- }
3206
- getAgentComponent() {
3207
- return this.agentComponent;
3208
- }
3209
- agentSessionPrefixes = new Map;
3210
- }
3211
- var init_agent_component_adapter = __esm(() => {
3212
- init_workflow_hil();
3213
- });
3214
-
3215
- // packages/core/src/env/workflow/nodes/workflow-node.ts
2064
+ // src/env/workflow/nodes/workflow-node.ts
3216
2065
  class WorkflowNode {
3217
2066
  workflowRunner;
3218
2067
  type = "workflow";
@@ -3345,8 +2194,9 @@ class WorkflowNode {
3345
2194
  return JSON.stringify(value);
3346
2195
  }
3347
2196
  }
2197
+ var init_workflow_node = () => {};
3348
2198
 
3349
- // packages/core/src/env/workflow/nodes/ask-user-node.ts
2199
+ // src/env/workflow/nodes/ask-user-node.ts
3350
2200
  class AskUserNode {
3351
2201
  type = "ask_user";
3352
2202
  id;
@@ -3356,9 +2206,9 @@ class AskUserNode {
3356
2206
  this.config = definition.config || {};
3357
2207
  }
3358
2208
  async execute(context2) {
3359
- const query = this.config.query || "\u786E\u8BA4\u7EE7\u7EED\u5417\uFF1F";
2209
+ const query = this.config.query || "确认继续吗?";
3360
2210
  const options = this.config.options;
3361
- const fullQuery = options ? `${query} (\u9009\u9879: ${options.join(", ")})` : query;
2211
+ const fullQuery = options ? `${query} (选项: ${options.join(", ")})` : query;
3362
2212
  await context2.eventBus.publish(createNodeInterruptEvent(context2.runId, this.id, this.type, fullQuery));
3363
2213
  throw new AskUserError(context2.runId, context2.sessionId, this.id, this.type, query);
3364
2214
  }
@@ -3370,7 +2220,7 @@ var init_ask_user_node = __esm(() => {
3370
2220
  init_workflow_hil();
3371
2221
  });
3372
2222
 
3373
- // packages/core/src/env/workflow/engine/node-registry.ts
2223
+ // src/env/workflow/engine/node-registry.ts
3374
2224
  class NodeRegistry {
3375
2225
  factories = new Map;
3376
2226
  toolRegistry;
@@ -3460,119 +2310,23 @@ class NodeRegistry {
3460
2310
  }
3461
2311
  }
3462
2312
  var init_node_registry = __esm(() => {
2313
+ init_tool_node();
2314
+ init_skill_node();
3463
2315
  init_agent_node();
3464
2316
  init_agent_component_adapter();
2317
+ init_workflow_node();
3465
2318
  init_ask_user_node();
3466
2319
  });
3467
2320
 
3468
- // packages/core/src/env/workflow/utils/session-recovery.ts
3469
- var exports_session_recovery = {};
3470
- __export(exports_session_recovery, {
3471
- parseNodeOutputs: () => parseNodeOutputs,
3472
- inferNextNode: () => inferNextNode,
3473
- hasPendingAskUser: () => hasPendingAskUser,
3474
- getAgentSessionIdFromInterrupt: () => getAgentSessionIdFromInterrupt,
3475
- findLastInterruptMessage: () => findLastInterruptMessage,
3476
- findLastCallMessage: () => findLastCallMessage
3477
- });
3478
- function inferNextNode(messages, definition) {
3479
- if (messages.length === 0) {
3480
- return { type: "entry_node", nodeId: definition.entryNode };
3481
- }
3482
- const lastMessage = messages[messages.length - 1];
3483
- const metadata = lastMessage.metadata;
3484
- switch (metadata?.type) {
3485
- case "workflow.node.call":
3486
- return {
3487
- type: "resume_node",
3488
- nodeId: metadata.workflowNodeId,
3489
- agentSessionId: metadata.agentSessionId
3490
- };
3491
- case "workflow.node.interrupt":
3492
- return {
3493
- type: "ask_user",
3494
- nodeId: metadata.workflowNodeId,
3495
- agentSessionId: metadata.agentSessionId
3496
- };
3497
- case "workflow.node.result":
3498
- return getNextNodes(metadata.workflowNodeId, definition);
3499
- default:
3500
- const lastCall = findLastCallMessage(messages);
3501
- if (lastCall) {
3502
- const callMetadata = lastCall.metadata;
3503
- return {
3504
- type: "resume_node",
3505
- nodeId: callMetadata.workflowNodeId,
3506
- agentSessionId: callMetadata.agentSessionId
3507
- };
3508
- }
3509
- return { type: "entry_node", nodeId: definition.entryNode };
3510
- }
3511
- }
3512
- function getNextNodes(completedNodeId, definition) {
3513
- if (!definition.edges) {
3514
- return { type: "next_nodes", nodeIds: [] };
3515
- }
3516
- const nextNodeIds = definition.edges.filter((edge) => edge.from === completedNodeId).map((edge) => edge.to);
3517
- return { type: "next_nodes", nodeIds: nextNodeIds };
3518
- }
3519
- function findLastInterruptMessage(messages) {
3520
- for (let i = messages.length - 1;i >= 0; i--) {
3521
- const msg = messages[i];
3522
- if (msg.metadata?.type === "workflow.node.interrupt") {
3523
- return msg;
3524
- }
3525
- }
3526
- return null;
3527
- }
3528
- function findLastCallMessage(messages) {
3529
- for (let i = messages.length - 1;i >= 0; i--) {
3530
- const msg = messages[i];
3531
- if (msg.metadata?.type === "workflow.node.call") {
3532
- return msg;
3533
- }
3534
- }
3535
- return null;
3536
- }
3537
- function parseNodeOutputs(messages) {
3538
- const outputs = new Map;
3539
- let lastCallNodeId = null;
3540
- for (const msg of messages) {
3541
- const metadata = msg.metadata;
3542
- if (metadata?.type === "workflow.node.call") {
3543
- lastCallNodeId = metadata.workflowNodeId;
3544
- } else if (metadata?.type === "workflow.node.result" && lastCallNodeId) {
3545
- try {
3546
- outputs.set(lastCallNodeId, JSON.parse(msg.content));
3547
- } catch {
3548
- outputs.set(lastCallNodeId, msg.content);
3549
- }
3550
- lastCallNodeId = null;
3551
- }
3552
- }
3553
- return outputs;
3554
- }
3555
- function hasPendingAskUser(messages) {
3556
- if (messages.length === 0)
3557
- return false;
3558
- const lastMessage = messages[messages.length - 1];
3559
- const metadata = lastMessage.metadata;
3560
- return metadata?.type === "workflow.node.interrupt";
3561
- }
3562
- function getAgentSessionIdFromInterrupt(messages) {
3563
- const lastInterrupt = findLastInterruptMessage(messages);
3564
- if (!lastInterrupt)
3565
- return null;
3566
- const metadata = lastInterrupt.metadata;
3567
- return metadata?.agentSessionId || null;
3568
- }
3569
-
3570
- // packages/core/src/env/workflow/engine/engine.ts
2321
+ // src/env/workflow/engine/engine.ts
3571
2322
  import { EventEmitter } from "events";
3572
2323
  var logger, WorkflowEngine;
3573
2324
  var init_engine = __esm(() => {
3574
2325
  init_event();
3575
2326
  init_workflow_hil();
2327
+ init_dag_manager();
2328
+ init_event_bus();
2329
+ init_scheduler();
3576
2330
  init_executor();
3577
2331
  init_node_registry();
3578
2332
  init_logger();
@@ -3691,10 +2445,10 @@ var init_engine = __esm(() => {
3691
2445
  return { runId: this.getRunIdFromSessionId(sessionId), status: "failed" };
3692
2446
  }
3693
2447
  const messages = this.sessionComponent ? await this.sessionComponent.getMessages(sessionId) : [];
3694
- const { inferNextNode: inferNextNode2 } = await Promise.resolve().then(() => exports_session_recovery);
2448
+ const { inferNextNode } = await import("./chunk-25x2pdtp.js");
3695
2449
  const entry = workflowDef.entry;
3696
2450
  const entryNode = Array.isArray(entry) ? entry[0] : entry;
3697
- const resumePoint = inferNextNode2(messages, {
2451
+ const resumePoint = inferNextNode(messages, {
3698
2452
  entryNode: entryNode !== "__default_entry__" ? entryNode : undefined,
3699
2453
  edges: undefined
3700
2454
  });
@@ -4364,7 +3118,7 @@ var init_engine = __esm(() => {
4364
3118
  ], WorkflowEngine.prototype, "failWorkflow", null);
4365
3119
  });
4366
3120
 
4367
- // packages/core/src/env/workflow/engine/index.ts
3121
+ // src/env/workflow/engine/index.ts
4368
3122
  var exports_engine = {};
4369
3123
  __export(exports_engine, {
4370
3124
  WorkflowEngine: () => WorkflowEngine,
@@ -4375,17 +3129,12 @@ __export(exports_engine, {
4375
3129
  DAGManager: () => DAGManager
4376
3130
  });
4377
3131
  var init_engine2 = __esm(() => {
3132
+ init_event_bus();
3133
+ init_dag_manager();
3134
+ init_scheduler();
4378
3135
  init_executor();
4379
3136
  init_engine();
4380
3137
  init_node_registry();
4381
3138
  });
4382
- init_engine2();
4383
3139
 
4384
- export {
4385
- WorkflowEngine,
4386
- Scheduler,
4387
- NodeRegistry,
4388
- Executor,
4389
- EventBus,
4390
- DAGManager
4391
- };
3140
+ export { Traced, TracedAs, TracedLightweight, wrapFunction, init_decorator, EventBus, DAGManager, Scheduler, Executor, NodeRegistry, WorkflowEngine, exports_engine, init_engine2 as init_engine };