@xagent-ai/cli 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (568) hide show
  1. package/.github/ISSUE_TEMPLATE/bug_report.md +38 -38
  2. package/.github/ISSUE_TEMPLATE/feature_request.md +20 -20
  3. package/.github/workflows/ci.yml +72 -0
  4. package/.github/workflows/release.yml +109 -0
  5. package/.gitmodules +3 -3
  6. package/README.md +326 -280
  7. package/README_CN.md +325 -279
  8. package/dist/ai-client/factory.d.ts +52 -0
  9. package/dist/ai-client/factory.d.ts.map +1 -0
  10. package/dist/ai-client/factory.js +132 -0
  11. package/dist/ai-client/factory.js.map +1 -0
  12. package/dist/ai-client/index.d.ts +20 -0
  13. package/dist/ai-client/index.d.ts.map +1 -0
  14. package/dist/ai-client/index.js +49 -0
  15. package/dist/ai-client/index.js.map +1 -0
  16. package/dist/ai-client/providers/anthropic.d.ts +57 -0
  17. package/dist/ai-client/providers/anthropic.d.ts.map +1 -0
  18. package/dist/ai-client/providers/anthropic.js +400 -0
  19. package/dist/ai-client/providers/anthropic.js.map +1 -0
  20. package/dist/ai-client/providers/openai.d.ts +57 -0
  21. package/dist/ai-client/providers/openai.d.ts.map +1 -0
  22. package/dist/ai-client/providers/openai.js +286 -0
  23. package/dist/ai-client/providers/openai.js.map +1 -0
  24. package/dist/ai-client/providers/remote.d.ts +111 -0
  25. package/dist/ai-client/providers/remote.d.ts.map +1 -0
  26. package/dist/ai-client/providers/remote.js +351 -0
  27. package/dist/ai-client/providers/remote.js.map +1 -0
  28. package/dist/ai-client/registry.d.ts +51 -0
  29. package/dist/ai-client/registry.d.ts.map +1 -0
  30. package/dist/ai-client/registry.js +81 -0
  31. package/dist/ai-client/registry.js.map +1 -0
  32. package/dist/ai-client/types.d.ts +260 -0
  33. package/dist/ai-client/types.d.ts.map +1 -0
  34. package/dist/ai-client/types.js +73 -0
  35. package/dist/ai-client/types.js.map +1 -0
  36. package/dist/ai-client-factory.d.ts +62 -0
  37. package/dist/ai-client-factory.d.ts.map +1 -0
  38. package/dist/ai-client-factory.js +157 -0
  39. package/dist/ai-client-factory.js.map +1 -0
  40. package/dist/auth.d.ts +23 -1
  41. package/dist/auth.d.ts.map +1 -1
  42. package/dist/auth.js +160 -168
  43. package/dist/auth.js.map +1 -1
  44. package/dist/cancellation.d.ts +5 -4
  45. package/dist/cancellation.d.ts.map +1 -1
  46. package/dist/cancellation.js +55 -32
  47. package/dist/cancellation.js.map +1 -1
  48. package/dist/checkpoint.d.ts +1 -1
  49. package/dist/checkpoint.d.ts.map +1 -1
  50. package/dist/checkpoint.js +2 -2
  51. package/dist/checkpoint.js.map +1 -1
  52. package/dist/cli.js +626 -13
  53. package/dist/cli.js.map +1 -1
  54. package/dist/config.d.ts +10 -4
  55. package/dist/config.d.ts.map +1 -1
  56. package/dist/config.js +62 -25
  57. package/dist/config.js.map +1 -1
  58. package/dist/context-compressor.d.ts +81 -16
  59. package/dist/context-compressor.d.ts.map +1 -1
  60. package/dist/context-compressor.js +712 -153
  61. package/dist/context-compressor.js.map +1 -1
  62. package/dist/gui-subagent/action-parser/actionParser.d.ts.map +1 -1
  63. package/dist/gui-subagent/action-parser/actionParser.js +4 -2
  64. package/dist/gui-subagent/action-parser/actionParser.js.map +1 -1
  65. package/dist/gui-subagent/agent/gui-agent.d.ts +29 -2
  66. package/dist/gui-subagent/agent/gui-agent.d.ts.map +1 -1
  67. package/dist/gui-subagent/agent/gui-agent.js +87 -45
  68. package/dist/gui-subagent/agent/gui-agent.js.map +1 -1
  69. package/dist/gui-subagent/index.d.ts +16 -1
  70. package/dist/gui-subagent/index.d.ts.map +1 -1
  71. package/dist/gui-subagent/index.js +4 -0
  72. package/dist/gui-subagent/index.js.map +1 -1
  73. package/dist/gui-subagent/operator/base-operator.d.ts.map +1 -1
  74. package/dist/gui-subagent/operator/base-operator.js +0 -1
  75. package/dist/gui-subagent/operator/base-operator.js.map +1 -1
  76. package/dist/gui-subagent/operator/computer-operator.d.ts.map +1 -1
  77. package/dist/gui-subagent/operator/computer-operator.js +29 -8
  78. package/dist/gui-subagent/operator/computer-operator.js.map +1 -1
  79. package/dist/gui-subagent/types/actions.d.ts +1 -1
  80. package/dist/gui-subagent/types/actions.d.ts.map +1 -1
  81. package/dist/gui-subagent/types/actions.js +0 -1
  82. package/dist/gui-subagent/types/actions.js.map +1 -1
  83. package/dist/gui-subagent/types/operator.d.ts +1 -1
  84. package/dist/gui-subagent/types/operator.d.ts.map +1 -1
  85. package/dist/index.d.ts +1 -2
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +1 -2
  88. package/dist/index.js.map +1 -1
  89. package/dist/input-processor.d.ts.map +1 -1
  90. package/dist/input-processor.js +6 -3
  91. package/dist/input-processor.js.map +1 -1
  92. package/dist/mcp.d.ts +5 -0
  93. package/dist/mcp.d.ts.map +1 -1
  94. package/dist/mcp.js +81 -35
  95. package/dist/mcp.js.map +1 -1
  96. package/dist/ripgrep.d.ts +29 -0
  97. package/dist/ripgrep.d.ts.map +1 -0
  98. package/dist/ripgrep.js +292 -0
  99. package/dist/ripgrep.js.map +1 -0
  100. package/dist/session.d.ts +23 -7
  101. package/dist/session.d.ts.map +1 -1
  102. package/dist/session.js +624 -243
  103. package/dist/session.js.map +1 -1
  104. package/dist/shell.d.ts +33 -0
  105. package/dist/shell.d.ts.map +1 -0
  106. package/dist/shell.js +125 -0
  107. package/dist/shell.js.map +1 -0
  108. package/dist/skill-installer.d.ts +38 -0
  109. package/dist/skill-installer.d.ts.map +1 -0
  110. package/dist/skill-installer.js +447 -0
  111. package/dist/skill-installer.js.map +1 -0
  112. package/dist/skill-invoker.d.ts +7 -1
  113. package/dist/skill-invoker.d.ts.map +1 -1
  114. package/dist/skill-invoker.js +34 -13
  115. package/dist/skill-invoker.js.map +1 -1
  116. package/dist/skill-loader.d.ts +8 -3
  117. package/dist/skill-loader.d.ts.map +1 -1
  118. package/dist/skill-loader.js +46 -44
  119. package/dist/skill-loader.js.map +1 -1
  120. package/dist/skill-manager.d.ts +85 -0
  121. package/dist/skill-manager.d.ts.map +1 -0
  122. package/dist/skill-manager.js +340 -0
  123. package/dist/skill-manager.js.map +1 -0
  124. package/dist/slash-commands.d.ts +38 -1
  125. package/dist/slash-commands.d.ts.map +1 -1
  126. package/dist/slash-commands.js +912 -296
  127. package/dist/slash-commands.js.map +1 -1
  128. package/dist/smart-approval.d.ts.map +1 -1
  129. package/dist/smart-approval.js +67 -55
  130. package/dist/smart-approval.js.map +1 -1
  131. package/dist/system-prompt-generator.d.ts +6 -0
  132. package/dist/system-prompt-generator.d.ts.map +1 -1
  133. package/dist/system-prompt-generator.js +84 -34
  134. package/dist/system-prompt-generator.js.map +1 -1
  135. package/dist/terminal.d.ts +28 -0
  136. package/dist/terminal.d.ts.map +1 -0
  137. package/dist/terminal.js +82 -0
  138. package/dist/terminal.js.map +1 -0
  139. package/dist/tools.d.ts +23 -7
  140. package/dist/tools.d.ts.map +1 -1
  141. package/dist/tools.js +797 -437
  142. package/dist/tools.js.map +1 -1
  143. package/dist/truncate.d.ts +55 -0
  144. package/dist/truncate.d.ts.map +1 -0
  145. package/dist/truncate.js +130 -0
  146. package/dist/truncate.js.map +1 -0
  147. package/dist/types.d.ts +27 -9
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/update.d.ts.map +1 -1
  150. package/dist/update.js +17 -28
  151. package/dist/update.js.map +1 -1
  152. package/dist/workflow.d.ts +5 -1
  153. package/dist/workflow.d.ts.map +1 -1
  154. package/dist/workflow.js +60 -47
  155. package/dist/workflow.js.map +1 -1
  156. package/docs/architecture/mcp-integration-guide.md +304 -194
  157. package/docs/architecture/overview.md +169 -169
  158. package/docs/architecture/tool-system-design.md +134 -134
  159. package/docs/cli/commands.md +349 -238
  160. package/docs/smart-mode.md +281 -281
  161. package/docs/third-party-models.md +439 -439
  162. package/find-skills/SKILL.md +133 -0
  163. package/package.json +89 -90
  164. package/scripts/install-ripgrep.js +241 -0
  165. package/src/ai-client/factory.ts +151 -0
  166. package/src/ai-client/index.ts +61 -0
  167. package/src/ai-client/providers/anthropic.ts +466 -0
  168. package/src/ai-client/providers/openai.ts +342 -0
  169. package/src/ai-client/providers/remote.ts +436 -0
  170. package/src/ai-client/registry.ts +97 -0
  171. package/src/ai-client/types.ts +345 -0
  172. package/src/ai-client-factory.ts +204 -0
  173. package/src/auth.ts +663 -614
  174. package/src/cancellation.ts +205 -176
  175. package/src/checkpoint.ts +219 -219
  176. package/src/cli.ts +1406 -743
  177. package/src/config.ts +341 -297
  178. package/src/context-compressor.ts +982 -290
  179. package/src/conversation.ts +288 -288
  180. package/src/gui-subagent/action-parser/actionParser.ts +318 -315
  181. package/src/gui-subagent/action-parser/constants.ts +14 -14
  182. package/src/gui-subagent/action-parser/index.ts +8 -8
  183. package/src/gui-subagent/action-parser/types.ts +31 -31
  184. package/src/gui-subagent/agent/gui-agent.ts +1151 -1089
  185. package/src/gui-subagent/agent/index.ts +5 -5
  186. package/src/gui-subagent/index.ts +177 -163
  187. package/src/gui-subagent/operator/base-operator.ts +244 -245
  188. package/src/gui-subagent/operator/computer-operator.ts +540 -520
  189. package/src/gui-subagent/operator/index.ts +6 -6
  190. package/src/gui-subagent/types/actions.ts +260 -262
  191. package/src/gui-subagent/types/index.ts +6 -6
  192. package/src/gui-subagent/types/operator.ts +106 -106
  193. package/src/gui-subagent/utils.ts +51 -51
  194. package/src/index.ts +17 -18
  195. package/src/input-processor.ts +6 -3
  196. package/src/logger.ts +438 -438
  197. package/src/mcp.ts +730 -682
  198. package/src/memory.ts +344 -344
  199. package/src/ripgrep.ts +368 -0
  200. package/src/session-manager.ts +308 -308
  201. package/src/session.ts +948 -386
  202. package/src/shell.ts +133 -0
  203. package/src/skill-installer.ts +518 -0
  204. package/src/skill-invoker.ts +960 -935
  205. package/src/skill-loader.ts +501 -496
  206. package/src/skill-manager.ts +384 -0
  207. package/src/slash-commands.ts +2181 -1389
  208. package/src/smart-approval.ts +117 -73
  209. package/src/system-prompt-generator.ts +89 -34
  210. package/src/terminal.ts +96 -0
  211. package/src/theme.ts +738 -738
  212. package/src/tools.ts +1336 -773
  213. package/src/truncate.ts +173 -0
  214. package/src/types.ts +219 -198
  215. package/src/update.ts +22 -32
  216. package/src/workflow.ts +523 -508
  217. package/tsconfig.json +22 -22
  218. package/vitest.config.ts +19 -19
  219. package/dist/ai-client.d.ts +0 -86
  220. package/dist/ai-client.d.ts.map +0 -1
  221. package/dist/ai-client.js +0 -1372
  222. package/dist/ai-client.js.map +0 -1
  223. package/dist/gui-subagent/operator/browser-operator.d.ts +0 -36
  224. package/dist/gui-subagent/operator/browser-operator.d.ts.map +0 -1
  225. package/dist/gui-subagent/operator/browser-operator.js +0 -306
  226. package/dist/gui-subagent/operator/browser-operator.js.map +0 -1
  227. package/dist/gui-subagent/operator/desktop-operator.d.ts +0 -55
  228. package/dist/gui-subagent/operator/desktop-operator.d.ts.map +0 -1
  229. package/dist/gui-subagent/operator/desktop-operator.js +0 -527
  230. package/dist/gui-subagent/operator/desktop-operator.js.map +0 -1
  231. package/dist/hook.d.ts +0 -73
  232. package/dist/hook.d.ts.map +0 -1
  233. package/dist/hook.js +0 -156
  234. package/dist/hook.js.map +0 -1
  235. package/dist/input-history.d.ts +0 -24
  236. package/dist/input-history.d.ts.map +0 -1
  237. package/dist/input-history.js +0 -94
  238. package/dist/input-history.js.map +0 -1
  239. package/dist/keyboard-manager.d.ts +0 -151
  240. package/dist/keyboard-manager.d.ts.map +0 -1
  241. package/dist/keyboard-manager.js +0 -396
  242. package/dist/keyboard-manager.js.map +0 -1
  243. package/dist/print-system-prompt.d.ts +0 -2
  244. package/dist/print-system-prompt.d.ts.map +0 -1
  245. package/dist/print-system-prompt.js +0 -40
  246. package/dist/print-system-prompt.js.map +0 -1
  247. package/dist/remote-ai-client.d.ts +0 -104
  248. package/dist/remote-ai-client.d.ts.map +0 -1
  249. package/dist/remote-ai-client.js +0 -552
  250. package/dist/remote-ai-client.js.map +0 -1
  251. package/dist/sdk-output-adapter.d.ts +0 -232
  252. package/dist/sdk-output-adapter.d.ts.map +0 -1
  253. package/dist/sdk-output-adapter.js +0 -636
  254. package/dist/sdk-output-adapter.js.map +0 -1
  255. package/dist/sdk-session-v2.d.ts +0 -13
  256. package/dist/sdk-session-v2.d.ts.map +0 -1
  257. package/dist/sdk-session-v2.js +0 -46
  258. package/dist/sdk-session-v2.js.map +0 -1
  259. package/dist/sdk-session.d.ts +0 -13
  260. package/dist/sdk-session.d.ts.map +0 -1
  261. package/dist/sdk-session.js +0 -48
  262. package/dist/sdk-session.js.map +0 -1
  263. package/dist/test-boundary-conditions.d.ts.map +0 -1
  264. package/dist/test-boundary-conditions.js.map +0 -1
  265. package/dist/test-cancellation-fix.d.ts.map +0 -1
  266. package/dist/test-cancellation-fix.js.map +0 -1
  267. package/dist/test-input-history.d.ts.map +0 -1
  268. package/dist/test-input-history.js.map +0 -1
  269. package/dist/test-interaction-flow.d.ts.map +0 -1
  270. package/dist/test-interaction-flow.js.map +0 -1
  271. package/dist/test-quick.d.ts.map +0 -1
  272. package/dist/test-quick.js.map +0 -1
  273. package/dist/test-user-interaction.d.ts.map +0 -1
  274. package/dist/test-user-interaction.js.map +0 -1
  275. package/dist/tools/edit-diff.d.ts +0 -32
  276. package/dist/tools/edit-diff.d.ts.map +0 -1
  277. package/dist/tools/edit-diff.js +0 -185
  278. package/dist/tools/edit-diff.js.map +0 -1
  279. package/dist/tools/edit.d.ts +0 -11
  280. package/dist/tools/edit.d.ts.map +0 -1
  281. package/dist/tools/edit.js +0 -129
  282. package/dist/tools/edit.js.map +0 -1
  283. package/dist/unified-session.d.ts +0 -42
  284. package/dist/unified-session.d.ts.map +0 -1
  285. package/dist/unified-session.js +0 -271
  286. package/dist/unified-session.js.map +0 -1
  287. package/skills/.claude-plugin/marketplace.json +0 -45
  288. package/skills/README.md +0 -94
  289. package/skills/THIRD_PARTY_NOTICES.md +0 -405
  290. package/skills/skills/algorithmic-art/LICENSE.txt +0 -202
  291. package/skills/skills/algorithmic-art/SKILL.md +0 -405
  292. package/skills/skills/algorithmic-art/templates/generator_template.js +0 -223
  293. package/skills/skills/algorithmic-art/templates/viewer.html +0 -599
  294. package/skills/skills/brand-guidelines/LICENSE.txt +0 -202
  295. package/skills/skills/brand-guidelines/SKILL.md +0 -73
  296. package/skills/skills/canvas-design/LICENSE.txt +0 -202
  297. package/skills/skills/canvas-design/SKILL.md +0 -130
  298. package/skills/skills/canvas-design/canvas-fonts/ArsenalSC-OFL.txt +0 -93
  299. package/skills/skills/canvas-design/canvas-fonts/ArsenalSC-Regular.ttf +0 -0
  300. package/skills/skills/canvas-design/canvas-fonts/BigShoulders-Bold.ttf +0 -0
  301. package/skills/skills/canvas-design/canvas-fonts/BigShoulders-OFL.txt +0 -93
  302. package/skills/skills/canvas-design/canvas-fonts/BigShoulders-Regular.ttf +0 -0
  303. package/skills/skills/canvas-design/canvas-fonts/Boldonse-OFL.txt +0 -93
  304. package/skills/skills/canvas-design/canvas-fonts/Boldonse-Regular.ttf +0 -0
  305. package/skills/skills/canvas-design/canvas-fonts/BricolageGrotesque-Bold.ttf +0 -0
  306. package/skills/skills/canvas-design/canvas-fonts/BricolageGrotesque-OFL.txt +0 -93
  307. package/skills/skills/canvas-design/canvas-fonts/BricolageGrotesque-Regular.ttf +0 -0
  308. package/skills/skills/canvas-design/canvas-fonts/CrimsonPro-Bold.ttf +0 -0
  309. package/skills/skills/canvas-design/canvas-fonts/CrimsonPro-Italic.ttf +0 -0
  310. package/skills/skills/canvas-design/canvas-fonts/CrimsonPro-OFL.txt +0 -93
  311. package/skills/skills/canvas-design/canvas-fonts/CrimsonPro-Regular.ttf +0 -0
  312. package/skills/skills/canvas-design/canvas-fonts/DMMono-OFL.txt +0 -93
  313. package/skills/skills/canvas-design/canvas-fonts/DMMono-Regular.ttf +0 -0
  314. package/skills/skills/canvas-design/canvas-fonts/EricaOne-OFL.txt +0 -94
  315. package/skills/skills/canvas-design/canvas-fonts/EricaOne-Regular.ttf +0 -0
  316. package/skills/skills/canvas-design/canvas-fonts/GeistMono-Bold.ttf +0 -0
  317. package/skills/skills/canvas-design/canvas-fonts/GeistMono-OFL.txt +0 -93
  318. package/skills/skills/canvas-design/canvas-fonts/GeistMono-Regular.ttf +0 -0
  319. package/skills/skills/canvas-design/canvas-fonts/Gloock-OFL.txt +0 -93
  320. package/skills/skills/canvas-design/canvas-fonts/Gloock-Regular.ttf +0 -0
  321. package/skills/skills/canvas-design/canvas-fonts/IBMPlexMono-Bold.ttf +0 -0
  322. package/skills/skills/canvas-design/canvas-fonts/IBMPlexMono-OFL.txt +0 -93
  323. package/skills/skills/canvas-design/canvas-fonts/IBMPlexMono-Regular.ttf +0 -0
  324. package/skills/skills/canvas-design/canvas-fonts/IBMPlexSerif-Bold.ttf +0 -0
  325. package/skills/skills/canvas-design/canvas-fonts/IBMPlexSerif-BoldItalic.ttf +0 -0
  326. package/skills/skills/canvas-design/canvas-fonts/IBMPlexSerif-Italic.ttf +0 -0
  327. package/skills/skills/canvas-design/canvas-fonts/IBMPlexSerif-Regular.ttf +0 -0
  328. package/skills/skills/canvas-design/canvas-fonts/InstrumentSans-Bold.ttf +0 -0
  329. package/skills/skills/canvas-design/canvas-fonts/InstrumentSans-BoldItalic.ttf +0 -0
  330. package/skills/skills/canvas-design/canvas-fonts/InstrumentSans-Italic.ttf +0 -0
  331. package/skills/skills/canvas-design/canvas-fonts/InstrumentSans-OFL.txt +0 -93
  332. package/skills/skills/canvas-design/canvas-fonts/InstrumentSans-Regular.ttf +0 -0
  333. package/skills/skills/canvas-design/canvas-fonts/InstrumentSerif-Italic.ttf +0 -0
  334. package/skills/skills/canvas-design/canvas-fonts/InstrumentSerif-Regular.ttf +0 -0
  335. package/skills/skills/canvas-design/canvas-fonts/Italiana-OFL.txt +0 -93
  336. package/skills/skills/canvas-design/canvas-fonts/Italiana-Regular.ttf +0 -0
  337. package/skills/skills/canvas-design/canvas-fonts/JetBrainsMono-Bold.ttf +0 -0
  338. package/skills/skills/canvas-design/canvas-fonts/JetBrainsMono-OFL.txt +0 -93
  339. package/skills/skills/canvas-design/canvas-fonts/JetBrainsMono-Regular.ttf +0 -0
  340. package/skills/skills/canvas-design/canvas-fonts/Jura-Light.ttf +0 -0
  341. package/skills/skills/canvas-design/canvas-fonts/Jura-Medium.ttf +0 -0
  342. package/skills/skills/canvas-design/canvas-fonts/Jura-OFL.txt +0 -93
  343. package/skills/skills/canvas-design/canvas-fonts/LibreBaskerville-OFL.txt +0 -93
  344. package/skills/skills/canvas-design/canvas-fonts/LibreBaskerville-Regular.ttf +0 -0
  345. package/skills/skills/canvas-design/canvas-fonts/Lora-Bold.ttf +0 -0
  346. package/skills/skills/canvas-design/canvas-fonts/Lora-BoldItalic.ttf +0 -0
  347. package/skills/skills/canvas-design/canvas-fonts/Lora-Italic.ttf +0 -0
  348. package/skills/skills/canvas-design/canvas-fonts/Lora-OFL.txt +0 -93
  349. package/skills/skills/canvas-design/canvas-fonts/Lora-Regular.ttf +0 -0
  350. package/skills/skills/canvas-design/canvas-fonts/NationalPark-Bold.ttf +0 -0
  351. package/skills/skills/canvas-design/canvas-fonts/NationalPark-OFL.txt +0 -93
  352. package/skills/skills/canvas-design/canvas-fonts/NationalPark-Regular.ttf +0 -0
  353. package/skills/skills/canvas-design/canvas-fonts/NothingYouCouldDo-OFL.txt +0 -93
  354. package/skills/skills/canvas-design/canvas-fonts/NothingYouCouldDo-Regular.ttf +0 -0
  355. package/skills/skills/canvas-design/canvas-fonts/Outfit-Bold.ttf +0 -0
  356. package/skills/skills/canvas-design/canvas-fonts/Outfit-OFL.txt +0 -93
  357. package/skills/skills/canvas-design/canvas-fonts/Outfit-Regular.ttf +0 -0
  358. package/skills/skills/canvas-design/canvas-fonts/PixelifySans-Medium.ttf +0 -0
  359. package/skills/skills/canvas-design/canvas-fonts/PixelifySans-OFL.txt +0 -93
  360. package/skills/skills/canvas-design/canvas-fonts/PoiretOne-OFL.txt +0 -93
  361. package/skills/skills/canvas-design/canvas-fonts/PoiretOne-Regular.ttf +0 -0
  362. package/skills/skills/canvas-design/canvas-fonts/RedHatMono-Bold.ttf +0 -0
  363. package/skills/skills/canvas-design/canvas-fonts/RedHatMono-OFL.txt +0 -93
  364. package/skills/skills/canvas-design/canvas-fonts/RedHatMono-Regular.ttf +0 -0
  365. package/skills/skills/canvas-design/canvas-fonts/Silkscreen-OFL.txt +0 -93
  366. package/skills/skills/canvas-design/canvas-fonts/Silkscreen-Regular.ttf +0 -0
  367. package/skills/skills/canvas-design/canvas-fonts/SmoochSans-Medium.ttf +0 -0
  368. package/skills/skills/canvas-design/canvas-fonts/SmoochSans-OFL.txt +0 -93
  369. package/skills/skills/canvas-design/canvas-fonts/Tektur-Medium.ttf +0 -0
  370. package/skills/skills/canvas-design/canvas-fonts/Tektur-OFL.txt +0 -93
  371. package/skills/skills/canvas-design/canvas-fonts/Tektur-Regular.ttf +0 -0
  372. package/skills/skills/canvas-design/canvas-fonts/WorkSans-Bold.ttf +0 -0
  373. package/skills/skills/canvas-design/canvas-fonts/WorkSans-BoldItalic.ttf +0 -0
  374. package/skills/skills/canvas-design/canvas-fonts/WorkSans-Italic.ttf +0 -0
  375. package/skills/skills/canvas-design/canvas-fonts/WorkSans-OFL.txt +0 -93
  376. package/skills/skills/canvas-design/canvas-fonts/WorkSans-Regular.ttf +0 -0
  377. package/skills/skills/canvas-design/canvas-fonts/YoungSerif-OFL.txt +0 -93
  378. package/skills/skills/canvas-design/canvas-fonts/YoungSerif-Regular.ttf +0 -0
  379. package/skills/skills/doc-coauthoring/SKILL.md +0 -375
  380. package/skills/skills/docx/LICENSE.txt +0 -30
  381. package/skills/skills/docx/SKILL.md +0 -197
  382. package/skills/skills/docx/docx-js.md +0 -350
  383. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +0 -1499
  384. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +0 -146
  385. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +0 -1085
  386. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +0 -11
  387. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd +0 -3081
  388. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +0 -23
  389. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +0 -185
  390. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +0 -287
  391. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd +0 -1676
  392. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +0 -28
  393. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +0 -144
  394. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +0 -174
  395. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +0 -25
  396. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +0 -18
  397. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +0 -59
  398. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +0 -56
  399. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +0 -195
  400. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd +0 -582
  401. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +0 -25
  402. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd +0 -4439
  403. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd +0 -570
  404. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +0 -509
  405. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +0 -12
  406. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +0 -108
  407. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +0 -96
  408. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd +0 -3646
  409. package/skills/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd +0 -116
  410. package/skills/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd +0 -42
  411. package/skills/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd +0 -50
  412. package/skills/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd +0 -49
  413. package/skills/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd +0 -33
  414. package/skills/skills/docx/ooxml/schemas/mce/mc.xsd +0 -75
  415. package/skills/skills/docx/ooxml/schemas/microsoft/wml-2010.xsd +0 -560
  416. package/skills/skills/docx/ooxml/schemas/microsoft/wml-2012.xsd +0 -67
  417. package/skills/skills/docx/ooxml/schemas/microsoft/wml-2018.xsd +0 -14
  418. package/skills/skills/docx/ooxml/schemas/microsoft/wml-cex-2018.xsd +0 -20
  419. package/skills/skills/docx/ooxml/schemas/microsoft/wml-cid-2016.xsd +0 -13
  420. package/skills/skills/docx/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd +0 -4
  421. package/skills/skills/docx/ooxml/schemas/microsoft/wml-symex-2015.xsd +0 -8
  422. package/skills/skills/docx/ooxml/scripts/pack.py +0 -159
  423. package/skills/skills/docx/ooxml/scripts/unpack.py +0 -29
  424. package/skills/skills/docx/ooxml/scripts/validate.py +0 -69
  425. package/skills/skills/docx/ooxml/scripts/validation/__init__.py +0 -15
  426. package/skills/skills/docx/ooxml/scripts/validation/base.py +0 -951
  427. package/skills/skills/docx/ooxml/scripts/validation/docx.py +0 -274
  428. package/skills/skills/docx/ooxml/scripts/validation/pptx.py +0 -315
  429. package/skills/skills/docx/ooxml/scripts/validation/redlining.py +0 -279
  430. package/skills/skills/docx/ooxml.md +0 -610
  431. package/skills/skills/docx/scripts/__init__.py +0 -1
  432. package/skills/skills/docx/scripts/document.py +0 -1276
  433. package/skills/skills/docx/scripts/templates/comments.xml +0 -3
  434. package/skills/skills/docx/scripts/templates/commentsExtended.xml +0 -3
  435. package/skills/skills/docx/scripts/templates/commentsExtensible.xml +0 -3
  436. package/skills/skills/docx/scripts/templates/commentsIds.xml +0 -3
  437. package/skills/skills/docx/scripts/templates/people.xml +0 -3
  438. package/skills/skills/docx/scripts/utilities.py +0 -374
  439. package/skills/skills/frontend-design/LICENSE.txt +0 -177
  440. package/skills/skills/frontend-design/SKILL.md +0 -42
  441. package/skills/skills/internal-comms/LICENSE.txt +0 -202
  442. package/skills/skills/internal-comms/SKILL.md +0 -32
  443. package/skills/skills/internal-comms/examples/3p-updates.md +0 -47
  444. package/skills/skills/internal-comms/examples/company-newsletter.md +0 -65
  445. package/skills/skills/internal-comms/examples/faq-answers.md +0 -30
  446. package/skills/skills/internal-comms/examples/general-comms.md +0 -16
  447. package/skills/skills/mcp-builder/LICENSE.txt +0 -202
  448. package/skills/skills/mcp-builder/SKILL.md +0 -236
  449. package/skills/skills/mcp-builder/reference/evaluation.md +0 -602
  450. package/skills/skills/mcp-builder/reference/mcp_best_practices.md +0 -249
  451. package/skills/skills/mcp-builder/reference/node_mcp_server.md +0 -970
  452. package/skills/skills/mcp-builder/reference/python_mcp_server.md +0 -719
  453. package/skills/skills/mcp-builder/scripts/connections.py +0 -151
  454. package/skills/skills/mcp-builder/scripts/evaluation.py +0 -373
  455. package/skills/skills/mcp-builder/scripts/example_evaluation.xml +0 -22
  456. package/skills/skills/mcp-builder/scripts/requirements.txt +0 -2
  457. package/skills/skills/pdf/LICENSE.txt +0 -30
  458. package/skills/skills/pdf/SKILL.md +0 -294
  459. package/skills/skills/pdf/forms.md +0 -205
  460. package/skills/skills/pdf/reference.md +0 -612
  461. package/skills/skills/pdf/scripts/check_bounding_boxes.py +0 -70
  462. package/skills/skills/pdf/scripts/check_bounding_boxes_test.py +0 -226
  463. package/skills/skills/pdf/scripts/check_fillable_fields.py +0 -12
  464. package/skills/skills/pdf/scripts/convert_pdf_to_images.py +0 -35
  465. package/skills/skills/pdf/scripts/create_validation_image.py +0 -41
  466. package/skills/skills/pdf/scripts/extract_form_field_info.py +0 -152
  467. package/skills/skills/pdf/scripts/fill_fillable_fields.py +0 -114
  468. package/skills/skills/pdf/scripts/fill_pdf_form_with_annotations.py +0 -108
  469. package/skills/skills/pptx/LICENSE.txt +0 -30
  470. package/skills/skills/pptx/SKILL.md +0 -484
  471. package/skills/skills/pptx/html2pptx.md +0 -625
  472. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +0 -1499
  473. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +0 -146
  474. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +0 -1085
  475. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +0 -11
  476. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd +0 -3081
  477. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +0 -23
  478. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +0 -185
  479. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +0 -287
  480. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd +0 -1676
  481. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +0 -28
  482. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +0 -144
  483. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +0 -174
  484. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +0 -25
  485. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +0 -18
  486. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +0 -59
  487. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +0 -56
  488. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +0 -195
  489. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd +0 -582
  490. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +0 -25
  491. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd +0 -4439
  492. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd +0 -570
  493. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +0 -509
  494. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +0 -12
  495. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +0 -108
  496. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +0 -96
  497. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd +0 -3646
  498. package/skills/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd +0 -116
  499. package/skills/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd +0 -42
  500. package/skills/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd +0 -50
  501. package/skills/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd +0 -49
  502. package/skills/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd +0 -33
  503. package/skills/skills/pptx/ooxml/schemas/mce/mc.xsd +0 -75
  504. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-2010.xsd +0 -560
  505. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-2012.xsd +0 -67
  506. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-2018.xsd +0 -14
  507. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-cex-2018.xsd +0 -20
  508. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-cid-2016.xsd +0 -13
  509. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd +0 -4
  510. package/skills/skills/pptx/ooxml/schemas/microsoft/wml-symex-2015.xsd +0 -8
  511. package/skills/skills/pptx/ooxml/scripts/pack.py +0 -159
  512. package/skills/skills/pptx/ooxml/scripts/unpack.py +0 -29
  513. package/skills/skills/pptx/ooxml/scripts/validate.py +0 -69
  514. package/skills/skills/pptx/ooxml/scripts/validation/__init__.py +0 -15
  515. package/skills/skills/pptx/ooxml/scripts/validation/base.py +0 -951
  516. package/skills/skills/pptx/ooxml/scripts/validation/docx.py +0 -274
  517. package/skills/skills/pptx/ooxml/scripts/validation/pptx.py +0 -315
  518. package/skills/skills/pptx/ooxml/scripts/validation/redlining.py +0 -279
  519. package/skills/skills/pptx/ooxml.md +0 -427
  520. package/skills/skills/pptx/scripts/html2pptx.js +0 -979
  521. package/skills/skills/pptx/scripts/inventory.py +0 -1020
  522. package/skills/skills/pptx/scripts/rearrange.py +0 -231
  523. package/skills/skills/pptx/scripts/replace.py +0 -385
  524. package/skills/skills/pptx/scripts/thumbnail.py +0 -450
  525. package/skills/skills/skill-creator/LICENSE.txt +0 -202
  526. package/skills/skills/skill-creator/SKILL.md +0 -356
  527. package/skills/skills/skill-creator/references/output-patterns.md +0 -82
  528. package/skills/skills/skill-creator/references/workflows.md +0 -28
  529. package/skills/skills/skill-creator/scripts/init_skill.py +0 -303
  530. package/skills/skills/skill-creator/scripts/package_skill.py +0 -110
  531. package/skills/skills/skill-creator/scripts/quick_validate.py +0 -95
  532. package/skills/skills/slack-gif-creator/LICENSE.txt +0 -202
  533. package/skills/skills/slack-gif-creator/SKILL.md +0 -254
  534. package/skills/skills/slack-gif-creator/core/easing.py +0 -234
  535. package/skills/skills/slack-gif-creator/core/frame_composer.py +0 -176
  536. package/skills/skills/slack-gif-creator/core/gif_builder.py +0 -269
  537. package/skills/skills/slack-gif-creator/core/validators.py +0 -136
  538. package/skills/skills/slack-gif-creator/requirements.txt +0 -4
  539. package/skills/skills/theme-factory/LICENSE.txt +0 -202
  540. package/skills/skills/theme-factory/SKILL.md +0 -59
  541. package/skills/skills/theme-factory/theme-showcase.pdf +0 -0
  542. package/skills/skills/theme-factory/themes/arctic-frost.md +0 -19
  543. package/skills/skills/theme-factory/themes/botanical-garden.md +0 -19
  544. package/skills/skills/theme-factory/themes/desert-rose.md +0 -19
  545. package/skills/skills/theme-factory/themes/forest-canopy.md +0 -19
  546. package/skills/skills/theme-factory/themes/golden-hour.md +0 -19
  547. package/skills/skills/theme-factory/themes/midnight-galaxy.md +0 -19
  548. package/skills/skills/theme-factory/themes/modern-minimalist.md +0 -19
  549. package/skills/skills/theme-factory/themes/ocean-depths.md +0 -19
  550. package/skills/skills/theme-factory/themes/sunset-boulevard.md +0 -19
  551. package/skills/skills/theme-factory/themes/tech-innovation.md +0 -19
  552. package/skills/skills/web-artifacts-builder/LICENSE.txt +0 -202
  553. package/skills/skills/web-artifacts-builder/SKILL.md +0 -74
  554. package/skills/skills/web-artifacts-builder/scripts/bundle-artifact.sh +0 -54
  555. package/skills/skills/web-artifacts-builder/scripts/init-artifact.sh +0 -322
  556. package/skills/skills/webapp-testing/LICENSE.txt +0 -202
  557. package/skills/skills/webapp-testing/SKILL.md +0 -96
  558. package/skills/skills/webapp-testing/examples/console_logging.py +0 -35
  559. package/skills/skills/webapp-testing/examples/element_discovery.py +0 -40
  560. package/skills/skills/webapp-testing/examples/static_html_automation.py +0 -33
  561. package/skills/skills/webapp-testing/scripts/with_server.py +0 -106
  562. package/skills/skills/xlsx/LICENSE.txt +0 -30
  563. package/skills/skills/xlsx/SKILL.md +0 -289
  564. package/skills/skills/xlsx/recalc.py +0 -178
  565. package/skills/spec/agent-skills-spec.md +0 -3
  566. package/skills/template/SKILL.md +0 -6
  567. package/src/ai-client.ts +0 -1560
  568. package/src/remote-ai-client.ts +0 -664
@@ -1,935 +1,960 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import os from 'os';
4
- import { getSkillLoader, SkillInfo, SkillLoader } from './skill-loader.js';
5
- import { getToolRegistry } from './tools.js';
6
- import { ExecutionMode, Tool } from './types.js';
7
- import { getConfigManager } from './config.js';
8
-
9
- // Re-export SkillInfo for other modules
10
- export type { SkillInfo };
11
-
12
- /**
13
- * Track skill execution history for tracking failures
14
- */
15
- export class SkillExecutionHistory {
16
- private history: Map<string, number> = new Map();
17
-
18
- /**
19
- * Get failure count for a task
20
- */
21
- getFailureCount(taskKey: string): number {
22
- return this.history.get(taskKey) || 0;
23
- }
24
-
25
- /**
26
- * Increment failure count for a task
27
- */
28
- incrementFailure(taskKey: string): number {
29
- const count = this.getFailureCount(taskKey) + 1;
30
- this.history.set(taskKey, count);
31
- return count;
32
- }
33
-
34
- /**
35
- * Reset failure count for a task (e.g., after success)
36
- */
37
- reset(taskKey: string): void {
38
- this.history.delete(taskKey);
39
- }
40
-
41
- /**
42
- * Check if threshold reached
43
- */
44
- shouldUseFallback(taskKey: string, threshold: number = 2): boolean {
45
- return this.getFailureCount(taskKey) >= threshold;
46
- }
47
- }
48
-
49
- // Singleton execution history
50
- const executionHistory = new SkillExecutionHistory();
51
-
52
- export function getExecutionHistory(): SkillExecutionHistory {
53
- return executionHistory;
54
- }
55
-
56
- export interface SkillExecutionParams {
57
- skillId: string;
58
- taskDescription: string;
59
- inputFile?: string;
60
- outputFile?: string;
61
- options?: Record<string, any>;
62
- /** Task ID for workspace directory naming */
63
- taskId?: string;
64
- }
65
-
66
- /**
67
- * Execution step interface - tells Agent what to do next
68
- */
69
- export interface ExecutionStep {
70
- step: number;
71
- action: string;
72
- description: string;
73
- command?: string;
74
- file?: string;
75
- reason: string;
76
- }
77
-
78
- /**
79
- * Skill execution result - contains guidance and next actions
80
- */
81
- export interface SkillExecutionResult {
82
- success: boolean;
83
- output?: string;
84
- error?: string;
85
- files?: string[];
86
- /** Tells Agent what to do next */
87
- nextSteps?: ExecutionStep[];
88
- /** Skill type for determining if manual execution is needed */
89
- requiresManualExecution?: boolean;
90
- /** Workspace directory used, for cleanup */
91
- workspaceDir?: string;
92
- /** Files to preserve (relative paths), skipped during cleanup */
93
- preserveFiles?: string[];
94
- }
95
-
96
- export interface SkillMatcherResult {
97
- skill: SkillInfo;
98
- confidence: number;
99
- matchedKeywords: string[];
100
- category: string;
101
- }
102
-
103
- // ============================================================
104
- // Workspace Utility Functions
105
- // ============================================================
106
-
107
- /**
108
- * Get workspace directory path
109
- * @param taskId Task ID for creating unique workspace directory
110
- * @returns Absolute path to workspace directory
111
- */
112
- export function getWorkspaceDir(taskId: string): string {
113
- // Try to get from config first
114
- try {
115
- const configManager = getConfigManager();
116
- const config = configManager.getSettings?.();
117
- if (config?.workspacePath) {
118
- return path.join(config.workspacePath, taskId);
119
- }
120
- } catch {
121
- // Config not available, use default
122
- }
123
-
124
- // Default to ~/.xagent/workspace
125
- return path.join(os.homedir(), '.xagent', 'workspace', taskId);
126
- }
127
-
128
- /**
129
- * Get base workspace directory (without task-id)
130
- */
131
- export function getBaseWorkspaceDir(): string {
132
- try {
133
- const configManager = getConfigManager();
134
- const config = configManager.getSettings?.();
135
- if (config?.workspacePath) {
136
- return config.workspacePath;
137
- }
138
- } catch {
139
- // Config not available, use default
140
- }
141
-
142
- return path.join(os.homedir(), '.xagent', 'workspace');
143
- }
144
-
145
- /**
146
- * Get workspace directory description for AI
147
- * Returns the actual workspace path from config, or default path
148
- */
149
- export function getWorkspaceDescription(): string {
150
- try {
151
- const configManager = getConfigManager();
152
- const config = configManager.getSettings?.();
153
- if (config?.workspacePath) {
154
- return config.workspacePath;
155
- }
156
- } catch {
157
- // Config not available, use default
158
- }
159
-
160
- return path.join(os.homedir(), '.xagent', 'workspace');
161
- }
162
-
163
- /**
164
- * Ensure workspace directory exists
165
- * @param workspaceDir Workspace directory path
166
- */
167
- export async function ensureWorkspaceDir(workspaceDir: string): Promise<void> {
168
- await fs.mkdir(workspaceDir, { recursive: true });
169
- }
170
-
171
- /**
172
- * Clean up workspace directory
173
- * @param workspaceDir Workspace directory path
174
- * @param preserveFiles Files to preserve (relative paths)
175
- */
176
- export async function cleanupWorkspace(workspaceDir: string, preserveFiles: string[] = []): Promise<void> {
177
- try {
178
- const entries = await fs.readdir(workspaceDir, { withFileTypes: true });
179
-
180
- for (const entry of entries) {
181
- const fullPath = path.join(workspaceDir, entry.name);
182
-
183
- // Skip files to preserve
184
- if (preserveFiles.includes(entry.name)) {
185
- continue;
186
- }
187
-
188
- if (entry.isDirectory()) {
189
- // Recursively delete subdirectories
190
- await fs.rm(fullPath, { recursive: true, force: true });
191
- } else {
192
- // Delete files
193
- await fs.unlink(fullPath);
194
- }
195
- }
196
- } catch (error: any) {
197
- if (error.code !== 'ENOENT') {
198
- console.warn(`Workspace cleanup failed: ${error.message}`);
199
- }
200
- }
201
- }
202
-
203
- /**
204
- * Determine if workspace should be auto-cleaned based on ExecutionMode
205
- * @param executionMode Execution mode
206
- * @returns Whether auto-cleanup should happen
207
- */
208
- export function shouldAutoCleanup(executionMode: ExecutionMode): boolean {
209
- // YOLO mode: fully automatic, clean up directly
210
- if (executionMode === ExecutionMode.YOLO) {
211
- return true;
212
- }
213
- // Other modes require user confirmation
214
- return false;
215
- }
216
-
217
- /**
218
- * Generate cleanup prompt message
219
- * @param workspaceDir Workspace directory path
220
- */
221
- export async function getCleanupInfo(workspaceDir: string): Promise<{ files: string[]; totalSize: string }> {
222
- try {
223
- const entries = await fs.readdir(workspaceDir, { withFileTypes: true });
224
- const files: string[] = [];
225
-
226
- for (const entry of entries) {
227
- files.push(entry.name);
228
- }
229
-
230
- // Calculate total size
231
- let totalSize = 0;
232
- for (const entry of entries) {
233
- if (entry.isFile()) {
234
- const stats = await fs.stat(path.join(workspaceDir, entry.name));
235
- totalSize += stats.size;
236
- }
237
- }
238
-
239
- const formatSize = (bytes: number): string => {
240
- if (bytes < 1024) return `${bytes} B`;
241
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
242
- return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
243
- };
244
-
245
- return { files, totalSize: formatSize(totalSize) };
246
- } catch {
247
- return { files: [], totalSize: '0 B' };
248
- }
249
- }
250
-
251
- // ============================================================
252
- // Shared Content Extraction Utilities
253
- // ============================================================
254
-
255
- /**
256
- * Remove Markdown formatting (bold, italic, etc.)
257
- */
258
- export function stripMarkdown(text: string): string {
259
- return text
260
- .replace(/\*\*(.+?)\*\*/g, '$1') // Remove bold **
261
- .replace(/\*(.+?)\*/g, '$1') // Remove italic *
262
- .replace(/`(.+?)`/g, '$1') // Remove inline code `
263
- .trim();
264
- }
265
-
266
- /**
267
- * Extract content related to keywords (for SKILL.md content matching)
268
- * @param content SKILL.md full content
269
- * @param keywords Keyword list
270
- * @param maxLength Maximum return length
271
- * @returns Extracted relevant content
272
- */
273
- export function extractContent(content: string, keywords: string[], maxLength: number = 5000): string {
274
- const lines = content.split('\n');
275
- const relevantLines: string[] = [];
276
- let inRelevantSection = false;
277
- let sectionDepth = 0;
278
- let found = false;
279
-
280
- for (let i = 0; i < lines.length; i++) {
281
- const line = lines[i];
282
-
283
- // Detect headings
284
- if (line.match(/^#{1,6}\s/)) {
285
- const strippedLine = stripMarkdown(line);
286
- const lowerLine = strippedLine.toLowerCase();
287
-
288
- // Check if contains keywords
289
- const hasKeyword = keywords.some(kw => lowerLine.includes(kw.toLowerCase()));
290
-
291
- if (hasKeyword) {
292
- inRelevantSection = true;
293
- found = true;
294
- sectionDepth = line.match(/^(#+)/)?.[1].length || 1;
295
- } else if (inRelevantSection) {
296
- // Check if same level or higher heading (end current section)
297
- const currentDepth = line.match(/^(#+)/)?.[1].length || 1;
298
- if (currentDepth <= sectionDepth) {
299
- inRelevantSection = false;
300
- }
301
- }
302
- }
303
-
304
- if (inRelevantSection || found) {
305
- relevantLines.push(line);
306
- }
307
-
308
- // Limit content length
309
- if (relevantLines.join('\n').length > maxLength) {
310
- relevantLines.push('\n...(content truncated for brevity)...');
311
- break;
312
- }
313
- }
314
-
315
- if (relevantLines.length > 0) {
316
- return relevantLines.join('\n').trim();
317
- }
318
-
319
- // If still not found, return first 100 lines
320
- return lines.slice(0, 100).join('\n').trim() + '\n\n...(See SKILL.md for full instructions)';
321
- }
322
-
323
- /**
324
- * Read SKILL.md and extract relevant content based on task
325
- */
326
- export async function readSkillContent(skillPath: string, keywords: string[], maxLength: number = 5000): Promise<string> {
327
- const skillMdPath = path.join(skillPath, 'SKILL.md');
328
- const content = await fs.readFile(skillMdPath, 'utf-8');
329
- return extractContent(content, keywords, maxLength);
330
- }
331
-
332
- // ============================================================
333
- // SKILL Trigger Keywords Mapping
334
- // ============================================================
335
-
336
- // NOTE: SKILL_TRIGGERS is disabled for experiment purposes.
337
- // Let the LLM decide which skill to use based on system prompt information.
338
-
339
- // interface SkillTrigger {
340
- // skillId: string;
341
- // keywords: string[];
342
- // category: string;
343
- // }
344
-
345
- // export const SKILL_TRIGGERS: Record<string, SkillTrigger> = {
346
- // docx: {
347
- // skillId: 'docx',
348
- // keywords: [
349
- // 'word document', 'docx', 'microsoft word', 'create word', 'edit word',
350
- // 'create .docx', '.docx file', 'word file', 'document creation',
351
- // 'word editing', 'tracked changes', 'comments'
352
- // ],
353
- // category: 'Document Processing'
354
- // },
355
- // pdf: {
356
- // skillId: 'pdf',
357
- // keywords: [
358
- // 'pdf', 'create pdf', 'edit pdf', 'pdf document', 'pdf file',
359
- // 'extract pdf', 'merge pdf', 'split pdf', 'pdf form', 'manipulate pdf'
360
- // ],
361
- // category: 'Document Processing'
362
- // },
363
- // pptx: {
364
- // skillId: 'pptx',
365
- // keywords: [
366
- // 'powerpoint', 'ppt', 'pptx', 'presentation', 'slide',
367
- // 'create presentation', 'edit powerpoint', 'create slides',
368
- // 'powerpoint file', 'presentation file'
369
- // ],
370
- // category: 'Document Processing'
371
- // },
372
- // xlsx: {
373
- // skillId: 'xlsx',
374
- // keywords: [
375
- // 'excel', 'spreadsheet', 'xlsx', 'create excel', 'edit spreadsheet',
376
- // 'excel file', 'spreadsheet file', 'formulas', 'data analysis'
377
- // ],
378
- // category: 'Spreadsheet & Data'
379
- // },
380
- // frontend_design: {
381
- // skillId: 'frontend-design',
382
- // keywords: [
383
- // 'web page', 'website', 'web app', 'frontend', 'ui', 'user interface',
384
- // 'create website', 'build website', 'web component', 'html css',
385
- // 'landing page', 'dashboard', 'react', 'vue', 'web interface'
386
- // ],
387
- // category: 'Frontend & Web Development'
388
- // },
389
- // web_artifacts_builder: {
390
- // skillId: 'web-artifacts-builder',
391
- // keywords: [
392
- // 'complex react', 'react artifact', 'stateful artifact', 'routing',
393
- // 'web artifact', 'interactive artifact', 'web-based tool'
394
- // ],
395
- // category: 'Frontend & Web Development'
396
- // },
397
- // webapp_testing: {
398
- // skillId: 'webapp-testing',
399
- // keywords: [
400
- // 'test web', 'web testing', 'browser test', 'playwright', 'e2e test',
401
- // 'frontend test', 'capture screenshot', 'verify web'
402
- // ],
403
- // category: 'Frontend & Web Development'
404
- // },
405
- // canvas_design: {
406
- // skillId: 'canvas-design',
407
- // keywords: [
408
- // 'poster', 'artwork', 'visual art', 'canvas', 'design art',
409
- // 'create poster', 'create artwork', 'visual design', 'graphic art'
410
- // ],
411
- // category: 'Visual & Creative Design'
412
- // },
413
- // algorithmic_art: {
414
- // skillId: 'algorithmic-art',
415
- // keywords: [
416
- // 'generative art', 'algorithmic art', 'p5.js', 'particle system',
417
- // 'flow field', 'creative coding', 'code art'
418
- // ],
419
- // category: 'Visual & Creative Design'
420
- // },
421
- // theme_factory: {
422
- // skillId: 'theme-factory',
423
- // keywords: [
424
- // 'theme', 'color scheme', 'font theme', 'styling theme',
425
- // 'consistent theme', 'apply theme', 'theme colors'
426
- // ],
427
- // category: 'Visual & Creative Design'
428
- // },
429
- // brand_guidelines: {
430
- // skillId: 'brand-guidelines',
431
- // keywords: [
432
- // 'brand colors', 'brand guidelines', 'anthropic brand',
433
- // 'official brand', 'brand styling'
434
- // ],
435
- // category: 'Visual & Creative Design'
436
- // },
437
- // slack_gif_creator: {
438
- // skillId: 'slack-gif-creator',
439
- // keywords: [
440
- // 'slack gif', 'animated gif', 'gif for slack', 'slack animation'
441
- // ],
442
- // category: 'Visual & Creative Design'
443
- // },
444
- // mcp_builder: {
445
- // skillId: 'mcp-builder',
446
- // keywords: [
447
- // 'mcp server', 'model context protocol', 'create mcp',
448
- // 'mcp integration', 'external api integration'
449
- // ],
450
- // category: 'Development & Integration'
451
- // },
452
- // skill_creator: {
453
- // skillId: 'skill-creator',
454
- // keywords: [
455
- // 'create skill', 'new skill', 'skill development',
456
- // 'extend capabilities', 'custom skill'
457
- // ],
458
- // category: 'Development & Integration'
459
- // },
460
- // doc_coauthoring: {
461
- // skillId: 'doc-coauthoring',
462
- // keywords: [
463
- // 'documentation', 'technical docs', 'write documentation',
464
- // 'coauthor', 'doc writing', 'technical writing'
465
- // ],
466
- // category: 'Communication & Documentation'
467
- // }
468
- // };
469
-
470
- // ============================================================
471
- // SkillInvoker Main Class
472
- // ============================================================
473
-
474
- export class SkillInvoker {
475
- private skillLoader: SkillLoader;
476
- private initialized: boolean = false;
477
- private skillCache: Map<string, SkillInfo> = new Map(); // Stores metadata only
478
- private skillContentCache: Map<string, string> = new Map(); // Stores full SKILL.md content
479
-
480
- constructor(skillLoader?: SkillLoader) {
481
- this.skillLoader = skillLoader || getSkillLoader();
482
- }
483
-
484
- async initialize(): Promise<void> {
485
- if (this.initialized) return;
486
-
487
- // Use discoverSkills to only discover directories without loading full content
488
- const skillIds = await this.skillLoader.discoverSkills();
489
-
490
- // Create minimal SkillInfo objects with metadata only
491
- for (const skillId of skillIds) {
492
- const skillPath = this.skillLoader.getSkillDirectory?.(skillId) || '';
493
- const skillInfo: SkillInfo = {
494
- id: skillId,
495
- name: skillId,
496
- description: '', // Will be loaded lazily
497
- license: 'Unknown',
498
- version: '1.0.0',
499
- author: 'Anonymous',
500
- category: '',
501
- markdown: '', // Full content loaded lazily
502
- skillsPath: skillPath
503
- };
504
- this.skillCache.set(skillId, skillInfo);
505
- }
506
-
507
- this.initialized = true;
508
- }
509
-
510
- /**
511
- * Load skill metadata (name, description, category) from SKILL.md frontmatter
512
- * This is called lazily when skill details are needed
513
- */
514
- async loadSkillMetadata(skillId: string): Promise<void> {
515
- const skill = this.skillCache.get(skillId);
516
- if (!skill) return;
517
-
518
- // Check if metadata already loaded
519
- if (skill.description && skill.category) return;
520
-
521
- const skillPath = skill.skillsPath;
522
- const skillMdPath = path.join(skillPath, 'SKILL.md');
523
-
524
- try {
525
- const content = await fs.readFile(skillMdPath, 'utf-8');
526
- const parsed = this.skillLoader.parseSkillMarkdown(content);
527
-
528
- skill.name = parsed.name || skillId;
529
- skill.description = parsed.description || '';
530
- skill.license = parsed.license || 'Unknown';
531
- skill.version = parsed.version || '1.0.0';
532
- skill.author = parsed.author || 'Anonymous';
533
-
534
- // Extract category from path
535
- const pathParts = skillPath.split(path.sep);
536
- const skillsIndex = pathParts.findIndex(p => p === 'skills');
537
- if (skillsIndex >= 0 && pathParts.length > skillsIndex + 1) {
538
- skill.category = pathParts[skillsIndex + 1];
539
- }
540
-
541
- skill.markdown = content; // Now we have the full content
542
- this.skillContentCache.set(skillId, content);
543
- } catch (error) {
544
- console.warn(`[SkillInvoker] Failed to load metadata for skill ${skillId}:`, error);
545
- }
546
- }
547
-
548
- /**
549
- * Get list of all available skills (with metadata)
550
- */
551
- async listAvailableSkills(): Promise<SkillInfo[]> {
552
- await this.initialize();
553
-
554
- // Load metadata for all skills if not already loaded
555
- for (const skillId of this.skillCache.keys()) {
556
- await this.loadSkillMetadata(skillId);
557
- }
558
-
559
- return Array.from(this.skillCache.values());
560
- }
561
-
562
- /**
563
- * Match the most relevant skill based on user input
564
- * NOTE: SKILL_TRIGGERS disabled. Let LLM decide based on system prompt.
565
- * Returns null to indicate no explicit match - LLM should use its own judgment.
566
- */
567
- async matchSkill(userInput: string): Promise<SkillMatcherResult | null> {
568
- // SKILL_TRIGGERS is disabled for experiment purposes.
569
- // The LLM should decide which skill to use based on system prompt information.
570
- return null;
571
- }
572
-
573
- /**
574
- * Get skill details
575
- */
576
- async getSkillDetails(skillId: string): Promise<SkillInfo | null> {
577
- await this.initialize();
578
- return this.skillLoader.getSkill(skillId) || null;
579
- }
580
-
581
- /**
582
- * Execute skill
583
- */
584
- async executeSkill(params: SkillExecutionParams): Promise<SkillExecutionResult> {
585
- // Ensure initialized
586
- await this.initialize();
587
-
588
- // Load skill metadata if not already loaded
589
- await this.loadSkillMetadata(params.skillId);
590
-
591
- const skill = this.skillCache.get(params.skillId);
592
-
593
- if (!skill) {
594
- return {
595
- success: false,
596
- error: `Skill not found: ${params.skillId}`
597
- };
598
- }
599
-
600
- // Generate task ID (if not provided)
601
- const taskId = params.taskId || `${params.skillId}-${Date.now()}`;
602
-
603
- try {
604
- // Execute based on skillId
605
- const executor = this.getSkillExecutor(skill.id);
606
- const result = await executor.execute(skill, { ...params, taskId });
607
-
608
- // Add workspaceDir to result
609
- if (result.success && result.nextSteps && result.nextSteps.length > 0) {
610
- result.workspaceDir = getWorkspaceDir(taskId);
611
- await ensureWorkspaceDir(result.workspaceDir);
612
- }
613
-
614
- return result;
615
- } catch (error: any) {
616
- return {
617
- success: false,
618
- error: error.message
619
- };
620
- }
621
- }
622
-
623
- /**
624
- * Clean up workspace based on execution result
625
- * @param result Skill execution result
626
- * @param executionMode Execution mode
627
- * @returns Whether cleanup was performed
628
- */
629
- async cleanupAfterExecution(result: SkillExecutionResult, executionMode: ExecutionMode): Promise<boolean> {
630
- if (!result.workspaceDir) {
631
- return false;
632
- }
633
-
634
- // YOLO mode: auto cleanup
635
- if (executionMode === ExecutionMode.YOLO) {
636
- await cleanupWorkspace(result.workspaceDir, result.preserveFiles || []);
637
- return true;
638
- }
639
-
640
- // Other modes: don't auto cleanup, let user decide
641
- return false;
642
- }
643
-
644
- /**
645
- * Get cleanup prompt (for asking user)
646
- */
647
- async getCleanupPrompt(result: SkillExecutionResult): Promise<string | null> {
648
- if (!result.workspaceDir) {
649
- return null;
650
- }
651
-
652
- const info = await getCleanupInfo(result.workspaceDir);
653
- if (info.files.length === 0) {
654
- return null;
655
- }
656
-
657
- return `Task completed! Workspace directory contains the following files:\n` +
658
- `📁 ${result.workspaceDir}\n` +
659
- `Files: ${info.files.join(', ')}\n` +
660
- `Size: ${info.totalSize}\n\n` +
661
- `Do you want to clean up these temporary files?`;
662
- }
663
-
664
- /**
665
- * Get executor for skill
666
- * Unified dynamic approach - all skills use GenericSkillExecutor
667
- */
668
- private getSkillExecutor(skillId: string): SkillExecutor {
669
- return new GenericSkillExecutor();
670
- }
671
-
672
- // ============================================================================
673
- // Remote Mode Tool Support Methods
674
- // ============================================================================
675
-
676
- /**
677
- * Check if it's a Skill tool
678
- * Used for remote mode tool execution
679
- */
680
- isSkillTool(toolName: string): boolean {
681
- // Check if it's a skill ID in cache
682
- return this.skillCache.has(toolName);
683
- }
684
-
685
- /**
686
- * Get all Skill definitions (for syncing to remote server)
687
- * NOTE: triggers field is empty since SKILL_TRIGGERS is disabled
688
- */
689
- getAllSkillDefinitions(): Array<{
690
- id: string;
691
- name: string;
692
- description: string;
693
- category: string;
694
- triggers: string[];
695
- }> {
696
- const definitions: Array<{
697
- id: string;
698
- name: string;
699
- description: string;
700
- category: string;
701
- triggers: string[];
702
- }> = [];
703
-
704
- for (const skill of this.skillCache.values()) {
705
- definitions.push({
706
- id: skill.id,
707
- name: skill.name,
708
- description: skill.description,
709
- category: skill.category,
710
- triggers: [] // SKILL_TRIGGERS disabled - LLM decides based on description
711
- });
712
- }
713
-
714
- return definitions;
715
- }
716
-
717
- /**
718
- * Execute Skill tool (for remote mode tool execution)
719
- * @param toolName - Tool name (skillId)
720
- * @param params - Tool parameters
721
- * @returns Execution result
722
- */
723
- async executeSkillTool(
724
- toolName: string,
725
- params: Record<string, any>
726
- ): Promise<{ success: boolean; result?: any; error?: string }> {
727
- // Check if skill exists in cache
728
- if (!this.skillCache.has(toolName)) {
729
- return { success: false, error: `Skill not found: ${toolName}` };
730
- }
731
-
732
- try {
733
- const result = await this.executeSkill({
734
- skillId: toolName,
735
- taskDescription: params.taskDescription || params.description || '',
736
- inputFile: params.inputFile,
737
- outputFile: params.outputFile,
738
- options: params.options || {}
739
- });
740
-
741
- return { success: result.success, result };
742
- } catch (error: any) {
743
- return { success: false, error: error.message };
744
- }
745
- }
746
-
747
- /**
748
- * Get all available Skill ID list
749
- * NOTE: SKILL_TRIGGERS disabled - return all skill IDs from cache
750
- */
751
- getAvailableSkillIds(): string[] {
752
- return Array.from(this.skillCache.keys());
753
- }
754
- }
755
-
756
- // ============================================================
757
- // Skill Executor Interface and Implementation
758
- // ============================================================
759
-
760
- interface SkillExecutor {
761
- execute(skill: SkillInfo, params: SkillExecutionParams): Promise<SkillExecutionResult>;
762
- }
763
-
764
- /**
765
- * Generic Skill Executor - Unified dynamic approach for all skills
766
- */
767
- class GenericSkillExecutor implements SkillExecutor {
768
- async execute(skill: SkillInfo, params: SkillExecutionParams): Promise<SkillExecutionResult> {
769
- const outputMessages: string[] = [];
770
- const files: string[] = [];
771
- const nextSteps: ExecutionStep[] = [];
772
-
773
- outputMessages.push(`## ${skill.name} Skill - Execution Guide\n`);
774
- outputMessages.push(`**Task**: ${params.taskDescription}\n`);
775
-
776
- try {
777
- // Generate task ID
778
- const taskId = params.taskId || `${skill.id}-${Date.now()}`;
779
-
780
- // Read complete skill documentation
781
- const skillPath = skill.skillsPath;
782
- const skillMdPath = path.join(skillPath, 'SKILL.md');
783
- files.push(skillMdPath);
784
-
785
- // Read SKILL.md content
786
- const skillContent = await fs.readFile(skillMdPath, 'utf-8');
787
-
788
- // Extract relevant content based on task type and generate execution steps
789
- const taskContent = await this.extractRelevantContent(skill, params, skillContent, nextSteps, taskId);
790
- outputMessages.push(taskContent);
791
-
792
- // Add input/output files to list if they exist
793
- if (params.inputFile) files.push(params.inputFile);
794
- if (params.outputFile) files.push(params.outputFile);
795
-
796
- return {
797
- success: true,
798
- output: outputMessages.join('\n'),
799
- files: files,
800
- nextSteps: nextSteps,
801
- requiresManualExecution: true
802
- };
803
- } catch (error: any) {
804
- return {
805
- success: false,
806
- error: error.message
807
- };
808
- }
809
- }
810
-
811
- /**
812
- * Extract relevant skill content dynamically
813
- */
814
- private async extractRelevantContent(
815
- skill: SkillInfo,
816
- params: SkillExecutionParams,
817
- fullContent: string,
818
- nextSteps: ExecutionStep[],
819
- taskId: string
820
- ): Promise<string> {
821
- const workspaceBase = getWorkspaceDescription();
822
- const taskWorkspace = `${workspaceBase}/${taskId}`;
823
-
824
- // Dynamically discover files in skill directory
825
- const skillPath = skill.skillsPath;
826
- let allFiles: string[] = [];
827
-
828
- try {
829
- const entries = await fs.readdir(skillPath, { withFileTypes: true });
830
- for (const entry of entries) {
831
- const fullPath = path.join(skillPath, entry.name);
832
- if (entry.isFile()) {
833
- allFiles.push(fullPath);
834
- } else if (entry.isDirectory()) {
835
- // Recursively list files in subdirectories (limited depth)
836
- const subEntries = await fs.readdir(fullPath, { withFileTypes: true });
837
- for (const subEntry of subEntries) {
838
- if (subEntry.isFile()) {
839
- allFiles.push(path.join(fullPath, subEntry.name));
840
- }
841
- }
842
- }
843
- }
844
- } catch {
845
- // Fallback to just SKILL.md if directory can't be read
846
- allFiles = [path.join(skillPath, 'SKILL.md')];
847
- }
848
-
849
- // Step 1: Read SKILL.md first
850
- const skillMdPathOnly = path.join(skillPath, 'SKILL.md');
851
- nextSteps.push({
852
- step: 1,
853
- action: 'Read SKILL.md to understand the skill workflow',
854
- description: `Read: ${skillMdPathOnly}`,
855
- reason: 'Understand the skill workflow and best practices from the main documentation'
856
- });
857
-
858
- // Step 2: Explore skill directory and read reference files if needed (optional)
859
- nextSteps.push({
860
- step: 2,
861
- action: 'Explore skill directory and read reference files (if needed)',
862
- description: `Explore: ${skillPath}`,
863
- reason: 'Discover available reference files and read them based on SKILL.md guidance'
864
- });
865
-
866
- nextSteps.push({
867
- step: 3,
868
- action: 'Analyze documentation, verify data/content completeness, and design approach',
869
- description: `For content creation: ensure all info/materials collected. For info retrieval: ensure all required data retrieved. Then design execution plan for: ${taskWorkspace}`,
870
- reason: 'Review requirements, verify data/content completeness, fill gaps if needed, then plan execution based on the documentation'
871
- });
872
-
873
- nextSteps.push({
874
- step: 4,
875
- action: 'Execute your plan',
876
- description: 'Create workspace, write code, run scripts, verify output',
877
- reason: 'Execute the task using your own understanding'
878
- });
879
-
880
- return `### Skill Execution\n\n` +
881
- `**Your task**: ${params.taskDescription}\n\n` +
882
- `**Step 1**: Read SKILL.md to understand the skill workflow\n` +
883
- ` - read_file: ${skillMdPathOnly}\n\n` +
884
- `**Step 2**: Explore skill directory and read reference files (if needed)\n` +
885
- ` - ListDirectory(path="${skillPath}")\n` +
886
- ` - read_file relevant .md and script files as needed\n\n` +
887
- `Then analyze the documentation and create your own execution plan.\n\n` +
888
- `**Workspace**: \`${taskWorkspace}\`\n\n` +
889
- `**⚠️ Windows Path Execution**: Use absolute paths, NOT \`cd && command\`:\n` +
890
- ` - ✅ Correct: \`node "${taskWorkspace}/script.js"\`\n` +
891
- ` - ❌ Wrong: \`cd "${taskWorkspace}" && node script.js\` (fails in PowerShell 5.1)\n` +
892
- ` - ✅ Correct: \`python "${taskWorkspace}/script.py"\`\n\n` +
893
- `**📦 Dependency Management**:\n` +
894
- ` - BashTool automatically sets NODE_PATH when executing, scripts can use require() directly\n` +
895
- ` - Correct: Bash(command="node script.js", cwd="${taskWorkspace}")\n` +
896
- ` - ❌ Wrong: cd "${taskWorkspace}" && node script.js (loses NODE_PATH!)\n` +
897
- ` - If script needs to run by user manually, pass NODE_PATH in command:\n` +
898
- ` Windows: set NODE_PATH=xAgent/node_modules/path && node script.js\n` +
899
- ` Linux/Mac: NODE_PATH=xAgent/node_modules/path node script.js\n\n` +
900
- `**🧹 Cleanup**: Delete all intermediate/temporary files when task completes:\n` +
901
- ` - Remove: all files generated during the task\n` +
902
- ` - Keep: Only the final output file (output.pptx/docx/xlsx/pdf)\n\n` +
903
- `**Instructions**: read_file the documentation, understand the API, and create your own execution plan.\n` +
904
- `**If you encounter issues**: Explain what went wrong and suggest a different approach.\n`;
905
- }
906
- }
907
- // ============================================================
908
- // ============================================================
909
-
910
- /**
911
- * Execute skill - LLM analyzes SKILL.md and generates its own steps
912
- * @param skill Skill to execute
913
- * @param params Execution parameters
914
- * @returns Execution result with guidance
915
- */
916
- export async function executeSkill(
917
- skill: SkillInfo,
918
- params: SkillExecutionParams
919
- ): Promise<SkillExecutionResult> {
920
- const executor = new GenericSkillExecutor();
921
- return executor.execute(skill, params);
922
- }
923
-
924
- // ============================================================
925
- // Singleton Instance and Exports
926
- // ============================================================
927
-
928
- let skillInvokerInstance: SkillInvoker | null = null;
929
-
930
- export function getSkillInvoker(): SkillInvoker {
931
- if (!skillInvokerInstance) {
932
- skillInvokerInstance = new SkillInvoker();
933
- }
934
- return skillInvokerInstance;
935
- }
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { getSkillLoader, SkillInfo, SkillLoader } from './skill-loader.js';
5
+ import { getToolRegistry } from './tools.js';
6
+ import { ExecutionMode, Tool } from './types.js';
7
+ import { getConfigManager } from './config.js';
8
+
9
+ // Re-export SkillInfo for other modules
10
+ export type { SkillInfo };
11
+
12
+ /**
13
+ * Track skill execution history for tracking failures
14
+ */
15
+ export class SkillExecutionHistory {
16
+ private history: Map<string, number> = new Map();
17
+
18
+ /**
19
+ * Get failure count for a task
20
+ */
21
+ getFailureCount(taskKey: string): number {
22
+ return this.history.get(taskKey) || 0;
23
+ }
24
+
25
+ /**
26
+ * Increment failure count for a task
27
+ */
28
+ incrementFailure(taskKey: string): number {
29
+ const count = this.getFailureCount(taskKey) + 1;
30
+ this.history.set(taskKey, count);
31
+ return count;
32
+ }
33
+
34
+ /**
35
+ * Reset failure count for a task (e.g., after success)
36
+ */
37
+ reset(taskKey: string): void {
38
+ this.history.delete(taskKey);
39
+ }
40
+
41
+ /**
42
+ * Check if threshold reached
43
+ */
44
+ shouldUseFallback(taskKey: string, threshold: number = 2): boolean {
45
+ return this.getFailureCount(taskKey) >= threshold;
46
+ }
47
+ }
48
+
49
+ // Singleton execution history
50
+ const executionHistory = new SkillExecutionHistory();
51
+
52
+ export function getExecutionHistory(): SkillExecutionHistory {
53
+ return executionHistory;
54
+ }
55
+
56
+ export interface SkillExecutionParams {
57
+ skillId: string;
58
+ taskDescription: string;
59
+ inputFile?: string;
60
+ outputFile?: string;
61
+ options?: Record<string, any>;
62
+ /** Task ID for workspace directory naming */
63
+ taskId?: string;
64
+ }
65
+
66
+ /**
67
+ * Execution step interface - tells Agent what to do next
68
+ */
69
+ export interface ExecutionStep {
70
+ step: number;
71
+ action: string;
72
+ description: string;
73
+ command?: string;
74
+ file?: string;
75
+ reason: string;
76
+ }
77
+
78
+ /**
79
+ * Skill execution result - contains guidance and next actions
80
+ */
81
+ export interface SkillExecutionResult {
82
+ success: boolean;
83
+ output?: string;
84
+ error?: string;
85
+ files?: string[];
86
+ /** Tells Agent what to do next */
87
+ nextSteps?: ExecutionStep[];
88
+ /** Skill type for determining if manual execution is needed */
89
+ requiresManualExecution?: boolean;
90
+ /** Workspace directory used, for cleanup */
91
+ workspaceDir?: string;
92
+ /** Files to preserve (relative paths), skipped during cleanup */
93
+ preserveFiles?: string[];
94
+ /** Skill directory path - for dependency management and file operations */
95
+ skillPath?: string;
96
+ }
97
+
98
+ export interface SkillMatcherResult {
99
+ skill: SkillInfo;
100
+ confidence: number;
101
+ matchedKeywords: string[];
102
+ category: string;
103
+ }
104
+
105
+ // ============================================================
106
+ // Workspace Utility Functions
107
+ // ============================================================
108
+
109
+ /**
110
+ * Get workspace directory path
111
+ * @param taskId Task ID for creating unique workspace directory
112
+ * @returns Absolute path to workspace directory
113
+ */
114
+ export function getWorkspaceDir(taskId: string): string {
115
+ // Try to get from config first
116
+ try {
117
+ const configManager = getConfigManager();
118
+ const config = configManager.getSettings?.();
119
+ if (config?.workspacePath) {
120
+ return path.join(config.workspacePath, taskId);
121
+ }
122
+ } catch {
123
+ // Config not available, use default
124
+ }
125
+
126
+ // Default to ~/.xagent/workspace
127
+ return path.join(os.homedir(), '.xagent', 'workspace', taskId);
128
+ }
129
+
130
+ /**
131
+ * Get base workspace directory (without task-id)
132
+ */
133
+ export function getBaseWorkspaceDir(): string {
134
+ try {
135
+ const configManager = getConfigManager();
136
+ const config = configManager.getSettings?.();
137
+ if (config?.workspacePath) {
138
+ return config.workspacePath;
139
+ }
140
+ } catch {
141
+ // Config not available, use default
142
+ }
143
+
144
+ return path.join(os.homedir(), '.xagent', 'workspace');
145
+ }
146
+
147
+ /**
148
+ * Get workspace directory description for AI
149
+ * Returns the actual workspace path from config, or default path
150
+ */
151
+ export function getWorkspaceDescription(): string {
152
+ try {
153
+ const configManager = getConfigManager();
154
+ const config = configManager.getSettings?.();
155
+ if (config?.workspacePath) {
156
+ return config.workspacePath;
157
+ }
158
+ } catch {
159
+ // Config not available, use default
160
+ }
161
+
162
+ return path.join(os.homedir(), '.xagent', 'workspace');
163
+ }
164
+
165
+ /**
166
+ * Ensure workspace directory exists
167
+ * @param workspaceDir Workspace directory path
168
+ */
169
+ export async function ensureWorkspaceDir(workspaceDir: string): Promise<void> {
170
+ await fs.mkdir(workspaceDir, { recursive: true });
171
+ }
172
+
173
+ /**
174
+ * Clean up workspace directory
175
+ * @param workspaceDir Workspace directory path
176
+ * @param preserveFiles Files to preserve (relative paths)
177
+ */
178
+ export async function cleanupWorkspace(workspaceDir: string, preserveFiles: string[] = []): Promise<void> {
179
+ try {
180
+ const entries = await fs.readdir(workspaceDir, { withFileTypes: true });
181
+
182
+ for (const entry of entries) {
183
+ const fullPath = path.join(workspaceDir, entry.name);
184
+
185
+ // Skip files to preserve
186
+ if (preserveFiles.includes(entry.name)) {
187
+ continue;
188
+ }
189
+
190
+ if (entry.isDirectory()) {
191
+ // Recursively delete subdirectories
192
+ await fs.rm(fullPath, { recursive: true, force: true });
193
+ } else {
194
+ // Delete files
195
+ await fs.unlink(fullPath);
196
+ }
197
+ }
198
+ } catch (error: any) {
199
+ if (error.code !== 'ENOENT') {
200
+ console.warn(`Workspace cleanup failed: ${error.message}`);
201
+ }
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Determine if workspace should be auto-cleaned based on ExecutionMode
207
+ * @param executionMode Execution mode
208
+ * @returns Whether auto-cleanup should happen
209
+ */
210
+ export function shouldAutoCleanup(executionMode: ExecutionMode): boolean {
211
+ // YOLO mode: fully automatic, clean up directly
212
+ if (executionMode === ExecutionMode.YOLO) {
213
+ return true;
214
+ }
215
+ // Other modes require user confirmation
216
+ return false;
217
+ }
218
+
219
+ /**
220
+ * Generate cleanup prompt message
221
+ * @param workspaceDir Workspace directory path
222
+ */
223
+ export async function getCleanupInfo(workspaceDir: string): Promise<{ files: string[]; totalSize: string }> {
224
+ try {
225
+ const entries = await fs.readdir(workspaceDir, { withFileTypes: true });
226
+ const files: string[] = [];
227
+
228
+ for (const entry of entries) {
229
+ files.push(entry.name);
230
+ }
231
+
232
+ // Calculate total size
233
+ let totalSize = 0;
234
+ for (const entry of entries) {
235
+ if (entry.isFile()) {
236
+ const stats = await fs.stat(path.join(workspaceDir, entry.name));
237
+ totalSize += stats.size;
238
+ }
239
+ }
240
+
241
+ const formatSize = (bytes: number): string => {
242
+ if (bytes < 1024) return `${bytes} B`;
243
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;
244
+ return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
245
+ };
246
+
247
+ return { files, totalSize: formatSize(totalSize) };
248
+ } catch {
249
+ return { files: [], totalSize: '0 B' };
250
+ }
251
+ }
252
+
253
+ // ============================================================
254
+ // Shared Content Extraction Utilities
255
+ // ============================================================
256
+
257
+ /**
258
+ * Remove Markdown formatting (bold, italic, etc.)
259
+ */
260
+ export function stripMarkdown(text: string): string {
261
+ return text
262
+ .replace(/\*\*(.+?)\*\*/g, '$1') // Remove bold **
263
+ .replace(/\*(.+?)\*/g, '$1') // Remove italic *
264
+ .replace(/`(.+?)`/g, '$1') // Remove inline code `
265
+ .trim();
266
+ }
267
+
268
+ /**
269
+ * Extract content related to keywords (for SKILL.md content matching)
270
+ * @param content SKILL.md full content
271
+ * @param keywords Keyword list
272
+ * @param maxLength Maximum return length
273
+ * @returns Extracted relevant content
274
+ */
275
+ export function extractContent(content: string, keywords: string[], maxLength: number = 5000): string {
276
+ const lines = content.split('\n');
277
+ const relevantLines: string[] = [];
278
+ let inRelevantSection = false;
279
+ let sectionDepth = 0;
280
+ let found = false;
281
+
282
+ for (let i = 0; i < lines.length; i++) {
283
+ const line = lines[i];
284
+
285
+ // Detect headings
286
+ if (line.match(/^#{1,6}\s/)) {
287
+ const strippedLine = stripMarkdown(line);
288
+ const lowerLine = strippedLine.toLowerCase();
289
+
290
+ // Check if contains keywords
291
+ const hasKeyword = keywords.some(kw => lowerLine.includes(kw.toLowerCase()));
292
+
293
+ if (hasKeyword) {
294
+ inRelevantSection = true;
295
+ found = true;
296
+ sectionDepth = line.match(/^(#+)/)?.[1].length || 1;
297
+ } else if (inRelevantSection) {
298
+ // Check if same level or higher heading (end current section)
299
+ const currentDepth = line.match(/^(#+)/)?.[1].length || 1;
300
+ if (currentDepth <= sectionDepth) {
301
+ inRelevantSection = false;
302
+ }
303
+ }
304
+ }
305
+
306
+ if (inRelevantSection || found) {
307
+ relevantLines.push(line);
308
+ }
309
+
310
+ // Limit content length
311
+ if (relevantLines.join('\n').length > maxLength) {
312
+ relevantLines.push('\n...(content truncated for brevity)...');
313
+ break;
314
+ }
315
+ }
316
+
317
+ if (relevantLines.length > 0) {
318
+ return relevantLines.join('\n').trim();
319
+ }
320
+
321
+ // If still not found, return first 100 lines
322
+ return lines.slice(0, 100).join('\n').trim() + '\n\n...(See SKILL.md for full instructions)';
323
+ }
324
+
325
+ /**
326
+ * Read SKILL.md and extract relevant content based on task
327
+ */
328
+ export async function readSkillContent(skillPath: string, keywords: string[], maxLength: number = 5000): Promise<string> {
329
+ const skillMdPath = path.join(skillPath, 'SKILL.md');
330
+ const content = await fs.readFile(skillMdPath, 'utf-8');
331
+ return extractContent(content, keywords, maxLength);
332
+ }
333
+
334
+ // ============================================================
335
+ // SKILL Trigger Keywords Mapping
336
+ // ============================================================
337
+
338
+ // NOTE: SKILL_TRIGGERS is disabled for experiment purposes.
339
+ // Let the LLM decide which skill to use based on system prompt information.
340
+
341
+ // interface SkillTrigger {
342
+ // skillId: string;
343
+ // keywords: string[];
344
+ // category: string;
345
+ // }
346
+
347
+ // export const SKILL_TRIGGERS: Record<string, SkillTrigger> = {
348
+ // docx: {
349
+ // skillId: 'docx',
350
+ // keywords: [
351
+ // 'word document', 'docx', 'microsoft word', 'create word', 'edit word',
352
+ // 'create .docx', '.docx file', 'word file', 'document creation',
353
+ // 'word editing', 'tracked changes', 'comments'
354
+ // ],
355
+ // category: 'Document Processing'
356
+ // },
357
+ // pdf: {
358
+ // skillId: 'pdf',
359
+ // keywords: [
360
+ // 'pdf', 'create pdf', 'edit pdf', 'pdf document', 'pdf file',
361
+ // 'extract pdf', 'merge pdf', 'split pdf', 'pdf form', 'manipulate pdf'
362
+ // ],
363
+ // category: 'Document Processing'
364
+ // },
365
+ // pptx: {
366
+ // skillId: 'pptx',
367
+ // keywords: [
368
+ // 'powerpoint', 'ppt', 'pptx', 'presentation', 'slide',
369
+ // 'create presentation', 'edit powerpoint', 'create slides',
370
+ // 'powerpoint file', 'presentation file'
371
+ // ],
372
+ // category: 'Document Processing'
373
+ // },
374
+ // xlsx: {
375
+ // skillId: 'xlsx',
376
+ // keywords: [
377
+ // 'excel', 'spreadsheet', 'xlsx', 'create excel', 'edit spreadsheet',
378
+ // 'excel file', 'spreadsheet file', 'formulas', 'data analysis'
379
+ // ],
380
+ // category: 'Spreadsheet & Data'
381
+ // },
382
+ // frontend_design: {
383
+ // skillId: 'frontend-design',
384
+ // keywords: [
385
+ // 'web page', 'website', 'web app', 'frontend', 'ui', 'user interface',
386
+ // 'create website', 'build website', 'web component', 'html css',
387
+ // 'landing page', 'dashboard', 'react', 'vue', 'web interface'
388
+ // ],
389
+ // category: 'Frontend & Web Development'
390
+ // },
391
+ // web_artifacts_builder: {
392
+ // skillId: 'web-artifacts-builder',
393
+ // keywords: [
394
+ // 'complex react', 'react artifact', 'stateful artifact', 'routing',
395
+ // 'web artifact', 'interactive artifact', 'web-based tool'
396
+ // ],
397
+ // category: 'Frontend & Web Development'
398
+ // },
399
+ // webapp_testing: {
400
+ // skillId: 'webapp-testing',
401
+ // keywords: [
402
+ // 'test web', 'web testing', 'browser test', 'playwright', 'e2e test',
403
+ // 'frontend test', 'capture screenshot', 'verify web'
404
+ // ],
405
+ // category: 'Frontend & Web Development'
406
+ // },
407
+ // canvas_design: {
408
+ // skillId: 'canvas-design',
409
+ // keywords: [
410
+ // 'poster', 'artwork', 'visual art', 'canvas', 'design art',
411
+ // 'create poster', 'create artwork', 'visual design', 'graphic art'
412
+ // ],
413
+ // category: 'Visual & Creative Design'
414
+ // },
415
+ // algorithmic_art: {
416
+ // skillId: 'algorithmic-art',
417
+ // keywords: [
418
+ // 'generative art', 'algorithmic art', 'p5.js', 'particle system',
419
+ // 'flow field', 'creative coding', 'code art'
420
+ // ],
421
+ // category: 'Visual & Creative Design'
422
+ // },
423
+ // theme_factory: {
424
+ // skillId: 'theme-factory',
425
+ // keywords: [
426
+ // 'theme', 'color scheme', 'font theme', 'styling theme',
427
+ // 'consistent theme', 'apply theme', 'theme colors'
428
+ // ],
429
+ // category: 'Visual & Creative Design'
430
+ // },
431
+ // brand_guidelines: {
432
+ // skillId: 'brand-guidelines',
433
+ // keywords: [
434
+ // 'brand colors', 'brand guidelines', 'anthropic brand',
435
+ // 'official brand', 'brand styling'
436
+ // ],
437
+ // category: 'Visual & Creative Design'
438
+ // },
439
+ // slack_gif_creator: {
440
+ // skillId: 'slack-gif-creator',
441
+ // keywords: [
442
+ // 'slack gif', 'animated gif', 'gif for slack', 'slack animation'
443
+ // ],
444
+ // category: 'Visual & Creative Design'
445
+ // },
446
+ // mcp_builder: {
447
+ // skillId: 'mcp-builder',
448
+ // keywords: [
449
+ // 'mcp server', 'model context protocol', 'create mcp',
450
+ // 'mcp integration', 'external api integration'
451
+ // ],
452
+ // category: 'Development & Integration'
453
+ // },
454
+ // skill_creator: {
455
+ // skillId: 'skill-creator',
456
+ // keywords: [
457
+ // 'create skill', 'new skill', 'skill development',
458
+ // 'extend capabilities', 'custom skill'
459
+ // ],
460
+ // category: 'Development & Integration'
461
+ // },
462
+ // doc_coauthoring: {
463
+ // skillId: 'doc-coauthoring',
464
+ // keywords: [
465
+ // 'documentation', 'technical docs', 'write documentation',
466
+ // 'coauthor', 'doc writing', 'technical writing'
467
+ // ],
468
+ // category: 'Communication & Documentation'
469
+ // }
470
+ // };
471
+
472
+ // ============================================================
473
+ // SkillInvoker Main Class
474
+ // ============================================================
475
+
476
+ export class SkillInvoker {
477
+ private skillLoader: SkillLoader;
478
+ private initialized: boolean = false;
479
+ private skillCache: Map<string, SkillInfo> = new Map(); // Stores metadata only
480
+ // private skillContentCache: Map<string, string> = new Map(); // Stores full SKILL.md content - UNUSED
481
+
482
+ constructor(skillLoader?: SkillLoader) {
483
+ this.skillLoader = skillLoader || getSkillLoader();
484
+ }
485
+
486
+ async initialize(): Promise<void> {
487
+ if (this.initialized) return;
488
+
489
+ // Use discoverSkills to only discover directories without loading full content
490
+ const skillIds = await this.skillLoader.discoverSkills();
491
+
492
+ // Create minimal SkillInfo objects with metadata only
493
+ for (const skillId of skillIds) {
494
+ const skillPath = this.skillLoader.getSkillDirectory?.(skillId) || '';
495
+ const skillInfo: SkillInfo = {
496
+ id: skillId,
497
+ name: skillId,
498
+ description: '', // Will be loaded lazily
499
+ license: 'Unknown',
500
+ version: '1.0.0',
501
+ author: 'Anonymous',
502
+ category: '',
503
+ markdown: '', // Full content loaded lazily
504
+ skillsPath: skillPath
505
+ };
506
+ this.skillCache.set(skillId, skillInfo);
507
+ }
508
+
509
+ this.initialized = true;
510
+ }
511
+
512
+ /**
513
+ * Load skill metadata (name, description, category) from SKILL.md frontmatter
514
+ * This is called lazily when skill details are needed
515
+ */
516
+ async loadSkillMetadata(skillId: string): Promise<void> {
517
+ const skill = this.skillCache.get(skillId);
518
+ if (!skill) return;
519
+
520
+ // Check if metadata already loaded
521
+ if (skill.description && skill.category) return;
522
+
523
+ const skillPath = skill.skillsPath;
524
+ const skillMdPath = path.join(skillPath, 'SKILL.md');
525
+
526
+ try {
527
+ const content = await fs.readFile(skillMdPath, 'utf-8');
528
+ const parsed = this.skillLoader.parseSkillMarkdown(content);
529
+
530
+ skill.name = parsed.name || skillId;
531
+ skill.description = parsed.description || '';
532
+ skill.license = parsed.license || 'Unknown';
533
+ skill.version = parsed.version || '1.0.0';
534
+ skill.author = parsed.author || 'Anonymous';
535
+
536
+ // Extract category from path
537
+ const pathParts = skillPath.split(path.sep);
538
+ const skillsIndex = pathParts.findIndex(p => p === 'skills');
539
+ if (skillsIndex >= 0 && pathParts.length > skillsIndex + 1) {
540
+ skill.category = pathParts[skillsIndex + 1];
541
+ }
542
+
543
+ skill.markdown = content; // Now we have the full content
544
+ // this.skillContentCache.set(skillId, content); // UNUSED
545
+ } catch (error) {
546
+ console.warn(`[SkillInvoker] Failed to load metadata for skill ${skillId}:`, error);
547
+ }
548
+ }
549
+
550
+ /**
551
+ * Get list of all available skills (with metadata)
552
+ */
553
+ async listAvailableSkills(): Promise<SkillInfo[]> {
554
+ await this.initialize();
555
+
556
+ // Load metadata for all skills if not already loaded
557
+ for (const skillId of this.skillCache.keys()) {
558
+ await this.loadSkillMetadata(skillId);
559
+ }
560
+
561
+ return Array.from(this.skillCache.values());
562
+ }
563
+
564
+ /**
565
+ * Reload all skills (e.g., after adding/removing a skill via CLI)
566
+ * Clears the cache and re-discovers all skills
567
+ */
568
+ async reload(): Promise<void> {
569
+ // Reset initialization state to allow re-discovery
570
+ this.initialized = false;
571
+ this.skillCache.clear();
572
+
573
+ // Re-initialize
574
+ await this.initialize();
575
+ }
576
+
577
+ /**
578
+ * Match the most relevant skill based on user input
579
+ * NOTE: SKILL_TRIGGERS disabled. Let LLM decide based on system prompt.
580
+ * Returns null to indicate no explicit match - LLM should use its own judgment.
581
+ */
582
+ async matchSkill(userInput: string): Promise<SkillMatcherResult | null> {
583
+ // SKILL_TRIGGERS is disabled for experiment purposes.
584
+ // The LLM should decide which skill to use based on system prompt information.
585
+ return null;
586
+ }
587
+
588
+ /**
589
+ * Get skill details
590
+ */
591
+ async getSkillDetails(skillId: string): Promise<SkillInfo | null> {
592
+ await this.initialize();
593
+ return this.skillLoader.getSkill(skillId) || null;
594
+ }
595
+
596
+ /**
597
+ * Execute skill
598
+ */
599
+ async executeSkill(params: SkillExecutionParams): Promise<SkillExecutionResult> {
600
+ // Ensure initialized
601
+ await this.initialize();
602
+
603
+ // Load skill metadata if not already loaded
604
+ await this.loadSkillMetadata(params.skillId);
605
+
606
+ const skill = this.skillCache.get(params.skillId);
607
+
608
+ if (!skill) {
609
+ return {
610
+ success: false,
611
+ error: `Skill not found: ${params.skillId}`
612
+ };
613
+ }
614
+
615
+ // Generate task ID (if not provided)
616
+ const taskId = params.taskId || `${params.skillId}-${Date.now()}`;
617
+
618
+ try {
619
+ // Execute based on skillId
620
+ const executor = this.getSkillExecutor(skill.id);
621
+ const result = await executor.execute(skill, { ...params, taskId });
622
+
623
+ // Add skillPath and workspaceDir to result (delay creation until actually needed)
624
+ if (result.success) {
625
+ // Get skillPath directly from skillDirectories (more reliable)
626
+ result.skillPath = this.skillLoader.getSkillDirectory?.(params.skillId) || skill.skillsPath || '';
627
+ if (result.nextSteps && result.nextSteps.length > 0) {
628
+ result.workspaceDir = getWorkspaceDir(taskId);
629
+ // Don't pre-create workspace - only create when actually used by LLM
630
+ }
631
+ }
632
+
633
+ return result;
634
+ } catch (error: any) {
635
+ return {
636
+ success: false,
637
+ error: error.message
638
+ };
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Clean up workspace based on execution result
644
+ * @param result Skill execution result
645
+ * @param executionMode Execution mode
646
+ * @returns Whether cleanup was performed
647
+ */
648
+ async cleanupAfterExecution(result: SkillExecutionResult, executionMode: ExecutionMode): Promise<boolean> {
649
+ if (!result.workspaceDir) {
650
+ return false;
651
+ }
652
+
653
+ // YOLO mode: auto cleanup
654
+ if (executionMode === ExecutionMode.YOLO) {
655
+ await cleanupWorkspace(result.workspaceDir, result.preserveFiles || []);
656
+ return true;
657
+ }
658
+
659
+ // Other modes: don't auto cleanup, let user decide
660
+ return false;
661
+ }
662
+
663
+ /**
664
+ * Get cleanup prompt (for asking user)
665
+ */
666
+ async getCleanupPrompt(result: SkillExecutionResult): Promise<string | null> {
667
+ if (!result.workspaceDir) {
668
+ return null;
669
+ }
670
+
671
+ const info = await getCleanupInfo(result.workspaceDir);
672
+ if (info.files.length === 0) {
673
+ return null;
674
+ }
675
+
676
+ return `Task completed! Workspace directory contains the following files:\n` +
677
+ `📁 ${result.workspaceDir}\n` +
678
+ `Files: ${info.files.join(', ')}\n` +
679
+ `Size: ${info.totalSize}\n\n` +
680
+ `Do you want to clean up these temporary files?`;
681
+ }
682
+
683
+ /**
684
+ * Get executor for skill
685
+ * Unified dynamic approach - all skills use GenericSkillExecutor
686
+ */
687
+ private getSkillExecutor(skillId: string): SkillExecutor {
688
+ return new GenericSkillExecutor();
689
+ }
690
+
691
+ // ============================================================================
692
+ // Remote Mode Tool Support Methods
693
+ // ============================================================================
694
+
695
+ /**
696
+ * Check if it's a Skill tool
697
+ * Used for remote mode tool execution
698
+ */
699
+ isSkillTool(toolName: string): boolean {
700
+ // Check if it's a skill ID in cache
701
+ return this.skillCache.has(toolName);
702
+ }
703
+
704
+ /**
705
+ * Get all Skill definitions (for syncing to remote server)
706
+ * NOTE: triggers field is empty since SKILL_TRIGGERS is disabled
707
+ */
708
+ getAllSkillDefinitions(): Array<{
709
+ id: string;
710
+ name: string;
711
+ description: string;
712
+ category: string;
713
+ triggers: string[];
714
+ }> {
715
+ const definitions: Array<{
716
+ id: string;
717
+ name: string;
718
+ description: string;
719
+ category: string;
720
+ triggers: string[];
721
+ }> = [];
722
+
723
+ for (const skill of this.skillCache.values()) {
724
+ definitions.push({
725
+ id: skill.id,
726
+ name: skill.name,
727
+ description: skill.description,
728
+ category: skill.category,
729
+ triggers: [] // SKILL_TRIGGERS disabled - LLM decides based on description
730
+ });
731
+ }
732
+
733
+ return definitions;
734
+ }
735
+
736
+ /**
737
+ * Execute Skill tool (for remote mode tool execution)
738
+ * @param toolName - Tool name (skillId)
739
+ * @param params - Tool parameters
740
+ * @returns Execution result
741
+ */
742
+ async executeSkillTool(
743
+ toolName: string,
744
+ params: Record<string, any>
745
+ ): Promise<{ success: boolean; result?: any; error?: string }> {
746
+ // Check if skill exists in cache
747
+ if (!this.skillCache.has(toolName)) {
748
+ return { success: false, error: `Skill not found: ${toolName}` };
749
+ }
750
+
751
+ try {
752
+ const result = await this.executeSkill({
753
+ skillId: toolName,
754
+ taskDescription: params.taskDescription || params.description || '',
755
+ inputFile: params.inputFile,
756
+ outputFile: params.outputFile,
757
+ options: params.options || {}
758
+ });
759
+
760
+ return { success: result.success, result };
761
+ } catch (error: any) {
762
+ return { success: false, error: error.message };
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Get all available Skill ID list
768
+ * NOTE: SKILL_TRIGGERS disabled - return all skill IDs from cache
769
+ */
770
+ getAvailableSkillIds(): string[] {
771
+ return Array.from(this.skillCache.keys());
772
+ }
773
+ }
774
+
775
+ // ============================================================
776
+ // Skill Executor Interface and Implementation
777
+ // ============================================================
778
+
779
+ interface SkillExecutor {
780
+ execute(skill: SkillInfo, params: SkillExecutionParams): Promise<SkillExecutionResult>;
781
+ }
782
+
783
+ /**
784
+ * Generic Skill Executor - Unified dynamic approach for all skills
785
+ */
786
+ class GenericSkillExecutor implements SkillExecutor {
787
+ async execute(skill: SkillInfo, params: SkillExecutionParams): Promise<SkillExecutionResult> {
788
+ const outputMessages: string[] = [];
789
+ const files: string[] = [];
790
+ const nextSteps: ExecutionStep[] = [];
791
+
792
+ outputMessages.push(`## ${skill.name} Skill - Execution Guide\n`);
793
+ outputMessages.push(`**Task**: ${params.taskDescription}\n`);
794
+
795
+ try {
796
+ // Generate task ID
797
+ const taskId = params.taskId || `${skill.id}-${Date.now()}`;
798
+
799
+ // Read complete skill documentation
800
+ const skillPath = skill.skillsPath;
801
+ const skillMdPath = path.join(skillPath, 'SKILL.md');
802
+ files.push(skillMdPath);
803
+
804
+ // Read SKILL.md content
805
+ const skillContent = await fs.readFile(skillMdPath, 'utf-8');
806
+
807
+ // Extract relevant content based on task type and generate execution steps
808
+ const taskContent = await this.extractRelevantContent(skill, params, skillContent, nextSteps, taskId);
809
+ outputMessages.push(taskContent);
810
+
811
+ // Add input/output files to list if they exist
812
+ if (params.inputFile) files.push(params.inputFile);
813
+ if (params.outputFile) files.push(params.outputFile);
814
+
815
+ return {
816
+ success: true,
817
+ output: outputMessages.join('\n'),
818
+ files: files,
819
+ nextSteps: nextSteps,
820
+ requiresManualExecution: true
821
+ };
822
+ } catch (error: any) {
823
+ return {
824
+ success: false,
825
+ error: error.message
826
+ };
827
+ }
828
+ }
829
+
830
+ /**
831
+ * Extract relevant skill content dynamically
832
+ */
833
+ private async extractRelevantContent(
834
+ skill: SkillInfo,
835
+ params: SkillExecutionParams,
836
+ fullContent: string,
837
+ nextSteps: ExecutionStep[],
838
+ taskId: string
839
+ ): Promise<string> {
840
+ const workspaceBase = getWorkspaceDescription();
841
+ const taskWorkspace = `${workspaceBase}/${taskId}`;
842
+
843
+ // Dynamically discover files in skill directory
844
+ const skillPath = skill.skillsPath;
845
+ let allFiles: string[] = [];
846
+
847
+ try {
848
+ const entries = await fs.readdir(skillPath, { withFileTypes: true });
849
+ for (const entry of entries) {
850
+ const fullPath = path.join(skillPath, entry.name);
851
+ if (entry.isFile()) {
852
+ allFiles.push(fullPath);
853
+ } else if (entry.isDirectory()) {
854
+ // Recursively list files in subdirectories (limited depth)
855
+ const subEntries = await fs.readdir(fullPath, { withFileTypes: true });
856
+ for (const subEntry of subEntries) {
857
+ if (subEntry.isFile()) {
858
+ allFiles.push(path.join(fullPath, subEntry.name));
859
+ }
860
+ }
861
+ }
862
+ }
863
+ } catch {
864
+ // Fallback to just SKILL.md if directory can't be read
865
+ allFiles = [path.join(skillPath, 'SKILL.md')];
866
+ }
867
+
868
+ // Step 1: Read SKILL.md first
869
+ const skillMdPathOnly = path.join(skillPath, 'SKILL.md');
870
+ nextSteps.push({
871
+ step: 1,
872
+ action: 'Read SKILL.md to understand the skill workflow',
873
+ description: `Read: ${skillMdPathOnly}`,
874
+ reason: 'Understand the skill workflow and best practices from the main documentation'
875
+ });
876
+
877
+ // Step 2: Explore skill directory and read reference files if needed (optional)
878
+ nextSteps.push({
879
+ step: 2,
880
+ action: 'Explore skill directory and read reference files (if needed)',
881
+ description: `Explore: ${skillPath}`,
882
+ reason: 'Discover available reference files and read them based on SKILL.md guidance'
883
+ });
884
+
885
+ nextSteps.push({
886
+ step: 3,
887
+ action: 'Analyze documentation, verify data/content completeness, and design approach',
888
+ description: `For content creation: ensure all info/materials collected. For info retrieval: ensure all required data retrieved. Then design execution plan for: ${taskWorkspace}`,
889
+ reason: 'Review requirements, verify data/content completeness, fill gaps if needed, then plan execution based on the documentation'
890
+ });
891
+
892
+ nextSteps.push({
893
+ step: 4,
894
+ action: 'Execute your plan',
895
+ description: 'Create workspace, write code, run scripts, verify output',
896
+ reason: 'Execute the task using your own understanding'
897
+ });
898
+
899
+ return `### Skill Execution\n\n` +
900
+ `**Your task**: ${params.taskDescription}\n\n` +
901
+ `**Step 1**: Read SKILL.md to understand the skill workflow\n` +
902
+ ` - read_file: ${skillMdPathOnly}\n\n` +
903
+ `**Step 2**: Explore skill directory and read reference files (if needed)\n` +
904
+ ` - ListDirectory(path="${skillPath}")\n` +
905
+ ` - read_file relevant .md and script files as needed\n\n` +
906
+ `Then analyze the documentation and create your own execution plan.\n\n` +
907
+ `**Workspace**: \`${taskWorkspace}\`\n\n` +
908
+ `**⚠️ Windows Path Execution**: Use absolute paths, NOT \`cd && command\`:\n` +
909
+ ` - ✅ Correct: \`node "${taskWorkspace}/script.js"\`\n` +
910
+ ` - ❌ Wrong: \`cd "${taskWorkspace}" && node script.js\` (fails in PowerShell 5.1)\n` +
911
+ ` - Correct: \`python "${taskWorkspace}/script.py"\`\n\n` +
912
+ `**📦 Dependency Management**:\n` +
913
+ ` - Use \`skillPath\` parameter to install dependencies to skill's node_modules (persists across invocations)\n` +
914
+ ` - Correct: Bash(command="npm install <package>", skillPath="${skillPath}")\n` +
915
+ ` - ✅ Correct: Bash(command="npm install", skillPath="${skillPath}")\n` +
916
+ ` - Dependencies are saved to: <userSkillsPath>/<skillName>/node_modules\n` +
917
+ ` - 💡 Tip: Install once, reuse forever - no need to reinstall on each call!\n` +
918
+ ` - After install, scripts can use require() directly with NODE_PATH auto-set\n` +
919
+ ` - NODE_PATH precedence: skill's node_modules > xAgent's node_modules\n` +
920
+ ` - Manual execution (Windows): set "NODE_PATH=${skillPath}/node_modules;<xAgentPath>/node_modules" && node script.js\n` +
921
+ ` - Manual execution (Linux/Mac): NODE_PATH=${skillPath}/node_modules:${process.cwd()}/node_modules node script.js\n` +
922
+ ` - ⚠️ If skillPath approach fails (module not found errors): Install directly in workspace\n` +
923
+ ` Priority: skill's node_modules > workspace's node_modules > xAgent's node_modules\n\n` +
924
+ `**🧹 Cleanup**: Delete all intermediate/temporary files when task completes:\n` +
925
+ ` - Remove: all files generated during the task\n` +
926
+ ` - Keep: Only the final output file (output.pptx/docx/xlsx/pdf or other file format required by user)\n` +
927
+ ` - ⚠️ If user needs to check results or make adjustments: RETAIN intermediate/temporary files for debugging\n\n` +
928
+ `**Instructions**: read_file the documentation, understand the API, and create your own execution plan.\n` +
929
+ `**If you encounter issues**: Explain what went wrong and suggest a different approach.\n`;
930
+ }
931
+ }
932
+ // ============================================================
933
+ // ============================================================
934
+
935
+ /**
936
+ * Execute skill - LLM analyzes SKILL.md and generates its own steps
937
+ * @param skill Skill to execute
938
+ * @param params Execution parameters
939
+ * @returns Execution result with guidance
940
+ */
941
+ export async function executeSkill(
942
+ skill: SkillInfo,
943
+ params: SkillExecutionParams
944
+ ): Promise<SkillExecutionResult> {
945
+ const executor = new GenericSkillExecutor();
946
+ return executor.execute(skill, params);
947
+ }
948
+
949
+ // ============================================================
950
+ // Singleton Instance and Exports
951
+ // ============================================================
952
+
953
+ let skillInvokerInstance: SkillInvoker | null = null;
954
+
955
+ export function getSkillInvoker(): SkillInvoker {
956
+ if (!skillInvokerInstance) {
957
+ skillInvokerInstance = new SkillInvoker();
958
+ }
959
+ return skillInvokerInstance;
960
+ }