@fortressllm/sybil 0.0.3

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 (288) hide show
  1. package/.env copy +91 -0
  2. package/.env.example +139 -0
  3. package/BROWSER_CONTROL.md +354 -0
  4. package/CLI_CHAT_FEATURE.md +224 -0
  5. package/CLI_GUIDE.md +359 -0
  6. package/DYNAMIC_SKILLS.md +345 -0
  7. package/DockerFile.sandbox +14 -0
  8. package/PROGRESS.md +249 -0
  9. package/README.md +281 -0
  10. package/RENAME_LOG.md +62 -0
  11. package/SIMPLIFIED_TELEGRAM_UX.md +273 -0
  12. package/SYBIL_SUMMARY.md +360 -0
  13. package/TASK11_NETWORK.md +202 -0
  14. package/TASK14_CLI.md +432 -0
  15. package/TASK8_SAFETY.md +317 -0
  16. package/TASK9_COMPLETION.md +186 -0
  17. package/TASK9_SUMMARY.md +201 -0
  18. package/TELEGRAM_OTP_AUTH.md +359 -0
  19. package/VECTOR_MEMORY.md +163 -0
  20. package/assets/logo.png +0 -0
  21. package/cypfq_code_search.md +287 -0
  22. package/cypfq_driver_search.md +297 -0
  23. package/cypfq_github_search.md +297 -0
  24. package/cypfq_repo_search.md +370 -0
  25. package/dist/agents/autonomous-agent.d.ts +61 -0
  26. package/dist/agents/autonomous-agent.d.ts.map +1 -0
  27. package/dist/agents/autonomous-agent.js +536 -0
  28. package/dist/agents/autonomous-agent.js.map +1 -0
  29. package/dist/agents/network.d.ts +1006 -0
  30. package/dist/agents/network.d.ts.map +1 -0
  31. package/dist/agents/network.js +1266 -0
  32. package/dist/agents/network.js.map +1 -0
  33. package/dist/cli/commands/backup.d.ts +3 -0
  34. package/dist/cli/commands/backup.d.ts.map +1 -0
  35. package/dist/cli/commands/backup.js +63 -0
  36. package/dist/cli/commands/backup.js.map +1 -0
  37. package/dist/cli/commands/config.d.ts +3 -0
  38. package/dist/cli/commands/config.d.ts.map +1 -0
  39. package/dist/cli/commands/config.js +163 -0
  40. package/dist/cli/commands/config.js.map +1 -0
  41. package/dist/cli/commands/doctor.d.ts +3 -0
  42. package/dist/cli/commands/doctor.d.ts.map +1 -0
  43. package/dist/cli/commands/doctor.js +107 -0
  44. package/dist/cli/commands/doctor.js.map +1 -0
  45. package/dist/cli/commands/init.d.ts +3 -0
  46. package/dist/cli/commands/init.d.ts.map +1 -0
  47. package/dist/cli/commands/init.js +138 -0
  48. package/dist/cli/commands/init.js.map +1 -0
  49. package/dist/cli/commands/logs.d.ts +3 -0
  50. package/dist/cli/commands/logs.d.ts.map +1 -0
  51. package/dist/cli/commands/logs.js +81 -0
  52. package/dist/cli/commands/logs.js.map +1 -0
  53. package/dist/cli/commands/otp.d.ts +3 -0
  54. package/dist/cli/commands/otp.d.ts.map +1 -0
  55. package/dist/cli/commands/otp.js +142 -0
  56. package/dist/cli/commands/otp.js.map +1 -0
  57. package/dist/cli/commands/restore.d.ts +3 -0
  58. package/dist/cli/commands/restore.d.ts.map +1 -0
  59. package/dist/cli/commands/restore.js +99 -0
  60. package/dist/cli/commands/restore.js.map +1 -0
  61. package/dist/cli/commands/start.d.ts +3 -0
  62. package/dist/cli/commands/start.d.ts.map +1 -0
  63. package/dist/cli/commands/start.js +65 -0
  64. package/dist/cli/commands/start.js.map +1 -0
  65. package/dist/cli/commands/status.d.ts +3 -0
  66. package/dist/cli/commands/status.d.ts.map +1 -0
  67. package/dist/cli/commands/status.js +68 -0
  68. package/dist/cli/commands/status.js.map +1 -0
  69. package/dist/cli/commands/stop.d.ts +3 -0
  70. package/dist/cli/commands/stop.d.ts.map +1 -0
  71. package/dist/cli/commands/stop.js +62 -0
  72. package/dist/cli/commands/stop.js.map +1 -0
  73. package/dist/cli/commands/update.d.ts +3 -0
  74. package/dist/cli/commands/update.d.ts.map +1 -0
  75. package/dist/cli/commands/update.js +49 -0
  76. package/dist/cli/commands/update.js.map +1 -0
  77. package/dist/cli/commands/whatsapp.d.ts +3 -0
  78. package/dist/cli/commands/whatsapp.d.ts.map +1 -0
  79. package/dist/cli/commands/whatsapp.js +281 -0
  80. package/dist/cli/commands/whatsapp.js.map +1 -0
  81. package/dist/cli/index.d.ts +7 -0
  82. package/dist/cli/index.d.ts.map +1 -0
  83. package/dist/cli/index.js +58 -0
  84. package/dist/cli/index.js.map +1 -0
  85. package/dist/cli.d.ts +9 -0
  86. package/dist/cli.d.ts.map +1 -0
  87. package/dist/cli.js +750 -0
  88. package/dist/cli.js.map +1 -0
  89. package/dist/index.d.ts +2 -0
  90. package/dist/index.d.ts.map +1 -0
  91. package/dist/index.js +109 -0
  92. package/dist/index.js.map +1 -0
  93. package/dist/mastra/index.d.ts +4 -0
  94. package/dist/mastra/index.d.ts.map +1 -0
  95. package/dist/mastra/index.js +37 -0
  96. package/dist/mastra/index.js.map +1 -0
  97. package/dist/mastra/memory.d.ts +9 -0
  98. package/dist/mastra/memory.d.ts.map +1 -0
  99. package/dist/mastra/memory.js +92 -0
  100. package/dist/mastra/memory.js.map +1 -0
  101. package/dist/processors/index.d.ts +74 -0
  102. package/dist/processors/index.d.ts.map +1 -0
  103. package/dist/processors/index.js +153 -0
  104. package/dist/processors/index.js.map +1 -0
  105. package/dist/processors/semantic-recall.d.ts +63 -0
  106. package/dist/processors/semantic-recall.d.ts.map +1 -0
  107. package/dist/processors/semantic-recall.js +216 -0
  108. package/dist/processors/semantic-recall.js.map +1 -0
  109. package/dist/processors/tool-search.d.ts +26 -0
  110. package/dist/processors/tool-search.d.ts.map +1 -0
  111. package/dist/processors/tool-search.js +41 -0
  112. package/dist/processors/tool-search.js.map +1 -0
  113. package/dist/skills/dynamic/skill-generator.d.ts +169 -0
  114. package/dist/skills/dynamic/skill-generator.d.ts.map +1 -0
  115. package/dist/skills/dynamic/skill-generator.js +488 -0
  116. package/dist/skills/dynamic/skill-generator.js.map +1 -0
  117. package/dist/tools/agent-delegation-tools.d.ts +142 -0
  118. package/dist/tools/agent-delegation-tools.d.ts.map +1 -0
  119. package/dist/tools/agent-delegation-tools.js +263 -0
  120. package/dist/tools/agent-delegation-tools.js.map +1 -0
  121. package/dist/tools/browser-tools.d.ts +374 -0
  122. package/dist/tools/browser-tools.d.ts.map +1 -0
  123. package/dist/tools/browser-tools.js +752 -0
  124. package/dist/tools/browser-tools.js.map +1 -0
  125. package/dist/tools/dynamic/registry.d.ts +61 -0
  126. package/dist/tools/dynamic/registry.d.ts.map +1 -0
  127. package/dist/tools/dynamic/registry.js +121 -0
  128. package/dist/tools/dynamic/registry.js.map +1 -0
  129. package/dist/tools/dynamic/tool-generator.d.ts +99 -0
  130. package/dist/tools/dynamic/tool-generator.d.ts.map +1 -0
  131. package/dist/tools/dynamic/tool-generator.js +367 -0
  132. package/dist/tools/dynamic/tool-generator.js.map +1 -0
  133. package/dist/tools/extended-tools.d.ts +176 -0
  134. package/dist/tools/extended-tools.d.ts.map +1 -0
  135. package/dist/tools/extended-tools.js +464 -0
  136. package/dist/tools/extended-tools.js.map +1 -0
  137. package/dist/tools/library/calendar/index.d.ts +134 -0
  138. package/dist/tools/library/calendar/index.d.ts.map +1 -0
  139. package/dist/tools/library/calendar/index.js +160 -0
  140. package/dist/tools/library/calendar/index.js.map +1 -0
  141. package/dist/tools/podman-workspace-mcp-cli.d.ts +3 -0
  142. package/dist/tools/podman-workspace-mcp-cli.d.ts.map +1 -0
  143. package/dist/tools/podman-workspace-mcp-cli.js +12 -0
  144. package/dist/tools/podman-workspace-mcp-cli.js.map +1 -0
  145. package/dist/tools/podman-workspace-mcp.d.ts +247 -0
  146. package/dist/tools/podman-workspace-mcp.d.ts.map +1 -0
  147. package/dist/tools/podman-workspace-mcp.js +1093 -0
  148. package/dist/tools/podman-workspace-mcp.js.map +1 -0
  149. package/dist/tools/podman-workspace.d.ts +148 -0
  150. package/dist/tools/podman-workspace.d.ts.map +1 -0
  151. package/dist/tools/podman-workspace.js +682 -0
  152. package/dist/tools/podman-workspace.js.map +1 -0
  153. package/dist/tools/telegram-file-tools.d.ts +78 -0
  154. package/dist/tools/telegram-file-tools.d.ts.map +1 -0
  155. package/dist/tools/telegram-file-tools.js +294 -0
  156. package/dist/tools/telegram-file-tools.js.map +1 -0
  157. package/dist/tools/tool-registry.d.ts +467 -0
  158. package/dist/tools/tool-registry.d.ts.map +1 -0
  159. package/dist/tools/tool-registry.js +156 -0
  160. package/dist/tools/tool-registry.js.map +1 -0
  161. package/dist/tools/web-tools.d.ts +77 -0
  162. package/dist/tools/web-tools.d.ts.map +1 -0
  163. package/dist/tools/web-tools.js +416 -0
  164. package/dist/tools/web-tools.js.map +1 -0
  165. package/dist/tools/whatsapp-autoreply-tools.d.ts +118 -0
  166. package/dist/tools/whatsapp-autoreply-tools.d.ts.map +1 -0
  167. package/dist/tools/whatsapp-autoreply-tools.js +503 -0
  168. package/dist/tools/whatsapp-autoreply-tools.js.map +1 -0
  169. package/dist/tools/whatsapp-tools.d.ts +175 -0
  170. package/dist/tools/whatsapp-tools.d.ts.map +1 -0
  171. package/dist/tools/whatsapp-tools.js +566 -0
  172. package/dist/tools/whatsapp-tools.js.map +1 -0
  173. package/dist/utils/logger.d.ts +65 -0
  174. package/dist/utils/logger.d.ts.map +1 -0
  175. package/dist/utils/logger.js +307 -0
  176. package/dist/utils/logger.js.map +1 -0
  177. package/dist/utils/model-config.d.ts +73 -0
  178. package/dist/utils/model-config.d.ts.map +1 -0
  179. package/dist/utils/model-config.js +366 -0
  180. package/dist/utils/model-config.js.map +1 -0
  181. package/dist/utils/semantic-memory.d.ts +82 -0
  182. package/dist/utils/semantic-memory.d.ts.map +1 -0
  183. package/dist/utils/semantic-memory.js +189 -0
  184. package/dist/utils/semantic-memory.js.map +1 -0
  185. package/dist/utils/system.d.ts +2 -0
  186. package/dist/utils/system.d.ts.map +1 -0
  187. package/dist/utils/system.js +24 -0
  188. package/dist/utils/system.js.map +1 -0
  189. package/dist/utils/telegram-auth.d.ts +54 -0
  190. package/dist/utils/telegram-auth.d.ts.map +1 -0
  191. package/dist/utils/telegram-auth.js +146 -0
  192. package/dist/utils/telegram-auth.js.map +1 -0
  193. package/dist/utils/telegram.d.ts +7 -0
  194. package/dist/utils/telegram.d.ts.map +1 -0
  195. package/dist/utils/telegram.js +1494 -0
  196. package/dist/utils/telegram.js.map +1 -0
  197. package/dist/utils/whatsapp-client.d.ts +166 -0
  198. package/dist/utils/whatsapp-client.d.ts.map +1 -0
  199. package/dist/utils/whatsapp-client.js +722 -0
  200. package/dist/utils/whatsapp-client.js.map +1 -0
  201. package/dist/workflows/planner-workflow.d.ts +39 -0
  202. package/dist/workflows/planner-workflow.d.ts.map +1 -0
  203. package/dist/workflows/planner-workflow.js +165 -0
  204. package/dist/workflows/planner-workflow.js.map +1 -0
  205. package/dist/workflows/skill-builder-workflow.d.ts +16 -0
  206. package/dist/workflows/skill-builder-workflow.d.ts.map +1 -0
  207. package/dist/workflows/skill-builder-workflow.js +157 -0
  208. package/dist/workflows/skill-builder-workflow.js.map +1 -0
  209. package/dist/workspace/index.d.ts +23 -0
  210. package/dist/workspace/index.d.ts.map +1 -0
  211. package/dist/workspace/index.js +64 -0
  212. package/dist/workspace/index.js.map +1 -0
  213. package/docs/README.md +140 -0
  214. package/docs/api/agents.md +481 -0
  215. package/docs/api/browser-tools.md +469 -0
  216. package/docs/api/memory.md +629 -0
  217. package/docs/architecture/agent-networks.md +586 -0
  218. package/docs/architecture/memory.md +579 -0
  219. package/docs/architecture/overview.md +436 -0
  220. package/docs/architecture/tools.md +637 -0
  221. package/docs/cli-tui.md +367 -0
  222. package/docs/guides/environment-variables.md +502 -0
  223. package/docs/guides/troubleshooting.md +882 -0
  224. package/docs/tutorials/agent-networks.md +432 -0
  225. package/docs/tutorials/dynamic-tools.md +469 -0
  226. package/docs/tutorials/getting-started.md +263 -0
  227. package/docs/tutorials/skills.md +561 -0
  228. package/docs/tutorials/web-browsing.md +329 -0
  229. package/mastra.db-shm +0 -0
  230. package/mastra.db-wal +0 -0
  231. package/package.json +71 -0
  232. package/plan.md +601 -0
  233. package/skills/code-review/SKILL.md +48 -0
  234. package/skills/task-planning/SKILL.md +55 -0
  235. package/skills/web-research/SKILL.md +79 -0
  236. package/skills/whatsapp-management/SKILL.md +78 -0
  237. package/src/agents/autonomous-agent.ts +626 -0
  238. package/src/agents/network.ts +1307 -0
  239. package/src/cli/commands/backup.ts +78 -0
  240. package/src/cli/commands/config.ts +176 -0
  241. package/src/cli/commands/doctor.ts +111 -0
  242. package/src/cli/commands/init.ts +150 -0
  243. package/src/cli/commands/logs.ts +94 -0
  244. package/src/cli/commands/otp.ts +162 -0
  245. package/src/cli/commands/restore.ts +118 -0
  246. package/src/cli/commands/start.ts +76 -0
  247. package/src/cli/commands/status.ts +81 -0
  248. package/src/cli/commands/stop.ts +68 -0
  249. package/src/cli/commands/update.ts +61 -0
  250. package/src/cli/commands/whatsapp.ts +322 -0
  251. package/src/cli/index.ts +69 -0
  252. package/src/cli.ts +830 -0
  253. package/src/index.ts +124 -0
  254. package/src/mastra/index.ts +49 -0
  255. package/src/mastra/memory.ts +99 -0
  256. package/src/mastra/public/workspace/plan.md +115 -0
  257. package/src/mastra/public/workspace/research/react-tailwind/skill.md +47 -0
  258. package/src/processors/index.ts +170 -0
  259. package/src/processors/semantic-recall.ts +277 -0
  260. package/src/processors/tool-search.ts +46 -0
  261. package/src/skills/dynamic/skill-generator.ts +568 -0
  262. package/src/tools/agent-delegation-tools.ts +301 -0
  263. package/src/tools/browser-tools.ts +792 -0
  264. package/src/tools/dynamic/registry.ts +144 -0
  265. package/src/tools/dynamic/tool-generator.ts +406 -0
  266. package/src/tools/extended-tools.ts +498 -0
  267. package/src/tools/library/calendar/index.ts +172 -0
  268. package/src/tools/podman-workspace-mcp-cli.ts +14 -0
  269. package/src/tools/podman-workspace-mcp.ts +1290 -0
  270. package/src/tools/podman-workspace.ts +858 -0
  271. package/src/tools/telegram-file-tools.ts +320 -0
  272. package/src/tools/tool-registry.ts +233 -0
  273. package/src/tools/web-tools.ts +461 -0
  274. package/src/tools/whatsapp-autoreply-tools.ts +616 -0
  275. package/src/tools/whatsapp-tools.ts +602 -0
  276. package/src/utils/logger.ts +368 -0
  277. package/src/utils/model-config.ts +437 -0
  278. package/src/utils/semantic-memory.ts +230 -0
  279. package/src/utils/system.ts +25 -0
  280. package/src/utils/telegram-auth.ts +201 -0
  281. package/src/utils/telegram.ts +1847 -0
  282. package/src/utils/whatsapp-client.ts +808 -0
  283. package/src/workflows/planner-workflow.ts +178 -0
  284. package/src/workflows/skill-builder-workflow.ts +175 -0
  285. package/src/workspace/index.ts +69 -0
  286. package/tsconfig.json +22 -0
  287. package/view-logs.sh +116 -0
  288. package/whatsapp-session.sh +197 -0
@@ -0,0 +1,626 @@
1
+ import { Agent } from "@mastra/core/agent";
2
+ import { createTool } from "@mastra/core/tools";
3
+ import { z } from "zod";
4
+ import { memory } from "../mastra/memory.js";
5
+ import { getAgentProcessors } from "../processors/index.js";
6
+ import { workspace } from "../workspace/index.js";
7
+ import * as browserTools from "../tools/browser-tools.js";
8
+ import { createDirectoryTool,writeFileTool,deleteFileTool,executeBashTool,executeCommandTool,executeJavaScriptTool,installPackageTool,listFilesTool,uninstallPackageTool,getSystemInfoTool,executePythonTool, } from "../tools/podman-workspace-mcp.js";
9
+ const sandboxTools = {
10
+ createDirectory: createDirectoryTool,
11
+ writeFile: writeFileTool,
12
+ deleteFile: deleteFileTool,
13
+ executeBash: executeBashTool,
14
+ executeCommand: executeCommandTool,
15
+ executeJavaScript: executeJavaScriptTool,
16
+ installPackage: installPackageTool,
17
+ listFiles: listFilesTool,
18
+ uninstallPackage: uninstallPackageTool,
19
+ getSystemInfo: getSystemInfoTool,
20
+ executePython: executePythonTool,
21
+ }
22
+ // Type definitions for workflow tools
23
+ interface WorkflowResult {
24
+ success: boolean;
25
+ result: any;
26
+ workflowId: string;
27
+ steps: string[];
28
+ duration: string;
29
+ }
30
+
31
+ interface PlannerWorkflowInput {
32
+ goal: string;
33
+ userContext?: string;
34
+ }
35
+
36
+ interface SkillBuilderWorkflowInput {
37
+ recentTasks: string[];
38
+ userGoals: string[];
39
+ currentSkills: string[];
40
+ }
41
+ import {
42
+ fetchWebContentTool,
43
+ searchWebTool,
44
+ extractStructuredDataTool,
45
+ deepResearchTool
46
+ } from "../tools/web-tools.js";
47
+ import {
48
+ getWhatsAppStatusTool,
49
+ initializeWhatsAppTool,
50
+ sendWhatsAppMessageTool,
51
+ getWhatsAppChatsTool,
52
+ getWhatsAppMessagesTool,
53
+ getWhatsAppContactTool,
54
+ getMyWhatsAppInfoTool,
55
+ broadcastWhatsAppMessageTool,
56
+ } from "../tools/whatsapp-tools.js";
57
+ import {
58
+ configureAutoReplyTool,
59
+ approvePendingReplyTool,
60
+ } from "../tools/whatsapp-autoreply-tools.js";
61
+ import { createModel, getModelConfig, getProviderDisplayName } from "../utils/model-config.js";
62
+ import { telegramTools } from "../tools/telegram-file-tools.js";
63
+ import { agentDelegationTools } from "../tools/agent-delegation-tools.js";
64
+ // NOTE: mastra is imported lazily (via dynamic import) inside workflow tool
65
+ // execute functions to avoid circular dependency: mastra/index.ts ↔ this file
66
+ import { allTools, toolCategories } from "../tools/tool-registry.js";
67
+ import {
68
+ generateToolTool,
69
+ listGeneratedToolsTool,
70
+ deleteGeneratedToolTool,
71
+ } from "../tools/dynamic/tool-generator.js";
72
+ import {
73
+ generateSkillTool,
74
+ learnSkillFromFeedbackTool,
75
+ listSkillsTool,
76
+ activateSkillTool,
77
+ analyzeForSkillOpportunityTool,
78
+ } from "../skills/dynamic/skill-generator.js";
79
+ import { getSystemContext } from "../utils/system.js";
80
+
81
+ const systemContext = getSystemContext();
82
+
83
+ // Tool: Learn from interaction
84
+ export const learnFromInteractionTool = createTool({
85
+ id: "learn-from-interaction",
86
+ description: `
87
+ Analyze the current interaction and extract learnings about the user.
88
+ This tool updates the working memory with new insights about:
89
+ - User preferences
90
+ - Communication patterns
91
+ - Goals and objectives
92
+ - Knowledge gaps that need addressing
93
+ `,
94
+ inputSchema: z.object({
95
+ userMessage: z.string().describe("The user's message"),
96
+ context: z.string().describe("Current conversation context"),
97
+ insights: z.array(z.string()).describe("New insights learned from this interaction"),
98
+ }),
99
+ outputSchema: z.object({
100
+ success: z.boolean(),
101
+ summary: z.string(),
102
+ memoryUpdates: z.array(z.string()).describe("What was updated in memory"),
103
+ }),
104
+ execute: async (inputData) => {
105
+ const { userMessage, context, insights } = inputData;
106
+
107
+ // Process insights dynamically
108
+ const processedInsights = insights.map(insight => {
109
+ // Extract actual learning patterns
110
+ const hasQuestionPattern = userMessage.includes('?') || userMessage.toLowerCase().includes('what') || userMessage.toLowerCase().includes('how');
111
+ const hasTaskPattern = userMessage.toLowerCase().includes('do') || userMessage.toLowerCase().includes('make') || userMessage.toLowerCase().includes('create');
112
+
113
+ if (hasQuestionPattern) {
114
+ return `User is seeking information about: ${userMessage.substring(0, 50)}...`;
115
+ } else if (hasTaskPattern) {
116
+ return `User wants to accomplish: ${userMessage.substring(0, 50)}...`;
117
+ }
118
+ return insight;
119
+ });
120
+
121
+ const memoryUpdates = [
122
+ `Interaction processed: ${new Date().toISOString()}`,
123
+ `User message pattern: ${userMessage.length > 100 ? 'detailed' : 'brief'}`,
124
+ ...processedInsights
125
+ ];
126
+
127
+ return {
128
+ success: true,
129
+ summary: `Successfully learned ${processedInsights.length} insights from this interaction`,
130
+ memoryUpdates,
131
+ };
132
+ },
133
+ });
134
+
135
+ // Tool: Plan autonomous task
136
+ export const planAutonomousTaskTool = createTool({
137
+ id: "plan-autonomous-task",
138
+ description: `
139
+ Create a plan for an autonomous task based on user goals.
140
+ This tool breaks down complex objectives into actionable steps.
141
+ `,
142
+ inputSchema: z.object({
143
+ goal: z.string().describe("The goal to achieve"),
144
+ timeframe: z.enum(["immediate", "short-term", "long-term"]).describe("When this should be completed"),
145
+ priority: z.enum(["low", "medium", "high", "critical"]).describe("Task priority"),
146
+ }),
147
+ outputSchema: z.object({
148
+ planId: z.string(),
149
+ steps: z.array(z.object({
150
+ step: z.number(),
151
+ action: z.string(),
152
+ estimatedTime: z.string(),
153
+ tools: z.array(z.string()).describe("Tools needed for this step"),
154
+ })),
155
+ totalEstimatedTime: z.string(),
156
+ complexity: z.string().describe("Complexity assessment"),
157
+ }),
158
+ execute: async (inputData) => {
159
+ const { goal, timeframe, priority } = inputData;
160
+
161
+ // Dynamic plan generation based on goal analysis
162
+ const goalLower = goal.toLowerCase();
163
+ const isResearchTask = goalLower.includes('research') || goalLower.includes('find') || goalLower.includes('search');
164
+ const isCreationTask = goalLower.includes('create') || goalLower.includes('make') || goalLower.includes('build');
165
+ const isAnalysisTask = goalLower.includes('analyze') || goalLower.includes('review') || goalLower.includes('check');
166
+
167
+ const steps = [];
168
+ let stepCounter = 1;
169
+
170
+ // Research phase (if needed)
171
+ if (isResearchTask || goal.length > 50) {
172
+ steps.push({
173
+ step: stepCounter++,
174
+ action: `Research: Gather information about "${goal.substring(0, 60)}..."`,
175
+ estimatedTime: timeframe === "immediate" ? "5 mins" : "10-15 mins",
176
+ tools: ["searchWeb", "fetchWebContent"]
177
+ });
178
+ }
179
+
180
+ // Analysis phase
181
+ if (isAnalysisTask || isResearchTask) {
182
+ steps.push({
183
+ step: stepCounter++,
184
+ action: `Analyze: Process and structure findings from research`,
185
+ estimatedTime: "5-10 mins",
186
+ tools: ["deepResearch"]
187
+ });
188
+ }
189
+
190
+ // Execution phase
191
+ const executionAction = isCreationTask ? "Create the requested output" :
192
+ isResearchTask ? "Synthesize research findings" :
193
+ isAnalysisTask ? "Complete analysis and provide insights" :
194
+ `Execute actions to achieve: "${goal.substring(0, 40)}..."`;
195
+
196
+ steps.push({
197
+ step: stepCounter++,
198
+ action: executionAction,
199
+ estimatedTime: timeframe === "immediate" ? "10 mins" : "15-20 mins",
200
+ tools: isCreationTask ? [] : ["extractStructuredData"]
201
+ });
202
+
203
+ // Verification phase
204
+ steps.push({
205
+ step: stepCounter++,
206
+ action: `Verify: Confirm successful completion and quality check`,
207
+ estimatedTime: "3-5 mins",
208
+ tools: []
209
+ });
210
+
211
+ const totalTime = steps.reduce((sum, step) => {
212
+ const time = parseInt(step.estimatedTime.split('-')[1] || step.estimatedTime.split(' ')[0]);
213
+ return sum + (isNaN(time) ? 10 : time);
214
+ }, 0);
215
+
216
+ const complexity = steps.length > 4 ? "high" : steps.length > 2 ? "medium" : "low";
217
+
218
+ return {
219
+ planId: `plan-${Date.now()}`,
220
+ steps,
221
+ totalEstimatedTime: `~${totalTime} mins`,
222
+ complexity,
223
+ };
224
+ },
225
+ });
226
+
227
+ // Tool: Execute planner workflow for complex tasks
228
+ export const executePlannerWorkflowTool = createTool({
229
+ id: "execute-planner-workflow",
230
+ description: `
231
+ Execute the planner workflow for creating detailed execution plans.
232
+ Use this when the user's request requires structured planning with multiple steps.
233
+ `,
234
+ inputSchema: z.object({
235
+ goal: z.string().describe("The main goal to achieve"),
236
+ userContext: z.string().optional().describe("Additional context about the user"),
237
+ }),
238
+ outputSchema: z.object({
239
+ success: z.boolean(),
240
+ result: z.any().describe("Workflow execution result"),
241
+ workflowId: z.string(),
242
+ steps: z.array(z.string()).describe("Steps executed by workflow"),
243
+ duration: z.string().describe("Execution duration"),
244
+ }),
245
+ execute: async (inputData: PlannerWorkflowInput): Promise<WorkflowResult> => {
246
+ const startTime = Date.now();
247
+
248
+ try {
249
+ // Lazy import to avoid circular dependency: mastra/index.ts ↔ autonomous-agent.ts
250
+ const { mastra } = await import("../mastra/index.js");
251
+ const workflow: any = mastra.getWorkflow("plannerWorkflow");
252
+
253
+ if (!workflow) {
254
+ throw new Error("Planner workflow not found");
255
+ }
256
+
257
+ // Create and run workflow
258
+ const run: any = await workflow.createRun();
259
+ const result: any = await run.start({
260
+ inputData: inputData
261
+ });
262
+
263
+ const duration = Date.now() - startTime;
264
+
265
+ return {
266
+ success: result.status === "success",
267
+ result: result.status === "success" ? result.result : null,
268
+ workflowId: run.runId,
269
+ steps: result.steps ? Object.keys(result.steps) : [],
270
+ duration: `${duration}ms`,
271
+ };
272
+
273
+ } catch (error) {
274
+ const duration = Date.now() - startTime;
275
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
276
+
277
+ return {
278
+ success: false,
279
+ result: { error: errorMessage },
280
+ workflowId: `failed-${Date.now()}`,
281
+ steps: [],
282
+ duration: `${duration}ms`,
283
+ };
284
+ }
285
+ },
286
+ });
287
+
288
+ // Tool: Execute skill builder workflow
289
+ export const executeSkillBuilderWorkflowTool = createTool({
290
+ id: "execute-skill-builder-workflow",
291
+ description: `
292
+ Execute the skill builder workflow for identifying and developing new skills.
293
+ Use this when the user wants to build capabilities or learn new approaches.
294
+ `,
295
+ inputSchema: z.object({
296
+ recentTasks: z.array(z.string()).describe("Recent tasks the user has requested"),
297
+ userGoals: z.array(z.string()).describe("User's stated goals"),
298
+ currentSkills: z.array(z.string()).describe("Skills the bot currently demonstrates"),
299
+ }),
300
+ outputSchema: z.object({
301
+ success: z.boolean(),
302
+ result: z.any().describe("Workflow execution result"),
303
+ workflowId: z.string(),
304
+ steps: z.array(z.string()).describe("Steps executed by workflow"),
305
+ duration: z.string().describe("Execution duration"),
306
+ }),
307
+ execute: async (inputData: SkillBuilderWorkflowInput): Promise<WorkflowResult> => {
308
+ const startTime = Date.now();
309
+
310
+ try {
311
+ // Lazy import to avoid circular dependency: mastra/index.ts ↔ autonomous-agent.ts
312
+ const { mastra } = await import("../mastra/index.js");
313
+ const workflow: any = mastra.getWorkflow("skillBuilderWorkflow");
314
+
315
+ if (!workflow) {
316
+ throw new Error("Skill builder workflow not found");
317
+ }
318
+
319
+ // Create and run workflow
320
+ const run: any = await workflow.createRun();
321
+ const result: any = await run.start({
322
+ inputData: inputData
323
+ });
324
+
325
+ const duration = Date.now() - startTime;
326
+
327
+ return {
328
+ success: result.status === "success",
329
+ result: result.status === "success" ? result.result : null,
330
+ workflowId: run.runId,
331
+ steps: result.steps ? Object.keys(result.steps) : [],
332
+ duration: `${duration}ms`,
333
+ };
334
+
335
+ } catch (error) {
336
+ const duration = Date.now() - startTime;
337
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
338
+
339
+ return {
340
+ success: false,
341
+ result: { error: errorMessage },
342
+ workflowId: `failed-${Date.now()}`,
343
+ steps: [],
344
+ duration: `${duration}ms`,
345
+ };
346
+ }
347
+ },
348
+ });
349
+
350
+ // Tool: Self-reflection and improvement
351
+ export const selfReflectTool = createTool({
352
+ id: "self-reflect",
353
+ description: `
354
+ Reflect on recent interactions and identify areas for improvement.
355
+ This helps the bot continuously improve its performance and adapt to user needs.
356
+ `,
357
+ inputSchema: z.object({
358
+ recentInteractions: z.number().default(5).describe("Number of recent interactions to analyze"),
359
+ focusArea: z.enum(["communication", "knowledge", "efficiency", "all"]).describe("What to focus on"),
360
+ }),
361
+ outputSchema: z.object({
362
+ reflections: z.array(z.object({
363
+ area: z.string(),
364
+ observation: z.string(),
365
+ improvement: z.string(),
366
+ priority: z.string().describe("Priority of this improvement"),
367
+ })),
368
+ overallScore: z.number(),
369
+ recommendations: z.array(z.string()).describe("Specific actionable recommendations"),
370
+ }),
371
+ execute: async (inputData) => {
372
+ const { recentInteractions, focusArea } = inputData;
373
+
374
+ // Dynamic reflection based on focus area
375
+ const reflections = [];
376
+ const recommendations = [];
377
+
378
+ if (focusArea === "communication" || focusArea === "all") {
379
+ reflections.push({
380
+ area: "communication",
381
+ observation: `Analyzed ${recentInteractions} recent interactions for communication patterns`,
382
+ improvement: "Adopt more proactive communication style when user seems uncertain",
383
+ priority: "high"
384
+ });
385
+ recommendations.push("Ask clarifying questions when user requests are ambiguous");
386
+ }
387
+
388
+ if (focusArea === "knowledge" || focusArea === "all") {
389
+ reflections.push({
390
+ area: "knowledge",
391
+ observation: "Identified gaps in real-time information access",
392
+ improvement: "Prioritize web search for time-sensitive queries",
393
+ priority: "medium"
394
+ });
395
+ recommendations.push("Always verify information currency for time-critical requests");
396
+ }
397
+
398
+ if (focusArea === "efficiency" || focusArea === "all") {
399
+ reflections.push({
400
+ area: "efficiency",
401
+ observation: "Multi-step tasks could be better structured",
402
+ improvement: "Use workflows for complex multi-step objectives",
403
+ priority: "high"
404
+ });
405
+ recommendations.push("Break down complex requests into clear, sequential steps");
406
+ }
407
+
408
+ // Calculate dynamic score based on reflections
409
+ const highPriorityCount = reflections.filter(r => r.priority === "high").length;
410
+ const baseScore = 0.9;
411
+ const scorePenalty = highPriorityCount * 0.05;
412
+ const overallScore = Math.max(0.6, baseScore - scorePenalty);
413
+
414
+ // Add general recommendations
415
+ recommendations.push("Continue learning from user interactions to improve personalization");
416
+
417
+ return {
418
+ reflections,
419
+ overallScore,
420
+ recommendations,
421
+ };
422
+ },
423
+ });
424
+
425
+ // Main autonomous agent
426
+ export const autonomousAgent: Agent = new Agent({
427
+ id: "autonomous-agent",
428
+ name: "sybil",
429
+ description: `
430
+ An autonomous AI assistant that learns, plans, and improves over time.
431
+ Capable of working independently, building skills, maintaining deep context about users,
432
+ browsing the web to gather information, and integrating with WhatsApp for messaging.
433
+ `,
434
+ instructions: `You are sybil, an autonomous AI assistant. ${systemContext}
435
+
436
+ ## Core Identity
437
+ An autonomous AI assistant that learns, plans, and improves over time. Capable of working independently, building skills, maintaining deep context about users, browsing the web to gather information, and integrating with WhatsApp for messaging.
438
+
439
+ ## Tools (33+ available)
440
+
441
+ **Code & Execution:**
442
+ - createDirectory: Create new directories in workspace
443
+ - writeFile: Write content to files
444
+ - deleteFile: Delete files from workspace
445
+ - listFiles: List directory contents
446
+ - executePython: Run Python code
447
+ - executeJavaScript: Run JavaScript/TypeScript code
448
+ - executeBash: Execute bash commands
449
+ - executeCommand: Execute system commands
450
+ - installPackage: Install npm/pip packages
451
+ - uninstallPackage: Remove packages
452
+ - getSystemInfo: Get system information
453
+
454
+ **Web & Research:**
455
+ - searchWeb: Search the internet for information
456
+ - fetchWebContent: Fetch content from URLs
457
+ - extractStructuredData: Extract structured data from content
458
+ - deepResearch: Perform comprehensive multi-source research
459
+
460
+ **Browser Automation:**
461
+ - browsePage: Navigate to web pages
462
+ - takeScreenshot: Capture page screenshots
463
+ - clickElement: Click elements on page
464
+ - fillForm: Fill form fields
465
+ - scrollPage: Scroll page content
466
+ - goBack: Browser back navigation
467
+ - goForward: Browser forward navigation
468
+ - getPageSource: Get page HTML source
469
+ - evaluatePage: Execute JavaScript on page
470
+ - waitForElement: Wait for elements to appear
471
+
472
+ **WhatsApp:**
473
+ - initializeWhatsApp: Initialize WhatsApp Web connection
474
+ - sendWhatsAppMessage: Send messages to contacts
475
+ - getWhatsAppChats: List recent conversations
476
+ - getWhatsAppMessages: Retrieve message history
477
+ - getWhatsAppContact: Get contact information
478
+ - getMyWhatsAppInfo: Get own WhatsApp profile
479
+ - broadcastWhatsAppMessage: Send to multiple recipients
480
+ - configureAutoReply: Set up auto-reply rules
481
+ - approvePendingReply: Approve AI-generated replies
482
+
483
+ **File Sharing:**
484
+ - sendTelegramFile: Send files via Telegram
485
+ - sendTelegramMessage: Send Telegram messages
486
+ - sendTelegramMediaGroup: Send multiple media files
487
+
488
+ **Memory & Learning:**
489
+ - learnFromInteraction: Extract insights from conversations
490
+ - planAutonomousTask: Create execution plans for goals
491
+ - selfReflect: Analyze and improve performance
492
+
493
+ **Dynamic Creation:**
494
+ - generateTool: Create new custom tools dynamically
495
+ - listGeneratedTools: View all generated tools
496
+ - deleteGeneratedTool: Remove generated tools
497
+ - generateSkill: Create new skills from patterns
498
+ - listSkills: View available skills
499
+ - activateSkill: Enable specific skills
500
+
501
+ **Agent Delegation:**
502
+ - delegateToAgent: Delegate tasks to other agents dynamically
503
+ - delegateToPlanner: Send planning tasks to Planner Agent
504
+ - delegateToResearcher: Send research tasks to Researcher Agent
505
+ - delegateToExecutor: Send execution tasks to Executor Agent
506
+
507
+ ## Behavioral Rules
508
+
509
+ 1. **Proactive Execution**: Use tools immediately rather than describing what you would do. Every significant claim must be backed by tool results.
510
+
511
+ 2. **Tool Call Transparency**: All tool calls are displayed to users with status indicators (✅ success, ❌ failed). Users see everything you execute.
512
+
513
+ 3. **Agent Delegation**: Delegate to specialized agents when appropriate:
514
+ - Use delegateToPlanner for complex planning tasks
515
+ - Use delegateToResearcher for information gathering
516
+ - Use delegateToExecutor for code/execution tasks
517
+ - Provide clear task descriptions and context
518
+
519
+ 4. **Web Research Protocol**:
520
+ - searchWeb to find sources
521
+ - fetchWebContent from top 5-7 results
522
+ - extractStructuredData for key information
523
+ - cite sources with URLs and quotes
524
+
525
+ 5. **File Creation Workflow**:
526
+ - Create files in workspace directory
527
+ - Offer to send files via Telegram
528
+ - Provide file paths for user reference
529
+
530
+ 6. **WhatsApp Protocol**:
531
+ - Always check status with getWhatsAppStatus first
532
+ - Use international format: +1234567890
533
+ - Initialize with QR scan if not connected
534
+ - Respect character limits (< 4096 chars)
535
+
536
+ 7. **Dynamic Tool Generation**: When functionality is missing, use generateTool to create it. Validate and test generated tools before using them.
537
+
538
+ 8. **Self-Reflection**: Periodically use selfReflect to analyze recent interactions and identify improvement opportunities.
539
+
540
+ 9. **Action Explanation (CRITICAL)**: Before EVERY tool call, explain in ONE clear sentence:
541
+ - **What** you're doing
542
+ - **Why** you're doing it
543
+ - **How** it helps achieve the user's goal
544
+ Example: "Searching the web for Python tutorials to find beginner-friendly resources that match your learning style."
545
+
546
+ 10. **Always Respond with Text**: NEVER just call tools silently. Always provide:
547
+ - Text explanation before tool calls
548
+ - Progress updates during multi-step operations
549
+ - Summary of results after tool calls
550
+ - Clear next steps or recommendations
551
+ - Conversational context around tool usage
552
+
553
+ ## Workspace Information
554
+ - Working directory: Project workspace
555
+ - Generated files persist across sessions
556
+ - Dynamic tools saved to workspace/generated-tools/
557
+ - Telegram files shared from workspace
558
+
559
+ ## Safety & Guidelines
560
+
561
+ **Security:**
562
+ - Never execute commands that could harm the system
563
+ - Validate all inputs before execution
564
+ - Avoid operations that modify system files outside workspace
565
+ - Generated tools are validated before persistence
566
+
567
+ **Privacy:**
568
+ - Handle user data responsibly
569
+ - Don't share sensitive information in tool outputs
570
+ - WhatsApp conversations handled securely
571
+
572
+ **Quality:**
573
+ - Cross-reference information from multiple sources
574
+ - Provide confidence levels for findings (HIGH/MEDIUM/LOW)
575
+ - Include source citations for research
576
+ - Test code before reporting completion
577
+
578
+ **Communication:**
579
+ - Explain your reasoning for complex decisions
580
+ - Ask clarifying questions when requirements are unclear
581
+ - Provide actionable next steps
582
+ - Keep responses focused and relevant
583
+
584
+ ## Current Model: ${getProviderDisplayName()} ${getModelConfig().model}
585
+ `,
586
+ model: createModel(),
587
+ memory, // Configure memory at agent level
588
+
589
+ // Add processors for enhanced message processing
590
+ inputProcessors: getAgentProcessors().inputProcessors,
591
+ outputProcessors: getAgentProcessors().outputProcessors,
592
+
593
+ tools: {
594
+ ...sandboxTools,
595
+ learnFromInteraction: learnFromInteractionTool,
596
+ planAutonomousTask: planAutonomousTaskTool,
597
+ selfReflect: selfReflectTool,
598
+ executePlannerWorkflow: executePlannerWorkflowTool,
599
+ executeSkillBuilderWorkflow: executeSkillBuilderWorkflowTool,
600
+ searchWeb: searchWebTool,
601
+ fetchWebContent: fetchWebContentTool,
602
+ extractStructuredData: extractStructuredDataTool,
603
+ deepResearch: deepResearchTool,
604
+ getWhatsAppStatus: getWhatsAppStatusTool,
605
+ initializeWhatsApp: initializeWhatsAppTool,
606
+ sendWhatsAppMessage: sendWhatsAppMessageTool,
607
+ getWhatsAppChats: getWhatsAppChatsTool,
608
+ getWhatsAppMessages: getWhatsAppMessagesTool,
609
+ getWhatsAppContact: getWhatsAppContactTool,
610
+ getMyWhatsAppInfo: getMyWhatsAppInfoTool,
611
+ broadcastWhatsAppMessage: broadcastWhatsAppMessageTool,
612
+ configureAutoReply: configureAutoReplyTool,
613
+ approvePendingReply: approvePendingReplyTool,
614
+ generateTool: generateToolTool,
615
+ listGeneratedTools: listGeneratedToolsTool,
616
+ deleteGeneratedTool: deleteGeneratedToolTool,
617
+ generateSkill: generateSkillTool,
618
+ learnSkillFromFeedback: learnSkillFromFeedbackTool,
619
+ listSkills: listSkillsTool,
620
+ activateSkill: activateSkillTool,
621
+ analyzeForSkillOpportunity: analyzeForSkillOpportunityTool,
622
+ ...browserTools,
623
+ ...telegramTools,
624
+ ...agentDelegationTools,
625
+ },
626
+ });