@crewx/sdk 0.8.0-rc.72 → 0.8.0-rc.74

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 (548) hide show
  1. package/README.md +380 -818
  2. package/dist/adapter/context-builder.d.ts +35 -0
  3. package/dist/adapter/context-builder.js +87 -0
  4. package/dist/adapter/index.d.ts +5 -0
  5. package/dist/{core/remote → adapter}/index.js +3 -2
  6. package/dist/adapter/plugin-helper.d.ts +19 -0
  7. package/dist/adapter/plugin-helper.js +45 -0
  8. package/dist/adapter/scoped-store.d.ts +12 -0
  9. package/dist/adapter/scoped-store.js +43 -0
  10. package/dist/adapter/types.d.ts +264 -0
  11. package/dist/adapter/types.js +23 -0
  12. package/dist/agent/resolver.d.ts +18 -0
  13. package/dist/agent/resolver.js +46 -0
  14. package/dist/boxing/box-storage.interface.d.ts +12 -0
  15. package/dist/boxing/box-storage.interface.js +3 -0
  16. package/dist/boxing/box.service.d.ts +4 -0
  17. package/dist/boxing/box.service.js +5 -1
  18. package/dist/boxing/box.types.d.ts +4 -0
  19. package/dist/boxing/box.types.js +3 -0
  20. package/dist/boxing/context-builder.d.ts +6 -7
  21. package/dist/boxing/context-builder.js +3 -0
  22. package/dist/client/CrewxClient.d.ts +65 -0
  23. package/dist/client/CrewxClient.js +86 -0
  24. package/dist/client/index.d.ts +3 -0
  25. package/dist/client/index.js +6 -0
  26. package/dist/config/loader.browser.d.ts +14 -0
  27. package/dist/config/loader.browser.js +59 -0
  28. package/dist/config/loader.d.ts +19 -0
  29. package/dist/config/loader.js +95 -0
  30. package/dist/conversation/index.d.ts +5 -3
  31. package/dist/conversation/index.js +8 -3
  32. package/dist/conversation/sqlite-provider.d.ts +21 -0
  33. package/dist/conversation/sqlite-provider.js +178 -0
  34. package/dist/conversation/to-task-reader.d.ts +14 -0
  35. package/dist/conversation/to-task-reader.js +28 -0
  36. package/dist/conversation/to-template-messages.d.ts +15 -0
  37. package/dist/conversation/to-template-messages.js +34 -0
  38. package/dist/conversation/types.d.ts +101 -0
  39. package/dist/conversation/types.js +10 -0
  40. package/dist/esm/agent/resolver.js +41 -0
  41. package/dist/esm/boxing/box-storage.interface.js +5 -0
  42. package/dist/esm/boxing/box.service.js +69 -0
  43. package/dist/esm/boxing/box.types.js +5 -0
  44. package/dist/esm/boxing/context-builder.js +76 -0
  45. package/dist/esm/client/CrewxClient.js +82 -0
  46. package/dist/esm/client/index.js +2 -0
  47. package/dist/esm/config/loader.browser.js +54 -0
  48. package/dist/esm/config/loader.js +77 -0
  49. package/dist/esm/events/TypedEventEmitter.js +61 -0
  50. package/dist/esm/events/types.js +8 -0
  51. package/dist/esm/facade/Crewx.browser.js +310 -0
  52. package/dist/esm/facade/Crewx.js +941 -0
  53. package/dist/esm/hooks/define.js +10 -0
  54. package/dist/esm/hooks/dispatch.js +76 -0
  55. package/dist/esm/hooks/index.js +6 -0
  56. package/dist/esm/hooks/observer.js +56 -0
  57. package/dist/esm/hooks/plugin.js +12 -0
  58. package/dist/esm/hooks/types.js +9 -0
  59. package/dist/esm/index.browser.js +15 -0
  60. package/dist/esm/index.js +60 -0
  61. package/dist/esm/layout/loader.js +268 -0
  62. package/dist/esm/layout/props-validator.js +297 -0
  63. package/dist/esm/layout/renderer.js +180 -0
  64. package/dist/esm/layout/types.js +31 -0
  65. package/dist/esm/parallel/agent-runtime.js +21 -0
  66. package/dist/esm/parallel/helpers.js +214 -0
  67. package/dist/esm/parallel/index.js +5 -0
  68. package/dist/esm/parallel/parallel-runner.js +221 -0
  69. package/dist/esm/parallel/types.js +5 -0
  70. package/dist/esm/parsers/agent-call.util.js +15 -0
  71. package/dist/esm/parsers/claude.parser.js +64 -0
  72. package/dist/esm/parsers/codex.parser.js +97 -0
  73. package/dist/esm/parsers/copilot.parser.js +63 -0
  74. package/dist/esm/parsers/gemini.parser.js +43 -0
  75. package/dist/esm/parsers/opencode.parser.js +73 -0
  76. package/dist/esm/parsers/router.js +53 -0
  77. package/dist/esm/platform/BrowserFsAdapter.js +80 -0
  78. package/dist/esm/platform/IFsAdapter.js +2 -0
  79. package/dist/esm/platform/NodeFsAdapter.js +34 -0
  80. package/dist/esm/plugin/plugin-provider.js +202 -0
  81. package/dist/esm/plugin/types.js +8 -0
  82. package/dist/esm/plugin.js +25 -0
  83. package/dist/esm/provider/bridge.browser.js +43 -0
  84. package/dist/esm/provider/bridge.js +373 -0
  85. package/dist/esm/provider/parse-usage.js +80 -0
  86. package/dist/esm/provider/register-api.js +21 -0
  87. package/dist/esm/provider/vercel-runtime.js +310 -0
  88. package/dist/esm/remote/index.js +10 -0
  89. package/dist/esm/remote/remote-agent-manager.js +194 -0
  90. package/dist/esm/remote/remote-provider.js +98 -0
  91. package/dist/esm/remote/remote-transport.js +79 -0
  92. package/dist/esm/remote/types.js +8 -0
  93. package/dist/esm/server/auth.js +31 -0
  94. package/dist/esm/server/handler.js +72 -0
  95. package/dist/esm/server/index.js +5 -0
  96. package/dist/esm/server/tool-adapter.js +92 -0
  97. package/dist/esm/template/engine.js +100 -0
  98. package/dist/esm/template/helpers/exec.browser.js +31 -0
  99. package/dist/esm/template/helpers/exec.js +220 -0
  100. package/dist/esm/template/helpers/fenced_code.js +17 -0
  101. package/dist/esm/template/helpers/include.js +20 -0
  102. package/dist/esm/template/helpers/p1p2.js +83 -0
  103. package/dist/esm/template/loader/DocumentLoader.js +124 -0
  104. package/dist/esm/template/types.js +5 -0
  105. package/dist/esm/tools/delegate.js +57 -0
  106. package/dist/esm/tools/index.js +5 -0
  107. package/dist/esm/tools/node/builtin.js +541 -0
  108. package/dist/esm/tools/node/index.js +54 -0
  109. package/dist/esm/types/index.js +27 -0
  110. package/dist/esm/types/task-log.types.js +5 -0
  111. package/dist/esm/utils/env-defaults.js +23 -0
  112. package/dist/esm/utils/glob-match.js +38 -0
  113. package/dist/esm/utils/id.js +46 -0
  114. package/dist/esm/utils/workspace.js +21 -0
  115. package/dist/events/TypedEventEmitter.d.ts +31 -0
  116. package/dist/events/TypedEventEmitter.js +65 -0
  117. package/dist/events/types.d.ts +139 -0
  118. package/dist/events/types.js +9 -0
  119. package/dist/facade/Crewx.browser.d.ts +73 -0
  120. package/dist/facade/Crewx.browser.js +314 -0
  121. package/dist/facade/Crewx.d.ts +267 -0
  122. package/dist/facade/Crewx.js +1299 -0
  123. package/dist/hooks/define.d.ts +10 -0
  124. package/dist/hooks/define.js +13 -0
  125. package/dist/hooks/dispatch.d.ts +61 -0
  126. package/dist/hooks/dispatch.js +147 -0
  127. package/dist/hooks/index.d.ts +13 -0
  128. package/dist/hooks/index.js +24 -0
  129. package/dist/hooks/observer.d.ts +20 -0
  130. package/dist/hooks/observer.js +60 -0
  131. package/dist/hooks/plugin.d.ts +19 -0
  132. package/dist/hooks/plugin.js +17 -0
  133. package/dist/hooks/tool-normalize.d.ts +29 -0
  134. package/dist/hooks/tool-normalize.js +110 -0
  135. package/dist/hooks/types.d.ts +79 -0
  136. package/dist/hooks/types.js +12 -0
  137. package/dist/hooks/yaml-plugin.d.ts +29 -0
  138. package/dist/hooks/yaml-plugin.js +356 -0
  139. package/dist/index.browser.d.ts +15 -0
  140. package/dist/index.browser.js +25 -0
  141. package/dist/index.d.ts +70 -58
  142. package/dist/index.js +144 -133
  143. package/dist/{services/layout-loader.service.d.ts → layout/loader.d.ts} +24 -4
  144. package/dist/{services/layout-loader.service.js → layout/loader.js} +103 -73
  145. package/dist/{services/props-validator.service.d.ts → layout/props-validator.d.ts} +7 -1
  146. package/dist/{services/props-validator.service.js → layout/props-validator.js} +28 -59
  147. package/dist/{services/layout-renderer.service.d.ts → layout/renderer.d.ts} +28 -14
  148. package/dist/layout/renderer.js +193 -0
  149. package/dist/{types/layout.types.d.ts → layout/types.d.ts} +47 -1
  150. package/dist/{types/layout.types.js → layout/types.js} +15 -1
  151. package/dist/parallel/agent-runtime.d.ts +31 -0
  152. package/dist/parallel/agent-runtime.js +25 -0
  153. package/dist/{core/parallel → parallel}/helpers.d.ts +2 -1
  154. package/dist/{core/parallel → parallel}/helpers.js +55 -88
  155. package/dist/parallel/index.d.ts +8 -0
  156. package/dist/{core/parallel → parallel}/index.js +5 -3
  157. package/dist/{core/parallel → parallel}/parallel-runner.d.ts +8 -1
  158. package/dist/{core/parallel → parallel}/parallel-runner.js +53 -57
  159. package/dist/parallel/types.d.ts +65 -0
  160. package/dist/parallel/types.js +6 -0
  161. package/dist/parsers/agent-call.util.d.ts +3 -0
  162. package/dist/parsers/agent-call.util.js +2 -0
  163. package/dist/parsers/api.parser.d.ts +10 -0
  164. package/dist/parsers/api.parser.js +26 -0
  165. package/dist/parsers/claude.parser.d.ts +8 -0
  166. package/dist/parsers/claude.parser.js +22 -1
  167. package/dist/parsers/codex.parser.d.ts +8 -0
  168. package/dist/parsers/codex.parser.js +11 -0
  169. package/dist/parsers/copilot.parser.d.ts +9 -0
  170. package/dist/parsers/copilot.parser.js +8 -0
  171. package/dist/parsers/gemini.parser.d.ts +10 -0
  172. package/dist/parsers/gemini.parser.js +10 -0
  173. package/dist/parsers/opencode.parser.d.ts +12 -0
  174. package/dist/parsers/opencode.parser.js +76 -0
  175. package/dist/parsers/router.d.ts +7 -0
  176. package/dist/parsers/router.js +56 -0
  177. package/dist/platform/BrowserFsAdapter.d.ts +37 -0
  178. package/dist/platform/BrowserFsAdapter.js +84 -0
  179. package/dist/platform/IFsAdapter.d.ts +29 -0
  180. package/dist/{core/remote/types.js → platform/IFsAdapter.js} +1 -1
  181. package/dist/platform/NodeFsAdapter.d.ts +16 -0
  182. package/dist/platform/NodeFsAdapter.js +38 -0
  183. package/dist/plugin/plugin-provider.d.ts +33 -0
  184. package/dist/plugin/plugin-provider.js +207 -0
  185. package/dist/plugin/types.d.ts +53 -0
  186. package/dist/plugin/types.js +9 -0
  187. package/dist/plugin.d.ts +33 -0
  188. package/dist/plugin.js +29 -0
  189. package/dist/plugins/conversation.d.ts +18 -0
  190. package/dist/plugins/conversation.js +59 -0
  191. package/dist/plugins/file-logger.d.ts +29 -0
  192. package/dist/plugins/file-logger.js +87 -0
  193. package/dist/plugins/index.d.ts +16 -0
  194. package/dist/plugins/index.js +19 -0
  195. package/dist/plugins/sqlite-tracing.d.ts +29 -0
  196. package/dist/plugins/sqlite-tracing.js +112 -0
  197. package/dist/provider/bridge.browser.d.ts +49 -0
  198. package/dist/provider/bridge.browser.js +49 -0
  199. package/dist/provider/bridge.d.ts +106 -0
  200. package/dist/provider/bridge.js +380 -0
  201. package/dist/provider/mastra-runtime.d.ts +45 -0
  202. package/dist/provider/mastra-runtime.js +208 -0
  203. package/dist/provider/parse-usage.d.ts +20 -0
  204. package/dist/provider/parse-usage.js +83 -0
  205. package/dist/provider/register-api.d.ts +14 -0
  206. package/dist/provider/register-api.js +24 -0
  207. package/dist/provider/vercel-runtime.d.ts +54 -0
  208. package/dist/provider/vercel-runtime.js +347 -0
  209. package/dist/remote/index.d.ts +13 -0
  210. package/dist/remote/index.js +32 -0
  211. package/dist/remote/remote-agent-manager.d.ts +54 -0
  212. package/dist/{core/remote → remote}/remote-agent-manager.js +100 -97
  213. package/dist/remote/remote-provider.d.ts +47 -0
  214. package/dist/remote/remote-provider.js +141 -0
  215. package/dist/remote/remote-transport.d.ts +32 -0
  216. package/dist/remote/remote-transport.js +83 -0
  217. package/dist/remote/types.d.ts +147 -0
  218. package/dist/remote/types.js +9 -0
  219. package/dist/server/auth.d.ts +21 -0
  220. package/dist/server/auth.js +35 -0
  221. package/dist/server/handler.d.ts +24 -0
  222. package/dist/server/handler.js +75 -0
  223. package/dist/server/index.d.ts +7 -0
  224. package/dist/server/index.js +9 -0
  225. package/dist/server/tool-adapter.d.ts +19 -0
  226. package/dist/server/tool-adapter.js +95 -0
  227. package/dist/template/engine.d.ts +28 -0
  228. package/dist/template/engine.js +137 -0
  229. package/dist/template/helpers/exec.browser.d.ts +22 -0
  230. package/dist/template/helpers/exec.browser.js +41 -0
  231. package/dist/template/helpers/exec.d.ts +60 -0
  232. package/dist/template/helpers/exec.js +230 -0
  233. package/dist/template/helpers/fenced_code.d.ts +22 -0
  234. package/dist/template/helpers/fenced_code.js +20 -0
  235. package/dist/template/helpers/format-conversation.d.ts +30 -0
  236. package/dist/template/helpers/format-conversation.js +53 -0
  237. package/dist/template/helpers/include.d.ts +16 -0
  238. package/dist/template/helpers/include.js +23 -0
  239. package/dist/template/helpers/p1p2.d.ts +37 -0
  240. package/dist/template/helpers/p1p2.js +90 -0
  241. package/dist/template/loader/DocumentLoader.d.ts +48 -0
  242. package/dist/template/loader/DocumentLoader.js +128 -0
  243. package/dist/template/types.d.ts +51 -0
  244. package/dist/template/types.js +6 -0
  245. package/dist/testing/index.d.ts +12 -0
  246. package/dist/testing/index.js +16 -0
  247. package/dist/testing/mock-audit.d.ts +10 -0
  248. package/dist/testing/mock-audit.js +13 -0
  249. package/dist/testing/mock-context.d.ts +27 -0
  250. package/dist/testing/mock-context.js +68 -0
  251. package/dist/testing/mock-logger.d.ts +15 -0
  252. package/dist/testing/mock-logger.js +27 -0
  253. package/dist/testing/mock-router.d.ts +16 -0
  254. package/dist/testing/mock-router.js +67 -0
  255. package/dist/testing/mock-storage.d.ts +9 -0
  256. package/dist/testing/mock-storage.js +21 -0
  257. package/dist/testing/mock-store.d.ts +3 -0
  258. package/dist/testing/mock-store.js +8 -0
  259. package/dist/tools/delegate.d.ts +10 -0
  260. package/dist/tools/delegate.js +60 -0
  261. package/dist/tools/index.d.ts +5 -12
  262. package/dist/tools/index.js +6 -37
  263. package/dist/tools/node/builtin.d.ts +23 -0
  264. package/dist/tools/node/builtin.js +547 -0
  265. package/dist/tools/node/index.d.ts +23 -0
  266. package/dist/tools/node/index.js +59 -0
  267. package/dist/types/index.d.ts +804 -6
  268. package/dist/types/index.js +29 -20
  269. package/dist/types/task-log.types.d.ts +4 -0
  270. package/dist/types/task-log.types.js +3 -0
  271. package/dist/utils/env-defaults.d.ts +18 -0
  272. package/dist/utils/env-defaults.js +27 -0
  273. package/dist/utils/glob-match.d.ts +18 -0
  274. package/dist/utils/glob-match.js +42 -0
  275. package/dist/{core → utils}/id.d.ts +15 -0
  276. package/dist/utils/id.js +50 -0
  277. package/dist/utils/timestamp.d.ts +2 -0
  278. package/dist/utils/timestamp.js +13 -0
  279. package/dist/{core → utils}/workspace.d.ts +4 -0
  280. package/dist/{core → utils}/workspace.js +3 -0
  281. package/package.json +67 -102
  282. package/src/schemas/hooks.schema.json +59 -0
  283. package/templates/agents/default.yaml +490 -0
  284. package/templates/agents/minimal.yaml +16 -0
  285. package/LICENSE +0 -201
  286. package/dist/adapters/MastraToolAdapter.d.ts +0 -9
  287. package/dist/adapters/MastraToolAdapter.js +0 -66
  288. package/dist/adapters/MastraToolAdapter.js.map +0 -1
  289. package/dist/api/index.d.ts +0 -2
  290. package/dist/api/index.js +0 -8
  291. package/dist/api/index.js.map +0 -1
  292. package/dist/boxing/box-storage.interface.js.map +0 -1
  293. package/dist/boxing/box.service.js.map +0 -1
  294. package/dist/boxing/box.types.js.map +0 -1
  295. package/dist/boxing/context-builder.js.map +0 -1
  296. package/dist/boxing/index.d.ts +0 -6
  297. package/dist/boxing/index.js +0 -11
  298. package/dist/boxing/index.js.map +0 -1
  299. package/dist/boxing/tokenizer.d.ts +0 -3
  300. package/dist/boxing/tokenizer.js +0 -11
  301. package/dist/boxing/tokenizer.js.map +0 -1
  302. package/dist/config/api-provider-parser.d.ts +0 -58
  303. package/dist/config/api-provider-parser.js +0 -212
  304. package/dist/config/api-provider-parser.js.map +0 -1
  305. package/dist/config/index.d.ts +0 -3
  306. package/dist/config/index.js +0 -20
  307. package/dist/config/index.js.map +0 -1
  308. package/dist/config/log.config.d.ts +0 -7
  309. package/dist/config/log.config.js +0 -20
  310. package/dist/config/log.config.js.map +0 -1
  311. package/dist/config/pricing.d.ts +0 -11
  312. package/dist/config/pricing.js +0 -53
  313. package/dist/config/pricing.js.map +0 -1
  314. package/dist/config/timeout.config.d.ts +0 -14
  315. package/dist/config/timeout.config.js +0 -34
  316. package/dist/config/timeout.config.js.map +0 -1
  317. package/dist/config/yaml-loader.d.ts +0 -8
  318. package/dist/config/yaml-loader.js +0 -155
  319. package/dist/config/yaml-loader.js.map +0 -1
  320. package/dist/constants/index.d.ts +0 -4
  321. package/dist/constants/index.js +0 -8
  322. package/dist/constants/index.js.map +0 -1
  323. package/dist/constants.d.ts +0 -1
  324. package/dist/constants.js +0 -18
  325. package/dist/constants.js.map +0 -1
  326. package/dist/conversation/conversation-config.d.ts +0 -9
  327. package/dist/conversation/conversation-config.js +0 -22
  328. package/dist/conversation/conversation-config.js.map +0 -1
  329. package/dist/conversation/conversation-history.interface.d.ts +0 -36
  330. package/dist/conversation/conversation-history.interface.js +0 -3
  331. package/dist/conversation/conversation-history.interface.js.map +0 -1
  332. package/dist/conversation/conversation-storage.service.d.ts +0 -16
  333. package/dist/conversation/conversation-storage.service.js +0 -213
  334. package/dist/conversation/conversation-storage.service.js.map +0 -1
  335. package/dist/conversation/index.js.map +0 -1
  336. package/dist/core/__tests__/id.test.d.ts +0 -1
  337. package/dist/core/__tests__/id.test.js +0 -115
  338. package/dist/core/__tests__/id.test.js.map +0 -1
  339. package/dist/core/agent/agent-factory.d.ts +0 -37
  340. package/dist/core/agent/agent-factory.js +0 -68
  341. package/dist/core/agent/agent-factory.js.map +0 -1
  342. package/dist/core/agent/agent-runtime.d.ts +0 -52
  343. package/dist/core/agent/agent-runtime.js +0 -206
  344. package/dist/core/agent/agent-runtime.js.map +0 -1
  345. package/dist/core/agent/event-bus.d.ts +0 -44
  346. package/dist/core/agent/event-bus.js +0 -43
  347. package/dist/core/agent/event-bus.js.map +0 -1
  348. package/dist/core/agent/index.d.ts +0 -3
  349. package/dist/core/agent/index.js +0 -13
  350. package/dist/core/agent/index.js.map +0 -1
  351. package/dist/core/env-defaults.d.ts +0 -1
  352. package/dist/core/env-defaults.js +0 -7
  353. package/dist/core/env-defaults.js.map +0 -1
  354. package/dist/core/id.js +0 -27
  355. package/dist/core/id.js.map +0 -1
  356. package/dist/core/parallel/helpers.js.map +0 -1
  357. package/dist/core/parallel/index.d.ts +0 -4
  358. package/dist/core/parallel/index.js.map +0 -1
  359. package/dist/core/parallel/parallel-runner.js.map +0 -1
  360. package/dist/core/parallel/types.d.ts +0 -41
  361. package/dist/core/parallel/types.js +0 -3
  362. package/dist/core/parallel/types.js.map +0 -1
  363. package/dist/core/providers/MastraAPIProvider.d.ts +0 -31
  364. package/dist/core/providers/MastraAPIProvider.js +0 -365
  365. package/dist/core/providers/MastraAPIProvider.js.map +0 -1
  366. package/dist/core/providers/ai-provider.interface.d.ts +0 -79
  367. package/dist/core/providers/ai-provider.interface.js +0 -23
  368. package/dist/core/providers/ai-provider.interface.js.map +0 -1
  369. package/dist/core/providers/base-ai.provider.d.ts +0 -84
  370. package/dist/core/providers/base-ai.provider.js +0 -1237
  371. package/dist/core/providers/base-ai.provider.js.map +0 -1
  372. package/dist/core/providers/base-ai.types.d.ts +0 -26
  373. package/dist/core/providers/base-ai.types.js +0 -3
  374. package/dist/core/providers/base-ai.types.js.map +0 -1
  375. package/dist/core/providers/claude.provider.d.ts +0 -19
  376. package/dist/core/providers/claude.provider.js +0 -170
  377. package/dist/core/providers/claude.provider.js.map +0 -1
  378. package/dist/core/providers/codex.provider.d.ts +0 -21
  379. package/dist/core/providers/codex.provider.js +0 -134
  380. package/dist/core/providers/codex.provider.js.map +0 -1
  381. package/dist/core/providers/copilot.provider.d.ts +0 -25
  382. package/dist/core/providers/copilot.provider.js +0 -146
  383. package/dist/core/providers/copilot.provider.js.map +0 -1
  384. package/dist/core/providers/dynamic-provider.factory.d.ts +0 -74
  385. package/dist/core/providers/dynamic-provider.factory.js +0 -645
  386. package/dist/core/providers/dynamic-provider.factory.js.map +0 -1
  387. package/dist/core/providers/gemini.provider.d.ts +0 -16
  388. package/dist/core/providers/gemini.provider.js +0 -101
  389. package/dist/core/providers/gemini.provider.js.map +0 -1
  390. package/dist/core/providers/index.d.ts +0 -8
  391. package/dist/core/providers/index.js +0 -20
  392. package/dist/core/providers/index.js.map +0 -1
  393. package/dist/core/providers/mock.provider.d.ts +0 -13
  394. package/dist/core/providers/mock.provider.js +0 -55
  395. package/dist/core/providers/mock.provider.js.map +0 -1
  396. package/dist/core/providers/provider-factory.d.ts +0 -3
  397. package/dist/core/providers/provider-factory.js +0 -65
  398. package/dist/core/providers/provider-factory.js.map +0 -1
  399. package/dist/core/providers/tool-call.types.d.ts +0 -39
  400. package/dist/core/providers/tool-call.types.js +0 -3
  401. package/dist/core/providers/tool-call.types.js.map +0 -1
  402. package/dist/core/remote/index.d.ts +0 -3
  403. package/dist/core/remote/index.js.map +0 -1
  404. package/dist/core/remote/remote-agent-manager.d.ts +0 -24
  405. package/dist/core/remote/remote-agent-manager.js.map +0 -1
  406. package/dist/core/remote/remote-transport.d.ts +0 -15
  407. package/dist/core/remote/remote-transport.js +0 -70
  408. package/dist/core/remote/remote-transport.js.map +0 -1
  409. package/dist/core/remote/types.d.ts +0 -79
  410. package/dist/core/remote/types.js.map +0 -1
  411. package/dist/core/workspace.js.map +0 -1
  412. package/dist/index.js.map +0 -1
  413. package/dist/internal/index.d.ts +0 -1
  414. package/dist/internal/index.js +0 -6
  415. package/dist/internal/index.js.map +0 -1
  416. package/dist/knowledge/DocumentManager.d.ts +0 -4
  417. package/dist/knowledge/DocumentManager.js +0 -119
  418. package/dist/knowledge/DocumentManager.js.map +0 -1
  419. package/dist/knowledge/index.d.ts +0 -1
  420. package/dist/knowledge/index.js +0 -18
  421. package/dist/knowledge/index.js.map +0 -1
  422. package/dist/parsers/agent-call.util.js.map +0 -1
  423. package/dist/parsers/claude.parser.js.map +0 -1
  424. package/dist/parsers/codex.parser.js.map +0 -1
  425. package/dist/parsers/copilot.parser.js.map +0 -1
  426. package/dist/parsers/gemini.parser.js.map +0 -1
  427. package/dist/parsers/index.d.ts +0 -7
  428. package/dist/parsers/index.js +0 -45
  429. package/dist/parsers/index.js.map +0 -1
  430. package/dist/schema/skills-parser.d.ts +0 -8
  431. package/dist/schema/skills-parser.js +0 -438
  432. package/dist/schema/skills-parser.js.map +0 -1
  433. package/dist/schema/skills.types.d.ts +0 -158
  434. package/dist/schema/skills.types.js +0 -41
  435. package/dist/schema/skills.types.js.map +0 -1
  436. package/dist/schemas/api-provider.schema.d.ts +0 -432
  437. package/dist/schemas/api-provider.schema.js +0 -50
  438. package/dist/schemas/api-provider.schema.js.map +0 -1
  439. package/dist/services/index.d.ts +0 -2
  440. package/dist/services/index.js +0 -19
  441. package/dist/services/index.js.map +0 -1
  442. package/dist/services/layout-loader.service.js.map +0 -1
  443. package/dist/services/layout-renderer.service.js +0 -325
  444. package/dist/services/layout-renderer.service.js.map +0 -1
  445. package/dist/services/props-validator.service.js.map +0 -1
  446. package/dist/skills/adapter/claude-skill-adapter.d.ts +0 -11
  447. package/dist/skills/adapter/claude-skill-adapter.js +0 -222
  448. package/dist/skills/adapter/claude-skill-adapter.js.map +0 -1
  449. package/dist/skills/index.d.ts +0 -6
  450. package/dist/skills/index.js +0 -31
  451. package/dist/skills/index.js.map +0 -1
  452. package/dist/skills/runtime/progressive-loader.d.ts +0 -27
  453. package/dist/skills/runtime/progressive-loader.js +0 -186
  454. package/dist/skills/runtime/progressive-loader.js.map +0 -1
  455. package/dist/skills/runtime/runtime-requirements-validator.d.ts +0 -23
  456. package/dist/skills/runtime/runtime-requirements-validator.js +0 -248
  457. package/dist/skills/runtime/runtime-requirements-validator.js.map +0 -1
  458. package/dist/skills/runtime/skill-runtime.service.d.ts +0 -42
  459. package/dist/skills/runtime/skill-runtime.service.js +0 -434
  460. package/dist/skills/runtime/skill-runtime.service.js.map +0 -1
  461. package/dist/tools/file-system.service.d.ts +0 -10
  462. package/dist/tools/file-system.service.js +0 -33
  463. package/dist/tools/file-system.service.js.map +0 -1
  464. package/dist/tools/find.tool.d.ts +0 -21
  465. package/dist/tools/find.tool.js +0 -139
  466. package/dist/tools/find.tool.js.map +0 -1
  467. package/dist/tools/glob.tool.d.ts +0 -24
  468. package/dist/tools/glob.tool.js +0 -153
  469. package/dist/tools/glob.tool.js.map +0 -1
  470. package/dist/tools/grep.tool.d.ts +0 -1
  471. package/dist/tools/grep.tool.js +0 -137
  472. package/dist/tools/grep.tool.js.map +0 -1
  473. package/dist/tools/index.js.map +0 -1
  474. package/dist/tools/ls.tool.d.ts +0 -1
  475. package/dist/tools/ls.tool.js +0 -94
  476. package/dist/tools/ls.tool.js.map +0 -1
  477. package/dist/tools/read-file.tool.d.ts +0 -1
  478. package/dist/tools/read-file.tool.js +0 -69
  479. package/dist/tools/read-file.tool.js.map +0 -1
  480. package/dist/tools/replace.tool.d.ts +0 -1
  481. package/dist/tools/replace.tool.js +0 -68
  482. package/dist/tools/replace.tool.js.map +0 -1
  483. package/dist/tools/run-shell-command.tool.d.ts +0 -1
  484. package/dist/tools/run-shell-command.tool.js +0 -64
  485. package/dist/tools/run-shell-command.tool.js.map +0 -1
  486. package/dist/tools/tree.tool.d.ts +0 -1
  487. package/dist/tools/tree.tool.js +0 -109
  488. package/dist/tools/tree.tool.js.map +0 -1
  489. package/dist/tools/types.d.ts +0 -42
  490. package/dist/tools/types.js +0 -13
  491. package/dist/tools/types.js.map +0 -1
  492. package/dist/tools/utils/file-utils.d.ts +0 -5
  493. package/dist/tools/utils/file-utils.js +0 -221
  494. package/dist/tools/utils/file-utils.js.map +0 -1
  495. package/dist/tools/write-file.tool.d.ts +0 -1
  496. package/dist/tools/write-file.tool.js +0 -55
  497. package/dist/tools/write-file.tool.js.map +0 -1
  498. package/dist/types/agent.types.d.ts +0 -134
  499. package/dist/types/agent.types.js +0 -16
  500. package/dist/types/agent.types.js.map +0 -1
  501. package/dist/types/api-provider.types.d.ts +0 -85
  502. package/dist/types/api-provider.types.js +0 -65
  503. package/dist/types/api-provider.types.js.map +0 -1
  504. package/dist/types/index.js.map +0 -1
  505. package/dist/types/layout.types.js.map +0 -1
  506. package/dist/types/provider.types.d.ts +0 -12
  507. package/dist/types/provider.types.js +0 -3
  508. package/dist/types/provider.types.js.map +0 -1
  509. package/dist/types/skill-runtime.types.d.ts +0 -244
  510. package/dist/types/skill-runtime.types.js +0 -44
  511. package/dist/types/skill-runtime.types.js.map +0 -1
  512. package/dist/types/structured-payload.types.d.ts +0 -46
  513. package/dist/types/structured-payload.types.js +0 -65
  514. package/dist/types/structured-payload.types.js.map +0 -1
  515. package/dist/types/task-log.types.js.map +0 -1
  516. package/dist/types/template.types.d.ts +0 -38
  517. package/dist/types/template.types.js +0 -3
  518. package/dist/types/template.types.js.map +0 -1
  519. package/dist/types.d.ts +0 -1
  520. package/dist/types.js +0 -18
  521. package/dist/types.js.map +0 -1
  522. package/dist/utils/api-provider-normalizer.d.ts +0 -16
  523. package/dist/utils/api-provider-normalizer.js +0 -135
  524. package/dist/utils/api-provider-normalizer.js.map +0 -1
  525. package/dist/utils/base-message-formatter.d.ts +0 -32
  526. package/dist/utils/base-message-formatter.js +0 -170
  527. package/dist/utils/base-message-formatter.js.map +0 -1
  528. package/dist/utils/error-utils.d.ts +0 -3
  529. package/dist/utils/error-utils.js +0 -27
  530. package/dist/utils/error-utils.js.map +0 -1
  531. package/dist/utils/index.d.ts +0 -4
  532. package/dist/utils/index.js +0 -21
  533. package/dist/utils/index.js.map +0 -1
  534. package/dist/utils/math-utils.d.ts +0 -3
  535. package/dist/utils/math-utils.js +0 -10
  536. package/dist/utils/math-utils.js.map +0 -1
  537. package/dist/utils/mention-parser.d.ts +0 -18
  538. package/dist/utils/mention-parser.js +0 -136
  539. package/dist/utils/mention-parser.js.map +0 -1
  540. package/dist/utils/string-utils.d.ts +0 -1
  541. package/dist/utils/string-utils.js +0 -10
  542. package/dist/utils/string-utils.js.map +0 -1
  543. package/dist/utils.d.ts +0 -3
  544. package/dist/utils.js +0 -20
  545. package/dist/utils.js.map +0 -1
  546. package/schema/api-provider-config.json +0 -138
  547. package/schema/crewx-config.json +0 -224
  548. package/schema/skills-config.json +0 -306
@@ -1,1237 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BaseAIProvider = exports.ConsoleLogger = void 0;
4
- exports.resolveCallerAgentId = resolveCallerAgentId;
5
- const child_process_1 = require("child_process");
6
- const fs_1 = require("fs");
7
- const path_1 = require("path");
8
- const timeout_config_1 = require("../../config/timeout.config");
9
- const log_config_1 = require("../../config/log.config");
10
- const parsers_1 = require("../../parsers");
11
- const id_1 = require("../../core/id");
12
- function resolveCallerAgentId(agentId) {
13
- return agentId
14
- || process.env.CREWX_CALLER_AGENT_ID
15
- || (process.env.CLAUDECODE === '1' ? 'claude-code' : '')
16
- || (process.env.CODEX_CI === '1' ? 'codex' : '');
17
- }
18
- class ConsoleLogger {
19
- constructor(context) {
20
- this.context = context;
21
- }
22
- log(message, ...optionalParams) {
23
- if (process.env.CREWX_VERBOSE === '1') {
24
- console.error(`[${this.context}]`, message, ...optionalParams);
25
- }
26
- }
27
- warn(message, ...optionalParams) {
28
- console.warn(`[${this.context}]`, message, ...optionalParams);
29
- }
30
- error(message, ...optionalParams) {
31
- const resolved = message instanceof Error ? message.message : message;
32
- console.error(`[${this.context}]`, resolved, ...optionalParams);
33
- }
34
- }
35
- exports.ConsoleLogger = ConsoleLogger;
36
- class BaseAIProvider {
37
- constructor(loggerContext, options = {}) {
38
- this.cachedPath = null;
39
- this.logger = options.logger ?? new ConsoleLogger(loggerContext);
40
- this.toolCallHandler = options.toolCallHandler;
41
- this.timeoutConfig = options.timeoutConfig ?? (0, timeout_config_1.getTimeoutConfig)();
42
- this.logConfig = options.logConfig ?? (0, log_config_1.getLogConfig)();
43
- this.logsDir = options.logsDir ?? (0, path_1.join)(process.cwd(), '.crewx', 'logs');
44
- this.crewxVersion = options.crewxVersion ?? 'unknown';
45
- this.taskLogHandler = options.taskLogHandler;
46
- try {
47
- (0, fs_1.mkdirSync)(this.logsDir, { recursive: true });
48
- }
49
- catch (error) {
50
- }
51
- }
52
- getPromptInArgs() {
53
- return false;
54
- }
55
- getDefaultQueryTimeout() {
56
- const providerName = this.name.toLowerCase();
57
- if (providerName.includes('claude'))
58
- return this.timeoutConfig.claudeQuery;
59
- if (providerName.includes('gemini'))
60
- return this.timeoutConfig.geminiQuery;
61
- if (providerName.includes('copilot'))
62
- return this.timeoutConfig.copilotQuery;
63
- return 600000;
64
- }
65
- getDefaultExecuteTimeout() {
66
- const providerName = this.name.toLowerCase();
67
- if (providerName.includes('claude'))
68
- return this.timeoutConfig.claudeExecute;
69
- if (providerName.includes('gemini'))
70
- return this.timeoutConfig.geminiExecute;
71
- if (providerName.includes('copilot'))
72
- return this.timeoutConfig.copilotExecute;
73
- return this.timeoutConfig.parallel;
74
- }
75
- getDefaultModel() {
76
- return null;
77
- }
78
- getEnv() {
79
- return {};
80
- }
81
- filterClaudePrefixedEnv(env) {
82
- return Object.fromEntries(Object.entries(env).filter(([key]) => !key.startsWith('CLAUDE')));
83
- }
84
- resolveRuntimeMode(options) {
85
- const runtime = options?.runtime;
86
- if (!runtime) {
87
- return 'native';
88
- }
89
- if (typeof runtime === 'string') {
90
- return (runtime === 'docker' || runtime === 'podman') ? 'container' : 'native';
91
- }
92
- return (runtime.type === 'docker' || runtime.type === 'podman') ? 'container' : 'native';
93
- }
94
- resolveContainerCommand(options) {
95
- const runtime = options?.runtime;
96
- if (typeof runtime === 'string') {
97
- return runtime === 'podman' ? 'podman' : 'docker';
98
- }
99
- if (runtime && typeof runtime === 'object') {
100
- return runtime.type === 'podman' ? 'podman' : 'docker';
101
- }
102
- return 'docker';
103
- }
104
- resolveDockerImage(options) {
105
- const runtime = options?.runtime;
106
- if (runtime && typeof runtime === 'object' && runtime.image?.trim()) {
107
- return runtime.image.trim();
108
- }
109
- return process.env.CREWX_DOCKER_AGENT_IMAGE || 'crewx-agent:latest';
110
- }
111
- resolveDockerMountPath(options) {
112
- const runtime = options?.runtime;
113
- if (runtime && typeof runtime === 'object' && runtime.mountPath?.trim()) {
114
- return runtime.mountPath.trim();
115
- }
116
- return '/workspace';
117
- }
118
- resolveDockerArgs(options) {
119
- const runtime = options?.runtime;
120
- if (runtime && typeof runtime === 'object' && Array.isArray(runtime.dockerArgs)) {
121
- return runtime.dockerArgs;
122
- }
123
- return [];
124
- }
125
- ensureContainerCredentials() {
126
- if (process.platform !== 'darwin')
127
- return;
128
- const homeDir = process.env.HOME || '';
129
- if (!homeDir)
130
- return;
131
- const credFile = (0, path_1.join)(homeDir, '.claude', '.credentials.json');
132
- try {
133
- const creds = (0, child_process_1.execSync)('security find-generic-password -s "Claude Code-credentials" -w', { encoding: 'utf-8', timeout: 5000 }).trim();
134
- if (creds) {
135
- (0, fs_1.mkdirSync)((0, path_1.join)(homeDir, '.claude'), { recursive: true });
136
- (0, fs_1.writeFileSync)(credFile, creds, { mode: 0o600 });
137
- this.logger.log('Extracted CLI credentials from macOS Keychain for container use');
138
- }
139
- }
140
- catch {
141
- }
142
- }
143
- buildDockerSpawnArgs(executable, args, cwd, env, options) {
144
- const image = this.resolveDockerImage(options);
145
- const mountPath = this.resolveDockerMountPath(options);
146
- const dockerArgs = this.resolveDockerArgs(options);
147
- const homeDir = process.env.HOME || process.env.USERPROFILE || '';
148
- delete env.HOME;
149
- delete env.USERPROFILE;
150
- const envKeys = Object.keys(env).filter((key) => env[key] !== undefined);
151
- const envFlags = envKeys.flatMap((key) => ['-e', `${key}=${env[key]}`]);
152
- const homeMounts = homeDir
153
- ? [
154
- '-v', `${homeDir}/.claude:/root/.claude`,
155
- '-v', `${homeDir}/.claude.json:/root/.claude.json`,
156
- ]
157
- : [];
158
- return [
159
- 'run',
160
- '--rm',
161
- '-i',
162
- ...dockerArgs,
163
- '-v',
164
- `${cwd}:${mountPath}`,
165
- ...homeMounts,
166
- '-w',
167
- mountPath,
168
- ...envFlags,
169
- image,
170
- executable,
171
- ...args,
172
- ];
173
- }
174
- substituteModelPlaceholders(args, model) {
175
- return args.map(arg => arg.replace(/\{model\}/g, model));
176
- }
177
- setToolCallService(toolCallHandler) {
178
- this.toolCallHandler = toolCallHandler;
179
- }
180
- setToolCallHandler(toolCallHandler) {
181
- this.toolCallHandler = toolCallHandler;
182
- }
183
- parseToolUse(content) {
184
- const xmlMatch = content.match(/<crew(?:code|x)_tool_call>\s*([\s\S]*?)\s*<\/crew(?:code|x)_tool_call>/);
185
- if (xmlMatch && xmlMatch[1]) {
186
- try {
187
- const jsonContent = xmlMatch[1].trim();
188
- const parsed = JSON.parse(jsonContent);
189
- if (parsed.type === 'tool_use' && parsed.name && parsed.input !== undefined) {
190
- this.logger.log(`Tool use detected from XML: ${parsed.name}`);
191
- return {
192
- isToolUse: true,
193
- toolName: parsed.name,
194
- toolInput: parsed.input,
195
- };
196
- }
197
- }
198
- catch (e) {
199
- }
200
- }
201
- try {
202
- const parsed = JSON.parse(content);
203
- if (parsed.type === 'tool_use' && parsed.name && parsed.input !== undefined) {
204
- this.logger.log(`Tool use detected from direct JSON: ${parsed.name}`);
205
- return {
206
- isToolUse: true,
207
- toolName: parsed.name,
208
- toolInput: parsed.input,
209
- };
210
- }
211
- if (parsed.content && Array.isArray(parsed.content)) {
212
- const toolUse = parsed.content.find((c) => c.type === 'tool_use');
213
- if (toolUse && toolUse.name && toolUse.input !== undefined) {
214
- this.logger.log(`Tool use detected from content array: ${toolUse.name}`);
215
- return {
216
- isToolUse: true,
217
- toolName: toolUse.name,
218
- toolInput: toolUse.input,
219
- };
220
- }
221
- }
222
- const providerSpecific = this.parseToolUseProviderSpecific(parsed);
223
- if (providerSpecific.isToolUse) {
224
- return providerSpecific;
225
- }
226
- }
227
- catch (e) {
228
- }
229
- const codeBlockMatch = content.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);
230
- if (codeBlockMatch && codeBlockMatch[1]) {
231
- try {
232
- const jsonContent = codeBlockMatch[1].trim();
233
- const parsed = JSON.parse(jsonContent);
234
- if (parsed.type === 'tool_use' && parsed.name && parsed.input !== undefined) {
235
- this.logger.log(`Tool use detected from code block: ${parsed.name}`);
236
- return {
237
- isToolUse: true,
238
- toolName: parsed.name,
239
- toolInput: parsed.input,
240
- };
241
- }
242
- }
243
- catch (e) {
244
- }
245
- }
246
- const jsonObjectPattern = /\{[\s\S]*?"type"\s*:\s*"tool_use"[\s\S]*?\}/;
247
- const jsonMatch = content.match(jsonObjectPattern);
248
- if (jsonMatch) {
249
- try {
250
- const parsed = JSON.parse(jsonMatch[0]);
251
- if (parsed.type === 'tool_use' && parsed.name && parsed.input !== undefined) {
252
- this.logger.log(`Tool use detected from plain text JSON: ${parsed.name}`);
253
- return {
254
- isToolUse: true,
255
- toolName: parsed.name,
256
- toolInput: parsed.input,
257
- };
258
- }
259
- }
260
- catch (e) {
261
- }
262
- }
263
- return { isToolUse: false };
264
- }
265
- parseToolUseProviderSpecific(_parsed) {
266
- return { isToolUse: false };
267
- }
268
- parseUsage(stdout) {
269
- if (!stdout || !stdout.trim()) {
270
- return undefined;
271
- }
272
- let lastUsage;
273
- try {
274
- const lines = stdout.split('\n').filter(line => line.trim());
275
- for (const line of lines) {
276
- try {
277
- const parsed = JSON.parse(line);
278
- if (parsed.type === 'usage' && parsed.input_tokens !== undefined && parsed.output_tokens !== undefined) {
279
- const cacheRead = parsed.cache_read_input_tokens ?? 0;
280
- const cachedInput = parsed.cached_input_tokens ?? 0;
281
- lastUsage = {
282
- inputTokens: cacheRead ? parsed.input_tokens + cacheRead : parsed.input_tokens,
283
- outputTokens: parsed.output_tokens,
284
- cachedInputTokens: cacheRead || cachedInput,
285
- };
286
- }
287
- if (parsed.usage?.input_tokens !== undefined && parsed.usage?.output_tokens !== undefined) {
288
- const cacheRead = parsed.usage.cache_read_input_tokens ?? 0;
289
- const cachedInput = parsed.usage.cached_input_tokens ?? 0;
290
- lastUsage = {
291
- inputTokens: cacheRead ? parsed.usage.input_tokens + cacheRead : parsed.usage.input_tokens,
292
- outputTokens: parsed.usage.output_tokens,
293
- cachedInputTokens: cacheRead || cachedInput,
294
- };
295
- }
296
- }
297
- catch (e) {
298
- }
299
- }
300
- if (lastUsage) {
301
- return lastUsage;
302
- }
303
- const parsed = JSON.parse(stdout);
304
- if (parsed.usage?.input_tokens !== undefined && parsed.usage?.output_tokens !== undefined) {
305
- const cacheRead = parsed.usage.cache_read_input_tokens ?? 0;
306
- const cachedInput = parsed.usage.cached_input_tokens ?? 0;
307
- return {
308
- inputTokens: cacheRead ? parsed.usage.input_tokens + cacheRead : parsed.usage.input_tokens,
309
- outputTokens: parsed.usage.output_tokens,
310
- cachedInputTokens: cacheRead || cachedInput,
311
- };
312
- }
313
- }
314
- catch (e) {
315
- }
316
- return lastUsage;
317
- }
318
- extractAgentMessageFromJsonLines(content) {
319
- if (!content) {
320
- return null;
321
- }
322
- const trimmed = content.trim();
323
- if (!trimmed) {
324
- return null;
325
- }
326
- const hasJsonlMarkers = /"type"\s*:\s*"(?:thread\.started|item\.completed|turn\.completed|response\.completed)"/.test(trimmed)
327
- || /"type"\s*:\s*"(?:agent_message|assistant_message)"/.test(trimmed)
328
- || /"item_type"\s*:\s*"assistant_message"/.test(trimmed);
329
- if (!hasJsonlMarkers) {
330
- return null;
331
- }
332
- const lines = trimmed.split('\n').map(line => line.trim()).filter(Boolean);
333
- let agentMessage = null;
334
- for (const line of lines) {
335
- let parsed;
336
- try {
337
- parsed = JSON.parse(line);
338
- }
339
- catch {
340
- continue;
341
- }
342
- const extracted = this.extractAgentMessageFromJsonItem(parsed);
343
- if (extracted) {
344
- agentMessage = extracted;
345
- }
346
- }
347
- return agentMessage;
348
- }
349
- extractAgentMessageFromJsonItem(parsed) {
350
- if (!parsed || typeof parsed !== 'object') {
351
- return null;
352
- }
353
- if (parsed?.type === 'item.completed' &&
354
- parsed?.item?.type === 'agent_message' &&
355
- typeof parsed.item.text === 'string') {
356
- return parsed.item.text.trim();
357
- }
358
- if (parsed?.type === 'item.completed' &&
359
- parsed?.item?.item_type === 'assistant_message' &&
360
- typeof parsed.item.text === 'string') {
361
- return parsed.item.text.trim();
362
- }
363
- if (parsed?.item?.type === 'agent_message' &&
364
- typeof parsed.item.text === 'string') {
365
- return parsed.item.text.trim();
366
- }
367
- if (parsed?.item?.item_type === 'assistant_message' &&
368
- typeof parsed.item.text === 'string') {
369
- return parsed.item.text.trim();
370
- }
371
- if (Array.isArray(parsed?.response?.output)) {
372
- const assistantEntries = parsed.response.output.filter((entry) => entry?.type === 'agent_message' || entry?.item_type === 'assistant_message');
373
- if (assistantEntries.length > 0) {
374
- const lastMessage = assistantEntries[assistantEntries.length - 1];
375
- if (typeof lastMessage?.text === 'string') {
376
- return lastMessage.text.trim();
377
- }
378
- }
379
- }
380
- return null;
381
- }
382
- filterToolUseFromResponse(content) {
383
- if (!content)
384
- return content;
385
- const jsonlMessage = this.extractAgentMessageFromJsonLines(content);
386
- if (jsonlMessage) {
387
- return jsonlMessage;
388
- }
389
- let filteredContent = content;
390
- filteredContent = filteredContent.replace(/^\s*\{[^}]*"type"\s*:\s*"tool_use"[^}]*\}\s*$/gm, '');
391
- filteredContent = filteredContent.replace(/(?:^\s*\{[^}]*"type"\s*:\s*"tool_use"[^}]*\}\s*\n?)+/gm, '');
392
- filteredContent = filteredContent.replace(/\n{3,}/g, '\n\n');
393
- if (filteredContent.trim() === '') {
394
- return '[Tool operations completed]';
395
- }
396
- return filteredContent.trim();
397
- }
398
- filterRuntimeLogs(content) {
399
- if (!content)
400
- return content;
401
- let filtered = content;
402
- if (this.shouldStripPromptContainers(filtered)) {
403
- const promptContainerPatterns = [
404
- /<(?:crewx_)?system_prompt\b[^>]*>[\s\S]*?<\/(?:crewx_)?system_prompt>/gi,
405
- /<conversation_history\b[^>]*>[\s\S]*?<\/conversation_history>/gi,
406
- /<user_query\b[^>]*>[\s\S]*?<\/user_query>/gi,
407
- ];
408
- for (const pattern of promptContainerPatterns) {
409
- filtered = filtered.replace(pattern, '');
410
- }
411
- }
412
- const runtimeLogPatterns = [
413
- /^\[AgentRuntime\].*$/gm,
414
- /^Loaded layout:.*$/gm,
415
- /^Loaded \d+ layouts? from.*$/gm,
416
- /^\[dotenv@[^\]]+\].*$/gm,
417
- /^Registered custom layout:.*$/gm,
418
- /^Updated custom layout:.*$/gm,
419
- /^\[Layout Fallback\].*$/gm,
420
- /^(?:💬\s*)?Message:\s*$/gm,
421
- ];
422
- for (const pattern of runtimeLogPatterns) {
423
- filtered = filtered.replace(pattern, '');
424
- }
425
- filtered = filtered
426
- .split('\n')
427
- .map((line) => line.trimEnd())
428
- .join('\n');
429
- filtered = filtered.replace(/\n{3,}/g, '\n\n');
430
- return filtered.trim();
431
- }
432
- shouldStripPromptContainers(content) {
433
- return (/^\s*<(?:crewx_)?system_prompt\b/i.test(content) ||
434
- /^\s*<conversation_history\b/i.test(content) ||
435
- /^\s*<user_query\b/i.test(content) ||
436
- /^(?:💬\s*)?Message:\s*<(?:(?:crewx_)?system_prompt|conversation_history|user_query)\b/im.test(content) ||
437
- /^\[AgentRuntime\].*$/m.test(content) ||
438
- /^Loaded layout:.*$/m.test(content) ||
439
- /^Loaded \d+ layouts? from.*$/m.test(content) ||
440
- /^\[dotenv@[^\]]+\].*$/m.test(content) ||
441
- /^Registered custom layout:.*$/m.test(content) ||
442
- /^Updated custom layout:.*$/m.test(content) ||
443
- /^\[Layout Fallback\].*$/m.test(content));
444
- }
445
- parseProviderError(stderr, stdout, exitCode) {
446
- if (stderr && (stderr.toLowerCase().includes('unknown option') ||
447
- stderr.toLowerCase().includes('invalid option'))) {
448
- return {
449
- error: true,
450
- message: stderr.split('\n')[0]?.trim() || 'Invalid CLI option',
451
- };
452
- }
453
- const knownWarningPatterns = [
454
- 'YOLO mode is enabled',
455
- 'Loaded cached credentials',
456
- 'MaxListenersExceededWarning',
457
- 'MaxListeners is',
458
- 'Use events.setMaxListeners()',
459
- 'Use `node --trace-warnings',
460
- ];
461
- if (exitCode === 0 && stderr && !stdout) {
462
- const isOnlyWarnings = knownWarningPatterns.some(pattern => stderr.includes(pattern));
463
- if (isOnlyWarnings) {
464
- return { error: false, message: '' };
465
- }
466
- }
467
- if (stderr && !stdout) {
468
- return { error: true, message: stderr };
469
- }
470
- return { error: false, message: '' };
471
- }
472
- async getToolPath() {
473
- if (this.cachedPath !== null) {
474
- return this.cachedPath;
475
- }
476
- try {
477
- const cliCommand = this.getCliCommand();
478
- const isWindows = process.platform === 'win32';
479
- const command = isWindows ? `where ${cliCommand}` : `which ${cliCommand}`;
480
- const path = (0, child_process_1.execSync)(command, { encoding: 'utf-8' }).trim();
481
- let finalPath;
482
- if (isWindows) {
483
- const paths = path.split('\n').map(p => p.trim()).filter(p => p);
484
- const pathWithExt = paths.find(p => /\.(cmd|exe|bat|ps1)$/i.test(p));
485
- finalPath = pathWithExt || paths[0] || '';
486
- }
487
- else {
488
- finalPath = path;
489
- }
490
- this.logger.log(`✅ Found ${this.name} CLI at: ${finalPath}`);
491
- this.cachedPath = finalPath;
492
- return finalPath;
493
- }
494
- catch (error) {
495
- this.logger.error(`❌ ${this.name} not found in PATH: ${error.message}`);
496
- this.cachedPath = '';
497
- return null;
498
- }
499
- }
500
- wrapUserQueryWithSecurity(userQuery, securityKey) {
501
- return `
502
- <user_query key="${securityKey}">
503
- ${userQuery}
504
- </user_query>`;
505
- }
506
- extractUserQuery(wrappedQuery, securityKey) {
507
- const regex = new RegExp(`<user_query key="${securityKey}">\\s*([\\s\\S]*?)\\s*</user_query>`, 'm');
508
- const match = wrappedQuery.match(regex);
509
- return match && match[1] ? match[1].trim() : wrappedQuery;
510
- }
511
- async isAvailable() {
512
- const path = await this.getToolPath();
513
- return path !== null && path !== '';
514
- }
515
- formatLogTimestamp(date) {
516
- const pad = (n) => String(n).padStart(2, '0');
517
- return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}T${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
518
- }
519
- createTaskLogFile(taskId, provider, command, agentId, model) {
520
- if (this.taskLogHandler)
521
- return '';
522
- const safeTaskId = taskId.replace(/[\\/]/g, '_');
523
- const now = new Date();
524
- const ts = this.formatLogTimestamp(now);
525
- const logFile = (0, path_1.join)(this.logsDir, `${ts}_${safeTaskId}.log`);
526
- const safeAgentId = agentId ? agentId.replace(/[\\/]/g, '_') : 'N/A';
527
- const timestamp = now.toLocaleString();
528
- const header = `=== TASK LOG: ${taskId} ===
529
- CrewX Version: ${this.crewxVersion}
530
- Provider: ${provider}
531
- Agent: ${safeAgentId}
532
- ${model ? `Model: ${model}\n` : ''}Command: ${command}
533
- Started: ${timestamp}
534
-
535
- `;
536
- (0, fs_1.writeFileSync)(logFile, header, 'utf8');
537
- return logFile;
538
- }
539
- appendTaskLog(taskId, level, message) {
540
- const timestamp = new Date();
541
- if (!this.taskLogHandler) {
542
- const safeTaskId = taskId.replace(/[\\/]/g, '_');
543
- const logFile = this.findTaskLogFile(safeTaskId);
544
- if (logFile) {
545
- const logEntry = `[${timestamp.toLocaleString()}] ${level}: ${message}\n`;
546
- try {
547
- (0, fs_1.appendFileSync)(logFile, logEntry, 'utf8');
548
- }
549
- catch (error) {
550
- this.logger.error(`Failed to append to task log ${taskId}:`, error);
551
- }
552
- }
553
- }
554
- if (this.taskLogHandler) {
555
- try {
556
- this.taskLogHandler({
557
- taskId,
558
- timestamp: timestamp.toISOString(),
559
- level,
560
- message,
561
- });
562
- }
563
- catch (error) {
564
- this.logger.warn(`Task log handler failed for ${taskId}: ${error instanceof Error ? error.message : String(error)}`);
565
- }
566
- }
567
- }
568
- findTaskLogFile(safeTaskId) {
569
- try {
570
- if (!(0, fs_1.existsSync)(this.logsDir))
571
- return null;
572
- const files = (0, fs_1.readdirSync)(this.logsDir);
573
- const match = files.find(f => f.endsWith(`_${safeTaskId}.log`));
574
- if (match)
575
- return (0, path_1.join)(this.logsDir, match);
576
- const legacy = (0, path_1.join)(this.logsDir, `${safeTaskId}.log`);
577
- if ((0, fs_1.existsSync)(legacy))
578
- return legacy;
579
- return null;
580
- }
581
- catch {
582
- return null;
583
- }
584
- }
585
- async query(prompt, options = {}) {
586
- const taskId = options.taskId || (0, id_1.generateId)('tsk');
587
- const executablePath = this.getCliCommand();
588
- const promptLength = prompt.length;
589
- try {
590
- const modelToUse = options.model || this.getDefaultModel();
591
- let args = [
592
- ...(options.additionalArgs || []),
593
- ...this.getDefaultArgs(),
594
- ];
595
- if (modelToUse) {
596
- args = this.substituteModelPlaceholders(args, modelToUse);
597
- }
598
- const isBuiltInProvider = this.name.startsWith('cli/');
599
- const hasModelInArgs = args.some(arg => arg.includes('--model') || arg.includes('{model}'));
600
- if (isBuiltInProvider && options.model && !hasModelInArgs) {
601
- args.unshift(`--model=${options.model}`);
602
- }
603
- const promptInArgs = this.getPromptInArgs();
604
- if (promptInArgs) {
605
- args.push(prompt);
606
- }
607
- const runtimeMode = this.resolveRuntimeMode(options);
608
- const command = runtimeMode === 'container'
609
- ? `${this.resolveContainerCommand(options)} run --rm -i -v ${options.workingDirectory || process.cwd()}:${this.resolveDockerMountPath(options)} ${this.resolveDockerImage(options)} ${this.getCliCommand()} ...`
610
- : (promptInArgs
611
- ? `${this.getCliCommand()} ${args.slice(0, -1).join(' ')} -p "<prompt>"`
612
- : `${this.getCliCommand()} ${args.join(' ')}`);
613
- this.createTaskLogFile(taskId, this.name, command, options.agentId, modelToUse);
614
- this.appendTaskLog(taskId, 'INFO', `Starting ${this.name} query mode`);
615
- this.appendTaskLog(taskId, 'INFO', `Prompt length: ${promptLength} characters`);
616
- this.appendTaskLog(taskId, 'INFO', `Prompt content:\n${prompt}`);
617
- this.logger.log(`Executing ${this.name} with prompt (length: ${promptLength})`);
618
- return new Promise((resolve) => {
619
- const env = this.filterClaudePrefixedEnv({
620
- ...process.env,
621
- LANG: 'en_US.UTF-8',
622
- LC_ALL: 'en_US.UTF-8',
623
- CREWX_TASK_ID: taskId,
624
- CREWX_WORKSPACE: process.env.CREWX_WORKSPACE || process.cwd(),
625
- CREWX_AGENT_ID: options.agentId || '',
626
- CREWX_USER_ID: process.env.USER || process.env.USERNAME || 'unknown',
627
- CREWX_TRACE_ID: options.traceId || process.env.CREWX_TRACE_ID || '',
628
- CREWX_PARENT_TASK_ID: taskId,
629
- CREWX_CALLER_AGENT_ID: resolveCallerAgentId(options.agentId),
630
- ...this.getEnv(),
631
- ...(options.env || {}),
632
- });
633
- if (process.platform === 'win32') {
634
- env.PYTHONIOENCODING = 'utf-8';
635
- }
636
- let executable = executablePath;
637
- let spawnArgs = args;
638
- let useShell = false;
639
- if (runtimeMode === 'container') {
640
- this.ensureContainerCredentials();
641
- delete env.CLAUDECODE;
642
- executable = this.resolveContainerCommand(options);
643
- spawnArgs = this.buildDockerSpawnArgs(executablePath, args, options.workingDirectory || process.cwd(), env, options);
644
- useShell = false;
645
- }
646
- else if (process.platform === 'win32') {
647
- useShell = true;
648
- }
649
- const startTime = Date.now();
650
- let firstOutputAt = undefined;
651
- const child = (0, child_process_1.spawn)(executable, spawnArgs, {
652
- stdio: ['pipe', 'pipe', 'pipe'],
653
- cwd: options.workingDirectory || process.cwd(),
654
- env,
655
- shell: useShell,
656
- });
657
- const childPid = child.pid;
658
- this.notifyProcessStart(options, childPid);
659
- let stdout = '';
660
- let stderr = '';
661
- let exitCode = null;
662
- const accumulatedLogs = [];
663
- child.stdin.on('error', (err) => {
664
- if (err.code !== 'EPIPE') {
665
- this.logger.warn(`stdin error: ${err.message}`);
666
- }
667
- });
668
- let stdoutLineBuffer = '';
669
- let stderrLineBuffer = '';
670
- child.stdout.on('data', (data) => {
671
- const output = data.toString();
672
- if (firstOutputAt === undefined) {
673
- firstOutputAt = Date.now();
674
- }
675
- stdout += output;
676
- stdoutLineBuffer += output;
677
- const lines = stdoutLineBuffer.split('\n');
678
- stdoutLineBuffer = lines.pop() || '';
679
- for (const line of lines) {
680
- if (line.trim()) {
681
- this.appendTaskLog(taskId, 'STDOUT', line);
682
- const timestamp = new Date().toISOString();
683
- const entries = (0, parsers_1.parseStdoutEvent)(timestamp, line);
684
- if (entries.length > 0) {
685
- accumulatedLogs.push(...entries);
686
- }
687
- }
688
- }
689
- });
690
- child.stderr.on('data', (data) => {
691
- const output = data.toString();
692
- if (firstOutputAt === undefined) {
693
- firstOutputAt = Date.now();
694
- }
695
- stderr += output;
696
- stderrLineBuffer += output;
697
- const lines = stderrLineBuffer.split('\n');
698
- stderrLineBuffer = lines.pop() || '';
699
- for (const line of lines) {
700
- if (line.trim()) {
701
- this.appendTaskLog(taskId, 'STDERR', line);
702
- }
703
- }
704
- });
705
- child.on('close', (code) => {
706
- exitCode = code;
707
- const completedAt = Date.now();
708
- const durationMs = completedAt - startTime;
709
- const timeToFirstOutputMs = firstOutputAt !== undefined ? firstOutputAt - startTime : undefined;
710
- if (stdoutLineBuffer.trim()) {
711
- this.appendTaskLog(taskId, 'STDOUT', stdoutLineBuffer);
712
- const timestamp = new Date().toISOString();
713
- const entries = (0, parsers_1.parseStdoutEvent)(timestamp, stdoutLineBuffer);
714
- if (entries.length > 0) {
715
- accumulatedLogs.push(...entries);
716
- }
717
- stdoutLineBuffer = '';
718
- }
719
- if (stderrLineBuffer.trim()) {
720
- this.appendTaskLog(taskId, 'STDERR', stderrLineBuffer);
721
- stderrLineBuffer = '';
722
- }
723
- this.appendTaskLog(taskId, 'INFO', `Process closed with exit code: ${exitCode}`);
724
- if (stderr) {
725
- this.logger.warn(`[${taskId}] ${this.name} stderr: ${stderr}`);
726
- }
727
- if (exitCode === 0 && stdout && stdout.trim().length > 0) {
728
- const filteredContent = this.filterRuntimeLogs(this.filterToolUseFromResponse(stdout.trim()));
729
- const usage = this.parseUsage(stdout);
730
- this.appendTaskLog(taskId, 'INFO', `${this.name} query completed successfully`);
731
- resolve({
732
- content: filteredContent,
733
- provider: this.name,
734
- command,
735
- success: true,
736
- taskId,
737
- pid: childPid,
738
- exitCode,
739
- durationMs,
740
- timeToFirstOutputMs,
741
- promptLength,
742
- usage,
743
- logs: accumulatedLogs,
744
- });
745
- return;
746
- }
747
- const providerError = this.parseProviderError(stderr, stdout, exitCode);
748
- if (exitCode !== 0 || providerError.error) {
749
- const errorMessage = providerError.message || stderr || `Exit code ${exitCode}`;
750
- this.appendTaskLog(taskId, 'ERROR', `${this.name} CLI failed: ${errorMessage}`);
751
- resolve({
752
- content: '',
753
- provider: this.name,
754
- command,
755
- success: false,
756
- error: `${this.name} CLI failed: ${errorMessage}`,
757
- taskId,
758
- pid: childPid,
759
- exitCode,
760
- durationMs,
761
- timeToFirstOutputMs,
762
- promptLength,
763
- });
764
- return;
765
- }
766
- this.appendTaskLog(taskId, 'INFO', `${this.name} query completed successfully`);
767
- let parsedContent = stdout.trim();
768
- try {
769
- JSON.parse(stdout);
770
- parsedContent = stdout.trim();
771
- this.appendTaskLog(taskId, 'INFO', 'JSON output detected and validated');
772
- }
773
- catch (jsonError) {
774
- this.appendTaskLog(taskId, 'INFO', 'Plain text output (not JSON)');
775
- }
776
- const filteredContent = this.filterRuntimeLogs(this.filterToolUseFromResponse(parsedContent));
777
- const usage = this.parseUsage(stdout);
778
- resolve({
779
- content: filteredContent,
780
- provider: this.name,
781
- command,
782
- success: true,
783
- taskId,
784
- pid: childPid,
785
- exitCode,
786
- durationMs,
787
- timeToFirstOutputMs,
788
- promptLength,
789
- usage,
790
- logs: accumulatedLogs,
791
- });
792
- });
793
- child.on('error', (error) => {
794
- const durationMs = Date.now() - startTime;
795
- const timeToFirstOutputMs = firstOutputAt !== undefined ? firstOutputAt - startTime : undefined;
796
- this.appendTaskLog(taskId, 'ERROR', `Process error: ${error.message}`);
797
- resolve({
798
- content: '',
799
- provider: this.name,
800
- command,
801
- success: false,
802
- error: error.code === 'ENOENT' ? this.getNotInstalledMessage() : error.message,
803
- taskId,
804
- pid: childPid,
805
- exitCode: null,
806
- durationMs,
807
- timeToFirstOutputMs,
808
- promptLength,
809
- });
810
- });
811
- const pipedContext = this.buildPipedContext(prompt, options);
812
- try {
813
- if (pipedContext && this.shouldPipeContext(options)) {
814
- child.stdin.write(pipedContext);
815
- if (!pipedContext.endsWith('\n')) {
816
- child.stdin.write('\n');
817
- }
818
- }
819
- if (!this.getPromptInArgs()) {
820
- child.stdin.write(prompt);
821
- }
822
- }
823
- catch (stdinError) {
824
- if (stdinError.code !== 'EPIPE') {
825
- this.logger.warn(`stdin write error: ${stdinError.message}`);
826
- }
827
- }
828
- finally {
829
- setImmediate(() => {
830
- try {
831
- child.stdin.end();
832
- }
833
- catch (endError) {
834
- if (endError.code !== 'EPIPE') {
835
- this.logger.warn(`stdin.end() error: ${endError.message}`);
836
- }
837
- }
838
- });
839
- }
840
- const timeout = setTimeout(() => {
841
- const durationMs = Date.now() - startTime;
842
- const timeToFirstOutputMs = firstOutputAt !== undefined ? firstOutputAt - startTime : undefined;
843
- child.kill();
844
- resolve({
845
- content: '',
846
- provider: this.name,
847
- command,
848
- success: false,
849
- error: `${this.name} CLI timeout`,
850
- taskId,
851
- pid: childPid,
852
- exitCode: null,
853
- durationMs,
854
- timeToFirstOutputMs,
855
- promptLength,
856
- });
857
- }, options.timeout || this.getDefaultQueryTimeout());
858
- child.on('close', () => clearTimeout(timeout));
859
- });
860
- }
861
- catch (error) {
862
- this.logger.error(`${this.name} execution failed: ${error.message}`, error.stack);
863
- return {
864
- content: '',
865
- provider: this.name,
866
- command: `${this.getCliCommand()} (error)`,
867
- success: false,
868
- error: error.message || 'Unknown error occurred',
869
- taskId,
870
- exitCode: null,
871
- promptLength,
872
- };
873
- }
874
- }
875
- async execute(prompt, options = {}) {
876
- const taskId = options.taskId || (0, id_1.generateId)('tsk');
877
- const executablePath = this.getCliCommand();
878
- const promptLength = prompt.length;
879
- try {
880
- const modelToUse = options.model || this.getDefaultModel();
881
- let args = [
882
- ...(options.additionalArgs || []),
883
- ...this.getExecuteArgs(),
884
- ];
885
- if (modelToUse) {
886
- args = this.substituteModelPlaceholders(args, modelToUse);
887
- }
888
- const isBuiltInProvider = this.name.startsWith('cli/');
889
- const hasModelInArgs = args.some(arg => arg.includes('--model') || arg.includes('{model}'));
890
- if (isBuiltInProvider && options.model && !hasModelInArgs) {
891
- args.unshift(`--model=${options.model}`);
892
- }
893
- if (this.getPromptInArgs()) {
894
- args.push(prompt);
895
- }
896
- const runtimeMode = this.resolveRuntimeMode(options);
897
- const command = runtimeMode === 'container'
898
- ? `${this.resolveContainerCommand(options)} run --rm -i -v ${options.workingDirectory || process.cwd()}:${this.resolveDockerMountPath(options)} ${this.resolveDockerImage(options)} ${this.getCliCommand()} ...`
899
- : `${this.getCliCommand()} ${args.join(' ')}`;
900
- this.createTaskLogFile(taskId, this.name, command, options.agentId, modelToUse);
901
- this.appendTaskLog(taskId, 'INFO', `Additional Args: ${JSON.stringify(options.additionalArgs || [])}`);
902
- this.appendTaskLog(taskId, 'INFO', `Execute Args: ${JSON.stringify(this.getExecuteArgs())}`);
903
- this.appendTaskLog(taskId, 'INFO', `Final Args: ${JSON.stringify(args)}`);
904
- this.appendTaskLog(taskId, 'INFO', `Starting ${this.name} execute mode`);
905
- this.appendTaskLog(taskId, 'INFO', `Prompt length: ${promptLength} characters`);
906
- const promptPreview = prompt.length > this.logConfig.promptMaxLength ?
907
- prompt.substring(0, this.logConfig.promptMaxLength) + '...[truncated]' :
908
- prompt;
909
- this.appendTaskLog(taskId, 'INFO', `Prompt content:\n${promptPreview}`);
910
- this.logger.log(`Executing ${this.name} in execute mode (length: ${promptLength})`);
911
- return new Promise((resolve) => {
912
- const env = this.filterClaudePrefixedEnv({
913
- ...process.env,
914
- LANG: 'en_US.UTF-8',
915
- LC_ALL: 'en_US.UTF-8',
916
- CREWX_TASK_ID: taskId,
917
- CREWX_WORKSPACE: process.env.CREWX_WORKSPACE || process.cwd(),
918
- CREWX_AGENT_ID: options.agentId || '',
919
- CREWX_USER_ID: process.env.USER || process.env.USERNAME || 'unknown',
920
- CREWX_TRACE_ID: options.traceId || process.env.CREWX_TRACE_ID || '',
921
- CREWX_PARENT_TASK_ID: taskId,
922
- CREWX_CALLER_AGENT_ID: resolveCallerAgentId(options.agentId),
923
- ...this.getEnv(),
924
- ...(options.env || {}),
925
- });
926
- if (process.platform === 'win32') {
927
- env.PYTHONIOENCODING = 'utf-8';
928
- }
929
- let executable = executablePath;
930
- let spawnArgs = args;
931
- let useShell = false;
932
- if (runtimeMode === 'container') {
933
- this.ensureContainerCredentials();
934
- delete env.CLAUDECODE;
935
- executable = this.resolveContainerCommand(options);
936
- spawnArgs = this.buildDockerSpawnArgs(executablePath, args, options.workingDirectory || process.cwd(), env, options);
937
- useShell = false;
938
- }
939
- else if (process.platform === 'win32') {
940
- useShell = true;
941
- }
942
- const startTime = Date.now();
943
- let firstOutputAt = undefined;
944
- const child = (0, child_process_1.spawn)(executable, spawnArgs, {
945
- stdio: ['pipe', 'pipe', 'pipe'],
946
- cwd: options.workingDirectory || process.cwd(),
947
- env,
948
- shell: useShell,
949
- });
950
- const childPid = child.pid;
951
- this.notifyProcessStart(options, childPid);
952
- let stdout = '';
953
- let stderr = '';
954
- let exitCode = null;
955
- const accumulatedLogs = [];
956
- child.stdin.on('error', (err) => {
957
- if (err.code !== 'EPIPE') {
958
- this.logger.warn(`stdin error: ${err.message}`);
959
- }
960
- });
961
- let stdoutLineBuffer = '';
962
- let stderrLineBuffer = '';
963
- child.stdout.on('data', (data) => {
964
- const output = data.toString();
965
- if (firstOutputAt === undefined) {
966
- firstOutputAt = Date.now();
967
- }
968
- stdout += output;
969
- stdoutLineBuffer += output;
970
- const lines = stdoutLineBuffer.split('\n');
971
- stdoutLineBuffer = lines.pop() || '';
972
- for (const line of lines) {
973
- if (line.trim()) {
974
- this.appendTaskLog(taskId, 'STDOUT', line);
975
- const timestamp = new Date().toISOString();
976
- const entries = (0, parsers_1.parseStdoutEvent)(timestamp, line);
977
- if (entries.length > 0) {
978
- accumulatedLogs.push(...entries);
979
- }
980
- }
981
- }
982
- });
983
- child.stderr.on('data', (data) => {
984
- const output = data.toString();
985
- if (firstOutputAt === undefined) {
986
- firstOutputAt = Date.now();
987
- }
988
- stderr += output;
989
- stderrLineBuffer += output;
990
- const lines = stderrLineBuffer.split('\n');
991
- stderrLineBuffer = lines.pop() || '';
992
- for (const line of lines) {
993
- if (line.trim()) {
994
- this.appendTaskLog(taskId, 'STDERR', line);
995
- }
996
- }
997
- });
998
- child.on('close', (code) => {
999
- exitCode = code;
1000
- const completedAt = Date.now();
1001
- const durationMs = completedAt - startTime;
1002
- const timeToFirstOutputMs = firstOutputAt !== undefined ? firstOutputAt - startTime : undefined;
1003
- if (stdoutLineBuffer.trim()) {
1004
- this.appendTaskLog(taskId, 'STDOUT', stdoutLineBuffer);
1005
- const timestamp = new Date().toISOString();
1006
- const entries = (0, parsers_1.parseStdoutEvent)(timestamp, stdoutLineBuffer);
1007
- if (entries.length > 0) {
1008
- accumulatedLogs.push(...entries);
1009
- }
1010
- stdoutLineBuffer = '';
1011
- }
1012
- if (stderrLineBuffer.trim()) {
1013
- this.appendTaskLog(taskId, 'STDERR', stderrLineBuffer);
1014
- stderrLineBuffer = '';
1015
- }
1016
- this.appendTaskLog(taskId, 'INFO', `Process closed with exit code: ${exitCode}`);
1017
- if (stderr) {
1018
- this.logger.warn(`[${taskId}] ${this.name} stderr: ${stderr}`);
1019
- }
1020
- if (exitCode === 0 && stdout && stdout.trim().length > 0) {
1021
- const filteredContent = this.filterRuntimeLogs(this.filterToolUseFromResponse(stdout.trim()));
1022
- const usage = this.parseUsage(stdout);
1023
- this.appendTaskLog(taskId, 'INFO', `${this.name} execution completed successfully`);
1024
- resolve({
1025
- content: filteredContent,
1026
- provider: this.name,
1027
- command,
1028
- success: true,
1029
- taskId,
1030
- pid: childPid,
1031
- exitCode,
1032
- durationMs,
1033
- timeToFirstOutputMs,
1034
- promptLength,
1035
- usage,
1036
- logs: accumulatedLogs,
1037
- });
1038
- return;
1039
- }
1040
- const providerError = this.parseProviderError(stderr, stdout, exitCode);
1041
- if (exitCode !== 0 || providerError.error) {
1042
- const errorMessage = providerError.message || stderr || `Exit code ${exitCode}`;
1043
- this.appendTaskLog(taskId, 'ERROR', `${this.name} CLI failed: ${errorMessage}`);
1044
- resolve({
1045
- content: '',
1046
- provider: this.name,
1047
- command,
1048
- success: false,
1049
- error: `${this.name} CLI execute failed: ${errorMessage}`,
1050
- taskId,
1051
- pid: childPid,
1052
- exitCode,
1053
- durationMs,
1054
- timeToFirstOutputMs,
1055
- promptLength,
1056
- });
1057
- return;
1058
- }
1059
- this.appendTaskLog(taskId, 'INFO', `${this.name} execute completed successfully`);
1060
- let parsedContent = stdout.trim();
1061
- try {
1062
- JSON.parse(stdout);
1063
- parsedContent = stdout.trim();
1064
- this.appendTaskLog(taskId, 'INFO', 'JSON output detected and validated');
1065
- }
1066
- catch (jsonError) {
1067
- this.appendTaskLog(taskId, 'INFO', 'Plain text output (not JSON)');
1068
- }
1069
- const filteredContent = this.filterRuntimeLogs(parsedContent);
1070
- const usage = this.parseUsage(stdout);
1071
- resolve({
1072
- content: filteredContent,
1073
- provider: this.name,
1074
- command,
1075
- success: true,
1076
- taskId,
1077
- pid: childPid,
1078
- exitCode,
1079
- durationMs,
1080
- timeToFirstOutputMs,
1081
- promptLength,
1082
- usage,
1083
- logs: accumulatedLogs,
1084
- });
1085
- });
1086
- child.on('error', (error) => {
1087
- const durationMs = Date.now() - startTime;
1088
- const timeToFirstOutputMs = firstOutputAt !== undefined ? firstOutputAt - startTime : undefined;
1089
- this.appendTaskLog(taskId, 'ERROR', `Process error: ${error.message}`);
1090
- resolve({
1091
- content: '',
1092
- provider: this.name,
1093
- command,
1094
- success: false,
1095
- error: error.code === 'ENOENT' ? this.getNotInstalledMessage() : error.message,
1096
- taskId,
1097
- pid: childPid,
1098
- exitCode: null,
1099
- durationMs,
1100
- timeToFirstOutputMs,
1101
- promptLength,
1102
- });
1103
- });
1104
- const pipedContext = this.buildPipedContext(prompt, options);
1105
- try {
1106
- if (pipedContext && this.shouldPipeContext(options)) {
1107
- child.stdin.write(pipedContext);
1108
- if (!pipedContext.endsWith('\n')) {
1109
- child.stdin.write('\n');
1110
- }
1111
- }
1112
- if (!this.getPromptInArgs()) {
1113
- child.stdin.write(prompt);
1114
- }
1115
- }
1116
- catch (stdinError) {
1117
- if (stdinError.code !== 'EPIPE') {
1118
- this.logger.warn(`stdin write error: ${stdinError.message}`);
1119
- }
1120
- }
1121
- finally {
1122
- setImmediate(() => {
1123
- try {
1124
- child.stdin.end();
1125
- }
1126
- catch (endError) {
1127
- if (endError.code !== 'EPIPE') {
1128
- this.logger.warn(`stdin.end() error: ${endError.message}`);
1129
- }
1130
- }
1131
- });
1132
- }
1133
- const timeout = setTimeout(() => {
1134
- const durationMs = Date.now() - startTime;
1135
- const timeToFirstOutputMs = firstOutputAt !== undefined ? firstOutputAt - startTime : undefined;
1136
- child.kill();
1137
- resolve({
1138
- content: '',
1139
- provider: this.name,
1140
- command,
1141
- success: false,
1142
- error: `${this.name} CLI execute timeout`,
1143
- taskId,
1144
- pid: childPid,
1145
- exitCode: null,
1146
- durationMs,
1147
- timeToFirstOutputMs,
1148
- promptLength,
1149
- });
1150
- }, options.timeout || this.getDefaultExecuteTimeout());
1151
- child.on('close', () => clearTimeout(timeout));
1152
- });
1153
- }
1154
- catch (error) {
1155
- this.logger.error(`${this.name} execute failed: ${error.message}`, error.stack);
1156
- return {
1157
- content: '',
1158
- provider: this.name,
1159
- command: `${this.getCliCommand()} execute (error)`,
1160
- success: false,
1161
- error: error.message || 'Unknown error occurred',
1162
- taskId,
1163
- exitCode: null,
1164
- promptLength,
1165
- };
1166
- }
1167
- }
1168
- shouldPipeContext(_options) {
1169
- return true;
1170
- }
1171
- notifyProcessStart(options, pid) {
1172
- if (typeof options.onProcessStart !== 'function' || typeof pid !== 'number') {
1173
- return;
1174
- }
1175
- try {
1176
- options.onProcessStart(pid);
1177
- }
1178
- catch (error) {
1179
- this.logger.warn(`onProcessStart callback failed: ${error instanceof Error ? error.message : String(error)}`);
1180
- }
1181
- }
1182
- buildPipedContext(prompt, options) {
1183
- const normalized = options?.pipedContext?.trim();
1184
- if (normalized) {
1185
- if (this.isStructuredPayload(normalized)) {
1186
- return normalized;
1187
- }
1188
- return this.createStructuredPayload(prompt, normalized, options);
1189
- }
1190
- if (options?.messages && options.messages.length > 0) {
1191
- return this.createStructuredPayload(prompt, null, options);
1192
- }
1193
- return null;
1194
- }
1195
- isStructuredPayload(value) {
1196
- try {
1197
- const parsed = JSON.parse(value);
1198
- return Boolean(parsed && typeof parsed === 'object' && 'prompt' in parsed && 'messages' in parsed);
1199
- }
1200
- catch {
1201
- return false;
1202
- }
1203
- }
1204
- createStructuredPayload(prompt, context, options) {
1205
- const safeMessages = Array.isArray(options?.messages) ? options.messages : [];
1206
- const fallbackHistory = safeMessages.length > 0
1207
- ? safeMessages
1208
- .map((msg, index) => {
1209
- const speaker = msg.isAssistant ? 'Assistant' : 'User';
1210
- return `${index + 1}. ${speaker}: ${msg.text}`;
1211
- })
1212
- .join('\n')
1213
- : '';
1214
- const normalizedContext = context?.trim() ?? '';
1215
- const payload = {
1216
- version: '1.0',
1217
- agent: {
1218
- id: options?.agentId ?? null,
1219
- provider: this.name,
1220
- mode: options?.additionalArgs?.includes('--execute') ? 'execute' : 'query',
1221
- model: options?.model ?? null,
1222
- },
1223
- prompt,
1224
- context: normalizedContext,
1225
- messages: safeMessages,
1226
- metadata: {
1227
- generatedAt: new Date().toISOString(),
1228
- messageCount: safeMessages.length,
1229
- formattedHistory: fallbackHistory,
1230
- originalContext: normalizedContext,
1231
- },
1232
- };
1233
- return JSON.stringify(payload);
1234
- }
1235
- }
1236
- exports.BaseAIProvider = BaseAIProvider;
1237
- //# sourceMappingURL=base-ai.provider.js.map