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

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 (127) hide show
  1. package/dist/packages/core/src/config/index.js +32 -0
  2. package/dist/packages/core/src/env/agent/index.js +24 -0
  3. package/dist/packages/core/src/env/commands/index.js +14 -0
  4. package/dist/packages/core/src/env/debug/formatters/index.js +11 -0
  5. package/dist/packages/core/src/env/debug/index.js +26 -0
  6. package/dist/packages/core/src/env/hook/index.js +29 -0
  7. package/dist/packages/core/src/env/index.js +81 -0
  8. package/dist/packages/core/src/env/llm/index.js +40 -0
  9. package/dist/packages/core/src/env/log-trace/index.js +83 -0
  10. package/dist/packages/core/src/env/mcp/index.js +39 -0
  11. package/dist/packages/core/src/env/mcp/tool/index.js +14 -0
  12. package/dist/packages/core/src/env/memory/built-in/index.js +11 -0
  13. package/dist/packages/core/src/env/memory/index.js +56 -0
  14. package/dist/packages/core/src/env/memory/plugin/index.js +36 -0
  15. package/dist/packages/core/src/env/prompt/index.js +20 -0
  16. package/dist/packages/core/src/env/session/index.js +25 -0
  17. package/dist/packages/core/src/env/session/storage/index.js +18 -0
  18. package/dist/packages/core/src/env/skill/index.js +34 -0
  19. package/dist/packages/core/src/env/skill/tool/index.js +9 -0
  20. package/dist/packages/core/src/env/task/delegate/index.js +18 -0
  21. package/dist/packages/core/src/env/task/hooks/index.js +7 -0
  22. package/dist/packages/core/src/env/task/index.js +30 -0
  23. package/dist/packages/core/src/env/task/plugins/index.js +23 -0
  24. package/dist/packages/core/src/env/task/storage/index.js +14 -0
  25. package/dist/packages/core/src/env/task/tools/index.js +17 -0
  26. package/dist/packages/core/src/env/task/tools/operation/index.js +15 -0
  27. package/dist/packages/core/src/env/tool/built-in/index.js +25 -0
  28. package/dist/packages/core/src/env/tool/index.js +39 -0
  29. package/dist/packages/core/src/env/workflow/decorators/index.js +27 -0
  30. package/dist/packages/core/src/env/workflow/engine/index.js +28 -0
  31. package/dist/packages/core/src/env/workflow/index.js +132 -0
  32. package/dist/packages/core/src/env/workflow/nodes/index.js +19 -0
  33. package/dist/packages/core/src/env/workflow/service/index.js +13 -0
  34. package/dist/packages/core/src/env/workflow/storage/index.js +27 -0
  35. package/dist/packages/core/src/env/workflow/tools/index.js +159 -0
  36. package/dist/packages/core/src/env/workflow/types/index.js +94 -0
  37. package/dist/packages/core/src/env/workflow/utils/index.js +637 -0
  38. package/dist/packages/core/src/index.js +398 -0
  39. package/dist/shared/@ai-setting/roy-agent-core-04fm8177.js +393 -0
  40. package/dist/shared/@ai-setting/roy-agent-core-04qgbjbe.js +172 -0
  41. package/dist/shared/@ai-setting/roy-agent-core-084qqd7t.js +11 -0
  42. package/dist/shared/@ai-setting/roy-agent-core-0gekht4e.js +1130 -0
  43. package/dist/shared/@ai-setting/roy-agent-core-0hdry23r.js +419 -0
  44. package/dist/shared/@ai-setting/roy-agent-core-0sgn3de4.js +102 -0
  45. package/dist/{env/task/tools/index.js → shared/@ai-setting/roy-agent-core-12x57kf1.js} +1 -59
  46. package/dist/shared/@ai-setting/roy-agent-core-1f3xrrm6.js +393 -0
  47. package/dist/shared/@ai-setting/roy-agent-core-1k28kg7h.js +368 -0
  48. package/dist/shared/@ai-setting/roy-agent-core-1z1zv5g8.js +258 -0
  49. package/dist/shared/@ai-setting/roy-agent-core-2hqxnaf3.js +851 -0
  50. package/dist/shared/@ai-setting/roy-agent-core-3dfq8awb.js +587 -0
  51. package/dist/shared/@ai-setting/roy-agent-core-3takar0s.js +93 -0
  52. package/dist/shared/@ai-setting/roy-agent-core-3tnb2005.js +117 -0
  53. package/dist/shared/@ai-setting/roy-agent-core-4vmcvkav.js +14 -0
  54. package/dist/shared/@ai-setting/roy-agent-core-4ws8atva.js +107 -0
  55. package/dist/{env/workflow/nodes/index.js → shared/@ai-setting/roy-agent-core-5fbp24se.js} +8 -55
  56. package/dist/shared/@ai-setting/roy-agent-core-5my94ywp.js +66 -0
  57. package/dist/shared/@ai-setting/roy-agent-core-6j0zcmwk.js +2146 -0
  58. package/dist/shared/@ai-setting/roy-agent-core-6w4pmxc7.js +266 -0
  59. package/dist/shared/@ai-setting/roy-agent-core-7vrk3add.js +10 -0
  60. package/dist/shared/@ai-setting/roy-agent-core-8dvbn7tw.js +64 -0
  61. package/dist/{env/memory/built-in/index.js → shared/@ai-setting/roy-agent-core-8mbmrwzs.js} +22 -76
  62. package/dist/shared/@ai-setting/roy-agent-core-8wzz66qe.js +620 -0
  63. package/dist/shared/@ai-setting/roy-agent-core-9ykq91jc.js +762 -0
  64. package/dist/shared/@ai-setting/roy-agent-core-dde19zke.js +1305 -0
  65. package/dist/shared/@ai-setting/roy-agent-core-f7g67gce.js +913 -0
  66. package/dist/{env/workflow/types/index.js → shared/@ai-setting/roy-agent-core-fq5mtxsy.js} +16 -154
  67. package/dist/{env/task/hooks/index.js → shared/@ai-setting/roy-agent-core-fs0mn2jk.js} +3 -18
  68. package/dist/{config/index.js → shared/@ai-setting/roy-agent-core-fvd9g6k8.js} +140 -605
  69. package/dist/shared/@ai-setting/roy-agent-core-gv1hrn3x.js +378 -0
  70. package/dist/{env/task/tools/operation/index.js → shared/@ai-setting/roy-agent-core-gy0wp5h7.js} +1 -58
  71. package/dist/shared/@ai-setting/roy-agent-core-hyza1gm7.js +15 -0
  72. package/dist/shared/@ai-setting/roy-agent-core-j8zx62zr.js +154 -0
  73. package/dist/shared/@ai-setting/roy-agent-core-jb2exr0d.js +442 -0
  74. package/dist/shared/@ai-setting/roy-agent-core-jv3b7v9w.js +57 -0
  75. package/dist/shared/@ai-setting/roy-agent-core-k1rxf9ya.js +513 -0
  76. package/dist/shared/@ai-setting/roy-agent-core-kydc9nwb.js +60 -0
  77. package/dist/shared/@ai-setting/roy-agent-core-m2x48hw6.js +97 -0
  78. package/dist/shared/@ai-setting/roy-agent-core-m6y668cc.js +377 -0
  79. package/dist/shared/@ai-setting/roy-agent-core-nczzf0ms.js +15 -0
  80. package/dist/shared/@ai-setting/roy-agent-core-nfj6knp5.js +36 -0
  81. package/dist/shared/@ai-setting/roy-agent-core-ntrp979d.js +204 -0
  82. package/dist/shared/@ai-setting/roy-agent-core-pd7g8z5v.js +1387 -0
  83. package/dist/shared/@ai-setting/roy-agent-core-pzk1syce.js +14 -0
  84. package/dist/shared/@ai-setting/roy-agent-core-q50tg9m2.js +862 -0
  85. package/dist/shared/@ai-setting/roy-agent-core-qg9tcaph.js +11 -0
  86. package/dist/shared/@ai-setting/roy-agent-core-qhyerewk.js +20 -0
  87. package/dist/shared/@ai-setting/roy-agent-core-qxybm159.js +82 -0
  88. package/dist/shared/@ai-setting/roy-agent-core-rh9dpkpw.js +549 -0
  89. package/dist/shared/@ai-setting/roy-agent-core-rr9p1g43.js +205 -0
  90. package/dist/{env/workflow/decorators/index.js → shared/@ai-setting/roy-agent-core-sbzvpfn7.js} +8 -173
  91. package/dist/shared/@ai-setting/roy-agent-core-t22nqt4d.js +788 -0
  92. package/dist/shared/@ai-setting/roy-agent-core-tkr5ynkh.js +200 -0
  93. package/dist/shared/@ai-setting/roy-agent-core-v4aabsf0.js +303 -0
  94. package/dist/{env/hook/index.js → shared/@ai-setting/roy-agent-core-w75rafhy.js} +3 -74
  95. package/dist/{env/debug/formatters/index.js → shared/@ai-setting/roy-agent-core-w76hqkmg.js} +11 -66
  96. package/dist/shared/@ai-setting/roy-agent-core-yfbgwes2.js +408 -0
  97. package/dist/shared/@ai-setting/roy-agent-core-yn761yve.js +299 -0
  98. package/dist/shared/@ai-setting/roy-agent-core-yrzmn4m1.js +492 -0
  99. package/dist/{env/workflow/service/index.js → shared/@ai-setting/roy-agent-core-yt8wdh2w.js} +1 -57
  100. package/package.json +3 -2
  101. package/dist/env/agent/index.js +0 -3035
  102. package/dist/env/commands/index.js +0 -1685
  103. package/dist/env/debug/index.js +0 -2300
  104. package/dist/env/index.js +0 -12591
  105. package/dist/env/llm/index.js +0 -2736
  106. package/dist/env/log-trace/index.js +0 -1779
  107. package/dist/env/mcp/index.js +0 -2173
  108. package/dist/env/mcp/tool/index.js +0 -1149
  109. package/dist/env/memory/index.js +0 -2171
  110. package/dist/env/memory/plugin/index.js +0 -1263
  111. package/dist/env/prompt/index.js +0 -2107
  112. package/dist/env/session/index.js +0 -3594
  113. package/dist/env/session/storage/index.js +0 -2049
  114. package/dist/env/skill/index.js +0 -1635
  115. package/dist/env/skill/tool/index.js +0 -114
  116. package/dist/env/task/delegate/index.js +0 -1844
  117. package/dist/env/task/index.js +0 -3578
  118. package/dist/env/task/plugins/index.js +0 -1626
  119. package/dist/env/task/storage/index.js +0 -1464
  120. package/dist/env/tool/built-in/index.js +0 -1151
  121. package/dist/env/tool/index.js +0 -2284
  122. package/dist/env/workflow/engine/index.js +0 -4391
  123. package/dist/env/workflow/index.js +0 -6214
  124. package/dist/env/workflow/storage/index.js +0 -1236
  125. package/dist/env/workflow/tools/index.js +0 -1081
  126. package/dist/env/workflow/utils/index.js +0 -1631
  127. package/dist/index.js +0 -22778
@@ -0,0 +1,393 @@
1
+ import {
2
+ TaskHookPoints
3
+ } from "./roy-agent-core-pzk1syce.js";
4
+ import {
5
+ createLogger,
6
+ init_logger
7
+ } from "./roy-agent-core-yn761yve.js";
8
+ import {
9
+ __require
10
+ } from "./roy-agent-core-fs0mn2jk.js";
11
+
12
+ // packages/core/src/env/task/plugins/task-plugin.ts
13
+ class TaskPlugin {
14
+ config;
15
+ constructor(config = {}) {
16
+ this.config = { enabled: true, priority: 0, ...config };
17
+ }
18
+ getHookPoints() {
19
+ return this.hooks.map((h) => h.point);
20
+ }
21
+ getPriorityForHook(hookPoint) {
22
+ const hook = this.hooks.find((h) => h.point === hookPoint);
23
+ return hook?.priority ?? this.config.priority ?? 0;
24
+ }
25
+ isEnabled() {
26
+ return this.config.enabled ?? true;
27
+ }
28
+ setEnabled(enabled) {
29
+ this.config.enabled = enabled;
30
+ }
31
+ }
32
+ // packages/core/src/env/task/plugins/task-tag-plugin.ts
33
+ init_logger();
34
+
35
+ // packages/core/src/env/task/plugins/workflow-extractor-agent.ts
36
+ var WORKFLOW_EXTRACTOR_PROMPT = `你是 Workflow 提取专家,负责将自然语言描述转换为符合规范的 Workflow YAML。
37
+
38
+ ## 提取原则
39
+
40
+ 1. **优先具象节点**:优先使用特定工具节点(如 read_file, write_file, grep, bash 等)
41
+ 2. **Fallback 到通用节点**:没有对应工具时,使用 agent/llm/bash 节点
42
+ 3. **避免条件分支**:不提取循环和条件判断,保持线性流程
43
+ 4. **泛化但可执行**:步骤描述可泛化,但节点类型和工具要具体
44
+
45
+ ## 构建流程
46
+
47
+ **重要**:构建的 Workflow 必须通过 \`roy workflow validate\` 验证才能输出。
48
+
49
+ \`\`\`
50
+ 1. 理解用户需求
51
+ 2. 参考 roy workflow nodes 查看可用节点类型
52
+ 3. 参考 roy workflow get <name> 查看已有 workflow 示例
53
+ 4. 生成 Workflow YAML
54
+ 5. 使用 roy workflow validate --yaml "<生成的YAML>" 验证
55
+ 6. 验证通过后输出最终结果
56
+ \`\`\`
57
+
58
+ ## 验证检查清单
59
+
60
+ 完成 Workflow 构建后,必须使用以下命令验证:
61
+
62
+ \`\`\`bash
63
+ roy workflow validate --yaml "<your-yaml>"
64
+ \`\`\`
65
+
66
+ 验证通过后(无错误输出)才输出最终结果。验证失败时根据错误信息修正后重新验证。
67
+
68
+ ## 可用的 Workflow 节点类型
69
+
70
+ 使用以下命令查看所有节点类型的详细配置:
71
+
72
+ \`\`\`bash
73
+ roy workflow nodes # 列出所有节点类型
74
+ roy workflow nodes <type> # 查看特定节点详情(如 tool, agent, skill)
75
+ \`\`\`
76
+
77
+ **支持的节点类型:**
78
+ - **tool**:执行工具(bash, read-file, write-file, grep 等)
79
+ - **skill**:调用技能
80
+ - **agent**:AI Agent
81
+ - **workflow**:子工作流
82
+ - **condition**:条件判断
83
+ - **merge**:合并结果
84
+ - **decorator**:装饰器方法
85
+
86
+ ## 查看已有 Workflow 示例
87
+
88
+ 使用以下命令查看已有 workflow 的 YAML 结构:
89
+
90
+ \`\`\`bash
91
+ roy workflow list # 列出所有 workflow
92
+ roy workflow get <name> # 获取指定 workflow 详情(YAML 格式)
93
+ \`\`\`
94
+
95
+ ## 输出要求
96
+
97
+ 验证通过后,输出符合以下格式的 YAML Workflow:
98
+
99
+ \`\`\`yaml
100
+ name: {泛化的任务名称}
101
+ version: "1.0"
102
+ description: {一句话描述}
103
+ nodes:
104
+ - id: node-1
105
+ type: tool|skill|agent|workflow|condition|merge|decorator
106
+ name: {节点名称}
107
+ config:
108
+ # 根据类型配置必填字段:
109
+ # tool: tool, input/args
110
+ # skill: skill, input
111
+ # agent: agent_type, prompt, options
112
+ # workflow: workflow_name, input
113
+ # condition: condition
114
+ # merge: strategy, depends_on
115
+ # decorator: _methodName, _instance
116
+ depends_on: []
117
+ outputs: []
118
+ \`\`\`
119
+
120
+ ## 限制
121
+
122
+ - 至少 2 个节点才有意义
123
+ - 不要生成条件节点(if/else/switch)
124
+ - 不要生成循环节点(while/for)
125
+ - 每个节点要有清晰的名称和描述
126
+ - 必须为 tool 节点指定 tool 名称
127
+ - 必须为 agent 节点指定 agent_type 和 prompt`;
128
+ function createWorkflowExtractorAgent() {
129
+ return {
130
+ type: "sub",
131
+ name: "workflow-extractor",
132
+ systemPrompt: WORKFLOW_EXTRACTOR_PROMPT,
133
+ maxIterations: 10,
134
+ filterHistory: false
135
+ };
136
+ }
137
+ function formatExtractorInput(params) {
138
+ const lines = [];
139
+ lines.push("# 任务信息");
140
+ lines.push(`- 标题: ${params.task.title}`);
141
+ if (params.task.description) {
142
+ lines.push(`- 描述: ${params.task.description}`);
143
+ }
144
+ if (params.task.goals_and_expected_deliverables) {
145
+ lines.push(`- 目标: ${params.task.goals_and_expected_deliverables}`);
146
+ }
147
+ lines.push("");
148
+ if (params.operations.length > 0) {
149
+ lines.push("# 操作记录");
150
+ for (const op of params.operations) {
151
+ lines.push(`- [${op.actionType}] ${op.actionTitle}`);
152
+ if (op.actionDescription) {
153
+ lines.push(` ${op.actionDescription.slice(0, 200)}`);
154
+ }
155
+ }
156
+ lines.push("");
157
+ }
158
+ lines.push("# Session 消息历史");
159
+ lines.push("(以下是相关的对话历史,请从中提取 Workflow)");
160
+ for (const msg of params.messages.slice(-50)) {
161
+ const content = typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content);
162
+ const truncated = content.slice(0, 500);
163
+ lines.push(`**${msg.role}**: ${truncated}${content.length > 500 ? "..." : ""}`);
164
+ }
165
+ lines.push("");
166
+ lines.push("## 任务");
167
+ lines.push("请分析以上信息,构建一个可复用的 Workflow。");
168
+ lines.push("使用迭代式流程:生成 YAML → validate 验证 → 修正错误 → 重复直到通过验证。");
169
+ return lines.join(`
170
+ `);
171
+ }
172
+ function formatExtractorInputFromDescription(params) {
173
+ const lines = [];
174
+ lines.push("# Workflow 描述");
175
+ lines.push(params.description);
176
+ lines.push("");
177
+ lines.push("## 任务");
178
+ lines.push("请根据以上描述,构建一个可复用的 Workflow。");
179
+ lines.push("使用迭代式流程:生成 YAML → validate 验证 → 修正错误 → 重复直到通过验证。");
180
+ return lines.join(`
181
+ `);
182
+ }
183
+ async function parseExtractorOutput(output) {
184
+ const yamlMatch = output.match(/```yaml\n?([\s\S]*?)\n?```/) || output.match(/```\n?([\s\S]*?)\n?```/) || output.match(/(\|[\s\S]*?)(?:\n\n|$)/);
185
+ const yamlContent = yamlMatch?.[1] || output;
186
+ try {
187
+ const YAML = await import("yaml");
188
+ const parsed = YAML.parse(yamlContent);
189
+ if (!parsed.name || !parsed.nodes || !Array.isArray(parsed.nodes)) {
190
+ return null;
191
+ }
192
+ if (parsed.nodes.length < 2) {
193
+ return null;
194
+ }
195
+ parsed.version = parsed.version || "1.0";
196
+ return parsed;
197
+ } catch {
198
+ return null;
199
+ }
200
+ }
201
+
202
+ // packages/core/src/env/task/plugins/task-tag-plugin.ts
203
+ var logger = createLogger("task:plugin:tag");
204
+
205
+ class TaskTagPlugin extends TaskPlugin {
206
+ name = "TaskTagPlugin";
207
+ hooks = [
208
+ { point: TaskHookPoints.DELEGATE_BEFORE, priority: 20 },
209
+ { point: TaskHookPoints.OPERATION_AFTER_CREATE, priority: 10 }
210
+ ];
211
+ taskComponent = null;
212
+ agentComponent = null;
213
+ constructor(config = {}) {
214
+ super({ enabled: true, priority: 0, ...config });
215
+ }
216
+ static getRequiredAgents() {
217
+ return [createWorkflowExtractorAgent()];
218
+ }
219
+ setComponents(_llmComponent, taskComponent) {
220
+ this.taskComponent = taskComponent;
221
+ if (taskComponent?.env) {
222
+ this.agentComponent = taskComponent.env.getComponent("agent");
223
+ }
224
+ }
225
+ async execute(ctx) {
226
+ if (!this.config.enabled)
227
+ return;
228
+ switch (ctx.hookPoint) {
229
+ case TaskHookPoints.DELEGATE_BEFORE:
230
+ await this.onDelegateBefore(ctx);
231
+ break;
232
+ case TaskHookPoints.OPERATION_AFTER_CREATE:
233
+ await this.onOperationAfterCreate(ctx);
234
+ break;
235
+ }
236
+ }
237
+ async onDelegateBefore(ctx) {
238
+ const { taskId, tagService, prompt } = ctx.data;
239
+ if (!taskId || !this.taskComponent) {
240
+ return;
241
+ }
242
+ try {
243
+ const currentTask = await this.taskComponent.getTask(taskId);
244
+ if (!currentTask)
245
+ return;
246
+ const keywords = this.extractKeywords(currentTask);
247
+ if (keywords.length === 0)
248
+ return;
249
+ const tagServiceForSearch = tagService;
250
+ const similarTasks = await tagServiceForSearch?.findSimilarTasksByKeywords?.(keywords, {
251
+ limit: 5,
252
+ excludeTaskId: taskId
253
+ }) ?? [];
254
+ if (similarTasks.length === 0)
255
+ return;
256
+ const hint = this.formatSimilarTasks(similarTasks);
257
+ ctx.data.prompt = `${hint}
258
+
259
+ ---
260
+
261
+ ## 用户指令
262
+
263
+ ${prompt}`;
264
+ logger.info(`[TaskTagPlugin] Injected ${similarTasks.length} similar tasks`);
265
+ } catch (error) {
266
+ logger.warn(`[TaskTagPlugin] Similar tasks injection failed: ${error}`);
267
+ }
268
+ }
269
+ extractKeywords(task) {
270
+ const keywords = [];
271
+ if (task.tags?.length) {
272
+ keywords.push(...task.tags);
273
+ }
274
+ if (task.title) {
275
+ const words = task.title.split(/[\s\-_,,。、#]+/).filter((w) => w.length > 2 && !/^\d+$/.test(w)).slice(0, 5);
276
+ keywords.push(...words);
277
+ }
278
+ return keywords;
279
+ }
280
+ formatSimilarTasks(tasks) {
281
+ const lines = [
282
+ "## \uD83D\uDD0D 类似任务参考",
283
+ "",
284
+ "_提示:可通过 `task_get <id>` 获取详情,`task_operation_list <id>` 获取操作记录_",
285
+ ""
286
+ ];
287
+ for (const task of tasks) {
288
+ lines.push(`### Task #${task.id}`);
289
+ lines.push(`**Title**: ${task.title}`);
290
+ if (task.description) {
291
+ const desc = task.description.slice(0, 100);
292
+ lines.push(`**Description**: ${desc}${task.description.length > 100 ? "..." : ""}`);
293
+ }
294
+ if (task.goals_and_expected_deliverables) {
295
+ const goal = task.goals_and_expected_deliverables.slice(0, 100);
296
+ lines.push(`**Goal**: ${goal}${task.goals_and_expected_deliverables.length > 100 ? "..." : ""}`);
297
+ }
298
+ lines.push("");
299
+ }
300
+ return lines.join(`
301
+ `);
302
+ }
303
+ async onOperationAfterCreate(ctx) {
304
+ const data = ctx.data;
305
+ const operation = data?.operation ?? data?.data?.operation;
306
+ if (!operation || operation?.actionType !== "completed")
307
+ return;
308
+ await this.extractWorkflow(operation.taskId, operation.sessionId);
309
+ }
310
+ async extractWorkflow(taskId, sessionId) {
311
+ try {
312
+ const task = await this.taskComponent?.getTask(taskId);
313
+ if (!task)
314
+ return;
315
+ const operations = await this.taskComponent?.listOperations({ taskId }) ?? [];
316
+ const allSessionIds = [...new Set([sessionId, ...operations.map((op) => op.sessionId).filter(Boolean)])];
317
+ const sessionComponent = this.taskComponent?.env?.getComponent("session");
318
+ const allMessages = [];
319
+ for (const sid of allSessionIds) {
320
+ try {
321
+ const ctx = await sessionComponent?.getContext(sid, { fullHistory: false, minUserMessages: 200 });
322
+ if (ctx?.messages)
323
+ allMessages.push(...ctx.messages);
324
+ } catch {}
325
+ }
326
+ if (!this.agentComponent)
327
+ return;
328
+ const input = formatExtractorInput({ task, operations, messages: allMessages });
329
+ const result = await this.agentComponent.run("workflow-extractor", input);
330
+ const workflowDef = await parseExtractorOutput(result.finalText || "");
331
+ if (!workflowDef)
332
+ return;
333
+ const workflowRepo = await this.getWorkflowRepository();
334
+ if (!workflowRepo)
335
+ return;
336
+ let version = workflowDef.version || "1.0";
337
+ const existingWf = workflowRepo.getByName(workflowDef.name);
338
+ if (existingWf) {
339
+ const parts = existingWf.version?.split(".") ?? ["1", "0"];
340
+ version = `${parts[0]}.${parseInt(parts[1] || "0") + 1}`;
341
+ }
342
+ const workflow = workflowRepo.create({
343
+ name: workflowDef.name,
344
+ version,
345
+ description: workflowDef.description,
346
+ definition: workflowDef,
347
+ config: workflowDef.config || {},
348
+ metadata: { author: "workflow-extractor", created_at: new Date().toISOString() },
349
+ tags: [`task:${taskId}`]
350
+ });
351
+ await this.taskComponent?.createOperation({
352
+ taskId,
353
+ sessionId,
354
+ actionType: "workflow_extracted",
355
+ actionTitle: `Workflow extracted: ${workflow.name}`,
356
+ actionDescription: workflow.id
357
+ });
358
+ logger.info(`Workflow extracted: ${workflow.id}`);
359
+ } catch (error) {
360
+ logger.warn(`Workflow extraction failed: ${error}`);
361
+ }
362
+ }
363
+ async getWorkflowRepository() {
364
+ const workflowComponent = this.taskComponent?.env?.getComponent("workflow");
365
+ if (workflowComponent?.workflowService?.workflowRepository) {
366
+ return workflowComponent.workflowService.workflowRepository;
367
+ }
368
+ if (!this._workflowRepo) {
369
+ try {
370
+ const sqlite = await import("./roy-agent-core-qhyerewk.js");
371
+ this.ensureDataDir();
372
+ const db = sqlite.getDatabase();
373
+ sqlite.initializeTables();
374
+ const { WorkflowRepository } = await import("./roy-agent-core-4vmcvkav.js");
375
+ this._workflowRepo = new WorkflowRepository(db);
376
+ return this._workflowRepo;
377
+ } catch {
378
+ return null;
379
+ }
380
+ }
381
+ return this._workflowRepo;
382
+ }
383
+ ensureDataDir() {
384
+ const { join } = __require("path");
385
+ const { mkdirSync, existsSync } = __require("fs");
386
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
387
+ const dataDir = join(home, ".local", "share", "roy-agent");
388
+ if (!existsSync(dataDir))
389
+ mkdirSync(dataDir, { recursive: true });
390
+ }
391
+ _workflowRepo = null;
392
+ }
393
+ export { TaskPlugin, WORKFLOW_EXTRACTOR_PROMPT, createWorkflowExtractorAgent, formatExtractorInput, formatExtractorInputFromDescription, parseExtractorOutput, TaskTagPlugin };
@@ -0,0 +1,172 @@
1
+ import {
2
+ createLogger,
3
+ getMaxOutput,
4
+ init_logger,
5
+ simplifyFilePath
6
+ } from "./roy-agent-core-yn761yve.js";
7
+ import {
8
+ getTracerProvider,
9
+ init_tracer_provider
10
+ } from "./roy-agent-core-1k28kg7h.js";
11
+ import {
12
+ __esm
13
+ } from "./roy-agent-core-fs0mn2jk.js";
14
+
15
+ // packages/core/src/env/log-trace/decorator.ts
16
+ function Traced(options) {
17
+ return function(target, propertyKey, descriptor) {
18
+ const originalFn = descriptor.value;
19
+ const spanName = options?.name || propertyKey;
20
+ descriptor.value = wrapFunction(originalFn, spanName, {
21
+ recordParams: options?.recordParams ?? true,
22
+ recordResult: options?.recordResult ?? false,
23
+ recordError: options?.recordError ?? true,
24
+ log: options?.log ?? false,
25
+ maxLogSize: options?.maxLogSize,
26
+ paramFilter: options?.paramFilter
27
+ });
28
+ return descriptor;
29
+ };
30
+ }
31
+ function TracedAs(name, options) {
32
+ return Traced({ name, ...options });
33
+ }
34
+ function TracedLightweight(options) {
35
+ return Traced({ recordParams: false, recordResult: false, log: options?.log ?? false, maxLogSize: options?.maxLogSize });
36
+ }
37
+ function wrapFunction(fn, name, options) {
38
+ const shouldLog = options?.log ?? false;
39
+ const getMaxLogSize = () => {
40
+ if (options?.maxLogSize !== undefined) {
41
+ return options.maxLogSize;
42
+ }
43
+ const configMaxOutput = getMaxOutput();
44
+ return configMaxOutput !== undefined ? configMaxOutput : 500;
45
+ };
46
+ const truncate = (obj) => {
47
+ if (obj === undefined)
48
+ return;
49
+ if (obj === null)
50
+ return null;
51
+ const maxLogSize = getMaxLogSize();
52
+ let str;
53
+ try {
54
+ str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
55
+ } catch (e) {
56
+ str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
57
+ }
58
+ if (maxLogSize > 0 && str.length > maxLogSize) {
59
+ return str.slice(0, maxLogSize) + " [TRUNCATED]";
60
+ }
61
+ try {
62
+ return JSON.parse(str);
63
+ } catch {
64
+ return str;
65
+ }
66
+ };
67
+ const truncateString = (obj) => {
68
+ if (obj === undefined)
69
+ return "undefined";
70
+ if (obj === null)
71
+ return "null";
72
+ const maxLogSize = getMaxLogSize();
73
+ let str;
74
+ try {
75
+ str = typeof obj === "string" ? obj : JSON.stringify(obj, null, 0).replace(/\n/g, "");
76
+ } catch (e) {
77
+ str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;
78
+ }
79
+ return maxLogSize > 0 && str.length > maxLogSize ? str.slice(0, maxLogSize) + " [TRUNCATED]" : str;
80
+ };
81
+ const TRACE_LOG_PREFIX = "[TRACE]";
82
+ const getCallerLocation = () => {
83
+ const originalLimit = Error.stackTraceLimit;
84
+ Error.stackTraceLimit = 15;
85
+ const err = new Error;
86
+ Error.captureStackTrace(err, getCallerLocation);
87
+ const stack = err.stack?.split(`
88
+ `) || [];
89
+ Error.stackTraceLimit = originalLimit;
90
+ for (let i = 1;i < stack.length; i++) {
91
+ const line = stack[i];
92
+ if (line.includes("decorator.ts") || line.includes("decorator.js") || line.includes("logFn") || line.includes("getCallerLocation"))
93
+ continue;
94
+ const match = line.match(/at\s+.+\s+\((.+):(\d+):\d+\)/) || line.match(/at\s+(.+):(\d+):\d+/);
95
+ if (match) {
96
+ const filePath = match[1];
97
+ if (!filePath || filePath === "native")
98
+ continue;
99
+ const relativePath = simplifyFilePath(filePath);
100
+ return `${relativePath}:${match[2]}`;
101
+ }
102
+ }
103
+ return "";
104
+ };
105
+ const logFn = (event, argsOrData, callerLocation) => {
106
+ if (!shouldLog)
107
+ return;
108
+ const logger = createLogger("traced:" + name);
109
+ const tag = event === "enter" ? ">>>" : event === "quit" ? "<<<" : "!!!";
110
+ const prefix = `${TRACE_LOG_PREFIX} ${tag} ${name}`;
111
+ const originalFnLocation = callerLocation || getCallerLocation();
112
+ const logMessage = (msg, data) => {
113
+ if (data !== undefined) {
114
+ logger.info(`${prefix} ${msg}: ${truncateString(data)}`, { callerLocation: originalFnLocation });
115
+ } else {
116
+ logger.info(`${prefix} ${msg}`, { callerLocation: originalFnLocation });
117
+ }
118
+ };
119
+ if (event === "enter") {
120
+ logMessage("enter", argsOrData);
121
+ } else if (event === "quit") {
122
+ logMessage("quit", options?.recordResult ? argsOrData : undefined);
123
+ } else {
124
+ logMessage("error", argsOrData);
125
+ }
126
+ };
127
+ return function(...args) {
128
+ const tracer = getTracerProvider().getTracer("roy-tracer");
129
+ const attributes = {};
130
+ if (options?.recordParams !== false) {
131
+ if (options?.paramFilter) {
132
+ attributes["params"] = truncate(options.paramFilter(args));
133
+ } else {
134
+ attributes["params"] = truncate(args);
135
+ }
136
+ }
137
+ const callerLocation = getCallerLocation();
138
+ logFn("enter", args, callerLocation);
139
+ const span = tracer.startSpan(name, { attributes });
140
+ try {
141
+ const result = fn.call(this, ...args);
142
+ if (result && typeof result === "object" && typeof result.then === "function") {
143
+ return result.then((resolved) => {
144
+ span.setAttribute("result", JSON.stringify(truncate(resolved)));
145
+ span.end(resolved);
146
+ logFn("quit", options?.recordResult ? resolved : undefined, callerLocation);
147
+ return resolved;
148
+ }, (rejected) => {
149
+ span.setAttribute("error", String(rejected));
150
+ span.end(undefined, rejected instanceof Error ? rejected : new Error(String(rejected)));
151
+ logFn("error", rejected.message, callerLocation);
152
+ throw rejected;
153
+ });
154
+ }
155
+ span.setAttribute("result", JSON.stringify(truncate(result)));
156
+ span.end(result);
157
+ logFn("quit", options?.recordResult ? result : undefined, callerLocation);
158
+ return result;
159
+ } catch (error) {
160
+ span.setAttribute("error", String(error));
161
+ span.end(undefined, error instanceof Error ? error : new Error(String(error)));
162
+ logFn("error", error.message, callerLocation);
163
+ throw error;
164
+ }
165
+ };
166
+ }
167
+ var init_decorator = __esm(() => {
168
+ init_tracer_provider();
169
+ init_logger();
170
+ });
171
+
172
+ export { Traced, TracedAs, TracedLightweight, wrapFunction, init_decorator };
@@ -0,0 +1,11 @@
1
+ // packages/core/src/env/hook/types.ts
2
+ function createHook(meta, fn) {
3
+ return {
4
+ ...meta,
5
+ execute: fn
6
+ };
7
+ }
8
+ function createPriorityHook(name, fn, priority) {
9
+ return createHook({ name, priority }, fn);
10
+ }
11
+ export { createHook, createPriorityHook };