@geminilight/mindos 1.1.26 → 1.1.28

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 (352) hide show
  1. package/dist/agent/bridges/index.d.ts +3 -0
  2. package/dist/agent/bridges/index.d.ts.map +1 -0
  3. package/dist/agent/bridges/index.js +3 -0
  4. package/dist/agent/bridges/index.js.map +1 -0
  5. package/dist/agent/bridges/runtime-permission-bridge.d.ts +34 -0
  6. package/dist/agent/bridges/runtime-permission-bridge.d.ts.map +1 -0
  7. package/dist/agent/bridges/runtime-permission-bridge.js +284 -0
  8. package/dist/agent/bridges/runtime-permission-bridge.js.map +1 -0
  9. package/dist/agent/bridges/user-question-bridge.d.ts +90 -0
  10. package/dist/agent/bridges/user-question-bridge.d.ts.map +1 -0
  11. package/dist/agent/bridges/user-question-bridge.js +260 -0
  12. package/dist/agent/bridges/user-question-bridge.js.map +1 -0
  13. package/dist/agent/index.d.ts +6 -7
  14. package/dist/agent/index.d.ts.map +1 -1
  15. package/dist/agent/index.js +6 -7
  16. package/dist/agent/index.js.map +1 -1
  17. package/dist/agent/ledger/index.d.ts +5 -0
  18. package/dist/agent/ledger/index.d.ts.map +1 -0
  19. package/dist/agent/ledger/index.js +5 -0
  20. package/dist/agent/ledger/index.js.map +1 -0
  21. package/dist/agent/ledger/run-cancellation.d.ts +13 -0
  22. package/dist/agent/ledger/run-cancellation.d.ts.map +1 -0
  23. package/dist/agent/ledger/run-cancellation.js +97 -0
  24. package/dist/agent/ledger/run-cancellation.js.map +1 -0
  25. package/dist/agent/ledger/run-ledger-types.d.ts +197 -0
  26. package/dist/agent/ledger/run-ledger-types.d.ts.map +1 -0
  27. package/dist/agent/ledger/run-ledger-types.js +9 -0
  28. package/dist/agent/ledger/run-ledger-types.js.map +1 -0
  29. package/dist/agent/ledger/run-ledger.d.ts +44 -0
  30. package/dist/agent/ledger/run-ledger.d.ts.map +1 -0
  31. package/dist/agent/ledger/run-ledger.js +814 -0
  32. package/dist/agent/ledger/run-ledger.js.map +1 -0
  33. package/dist/agent/ledger/run-timeline-events.d.ts +3 -0
  34. package/dist/agent/ledger/run-timeline-events.d.ts.map +1 -0
  35. package/dist/agent/ledger/run-timeline-events.js +239 -0
  36. package/dist/agent/ledger/run-timeline-events.js.map +1 -0
  37. package/dist/agent/mindos-pi/extension/extension-tools.d.ts +16 -0
  38. package/dist/agent/mindos-pi/extension/extension-tools.d.ts.map +1 -0
  39. package/dist/agent/mindos-pi/extension/extension-tools.js +115 -0
  40. package/dist/agent/mindos-pi/extension/extension-tools.js.map +1 -0
  41. package/dist/agent/mindos-pi/extension/index.d.ts +3 -0
  42. package/dist/agent/mindos-pi/extension/index.d.ts.map +1 -0
  43. package/dist/agent/mindos-pi/extension/index.js +3 -0
  44. package/dist/agent/mindos-pi/extension/index.js.map +1 -0
  45. package/dist/agent/mindos-pi/extension/kb-extension.d.ts +38 -0
  46. package/dist/agent/mindos-pi/extension/kb-extension.d.ts.map +1 -0
  47. package/dist/agent/mindos-pi/extension/kb-extension.js +140 -0
  48. package/dist/agent/mindos-pi/extension/kb-extension.js.map +1 -0
  49. package/dist/agent/mindos-pi/index.d.ts +5 -0
  50. package/dist/agent/mindos-pi/index.d.ts.map +1 -0
  51. package/dist/agent/mindos-pi/index.js +5 -0
  52. package/dist/agent/mindos-pi/index.js.map +1 -0
  53. package/dist/agent/mindos-pi/prompt.d.ts +3 -0
  54. package/dist/agent/mindos-pi/prompt.d.ts.map +1 -0
  55. package/dist/agent/mindos-pi/prompt.js +22 -0
  56. package/dist/agent/mindos-pi/prompt.js.map +1 -0
  57. package/dist/agent/mindos-pi/resource-types.d.ts +27 -0
  58. package/dist/agent/mindos-pi/resource-types.d.ts.map +1 -0
  59. package/dist/agent/mindos-pi/resource-types.js +2 -0
  60. package/dist/agent/mindos-pi/resource-types.js.map +1 -0
  61. package/dist/agent/mindos-pi/runtime.d.ts +10 -0
  62. package/dist/agent/mindos-pi/runtime.d.ts.map +1 -0
  63. package/dist/agent/mindos-pi/runtime.js +31 -0
  64. package/dist/agent/mindos-pi/runtime.js.map +1 -0
  65. package/dist/agent/pi/extension-tools.d.ts +2 -0
  66. package/dist/agent/pi/extension-tools.d.ts.map +1 -0
  67. package/dist/agent/pi/extension-tools.js +2 -0
  68. package/dist/agent/pi/extension-tools.js.map +1 -0
  69. package/dist/agent/pi/index.d.ts +2 -0
  70. package/dist/agent/pi/index.d.ts.map +1 -0
  71. package/dist/agent/pi/index.js +2 -0
  72. package/dist/agent/pi/index.js.map +1 -0
  73. package/dist/agent/pi/resource-types.d.ts +2 -0
  74. package/dist/agent/pi/resource-types.d.ts.map +1 -0
  75. package/dist/agent/pi/resource-types.js +2 -0
  76. package/dist/agent/pi/resource-types.js.map +1 -0
  77. package/dist/agent/pi/runtime.d.ts +2 -0
  78. package/dist/agent/pi/runtime.d.ts.map +1 -0
  79. package/dist/agent/pi/runtime.js +2 -0
  80. package/dist/agent/pi/runtime.js.map +1 -0
  81. package/dist/agent/prompt/context-prompt.d.ts +24 -0
  82. package/dist/agent/prompt/context-prompt.d.ts.map +1 -1
  83. package/dist/agent/prompt/context-prompt.js +15 -38
  84. package/dist/agent/prompt/context-prompt.js.map +1 -1
  85. package/dist/agent/prompt/index.d.ts +1 -1
  86. package/dist/agent/prompt/index.d.ts.map +1 -1
  87. package/dist/agent/prompt/index.js +1 -1
  88. package/dist/agent/prompt/index.js.map +1 -1
  89. package/dist/agent/result-reducer.d.ts +1 -1
  90. package/dist/agent/result-reducer.d.ts.map +1 -1
  91. package/dist/agent/run-cancellation.d.ts +1 -12
  92. package/dist/agent/run-cancellation.d.ts.map +1 -1
  93. package/dist/agent/run-cancellation.js +1 -96
  94. package/dist/agent/run-cancellation.js.map +1 -1
  95. package/dist/agent/run-ledger-types.d.ts +1 -196
  96. package/dist/agent/run-ledger-types.d.ts.map +1 -1
  97. package/dist/agent/run-ledger-types.js +1 -8
  98. package/dist/agent/run-ledger-types.js.map +1 -1
  99. package/dist/agent/run-ledger.d.ts +1 -43
  100. package/dist/agent/run-ledger.d.ts.map +1 -1
  101. package/dist/agent/run-ledger.js +1 -813
  102. package/dist/agent/run-ledger.js.map +1 -1
  103. package/dist/agent/run-timeline-events.d.ts +1 -2
  104. package/dist/agent/run-timeline-events.d.ts.map +1 -1
  105. package/dist/agent/run-timeline-events.js +1 -238
  106. package/dist/agent/run-timeline-events.js.map +1 -1
  107. package/dist/agent/runtime/adapters/index.d.ts +2 -0
  108. package/dist/agent/runtime/adapters/index.d.ts.map +1 -0
  109. package/dist/agent/runtime/adapters/index.js +2 -0
  110. package/dist/agent/runtime/adapters/index.js.map +1 -0
  111. package/dist/agent/runtime/adapters/mindos.d.ts +21 -0
  112. package/dist/agent/runtime/adapters/mindos.d.ts.map +1 -0
  113. package/dist/agent/runtime/adapters/mindos.js +14 -0
  114. package/dist/agent/runtime/adapters/mindos.js.map +1 -0
  115. package/dist/agent/runtime/attachments.d.ts +37 -0
  116. package/dist/agent/runtime/attachments.d.ts.map +1 -0
  117. package/dist/agent/runtime/attachments.js +187 -0
  118. package/dist/agent/runtime/attachments.js.map +1 -0
  119. package/dist/agent/runtime/capabilities.d.ts +10 -0
  120. package/dist/agent/runtime/capabilities.d.ts.map +1 -0
  121. package/dist/agent/runtime/capabilities.js +100 -0
  122. package/dist/agent/runtime/capabilities.js.map +1 -0
  123. package/dist/agent/runtime/child-process.d.ts +21 -0
  124. package/dist/agent/runtime/child-process.d.ts.map +1 -0
  125. package/dist/agent/runtime/child-process.js +29 -0
  126. package/dist/agent/runtime/child-process.js.map +1 -0
  127. package/dist/agent/runtime/claude-code-cli.d.ts +40 -0
  128. package/dist/agent/runtime/claude-code-cli.d.ts.map +1 -0
  129. package/dist/agent/runtime/claude-code-cli.js +288 -0
  130. package/dist/agent/runtime/claude-code-cli.js.map +1 -0
  131. package/dist/agent/runtime/claude-code-sdk.d.ts +62 -0
  132. package/dist/agent/runtime/claude-code-sdk.d.ts.map +1 -0
  133. package/dist/agent/runtime/claude-code-sdk.js +613 -0
  134. package/dist/agent/runtime/claude-code-sdk.js.map +1 -0
  135. package/dist/agent/runtime/codex-app-server.d.ts +172 -0
  136. package/dist/agent/runtime/codex-app-server.d.ts.map +1 -0
  137. package/dist/agent/runtime/codex-app-server.js +700 -0
  138. package/dist/agent/runtime/codex-app-server.js.map +1 -0
  139. package/dist/agent/runtime/codex-env.d.ts +42 -0
  140. package/dist/agent/runtime/codex-env.d.ts.map +1 -0
  141. package/dist/agent/runtime/codex-env.js +290 -0
  142. package/dist/agent/runtime/codex-env.js.map +1 -0
  143. package/dist/agent/runtime/descriptors.d.ts +19 -0
  144. package/dist/agent/runtime/descriptors.d.ts.map +1 -0
  145. package/dist/agent/runtime/descriptors.js +143 -0
  146. package/dist/agent/runtime/descriptors.js.map +1 -0
  147. package/dist/agent/runtime/detection.d.ts +15 -0
  148. package/dist/agent/runtime/detection.d.ts.map +1 -0
  149. package/dist/agent/runtime/detection.js +124 -0
  150. package/dist/agent/runtime/detection.js.map +1 -0
  151. package/dist/agent/runtime/index.d.ts +15 -0
  152. package/dist/agent/runtime/index.d.ts.map +1 -0
  153. package/dist/agent/runtime/index.js +15 -0
  154. package/dist/agent/runtime/index.js.map +1 -0
  155. package/dist/agent/runtime/registry.d.ts +152 -0
  156. package/dist/agent/runtime/registry.d.ts.map +1 -0
  157. package/dist/agent/runtime/registry.js +84 -0
  158. package/dist/agent/runtime/registry.js.map +1 -0
  159. package/dist/agent/runtime/run.d.ts +129 -0
  160. package/dist/agent/runtime/run.d.ts.map +1 -0
  161. package/dist/agent/runtime/run.js +739 -0
  162. package/dist/agent/runtime/run.js.map +1 -0
  163. package/dist/agent/runtime/runtime-env.d.ts +28 -0
  164. package/dist/agent/runtime/runtime-env.d.ts.map +1 -0
  165. package/dist/agent/runtime/runtime-env.js +66 -0
  166. package/dist/agent/runtime/runtime-env.js.map +1 -0
  167. package/dist/agent/runtime/runtime-errors.d.ts +20 -0
  168. package/dist/agent/runtime/runtime-errors.d.ts.map +1 -0
  169. package/dist/agent/runtime/runtime-errors.js +95 -0
  170. package/dist/agent/runtime/runtime-errors.js.map +1 -0
  171. package/dist/agent/runtime-permission-bridge.d.ts +1 -33
  172. package/dist/agent/runtime-permission-bridge.d.ts.map +1 -1
  173. package/dist/agent/runtime-permission-bridge.js +1 -283
  174. package/dist/agent/runtime-permission-bridge.js.map +1 -1
  175. package/dist/agent/selected-skills.d.ts +8 -0
  176. package/dist/agent/selected-skills.d.ts.map +1 -0
  177. package/dist/agent/selected-skills.js +27 -0
  178. package/dist/agent/selected-skills.js.map +1 -0
  179. package/dist/agent/session/index.d.ts +618 -0
  180. package/dist/agent/session/index.d.ts.map +1 -0
  181. package/dist/agent/session/index.js +1330 -0
  182. package/dist/agent/session/index.js.map +1 -0
  183. package/dist/agent/session/redaction.d.ts +3 -0
  184. package/dist/agent/session/redaction.d.ts.map +1 -0
  185. package/dist/agent/session/redaction.js +47 -0
  186. package/dist/agent/session/redaction.js.map +1 -0
  187. package/dist/agent/stream/index.d.ts +3 -0
  188. package/dist/agent/stream/index.d.ts.map +1 -0
  189. package/dist/agent/stream/index.js +3 -0
  190. package/dist/agent/stream/index.js.map +1 -0
  191. package/dist/agent/stream/stream-consumer.d.ts +65 -0
  192. package/dist/agent/stream/stream-consumer.d.ts.map +1 -0
  193. package/dist/agent/stream/stream-consumer.js +664 -0
  194. package/dist/agent/stream/stream-consumer.js.map +1 -0
  195. package/dist/agent/stream/stream-message-types.d.ts +128 -0
  196. package/dist/agent/stream/stream-message-types.d.ts.map +1 -0
  197. package/dist/agent/stream/stream-message-types.js +14 -0
  198. package/dist/agent/stream/stream-message-types.js.map +1 -0
  199. package/dist/agent/stream-consumer.d.ts +1 -64
  200. package/dist/agent/stream-consumer.d.ts.map +1 -1
  201. package/dist/agent/stream-consumer.js +1 -663
  202. package/dist/agent/stream-consumer.js.map +1 -1
  203. package/dist/agent/stream-message-types.d.ts +1 -137
  204. package/dist/agent/stream-message-types.d.ts.map +1 -1
  205. package/dist/agent/stream-message-types.js +1 -13
  206. package/dist/agent/stream-message-types.js.map +1 -1
  207. package/dist/agent/subagent/index.d.ts +3 -0
  208. package/dist/agent/subagent/index.d.ts.map +1 -0
  209. package/dist/agent/subagent/index.js +3 -0
  210. package/dist/agent/subagent/index.js.map +1 -0
  211. package/dist/agent/subagent/subagent-ledger-extension.d.ts +36 -0
  212. package/dist/agent/subagent/subagent-ledger-extension.d.ts.map +1 -0
  213. package/dist/agent/subagent/subagent-ledger-extension.js +572 -0
  214. package/dist/agent/subagent/subagent-ledger-extension.js.map +1 -0
  215. package/dist/agent/subagent/subagent-orchestrator.d.ts +62 -0
  216. package/dist/agent/subagent/subagent-orchestrator.d.ts.map +1 -0
  217. package/dist/agent/subagent/subagent-orchestrator.js +350 -0
  218. package/dist/agent/subagent/subagent-orchestrator.js.map +1 -0
  219. package/dist/agent/subagent-ledger-extension.d.ts +1 -35
  220. package/dist/agent/subagent-ledger-extension.d.ts.map +1 -1
  221. package/dist/agent/subagent-ledger-extension.js +1 -571
  222. package/dist/agent/subagent-ledger-extension.js.map +1 -1
  223. package/dist/agent/subagent-orchestrator.d.ts +1 -61
  224. package/dist/agent/subagent-orchestrator.d.ts.map +1 -1
  225. package/dist/agent/subagent-orchestrator.js +1 -349
  226. package/dist/agent/subagent-orchestrator.js.map +1 -1
  227. package/dist/agent/tool/executable-tool.d.ts +12 -0
  228. package/dist/agent/tool/executable-tool.d.ts.map +1 -0
  229. package/dist/agent/tool/executable-tool.js +2 -0
  230. package/dist/agent/tool/executable-tool.js.map +1 -0
  231. package/dist/agent/tool/index.d.ts +1 -1
  232. package/dist/agent/tool/index.d.ts.map +1 -1
  233. package/dist/agent/tool/index.js +1 -1
  234. package/dist/agent/tool/index.js.map +1 -1
  235. package/dist/agent/tool/kb-extension.d.ts +1 -37
  236. package/dist/agent/tool/kb-extension.d.ts.map +1 -1
  237. package/dist/agent/tool/kb-extension.js +1 -139
  238. package/dist/agent/tool/kb-extension.js.map +1 -1
  239. package/dist/agent/user-question-bridge.d.ts +1 -89
  240. package/dist/agent/user-question-bridge.d.ts.map +1 -1
  241. package/dist/agent/user-question-bridge.js +1 -259
  242. package/dist/agent/user-question-bridge.js.map +1 -1
  243. package/dist/agent-runtime/adapters/index.d.ts +2 -0
  244. package/dist/agent-runtime/adapters/index.d.ts.map +1 -0
  245. package/dist/agent-runtime/adapters/index.js +2 -0
  246. package/dist/agent-runtime/adapters/index.js.map +1 -0
  247. package/dist/agent-runtime/adapters/mindos.d.ts +2 -0
  248. package/dist/agent-runtime/adapters/mindos.d.ts.map +1 -0
  249. package/dist/agent-runtime/adapters/mindos.js +2 -0
  250. package/dist/agent-runtime/adapters/mindos.js.map +1 -0
  251. package/dist/agent-runtime/capabilities.d.ts +1 -9
  252. package/dist/agent-runtime/capabilities.d.ts.map +1 -1
  253. package/dist/agent-runtime/capabilities.js +1 -99
  254. package/dist/agent-runtime/capabilities.js.map +1 -1
  255. package/dist/agent-runtime/child-process.d.ts +1 -20
  256. package/dist/agent-runtime/child-process.d.ts.map +1 -1
  257. package/dist/agent-runtime/child-process.js +1 -28
  258. package/dist/agent-runtime/child-process.js.map +1 -1
  259. package/dist/agent-runtime/claude-code-cli.d.ts +1 -35
  260. package/dist/agent-runtime/claude-code-cli.d.ts.map +1 -1
  261. package/dist/agent-runtime/claude-code-cli.js +1 -287
  262. package/dist/agent-runtime/claude-code-cli.js.map +1 -1
  263. package/dist/agent-runtime/claude-code-sdk.d.ts +1 -40
  264. package/dist/agent-runtime/claude-code-sdk.d.ts.map +1 -1
  265. package/dist/agent-runtime/claude-code-sdk.js +1 -571
  266. package/dist/agent-runtime/claude-code-sdk.js.map +1 -1
  267. package/dist/agent-runtime/codex-app-server.d.ts +1 -157
  268. package/dist/agent-runtime/codex-app-server.d.ts.map +1 -1
  269. package/dist/agent-runtime/codex-app-server.js +1 -665
  270. package/dist/agent-runtime/codex-app-server.js.map +1 -1
  271. package/dist/agent-runtime/codex-env.d.ts +1 -41
  272. package/dist/agent-runtime/codex-env.d.ts.map +1 -1
  273. package/dist/agent-runtime/codex-env.js +1 -289
  274. package/dist/agent-runtime/codex-env.js.map +1 -1
  275. package/dist/agent-runtime/descriptors.d.ts +1 -18
  276. package/dist/agent-runtime/descriptors.d.ts.map +1 -1
  277. package/dist/agent-runtime/descriptors.js +1 -142
  278. package/dist/agent-runtime/descriptors.js.map +1 -1
  279. package/dist/agent-runtime/detection.d.ts +1 -14
  280. package/dist/agent-runtime/detection.d.ts.map +1 -1
  281. package/dist/agent-runtime/detection.js +1 -123
  282. package/dist/agent-runtime/detection.js.map +1 -1
  283. package/dist/agent-runtime/index.d.ts +1 -8
  284. package/dist/agent-runtime/index.d.ts.map +1 -1
  285. package/dist/agent-runtime/index.js +1 -8
  286. package/dist/agent-runtime/index.js.map +1 -1
  287. package/dist/agent-runtime/registry.d.ts +1 -151
  288. package/dist/agent-runtime/registry.d.ts.map +1 -1
  289. package/dist/agent-runtime/registry.js +1 -83
  290. package/dist/agent-runtime/registry.js.map +1 -1
  291. package/dist/agent-runtime/run.d.ts +1 -124
  292. package/dist/agent-runtime/run.d.ts.map +1 -1
  293. package/dist/agent-runtime/run.js +1 -720
  294. package/dist/agent-runtime/run.js.map +1 -1
  295. package/dist/agent-runtime/runtime-env.d.ts +1 -27
  296. package/dist/agent-runtime/runtime-env.d.ts.map +1 -1
  297. package/dist/agent-runtime/runtime-env.js +1 -65
  298. package/dist/agent-runtime/runtime-env.js.map +1 -1
  299. package/dist/agent-runtime/runtime-errors.d.ts +1 -19
  300. package/dist/agent-runtime/runtime-errors.d.ts.map +1 -1
  301. package/dist/agent-runtime/runtime-errors.js +1 -94
  302. package/dist/agent-runtime/runtime-errors.js.map +1 -1
  303. package/dist/agent-runtime.d.ts +1 -1
  304. package/dist/agent-runtime.js +1 -1
  305. package/dist/client.d.ts +8 -4
  306. package/dist/client.d.ts.map +1 -1
  307. package/dist/client.js.map +1 -1
  308. package/dist/foundation/config/schema.d.ts +1 -1
  309. package/dist/server/handlers/agent-runtime-codex.d.ts +1 -1
  310. package/dist/server/handlers/agent-runtime-codex.js +2 -2
  311. package/dist/server/handlers/agent-runtimes.d.ts +3 -3
  312. package/dist/server/handlers/agent-runtimes.js +5 -5
  313. package/dist/server/handlers/ask.d.ts +8 -4
  314. package/dist/server/handlers/ask.d.ts.map +1 -1
  315. package/dist/server/handlers/ask.js +7 -1
  316. package/dist/server/handlers/ask.js.map +1 -1
  317. package/dist/server/handlers/inbox-source.d.ts +1 -1
  318. package/dist/server/handlers/inbox-source.d.ts.map +1 -1
  319. package/dist/server/handlers/inbox-source.js +22 -0
  320. package/dist/server/handlers/inbox-source.js.map +1 -1
  321. package/dist/server/handlers/settings.d.ts +1 -1
  322. package/dist/server/handlers/settings.js +1 -1
  323. package/dist/server/handlers/setup.d.ts +2 -1
  324. package/dist/server/handlers/setup.d.ts.map +1 -1
  325. package/dist/server/handlers/setup.js +1 -0
  326. package/dist/server/handlers/setup.js.map +1 -1
  327. package/dist/server/index.d.ts +1 -1
  328. package/dist/server/index.d.ts.map +1 -1
  329. package/dist/server/index.js +1 -1
  330. package/dist/server/index.js.map +1 -1
  331. package/dist/server/runtime.d.ts +1 -1
  332. package/dist/session/index.d.ts +1 -650
  333. package/dist/session/index.d.ts.map +1 -1
  334. package/dist/session/index.js +1 -1455
  335. package/dist/session/index.js.map +1 -1
  336. package/dist/session/pi-coding-agent-runtime.d.ts +1 -9
  337. package/dist/session/pi-coding-agent-runtime.d.ts.map +1 -1
  338. package/dist/session/pi-coding-agent-runtime.js +1 -30
  339. package/dist/session/pi-coding-agent-runtime.js.map +1 -1
  340. package/dist/session/redaction.d.ts +1 -2
  341. package/dist/session/redaction.d.ts.map +1 -1
  342. package/dist/session/redaction.js +1 -46
  343. package/dist/session/redaction.js.map +1 -1
  344. package/dist/session.d.ts +1 -1
  345. package/dist/session.d.ts.map +1 -1
  346. package/dist/session.js +1 -1
  347. package/dist/session.js.map +1 -1
  348. package/dist/setup/index.d.ts +24 -3
  349. package/dist/setup/index.d.ts.map +1 -1
  350. package/dist/setup/index.js +102 -2
  351. package/dist/setup/index.js.map +1 -1
  352. package/package.json +97 -9
@@ -1,1456 +1,2 @@
1
- import { redactSensitiveObject, redactSensitiveText } from './redaction.js';
2
- export { redactSensitiveObject, redactSensitiveText } from './redaction.js';
3
- export const MINDOS_SESSION_STREAM_SCHEMA = {
4
- protocol: 'mindos.session.events',
5
- version: 1,
6
- events: [
7
- 'session.started',
8
- 'message.delta',
9
- 'tool.started',
10
- 'tool.completed',
11
- 'session.completed',
12
- 'session.failed',
13
- ],
14
- };
15
- export function createMindosSessionEvent(input) {
16
- return {
17
- ...input,
18
- timestamp: input.timestamp ?? new Date().toISOString(),
19
- };
20
- }
21
- export const MINDOS_ASK_STREAM_EVENT_TYPES = [
22
- 'text_delta',
23
- 'thinking_delta',
24
- 'agent_run_context',
25
- 'tool_start',
26
- 'tool_delta',
27
- 'tool_end',
28
- 'runtime_permission_request',
29
- 'runtime_permission_resolved',
30
- 'user_question_start',
31
- 'user_question_answered',
32
- 'user_question_cancelled',
33
- 'runtime_binding',
34
- 'done',
35
- 'error',
36
- 'status',
37
- ];
38
- export const MINDOS_SSE_HEADERS = {
39
- 'Content-Type': 'text/event-stream',
40
- 'Cache-Control': 'no-cache, no-transform',
41
- Connection: 'keep-alive',
42
- 'X-Accel-Buffering': 'no',
43
- };
44
- function isRecord(value) {
45
- return !!value && typeof value === 'object';
46
- }
47
- function nestedRecord(value, key) {
48
- const child = value[key];
49
- return isRecord(child) ? child : undefined;
50
- }
51
- export function isTextDeltaEvent(event) {
52
- if (!isRecord(event) || event.type !== 'message_update')
53
- return false;
54
- return nestedRecord(event, 'assistantMessageEvent')?.type === 'text_delta';
55
- }
56
- export function getTextDelta(event) {
57
- if (!isRecord(event))
58
- return '';
59
- const assistantEvent = nestedRecord(event, 'assistantMessageEvent');
60
- return typeof assistantEvent?.delta === 'string' ? assistantEvent.delta : '';
61
- }
62
- export function isThinkingDeltaEvent(event) {
63
- if (!isRecord(event) || event.type !== 'message_update')
64
- return false;
65
- return nestedRecord(event, 'assistantMessageEvent')?.type === 'thinking_delta';
66
- }
67
- export function getThinkingDelta(event) {
68
- return getTextDelta(event);
69
- }
70
- export function isToolExecutionStartEvent(event) {
71
- return isRecord(event) && event.type === 'tool_execution_start';
72
- }
73
- export function getToolExecutionStart(event) {
74
- if (!isRecord(event))
75
- return { toolCallId: '', toolName: 'unknown', args: {} };
76
- return {
77
- toolCallId: typeof event.toolCallId === 'string' ? event.toolCallId : '',
78
- toolName: typeof event.toolName === 'string' ? event.toolName : 'unknown',
79
- args: event.args ?? {},
80
- };
81
- }
82
- export function isToolExecutionEndEvent(event) {
83
- return isRecord(event) && event.type === 'tool_execution_end';
84
- }
85
- export function getToolExecutionEnd(event) {
86
- if (!isRecord(event))
87
- return { toolCallId: '', output: '', isError: false };
88
- const result = nestedRecord(event, 'result');
89
- const content = Array.isArray(result?.content) ? result.content : [];
90
- const output = content
91
- .filter((part) => isRecord(part) && part.type === 'text')
92
- .map((part) => part.text ?? '')
93
- .join('');
94
- return {
95
- toolCallId: typeof event.toolCallId === 'string' ? event.toolCallId : '',
96
- output,
97
- isError: event.isError === true,
98
- };
99
- }
100
- export function isTurnEndEvent(event) {
101
- return isRecord(event) && event.type === 'turn_end';
102
- }
103
- export function getTurnEndData(event) {
104
- if (!isRecord(event))
105
- return { toolResults: [] };
106
- return {
107
- toolResults: Array.isArray(event.toolResults)
108
- ? event.toolResults.filter((item) => isRecord(item) && typeof item.toolName === 'string')
109
- : [],
110
- };
111
- }
112
- export function createMindosAgentEventReducer(options) {
113
- const stepHistory = [];
114
- let stepCount = 0;
115
- let loopCooldown = 0;
116
- let lastModelError = '';
117
- const loopWarningMessage = options.loopWarningMessage
118
- ?? '[SYSTEM WARNING] You appear to be in a loop — repeating the same tool calls in a cycle. Try a completely different approach or ask the user for clarification.';
119
- return {
120
- get lastModelError() {
121
- return lastModelError;
122
- },
123
- get stepCount() {
124
- return stepCount;
125
- },
126
- handle(event) {
127
- if (isTextDeltaEvent(event)) {
128
- return { events: [{ type: 'text_delta', delta: getTextDelta(event) }], hasVisibleContent: true };
129
- }
130
- if (isThinkingDeltaEvent(event)) {
131
- return { events: [{ type: 'thinking_delta', delta: getThinkingDelta(event) }], hasVisibleContent: true };
132
- }
133
- if (isToolExecutionStartEvent(event)) {
134
- const { toolCallId, toolName, args } = getToolExecutionStart(event);
135
- return {
136
- events: [{ type: 'tool_start', toolCallId, toolName, args: sanitizeToolArgs(toolName, args) }],
137
- hasVisibleContent: true,
138
- };
139
- }
140
- if (isToolExecutionEndEvent(event)) {
141
- const { toolCallId, output, isError } = getToolExecutionEnd(event);
142
- return {
143
- events: [{ type: 'tool_end', toolCallId, output: sanitizeToolOutput(output), isError }],
144
- hasVisibleContent: false,
145
- toolExecutions: 1,
146
- };
147
- }
148
- if (isTurnEndEvent(event)) {
149
- stepCount += 1;
150
- const effect = {
151
- events: [],
152
- hasVisibleContent: false,
153
- stepCount,
154
- };
155
- const turnUsage = event.usage;
156
- if (turnUsage && typeof turnUsage.inputTokens === 'number') {
157
- effect.tokenUsage = { input: turnUsage.inputTokens, output: turnUsage.outputTokens ?? 0 };
158
- }
159
- const { toolResults } = getTurnEndData(event);
160
- if (toolResults.length > 0) {
161
- const newEntries = toolResults.map((toolResult) => ({
162
- tool: toolResult.toolName ?? 'unknown',
163
- input: JSON.stringify(toolResult.content, null, 0),
164
- }));
165
- stepHistory.push(...newEntries);
166
- if (stepHistory.length > 20)
167
- stepHistory.splice(0, stepHistory.length - 20);
168
- }
169
- if (loopCooldown > 0) {
170
- loopCooldown -= 1;
171
- }
172
- else if (detectMindosAgentLoop(stepHistory)) {
173
- loopCooldown = 3;
174
- effect.steerMessage = loopWarningMessage;
175
- }
176
- if (stepCount >= options.stepLimit) {
177
- effect.shouldAbort = true;
178
- }
179
- return effect;
180
- }
181
- if (isRecord(event) && event.type === 'agent_end') {
182
- const msgs = Array.isArray(event.messages) ? event.messages : [];
183
- for (let i = msgs.length - 1; i >= 0; i -= 1) {
184
- const message = msgs[i];
185
- if (isRecord(message)
186
- && message.role === 'assistant'
187
- && message.stopReason === 'error'
188
- && typeof message.errorMessage === 'string') {
189
- lastModelError = message.errorMessage;
190
- return { events: [], hasVisibleContent: false, lastModelError };
191
- }
192
- }
193
- }
194
- return { events: [], hasVisibleContent: false };
195
- },
196
- };
197
- }
198
- export function sanitizeToolArgs(toolName, args) {
199
- if (!isRecord(args))
200
- return typeof args === 'string' ? redactSensitiveText(args) : redactSensitiveObject(args);
201
- if (toolName === 'batch_create_files' && Array.isArray(args.files)) {
202
- return redactSensitiveObject({
203
- ...args,
204
- files: args.files
205
- .filter(isRecord)
206
- .map((file) => ({
207
- path: file.path,
208
- ...(file.description ? { description: file.description } : {}),
209
- })),
210
- });
211
- }
212
- if (typeof args.content === 'string' && args.content.length > 200) {
213
- return redactSensitiveObject({ ...args, content: `[${args.content.length} chars]` });
214
- }
215
- if (typeof args.text === 'string' && args.text.length > 200) {
216
- return redactSensitiveObject({ ...args, text: `[${args.text.length} chars]` });
217
- }
218
- return redactSensitiveObject(args);
219
- }
220
- export function sanitizeToolOutput(output) {
221
- return redactSensitiveText(output);
222
- }
223
- export function encodeMindosSseEvent(event) {
224
- return `data:${JSON.stringify(event)}\n\n`;
225
- }
226
- export function parseMindosSseLine(line) {
227
- const trimmed = line.trim();
228
- if (!trimmed.startsWith('data:'))
229
- return null;
230
- const json = trimmed.slice(5).trim();
231
- if (!json || json === '[DONE]')
232
- return null;
233
- try {
234
- const parsed = JSON.parse(json);
235
- if (!isRecord(parsed) || typeof parsed.type !== 'string')
236
- return null;
237
- if (!MINDOS_ASK_STREAM_EVENT_TYPES.includes(parsed.type))
238
- return null;
239
- return parsed;
240
- }
241
- catch {
242
- return null;
243
- }
244
- }
245
- export function normalizeMindosAskMode(mode) {
246
- if (mode === 'organize')
247
- return 'organize';
248
- return 'agent';
249
- }
250
- export function normalizeMindosAskStepLimit(options) {
251
- const defaultMaxSteps = options.agentMaxSteps ?? 20;
252
- const raw = typeof options.requestedMaxSteps === 'number' && Number.isFinite(options.requestedMaxSteps)
253
- ? options.requestedMaxSteps
254
- : defaultMaxSteps;
255
- return Math.min(999, Math.max(1, Number(raw)));
256
- }
257
- export function resolveMindosAgentTimeoutMs(raw = undefined, defaultMs = 600_000) {
258
- if (!raw)
259
- return defaultMs;
260
- const parsed = Number.parseInt(raw, 10);
261
- return Number.isFinite(parsed) && parsed > 0 ? parsed : defaultMs;
262
- }
263
- export function expandMindosAskAttachedFiles(raw, collectAllFiles, maxDirFiles = 30) {
264
- if (!Array.isArray(raw))
265
- return raw;
266
- const result = [];
267
- let allFiles;
268
- for (const entry of raw) {
269
- if (entry.endsWith('/')) {
270
- allFiles ??= collectAllFiles();
271
- let count = 0;
272
- for (const filePath of allFiles) {
273
- if (filePath.startsWith(entry) && ++count <= maxDirFiles)
274
- result.push(filePath);
275
- }
276
- }
277
- else {
278
- result.push(entry);
279
- }
280
- }
281
- return result;
282
- }
283
- export function loadMindosAskFileContext(attachedFiles, currentFile, mode, services) {
284
- const contextParts = [];
285
- const failedFiles = [];
286
- const seen = new Set();
287
- let cumulativeSize = 0;
288
- function appendFile(filePath, label) {
289
- if (seen.has(filePath))
290
- return;
291
- seen.add(filePath);
292
- const validation = services.validateFileSize?.(filePath, cumulativeSize) ?? {
293
- valid: true,
294
- newCumulativeSize: cumulativeSize,
295
- };
296
- if (!validation.valid) {
297
- services.warn?.(`[ask] ${mode}: file size validation failed for "${filePath}": ${validation.error ?? 'invalid'}`);
298
- failedFiles.push(filePath);
299
- return;
300
- }
301
- try {
302
- const raw = services.readFile(filePath);
303
- const content = services.truncate ? services.truncate(raw) : raw;
304
- contextParts.push(`### ${label}: ${filePath}\n\n${content}`);
305
- cumulativeSize = validation.newCumulativeSize;
306
- }
307
- catch (error) {
308
- services.warn?.(`[ask] ${mode}: failed to read ${label.startsWith('Attached') ? 'attached file' : 'currentFile'} "${filePath}":`, error);
309
- failedFiles.push(filePath);
310
- }
311
- }
312
- for (const filePath of attachedFiles ?? [])
313
- appendFile(filePath, 'Attached file from the MindOS knowledge base');
314
- if (currentFile)
315
- appendFile(currentFile, 'Current file from the MindOS knowledge base');
316
- return { contextParts, failedFiles };
317
- }
318
- export function createMindosUploadedFileParts(uploadedFiles, options = {}) {
319
- if (!Array.isArray(uploadedFiles))
320
- return [];
321
- const maxBytes = options.maxBytes ?? 100_000;
322
- const limit = options.limit ?? 8;
323
- const parts = [];
324
- for (const file of uploadedFiles.slice(0, limit)) {
325
- if (!file || typeof file !== 'object')
326
- continue;
327
- const record = file;
328
- if (typeof record.name !== 'string' || typeof record.content !== 'string')
329
- continue;
330
- const content = record.content.length > maxBytes
331
- ? `${record.content.slice(0, maxBytes)}\n\n[...truncated]`
332
- : record.content;
333
- parts.push(`### ${record.name}\n\n${content}`);
334
- }
335
- return parts;
336
- }
337
- export function buildMindosExternalRuntimePrompt(input) {
338
- const prompt = input.prompt.trim();
339
- const contextSections = [];
340
- const modeGuidance = getExternalRuntimeModeGuidance(input.mode);
341
- if (modeGuidance) {
342
- contextSections.push([
343
- '## MindOS Request Guidance',
344
- modeGuidance,
345
- ].join('\n'));
346
- }
347
- contextSections.push([
348
- '## MindOS Chat Panel Bridge',
349
- 'If the available tools include `AskUserQuestion`, use it for user confirmations or structured choices that affect the next action. Keep questions concise and include concrete options.',
350
- ].join('\n'));
351
- if (input.fileContext?.contextParts.length) {
352
- contextSections.push([
353
- '## Attached files from the MindOS knowledge base',
354
- 'The following content already exists in MindOS and was explicitly attached for this turn. Cite stable paths when using it.',
355
- '',
356
- input.fileContext.contextParts.join('\n\n---\n\n'),
357
- ].join('\n'));
358
- }
359
- if (input.uploadedParts?.length) {
360
- contextSections.push([
361
- '## Files uploaded by the user for this request',
362
- 'The user uploaded the following file content for this turn. It may not exist in the MindOS knowledge base yet; use it directly unless it is saved first.',
363
- '',
364
- input.uploadedParts.join('\n\n---\n\n'),
365
- ].join('\n'));
366
- }
367
- if (input.recalledKnowledge?.length) {
368
- const block = input.recalledKnowledge
369
- .map((item) => `### ${item.path}\n\n${item.content}`)
370
- .join('\n\n---\n\n');
371
- contextSections.push([
372
- '## Auto-Recalled MindOS Knowledge',
373
- 'MindOS found these related notes for the user request. Cite file paths when relying on them.',
374
- '',
375
- block,
376
- ].join('\n'));
377
- }
378
- if (input.fileContext?.failedFiles.length) {
379
- contextSections.push([
380
- '## Unavailable MindOS Context',
381
- `These attached files could not be loaded: ${input.fileContext.failedFiles.join(', ')}`,
382
- ].join('\n'));
383
- }
384
- if (contextSections.length === 0)
385
- return prompt;
386
- return [
387
- prompt,
388
- '---',
389
- '## MindOS Turn Context',
390
- ...contextSections,
391
- ].filter(Boolean).join('\n\n');
392
- }
393
- function getExternalRuntimeModeGuidance(mode) {
394
- if (mode === 'organize') {
395
- return 'Prioritize classification, cleanup, and knowledge organization. Use uploaded or selected materials as source material for well-structured MindOS notes when tools and permissions allow it.';
396
- }
397
- return null;
398
- }
399
- export function safeParseMindosJsonObject(raw) {
400
- if (!raw)
401
- return {};
402
- try {
403
- const parsed = JSON.parse(raw);
404
- return isRecord(parsed) ? parsed : {};
405
- }
406
- catch {
407
- return {};
408
- }
409
- }
410
- export function dirnameOfMindosPath(filePath) {
411
- if (!filePath)
412
- return null;
413
- const normalized = filePath.replace(/\\/g, '/');
414
- const idx = normalized.lastIndexOf('/');
415
- if (idx <= 0)
416
- return null;
417
- return normalized.slice(0, idx);
418
- }
419
- export function isMindosTransientError(err) {
420
- const msg = err.message.toLowerCase();
421
- if (msg.includes('timeout') || msg.includes('timed out') || msg.includes('etimedout'))
422
- return true;
423
- if (msg.includes('429') || msg.includes('rate limit') || msg.includes('too many requests'))
424
- return true;
425
- if (/\b5\d{2}\b/.test(msg) || msg.includes('internal server error') || msg.includes('service unavailable'))
426
- return true;
427
- if (msg.includes('econnreset') || msg.includes('econnrefused') || msg.includes('socket hang up'))
428
- return true;
429
- if (msg.includes('overloaded') || msg.includes('capacity'))
430
- return true;
431
- return false;
432
- }
433
- const MINDOS_NON_RETRYABLE_STATUS = new Set([401, 403, 429]);
434
- const MINDOS_NON_RETRYABLE_PATTERNS = [
435
- /api.?key/i,
436
- /model.*not.?found/i,
437
- /authentication/i,
438
- /unauthorized/i,
439
- /forbidden/i,
440
- ];
441
- export function isMindosRetryableError(err, httpStatus) {
442
- if (err instanceof DOMException && err.name === 'AbortError')
443
- return false;
444
- if (httpStatus && MINDOS_NON_RETRYABLE_STATUS.has(httpStatus))
445
- return false;
446
- if (err instanceof Error) {
447
- const msg = err.message;
448
- if (MINDOS_NON_RETRYABLE_PATTERNS.some((pattern) => pattern.test(msg)))
449
- return false;
450
- }
451
- return true;
452
- }
453
- export function mindosRetryDelay(attempt) {
454
- return Math.min(1000 * 2 ** attempt, 10_000);
455
- }
456
- export function sleepMindos(ms, signal) {
457
- return new Promise((resolveSleep, reject) => {
458
- const abortReason = () => signal?.reason ?? new DOMException('The operation was aborted.', 'AbortError');
459
- if (signal?.aborted) {
460
- reject(abortReason());
461
- return;
462
- }
463
- const timer = setTimeout(resolveSleep, ms);
464
- signal?.addEventListener('abort', () => {
465
- clearTimeout(timer);
466
- reject(abortReason());
467
- }, { once: true });
468
- });
469
- }
470
- export async function runMindosAskWithRetry(options) {
471
- const maxRetries = options.maxRetries ?? 3;
472
- const isTransient = options.isTransientError ?? isMindosTransientError;
473
- const delayForAttempt = options.retryDelay ?? mindosRetryDelay;
474
- const wait = options.sleep ?? sleepMindos;
475
- const retryMessage = options.retryMessage ?? ((attempt, max) => `Request failed, retrying (${attempt}/${max})...`);
476
- let lastError = null;
477
- for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
478
- try {
479
- await options.execute(attempt);
480
- return null;
481
- }
482
- catch (error) {
483
- lastError = error instanceof Error ? error : new Error(String(error));
484
- await options.onAttemptError?.(lastError, attempt);
485
- const canRetry = !options.hasContent() && attempt < maxRetries && isTransient(lastError);
486
- if (!canRetry)
487
- break;
488
- options.send({ type: 'status', message: retryMessage(attempt, maxRetries) });
489
- await wait(delayForAttempt(attempt), options.signal);
490
- }
491
- }
492
- return lastError;
493
- }
494
- export function mapMindosAcpUpdateToSseEvents(update, options = {}) {
495
- switch (update.type) {
496
- case 'agent_message_chunk':
497
- case 'text':
498
- if (!update.text)
499
- return { events: [], hasVisibleContent: false };
500
- return { events: [{ type: 'text_delta', delta: update.text }], hasVisibleContent: true };
501
- case 'agent_thought_chunk':
502
- if (!update.text)
503
- return { events: [], hasVisibleContent: false };
504
- return { events: [{ type: 'thinking_delta', delta: update.text }], hasVisibleContent: true };
505
- case 'tool_call':
506
- if (!update.toolCall)
507
- return { events: [], hasVisibleContent: false };
508
- return {
509
- events: [{
510
- type: 'tool_start',
511
- toolCallId: update.toolCall.toolCallId,
512
- toolName: update.toolCall.title ?? update.toolCall.kind ?? 'tool',
513
- args: sanitizeToolArgs(update.toolCall.title ?? update.toolCall.kind ?? 'tool', safeParseMindosJsonObject(update.toolCall.rawInput)),
514
- }],
515
- hasVisibleContent: true,
516
- };
517
- case 'tool_call_update':
518
- if (!update.toolCall || (update.toolCall.status !== 'completed' && update.toolCall.status !== 'failed')) {
519
- return { events: [], hasVisibleContent: false };
520
- }
521
- return {
522
- events: [{
523
- type: 'tool_end',
524
- toolCallId: update.toolCall.toolCallId,
525
- output: sanitizeToolOutput(update.toolCall.rawOutput ?? ''),
526
- isError: update.toolCall.status === 'failed',
527
- }],
528
- hasVisibleContent: false,
529
- };
530
- case 'plan':
531
- if (!update.plan?.entries)
532
- return { events: [], hasVisibleContent: false };
533
- return {
534
- events: [{
535
- type: 'text_delta',
536
- delta: `\n\n${update.plan.entries.map((entry) => `${planEntryIcon(entry.status)} ${entry.content ?? ''}`).join('\n')}\n\n`,
537
- }],
538
- hasVisibleContent: true,
539
- };
540
- case 'error':
541
- if (options.suppressErrors)
542
- return { events: [], hasVisibleContent: false };
543
- return { events: [{ type: 'error', message: update.error ?? 'ACP agent error' }], hasVisibleContent: false };
544
- default:
545
- return { events: [], hasVisibleContent: false };
546
- }
547
- }
548
- function planEntryIcon(status) {
549
- if (status === 'completed')
550
- return '\u2705';
551
- if (status === 'in_progress')
552
- return '\u26a1';
553
- return '\u23f3';
554
- }
555
- export async function runMindosAcpAskSession(options) {
556
- let sessionId;
557
- const closeCurrentSession = async () => {
558
- if (!sessionId)
559
- return;
560
- const id = sessionId;
561
- sessionId = undefined;
562
- await options.closeSession(id).catch(() => { });
563
- };
564
- try {
565
- const timeoutMs = options.timeoutMs ?? resolveMindosAgentTimeoutMs();
566
- const lastError = await runMindosAskWithRetry({
567
- maxRetries: options.maxRetries,
568
- signal: options.signal,
569
- hasContent: options.hasContent,
570
- send: options.send,
571
- sleep: options.sleep,
572
- retryDelay: options.retryDelay,
573
- onAttemptError: closeCurrentSession,
574
- execute: async () => {
575
- await closeCurrentSession();
576
- const session = await options.createSession(options.agentId, { cwd: options.cwd });
577
- sessionId = session.id;
578
- let removeAbortListener;
579
- const abortPrompt = new Promise((_resolve, reject) => {
580
- if (!options.signal)
581
- return;
582
- const abortReason = () => options.signal?.reason ?? new DOMException('The operation was aborted.', 'AbortError');
583
- if (options.signal.aborted) {
584
- void options.cancelPrompt?.(session.id).catch(() => { });
585
- reject(abortReason());
586
- return;
587
- }
588
- const onAbort = () => {
589
- void options.cancelPrompt?.(session.id).catch(() => { });
590
- reject(abortReason());
591
- };
592
- options.signal.addEventListener('abort', onAbort, { once: true });
593
- removeAbortListener = () => options.signal?.removeEventListener('abort', onAbort);
594
- });
595
- await runMindosWithTimeout(Promise.race([
596
- options.promptStream(sessionId, options.prompt, (update) => {
597
- const mapped = mapMindosAcpUpdateToSseEvents(update, { suppressErrors: options.hasContent() });
598
- if (mapped.hasVisibleContent)
599
- options.onVisibleContent?.();
600
- for (const event of mapped.events)
601
- options.send(event);
602
- }, options.signal),
603
- abortPrompt,
604
- ]).finally(() => removeAbortListener?.()), timeoutMs, options.timeoutMessage?.(timeoutMs) ?? `ACP agent execution timeout after ${timeoutMs / 1000} seconds`);
605
- },
606
- });
607
- if (lastError) {
608
- options.send({ type: 'error', message: options.errorMessage?.(lastError) ?? `ACP Agent Error: ${lastError.message}` });
609
- return { error: lastError };
610
- }
611
- options.send({ type: 'done' });
612
- return {};
613
- }
614
- finally {
615
- await closeCurrentSession();
616
- }
617
- }
618
- export async function runMindosWithTimeout(promise, timeoutMs, message) {
619
- let timer;
620
- const timeout = new Promise((_resolve, reject) => {
621
- timer = setTimeout(() => {
622
- const error = new Error(message);
623
- error.code = 'TIMEOUT';
624
- reject(error);
625
- }, timeoutMs);
626
- });
627
- try {
628
- return await Promise.race([promise, timeout]);
629
- }
630
- finally {
631
- if (timer)
632
- clearTimeout(timer);
633
- }
634
- }
635
- async function runMindosAbortable(promise, signal, onAbort, message) {
636
- if (!signal)
637
- return promise;
638
- const abortReason = () => {
639
- const reason = signal.reason;
640
- if (reason instanceof Error)
641
- return reason;
642
- const error = new Error(typeof reason === 'string' && reason ? reason : message);
643
- error.name = 'AbortError';
644
- return error;
645
- };
646
- if (signal.aborted) {
647
- await onAbort();
648
- throw abortReason();
649
- }
650
- let removeAbortListener;
651
- const abortPromise = new Promise((_resolve, reject) => {
652
- const abort = () => {
653
- void Promise.resolve(onAbort()).finally(() => reject(abortReason()));
654
- };
655
- signal.addEventListener('abort', abort, { once: true });
656
- removeAbortListener = () => signal.removeEventListener('abort', abort);
657
- });
658
- try {
659
- return await Promise.race([promise, abortPromise]);
660
- }
661
- finally {
662
- removeAbortListener?.();
663
- }
664
- }
665
- export async function runMindosPiAgentAskSession(options) {
666
- let hasContent = false;
667
- let lastModelError = '';
668
- const effectiveBaseUrlKey = options.effectiveBaseUrlKey ?? options.baseUrl ?? 'default';
669
- const reducer = createMindosAgentEventReducer({ stepLimit: options.stepLimit });
670
- options.session.subscribe((event) => {
671
- const effect = reducer.handle(event);
672
- if (effect.hasVisibleContent)
673
- hasContent = true;
674
- for (const sseEvent of effect.events)
675
- options.send(sseEvent);
676
- if (effect.toolExecutions)
677
- options.onToolExecution?.();
678
- if (effect.tokenUsage)
679
- options.onTokens?.(effect.tokenUsage.input, effect.tokenUsage.output);
680
- if (effect.steerMessage)
681
- void options.session.steer(effect.steerMessage);
682
- if (effect.shouldAbort)
683
- void options.session.abort();
684
- if (effect.lastModelError)
685
- lastModelError = effect.lastModelError;
686
- if (effect.stepCount)
687
- options.onStep?.(effect.stepCount, options.stepLimit);
688
- });
689
- const handledCachedProxyFallback = await runMindosAskProxyFallback({
690
- phase: 'before-stream',
691
- provider: options.provider,
692
- baseUrl: options.baseUrl,
693
- compatMode: options.compatMode,
694
- send: options.send,
695
- messages: options.proxyMessages,
696
- runFallback: options.runFallback,
697
- });
698
- if (handledCachedProxyFallback)
699
- return { hasContent, lastModelError };
700
- const timeoutMs = options.timeoutMs ?? resolveMindosAgentTimeoutMs();
701
- const lastPromptError = await runMindosAskWithRetry({
702
- signal: options.signal,
703
- hasContent: () => hasContent,
704
- send: options.send,
705
- sleep: options.sleep,
706
- retryDelay: options.retryDelay,
707
- execute: async () => {
708
- await runMindosWithTimeout(runMindosAbortable(options.session.prompt(options.prompt, options.promptOptions), options.signal, () => options.session.abort(), 'Agent run was canceled.'), timeoutMs, options.timeoutMessage?.(timeoutMs) ?? `Agent execution timeout after ${timeoutMs / 1000} seconds`);
709
- },
710
- });
711
- if (lastPromptError)
712
- throw lastPromptError;
713
- const handledProxyFallback = await runMindosAskProxyFallback({
714
- phase: 'after-stream',
715
- provider: options.provider,
716
- baseUrl: options.baseUrl,
717
- effectiveBaseUrlKey,
718
- hasContent,
719
- lastModelError,
720
- send: options.send,
721
- messages: options.proxyMessages,
722
- runFallback: options.runFallback,
723
- writeCompat: options.writeCompat,
724
- });
725
- if (!handledProxyFallback)
726
- options.send({ type: 'done' });
727
- return { hasContent, lastModelError };
728
- }
729
- function reportMindosExtensionLoadErrors(resourceLoader, onExtensionLoadErrors) {
730
- let errors = [];
731
- try {
732
- errors = resourceLoader.getExtensions?.().errors ?? [];
733
- }
734
- catch {
735
- return; // diagnostics must never break session setup
736
- }
737
- if (errors.length === 0)
738
- return;
739
- if (onExtensionLoadErrors) {
740
- onExtensionLoadErrors(errors);
741
- return;
742
- }
743
- for (const entry of errors) {
744
- console.error(`[mindos] extension failed to load: ${entry.path}: ${entry.error}`);
745
- }
746
- }
747
- export async function createMindosPiAgentRuntime(options) {
748
- const lastMessage = options.messages.length > 0 ? options.messages[options.messages.length - 1] : undefined;
749
- const lastUserContent = lastMessage?.role === 'user' ? lastMessage.content : '';
750
- const lastUserSkillName = lastMessage?.role === 'user' && typeof lastMessage.skillName === 'string'
751
- ? lastMessage.skillName
752
- : undefined;
753
- const lastUserImages = extractMindosUserImages(lastMessage);
754
- const modelConfig = options.services.resolveModelConfig({
755
- providerOverride: options.providerOverride,
756
- modelOverride: options.modelOverride,
757
- messages: options.messages,
758
- hasImages: hasMindosMessageImages(options.messages),
759
- });
760
- let systemPrompt = options.systemPrompt;
761
- if (modelConfig.provider === 'ollama' && options.services.getOllamaContextWindow && options.services.estimateTokens && options.services.compactPrompt) {
762
- const ollamaBase = modelConfig.baseUrl || 'http://localhost:11434/v1';
763
- const contextWindow = await options.services.getOllamaContextWindow(ollamaBase, modelConfig.modelName);
764
- const promptTokens = options.services.estimateTokens(systemPrompt);
765
- const maxPromptTokens = contextWindow ? Math.floor(contextWindow * 0.7) : undefined;
766
- options.services.onOllamaContext?.({ modelName: modelConfig.modelName, contextWindow, promptTokens, maxPromptTokens });
767
- if (maxPromptTokens && promptTokens > maxPromptTokens) {
768
- systemPrompt = options.services.compactPrompt(systemPrompt, {
769
- maxPromptTokens,
770
- estimateTokens: options.services.estimateTokens,
771
- onStrip: options.services.onOllamaCompactStrip,
772
- });
773
- options.services.onOllamaCompacted?.({
774
- beforeTokens: promptTokens,
775
- afterTokens: options.services.estimateTokens(systemPrompt),
776
- });
777
- }
778
- }
779
- const agentMessages = toMindosAgentMessages(options.messages);
780
- const historyMessages = agentMessages.slice(0, -1);
781
- const llmHistoryMessages = options.services.convertToLlm(historyMessages);
782
- options.services.setKbMode(options.mode);
783
- const authStorage = options.services.createAuthStorage();
784
- authStorage.setRuntimeApiKey(options.services.toRuntimeProvider(modelConfig.provider), modelConfig.apiKey);
785
- const modelRegistry = options.services.createModelRegistry(authStorage);
786
- const settingsManager = options.services.createSettingsManager(createMindosPiSettingsConfig(options.agentConfig, modelConfig.provider));
787
- const coreSkillNames = new Set(['mindos', 'mindos-zh', 'mindos-max', 'mindos-max-zh']);
788
- // Agent-mode skill-index additions are discovered only after the first
789
- // reload(), but the loader captured `systemPrompt` at construction. The
790
- // override below re-applies the suffix on every reload, so the streaming
791
- // session sees the available-skill index. Turn-local active skill requests
792
- // belong in the latest user/context prompt, not in system identity.
793
- let agentPromptSuffix = '';
794
- const resourceLoader = options.services.createResourceLoader({
795
- cwd: options.projectRoot,
796
- agentDir: options.agentDir,
797
- settingsManager,
798
- systemPrompt,
799
- systemPromptOverride: (base) => (agentPromptSuffix ? `${base ?? ''}${agentPromptSuffix}` : base),
800
- appendSystemPrompt: [],
801
- agentsFilesOverride: (result) => ({ ...result, agentsFiles: [] }),
802
- skillsOverride: (result) => ({
803
- ...result,
804
- skills: result.skills.filter((skill) => !coreSkillNames.has(skill.name)),
805
- }),
806
- additionalSkillPaths: options.additionalSkillPaths ?? [],
807
- additionalExtensionPaths: options.additionalExtensionPaths ?? [],
808
- });
809
- await resourceLoader.reload();
810
- reportMindosExtensionLoadErrors(resourceLoader, options.services.onExtensionLoadErrors);
811
- if (options.mode === 'agent') {
812
- const disabledSkillNames = new Set(options.serverSettings?.disabledSkills ?? []);
813
- const discoveredSkills = resourceLoader.getSkills?.().skills ?? [];
814
- const thirdPartySkills = discoveredSkills.filter((skill) => !coreSkillNames.has(skill.name) && !skill.disableModelInvocation && !disabledSkillNames.has(skill.name));
815
- if (thirdPartySkills.length > 0 && options.services.generateSkillsXml) {
816
- agentPromptSuffix += `\n\n---\n\n${options.services.generateSkillsXml(thirdPartySkills)}`;
817
- }
818
- if (agentPromptSuffix) {
819
- // Keep the returned prompt (used by the non-streaming fallback) in sync
820
- // with what the streaming session sees via the override.
821
- systemPrompt += agentPromptSuffix;
822
- await resourceLoader.reload();
823
- reportMindosExtensionLoadErrors(resourceLoader, options.services.onExtensionLoadErrors);
824
- }
825
- }
826
- const sessionManager = options.services.createSessionManager();
827
- for (const message of llmHistoryMessages) {
828
- sessionManager.appendMessage(message);
829
- }
830
- const { session } = await options.services.createAgentSession({
831
- cwd: options.projectRoot,
832
- model: modelConfig.model,
833
- thinkingLevel: options.agentConfig?.enableThinking && modelConfig.provider === 'anthropic' ? 'medium' : 'off',
834
- authStorage,
835
- modelRegistry,
836
- resourceLoader,
837
- sessionManager,
838
- settingsManager,
839
- // Builtin read/edit/write/bash stay off: KB file access must flow through
840
- // the extension-registered KB tools (write-protection + audit log). The
841
- // project-root bash tool is the only SDK customTool, and only when the
842
- // request permission policy allows terminal access. options.requestTools is
843
- // intentionally NOT passed here — SDK
844
- // customTools override extension-registered tools by name, which would
845
- // strip the kb-extension wrappers; requestTools is still used by the
846
- // non-streaming proxy fallback and exposed on the returned runtime.
847
- noTools: 'builtin',
848
- customTools: options.mode === 'agent' && options.allowProjectBash !== false ? [options.bashTool] : [],
849
- });
850
- const fallbackTools = collectMindosRuntimeToolsForFallback({
851
- requestTools: options.requestTools,
852
- resourceLoader,
853
- extensionContext: createMindosHeadlessExtensionContext({
854
- cwd: options.projectRoot,
855
- model: modelConfig.model,
856
- modelRegistry,
857
- sessionManager,
858
- settingsManager,
859
- resourceLoader,
860
- }),
861
- });
862
- return {
863
- session,
864
- agentRunContextResource: sessionManager,
865
- llmHistoryMessages,
866
- requestTools: fallbackTools,
867
- systemPrompt,
868
- model: modelConfig.model,
869
- modelName: modelConfig.modelName,
870
- apiKey: modelConfig.apiKey,
871
- provider: modelConfig.provider,
872
- baseUrl: modelConfig.baseUrl,
873
- lastUserContent,
874
- lastUserImages,
875
- lastUserSkillName,
876
- };
877
- }
878
- function createMindosHeadlessExtensionContext(input) {
879
- return {
880
- cwd: input.cwd,
881
- hasUI: false,
882
- model: input.model,
883
- modelRegistry: input.modelRegistry,
884
- sessionManager: input.sessionManager,
885
- settingsManager: input.settingsManager,
886
- resourceLoader: input.resourceLoader,
887
- ui: {
888
- notify: () => { },
889
- setWidget: () => { },
890
- custom: async () => undefined,
891
- },
892
- };
893
- }
894
- function collectMindosRuntimeToolsForFallback(input) {
895
- const byName = new Map();
896
- for (const tool of input.requestTools) {
897
- if (tool.name)
898
- byName.set(tool.name, tool);
899
- }
900
- let extensions = [];
901
- try {
902
- extensions = input.resourceLoader.getExtensions?.().extensions ?? [];
903
- }
904
- catch {
905
- return [...byName.values()];
906
- }
907
- for (const extension of extensions) {
908
- for (const [entryName, rawTool] of mindosExtensionToolEntries(extension.tools)) {
909
- const tool = mindosExtensionToolDefinition(rawTool);
910
- if (!tool)
911
- continue;
912
- const name = typeof tool.name === 'string' ? tool.name : entryName;
913
- if (!name || byName.has(name) || typeof tool.execute !== 'function')
914
- continue;
915
- byName.set(name, createMindosExecutableToolFromExtension(name, tool, input.extensionContext));
916
- }
917
- }
918
- return [...byName.values()];
919
- }
920
- function mindosExtensionToolEntries(tools) {
921
- if (!tools)
922
- return [];
923
- if (tools instanceof Map) {
924
- return [...tools.entries()].map(([name, tool]) => [
925
- typeof name === 'string' ? name : undefined,
926
- tool,
927
- ]);
928
- }
929
- if (Array.isArray(tools)) {
930
- return tools.map((tool) => [
931
- isRecord(tool) && typeof tool.name === 'string' ? tool.name : undefined,
932
- tool,
933
- ]);
934
- }
935
- if (isRecord(tools)) {
936
- return Object.entries(tools).map(([name, tool]) => [name, tool]);
937
- }
938
- return [];
939
- }
940
- function mindosExtensionToolDefinition(rawTool) {
941
- if (!isRecord(rawTool))
942
- return null;
943
- const wrappedDefinition = rawTool.definition;
944
- if (isRecord(wrappedDefinition))
945
- return wrappedDefinition;
946
- return rawTool;
947
- }
948
- function createMindosExecutableToolFromExtension(name, tool, extensionContext) {
949
- const execute = tool.execute;
950
- const prepareArguments = typeof tool.prepareArguments === 'function'
951
- ? tool.prepareArguments
952
- : undefined;
953
- return {
954
- name,
955
- description: typeof tool.description === 'string' ? tool.description : undefined,
956
- parameters: tool.parameters,
957
- execute: async (toolCallId, args, signal, onUpdate) => {
958
- const preparedArgs = prepareArguments ? prepareArguments(args) : args;
959
- const result = await execute.call(tool, toolCallId, preparedArgs, signal, onUpdate, extensionContext);
960
- return normalizeMindosExecutableToolResult(result);
961
- },
962
- };
963
- }
964
- function normalizeMindosExecutableToolResult(result) {
965
- if (isRecord(result) && Array.isArray(result.content)) {
966
- return {
967
- content: result.content
968
- .filter(isRecord)
969
- .map((part) => ({
970
- type: typeof part.type === 'string' ? part.type : 'text',
971
- ...(typeof part.text === 'string' ? { text: part.text } : {}),
972
- })),
973
- };
974
- }
975
- if (typeof result === 'string')
976
- return { content: [{ type: 'text', text: result }] };
977
- if (result == null)
978
- return { content: [] };
979
- return { content: [{ type: 'text', text: stringifyMindosToolResult(result) }] };
980
- }
981
- function stringifyMindosToolResult(result) {
982
- try {
983
- return JSON.stringify(result);
984
- }
985
- catch {
986
- return String(result);
987
- }
988
- }
989
- function createMindosPiSettingsConfig(agentConfig = {}, provider) {
990
- return {
991
- enableSkillCommands: true,
992
- ...(agentConfig.enableThinking && provider === 'anthropic'
993
- ? { thinkingBudgets: { medium: agentConfig.thinkingBudget ?? 5000 } }
994
- : {}),
995
- ...(agentConfig.contextStrategy === 'off' ? { compaction: { enabled: false } } : {}),
996
- };
997
- }
998
- function hasMindosMessageImages(messages) {
999
- return messages.some((message) => (extractMindosUserImages(message)?.length ?? 0) > 0);
1000
- }
1001
- function extractMindosUserImages(message) {
1002
- if (!message || message.role !== 'user')
1003
- return undefined;
1004
- const images = message.images?.filter((image) => image.data);
1005
- return images && images.length > 0 ? images : undefined;
1006
- }
1007
- export async function runMindosAskProxyFallback(options) {
1008
- if (options.phase === 'before-stream') {
1009
- if (options.compatMode !== 'non-streaming' || !isOpenAiCompatibleProxy(options))
1010
- return false;
1011
- options.send({ type: 'status', message: options.messages.proxyCompatMode });
1012
- try {
1013
- await options.runFallback();
1014
- options.send({ type: 'done' });
1015
- }
1016
- catch (error) {
1017
- options.send({ type: 'error', message: options.messages.proxyCompatFailed(errorMessage(error)) });
1018
- }
1019
- return true;
1020
- }
1021
- if (options.hasContent)
1022
- return false;
1023
- if (!options.lastModelError && !isOpenAiCompatibleProxy(options))
1024
- return false;
1025
- if (isOpenAiCompatibleProxy(options)) {
1026
- options.send({
1027
- type: 'status',
1028
- message: options.lastModelError ? options.messages.proxyCompatDetecting : options.messages.proxyCompatMode,
1029
- });
1030
- try {
1031
- await options.runFallback();
1032
- options.writeCompat?.(options.effectiveBaseUrlKey ?? options.baseUrl ?? 'default', 'non-streaming');
1033
- options.send({ type: 'done' });
1034
- }
1035
- catch (error) {
1036
- options.send({ type: 'error', message: options.messages.proxyCompatAlsoFailed(errorMessage(error)) });
1037
- }
1038
- return true;
1039
- }
1040
- if (options.lastModelError) {
1041
- options.send({ type: 'error', message: options.lastModelError });
1042
- return true;
1043
- }
1044
- return false;
1045
- }
1046
- function isOpenAiCompatibleProxy(options) {
1047
- return !!options.baseUrl && options.provider === 'openai';
1048
- }
1049
- function errorMessage(error) {
1050
- return error instanceof Error ? error.message : String(error);
1051
- }
1052
- export function buildMindosCompatEndpointCandidates(baseUrl, endpointPath, apiType) {
1053
- const base = baseUrl.replace(/\/+$/, '');
1054
- const cleanPath = endpointPath.startsWith('/') ? endpointPath : `/${endpointPath}`;
1055
- const hasVersionPrefix = /\/v\d+(?:$|\/)/.test(base);
1056
- const candidates = new Set();
1057
- candidates.add(`${base}${cleanPath}`);
1058
- if (!hasVersionPrefix && (apiType === 'openai-completions'
1059
- || apiType === 'openai-responses'
1060
- || apiType === 'anthropic-messages')) {
1061
- candidates.add(`${base}/v1${cleanPath}`);
1062
- }
1063
- return Array.from(candidates);
1064
- }
1065
- export function reassembleMindosOpenAISse(sseText) {
1066
- const lines = sseText.split('\n');
1067
- let content = '';
1068
- let role = 'assistant';
1069
- let finishReason = 'stop';
1070
- const toolCalls = new Map();
1071
- for (const line of lines) {
1072
- const trimmed = line.trim();
1073
- if (!trimmed.startsWith('data:'))
1074
- continue;
1075
- const payload = trimmed.slice(5).trim();
1076
- if (payload === '[DONE]')
1077
- break;
1078
- const chunk = parseUnknownJson(payload);
1079
- if (!isRecord(chunk))
1080
- continue;
1081
- const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
1082
- const firstChoice = choices[0];
1083
- if (!isRecord(firstChoice))
1084
- continue;
1085
- const delta = firstChoice.delta;
1086
- if (!isRecord(delta))
1087
- continue;
1088
- if (typeof delta.role === 'string')
1089
- role = delta.role;
1090
- if (typeof delta.content === 'string')
1091
- content += delta.content;
1092
- if (typeof firstChoice.finish_reason === 'string')
1093
- finishReason = firstChoice.finish_reason;
1094
- if (Array.isArray(delta.tool_calls)) {
1095
- for (const rawToolCall of delta.tool_calls) {
1096
- if (!isRecord(rawToolCall))
1097
- continue;
1098
- const toolCall = rawToolCall;
1099
- const idx = typeof toolCall.index === 'number' ? toolCall.index : 0;
1100
- const existing = toolCalls.get(idx);
1101
- if (!existing) {
1102
- toolCalls.set(idx, {
1103
- id: toolCall.id ?? '',
1104
- type: toolCall.type ?? 'function',
1105
- function: {
1106
- name: toolCall.function?.name ?? '',
1107
- arguments: toolCall.function?.arguments ?? '',
1108
- },
1109
- });
1110
- }
1111
- else {
1112
- if (toolCall.id)
1113
- existing.id = toolCall.id;
1114
- if (toolCall.function?.name)
1115
- existing.function.name += toolCall.function.name;
1116
- if (toolCall.function?.arguments)
1117
- existing.function.arguments += toolCall.function.arguments;
1118
- }
1119
- }
1120
- }
1121
- }
1122
- const message = { role, content: content || null };
1123
- if (toolCalls.size > 0)
1124
- message.tool_calls = Array.from(toolCalls.values());
1125
- return {
1126
- choices: [{ message, finish_reason: finishReason }],
1127
- };
1128
- }
1129
- export function mindosPiMessagesToOpenAI(piMessages) {
1130
- return piMessages
1131
- .map((message) => {
1132
- if (!isRecord(message))
1133
- return null;
1134
- const role = message.role;
1135
- if (role === 'system')
1136
- return null;
1137
- if (role === 'user') {
1138
- return {
1139
- role: 'user',
1140
- content: typeof message.content === 'string' ? message.content : message.content,
1141
- };
1142
- }
1143
- if (role === 'assistant') {
1144
- const assistantContent = message.content;
1145
- let textContent = '';
1146
- const toolCalls = [];
1147
- if (Array.isArray(assistantContent)) {
1148
- for (const rawPart of assistantContent) {
1149
- if (!isRecord(rawPart))
1150
- continue;
1151
- if (rawPart.type === 'text' && typeof rawPart.text === 'string') {
1152
- textContent += rawPart.text;
1153
- }
1154
- else if (rawPart.type === 'toolCall') {
1155
- toolCalls.push({
1156
- id: typeof rawPart.id === 'string' ? rawPart.id : `call_${Date.now()}`,
1157
- type: 'function',
1158
- function: {
1159
- name: typeof rawPart.name === 'string' ? rawPart.name : 'unknown',
1160
- arguments: JSON.stringify(rawPart.arguments ?? {}),
1161
- },
1162
- });
1163
- }
1164
- }
1165
- }
1166
- const result = { role: 'assistant', content: textContent || '' };
1167
- if (toolCalls.length > 0)
1168
- result.tool_calls = toolCalls;
1169
- return result;
1170
- }
1171
- if (role === 'toolResult') {
1172
- const contentText = Array.isArray(message.content)
1173
- ? message.content
1174
- .filter((part) => isRecord(part) && part.type === 'text')
1175
- .map((part) => part.text ?? '')
1176
- .join('\n')
1177
- : String(message.content ?? '');
1178
- return {
1179
- role: 'tool',
1180
- tool_call_id: typeof message.toolCallId === 'string' ? message.toolCallId : 'unknown',
1181
- content: contentText,
1182
- };
1183
- }
1184
- return null;
1185
- })
1186
- .filter((message) => message !== null);
1187
- }
1188
- export async function runMindosNonStreamingFallback(options) {
1189
- const { baseUrl, apiKey, model, systemPrompt, historyMessages, userContent, tools, send, signal, maxSteps, } = options;
1190
- const fetchImpl = options.fetch ?? fetch;
1191
- const chunkDelayMs = options.chunkDelayMs ?? 8;
1192
- const openaiTools = tools.map((tool) => ({
1193
- type: 'function',
1194
- function: {
1195
- name: tool.name,
1196
- description: tool.description ?? '',
1197
- parameters: tool.parameters ?? { type: 'object', properties: {} },
1198
- },
1199
- }));
1200
- const messages = [
1201
- { role: 'system', content: systemPrompt },
1202
- ...mindosPiMessagesToOpenAI(historyMessages),
1203
- { role: 'user', content: userContent },
1204
- ];
1205
- const toolMap = new Map(tools.map((tool) => [tool.name, tool]));
1206
- const endpoints = buildMindosCompatEndpointCandidates(baseUrl, '/chat/completions', 'openai-completions');
1207
- let step = 0;
1208
- while (step < maxSteps) {
1209
- if (signal.aborted)
1210
- throw new Error('Request aborted');
1211
- step += 1;
1212
- let response = null;
1213
- let lastEndpointError = '';
1214
- for (const endpoint of endpoints) {
1215
- const attempt = await fetchImpl(endpoint, {
1216
- method: 'POST',
1217
- headers: {
1218
- 'Content-Type': 'application/json',
1219
- Authorization: `Bearer ${apiKey}`,
1220
- },
1221
- body: JSON.stringify({
1222
- model,
1223
- messages,
1224
- tools: openaiTools.length > 0 ? openaiTools : undefined,
1225
- tool_choice: openaiTools.length > 0 ? 'auto' : undefined,
1226
- stream: true,
1227
- }),
1228
- signal,
1229
- });
1230
- if (attempt.ok) {
1231
- response = attempt;
1232
- break;
1233
- }
1234
- const errorText = await attempt.text().catch(() => '');
1235
- lastEndpointError = `HTTP ${attempt.status} @ ${endpoint}: ${errorText.slice(0, 200)}`;
1236
- if (attempt.status !== 404) {
1237
- throw new Error(`Non-streaming API error ${lastEndpointError}`);
1238
- }
1239
- }
1240
- if (!response) {
1241
- throw new Error(`Non-streaming API error ${lastEndpointError || 'all endpoint candidates failed'}; tried ${endpoints.length} endpoint candidate(s)`);
1242
- }
1243
- const rawText = await response.text();
1244
- const trimmed = rawText.trimStart();
1245
- const data = trimmed.startsWith('data:')
1246
- ? reassembleMindosOpenAISse(trimmed)
1247
- : parseUnknownJson(rawText);
1248
- if (!isRecord(data)) {
1249
- throw new Error(`API returned invalid response: ${rawText.slice(0, 200)}`);
1250
- }
1251
- const choices = Array.isArray(data.choices) ? data.choices : [];
1252
- const choice = choices[0];
1253
- if (!isRecord(choice))
1254
- throw new Error('Empty response from API');
1255
- const message = isRecord(choice.message) ? choice.message : isRecord(choice.delta) ? choice.delta : {};
1256
- const finishReason = typeof choice.finish_reason === 'string' ? choice.finish_reason : 'stop';
1257
- if (typeof message.content === 'string' && message.content) {
1258
- const chunkSize = 40;
1259
- for (let i = 0; i < message.content.length; i += chunkSize) {
1260
- send({ type: 'text_delta', delta: message.content.slice(i, i + chunkSize) });
1261
- if (chunkDelayMs > 0)
1262
- await new Promise((resolveDelay) => setTimeout(resolveDelay, chunkDelayMs));
1263
- }
1264
- }
1265
- const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
1266
- if (finishReason === 'stop' || toolCalls.length === 0)
1267
- break;
1268
- const toolResultMessages = [];
1269
- for (const rawToolCall of toolCalls) {
1270
- if (!isRecord(rawToolCall))
1271
- continue;
1272
- const functionCall = isRecord(rawToolCall.function) ? rawToolCall.function : {};
1273
- const toolName = typeof functionCall.name === 'string' ? functionCall.name : '';
1274
- const toolCallId = typeof rawToolCall.id === 'string' ? rawToolCall.id : `call_${Date.now()}`;
1275
- const parsedArgs = safeParseMindosJsonObject(typeof functionCall.arguments === 'string' ? functionCall.arguments : '{}');
1276
- const tool = toolMap.get(toolName);
1277
- send({ type: 'tool_start', toolCallId, toolName, args: sanitizeToolArgs(toolName, parsedArgs) });
1278
- let resultText = '';
1279
- let isError = false;
1280
- if (tool) {
1281
- try {
1282
- const result = await tool.execute(toolCallId, parsedArgs, signal, (update) => {
1283
- const delta = getMindosToolUpdateText(update);
1284
- if (delta)
1285
- send({ type: 'tool_delta', toolCallId, toolName, delta: sanitizeToolOutput(delta) });
1286
- });
1287
- resultText = result.content
1288
- .filter((part) => part.type === 'text')
1289
- .map((part) => part.text ?? '')
1290
- .join('\n');
1291
- }
1292
- catch (error) {
1293
- resultText = errorMessage(error);
1294
- isError = true;
1295
- }
1296
- }
1297
- else {
1298
- resultText = `Tool "${toolName}" not found`;
1299
- isError = true;
1300
- }
1301
- send({ type: 'tool_end', toolCallId, toolName, output: sanitizeToolOutput(resultText), isError });
1302
- toolResultMessages.push({ role: 'tool', tool_call_id: toolCallId, content: resultText });
1303
- }
1304
- messages.push({
1305
- role: 'assistant',
1306
- content: message.content ?? null,
1307
- tool_calls: message.tool_calls,
1308
- });
1309
- messages.push(...toolResultMessages);
1310
- }
1311
- }
1312
- function getMindosToolUpdateText(update) {
1313
- if (!isRecord(update) || !Array.isArray(update.content))
1314
- return '';
1315
- return update.content
1316
- .filter(isRecord)
1317
- .filter((part) => part.type === 'text' || part.type === undefined)
1318
- .map((part) => (typeof part.text === 'string' ? part.text : ''))
1319
- .filter(Boolean)
1320
- .join('\n');
1321
- }
1322
- function parseUnknownJson(raw) {
1323
- try {
1324
- return JSON.parse(raw);
1325
- }
1326
- catch {
1327
- return null;
1328
- }
1329
- }
1330
- export function detectMindosAgentLoop(history, threshold = 3) {
1331
- if (history.length < threshold)
1332
- return false;
1333
- const lastN = history.slice(-threshold);
1334
- if (lastN.every((step) => step.tool === lastN[0]?.tool && step.input === lastN[0]?.input)) {
1335
- return true;
1336
- }
1337
- if (history.length >= 4) {
1338
- const window = history.slice(-8);
1339
- for (let cycleLen = 2; cycleLen <= 4 && cycleLen * 2 <= window.length; cycleLen += 1) {
1340
- const tail = window.slice(-cycleLen * 2);
1341
- let toolsMatch = true;
1342
- let anyArgsMatch = false;
1343
- for (let i = 0; i < cycleLen; i += 1) {
1344
- const left = tail[i];
1345
- const right = tail[i + cycleLen];
1346
- if (!left || !right || left.tool !== right.tool) {
1347
- toolsMatch = false;
1348
- break;
1349
- }
1350
- if (left.input === right.input)
1351
- anyArgsMatch = true;
1352
- }
1353
- if (toolsMatch && anyArgsMatch)
1354
- return true;
1355
- }
1356
- }
1357
- return false;
1358
- }
1359
- export function toMindosAgentMessages(messages) {
1360
- const result = [];
1361
- for (const msg of messages) {
1362
- const timestamp = msg.timestamp ?? Date.now();
1363
- if (msg.role === 'user') {
1364
- result.push({
1365
- role: 'user',
1366
- content: buildMindosUserContent(msg.content, msg.images),
1367
- timestamp,
1368
- });
1369
- continue;
1370
- }
1371
- if (msg.content.startsWith('__error__'))
1372
- continue;
1373
- if (!msg.parts || msg.parts.length === 0) {
1374
- if (msg.content) {
1375
- result.push(createMindosAssistantHistoryMessage({
1376
- content: [{ type: 'text', text: msg.content }],
1377
- stopReason: 'stop',
1378
- timestamp,
1379
- }));
1380
- }
1381
- continue;
1382
- }
1383
- const assistantContent = [];
1384
- const toolCalls = [];
1385
- for (const part of msg.parts) {
1386
- if (part.type === 'text') {
1387
- if (part.text)
1388
- assistantContent.push({ type: 'text', text: part.text });
1389
- }
1390
- else if (part.type === 'tool-call') {
1391
- assistantContent.push({
1392
- type: 'toolCall',
1393
- id: part.toolCallId,
1394
- name: part.toolName,
1395
- arguments: part.input ?? {},
1396
- });
1397
- toolCalls.push(part);
1398
- }
1399
- else if (part.type === 'runtime-status') {
1400
- // UI-only runtime diagnostics should not become model conversation history.
1401
- }
1402
- }
1403
- if (assistantContent.length > 0) {
1404
- result.push(createMindosAssistantHistoryMessage({
1405
- content: assistantContent,
1406
- stopReason: toolCalls.length > 0 ? 'toolUse' : 'stop',
1407
- timestamp,
1408
- }));
1409
- }
1410
- for (const toolCall of toolCalls) {
1411
- result.push({
1412
- role: 'toolResult',
1413
- toolCallId: toolCall.toolCallId,
1414
- toolName: toolCall.toolName,
1415
- content: [{ type: 'text', text: toolCall.output ?? '' }],
1416
- isError: toolCall.state === 'error',
1417
- timestamp,
1418
- });
1419
- }
1420
- }
1421
- return result;
1422
- }
1423
- function buildMindosUserContent(text, images) {
1424
- const validImages = images?.filter((image) => image.data);
1425
- if (!validImages || validImages.length === 0)
1426
- return text;
1427
- const parts = validImages.map((image) => ({
1428
- type: 'image',
1429
- data: image.data,
1430
- mimeType: image.mimeType,
1431
- }));
1432
- if (text)
1433
- parts.push({ type: 'text', text });
1434
- return parts;
1435
- }
1436
- function createMindosAssistantHistoryMessage(input) {
1437
- return {
1438
- role: 'assistant',
1439
- content: input.content,
1440
- api: 'anthropic-messages',
1441
- provider: 'anthropic',
1442
- model: '',
1443
- usage: {
1444
- input: 0,
1445
- output: 0,
1446
- cacheRead: 0,
1447
- cacheWrite: 0,
1448
- totalTokens: 0,
1449
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1450
- },
1451
- stopReason: input.stopReason,
1452
- timestamp: input.timestamp,
1453
- };
1454
- }
1455
- export { detectMindosAgentLoop as detectLoop, isMindosRetryableError as isRetryableError, isMindosTransientError as isTransientError, mindosRetryDelay as retryDelay, sleepMindos as sleep, };
1
+ export * from '../agent/session/index.js';
1456
2
  //# sourceMappingURL=index.js.map