@jungjaehoon/mama-os 0.53.1 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1729) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +62 -259
  3. package/db/migrations/001-connector-event-index.sql +251 -0
  4. package/dist/agent/claude-native-tool-policy.d.ts +17 -0
  5. package/dist/agent/claude-native-tool-policy.d.ts.map +1 -0
  6. package/dist/agent/claude-native-tool-policy.js +88 -0
  7. package/dist/agent/claude-native-tool-policy.js.map +1 -0
  8. package/dist/api/attachment-actions.d.ts +16 -0
  9. package/dist/api/attachment-actions.d.ts.map +1 -0
  10. package/dist/api/attachment-actions.js +280 -0
  11. package/dist/api/attachment-actions.js.map +1 -0
  12. package/dist/api/auth-middleware.d.ts +15 -55
  13. package/dist/api/auth-middleware.d.ts.map +1 -1
  14. package/dist/api/auth-middleware.js +56 -233
  15. package/dist/api/auth-middleware.js.map +1 -1
  16. package/dist/api/cf-access.d.ts +6 -0
  17. package/dist/api/cf-access.d.ts.map +1 -0
  18. package/dist/api/cf-access.js +121 -0
  19. package/dist/api/cf-access.js.map +1 -0
  20. package/dist/api/file-delivery.d.ts +29 -0
  21. package/dist/api/file-delivery.d.ts.map +1 -0
  22. package/dist/api/file-delivery.js +90 -0
  23. package/dist/api/file-delivery.js.map +1 -0
  24. package/dist/api/help-actions.d.ts +12 -0
  25. package/dist/api/help-actions.d.ts.map +1 -0
  26. package/dist/api/help-actions.js +70 -0
  27. package/dist/api/help-actions.js.map +1 -0
  28. package/dist/api/owner-timezone-actions.d.ts +10 -0
  29. package/dist/api/owner-timezone-actions.d.ts.map +1 -0
  30. package/dist/api/owner-timezone-actions.js +73 -0
  31. package/dist/api/owner-timezone-actions.js.map +1 -0
  32. package/dist/api/record-actions.d.ts +8 -0
  33. package/dist/api/record-actions.d.ts.map +1 -0
  34. package/dist/api/record-actions.js +53 -0
  35. package/dist/api/record-actions.js.map +1 -0
  36. package/dist/api/report-actions.d.ts +20 -0
  37. package/dist/api/report-actions.d.ts.map +1 -0
  38. package/dist/api/report-actions.js +137 -0
  39. package/dist/api/report-actions.js.map +1 -0
  40. package/dist/api/report-handler.d.ts +15 -11
  41. package/dist/api/report-handler.d.ts.map +1 -1
  42. package/dist/api/report-handler.js +48 -120
  43. package/dist/api/report-handler.js.map +1 -1
  44. package/dist/api/report-persistence.d.ts +3 -3
  45. package/dist/api/report-persistence.d.ts.map +1 -1
  46. package/dist/api/report-persistence.js +35 -10
  47. package/dist/api/report-persistence.js.map +1 -1
  48. package/dist/api/report-source-actions.d.ts +11 -0
  49. package/dist/api/report-source-actions.d.ts.map +1 -0
  50. package/dist/api/report-source-actions.js +309 -0
  51. package/dist/api/report-source-actions.js.map +1 -0
  52. package/dist/api/security-events.d.ts +23 -0
  53. package/dist/api/security-events.d.ts.map +1 -0
  54. package/dist/api/security-events.js +71 -0
  55. package/dist/api/security-events.js.map +1 -0
  56. package/dist/api/source-actions.d.ts +9 -0
  57. package/dist/api/source-actions.d.ts.map +1 -0
  58. package/dist/api/source-actions.js +274 -0
  59. package/dist/api/source-actions.js.map +1 -0
  60. package/dist/api/stored-source-reader.d.ts +21 -0
  61. package/dist/api/stored-source-reader.d.ts.map +1 -0
  62. package/dist/api/stored-source-reader.js +269 -0
  63. package/dist/api/stored-source-reader.js.map +1 -0
  64. package/dist/api/viewer-data.d.ts +143 -0
  65. package/dist/api/viewer-data.d.ts.map +1 -0
  66. package/dist/api/viewer-data.js +518 -0
  67. package/dist/api/viewer-data.js.map +1 -0
  68. package/dist/api/viewer-request-security.d.ts +12 -0
  69. package/dist/api/viewer-request-security.d.ts.map +1 -0
  70. package/dist/api/viewer-request-security.js +217 -0
  71. package/dist/api/viewer-request-security.js.map +1 -0
  72. package/dist/api/viewer-server.d.ts +56 -0
  73. package/dist/api/viewer-server.d.ts.map +1 -0
  74. package/dist/api/viewer-server.js +937 -0
  75. package/dist/api/viewer-server.js.map +1 -0
  76. package/dist/api/wiki-actions.d.ts +20 -0
  77. package/dist/api/wiki-actions.d.ts.map +1 -0
  78. package/dist/api/wiki-actions.js +296 -0
  79. package/dist/api/wiki-actions.js.map +1 -0
  80. package/dist/api/work-actions.d.ts +96 -0
  81. package/dist/api/work-actions.d.ts.map +1 -0
  82. package/dist/api/work-actions.js +956 -0
  83. package/dist/api/work-actions.js.map +1 -0
  84. package/dist/cli/commands/daemon.d.ts +90 -0
  85. package/dist/cli/commands/daemon.d.ts.map +1 -0
  86. package/dist/cli/commands/daemon.js +632 -0
  87. package/dist/cli/commands/daemon.js.map +1 -0
  88. package/dist/cli/commands/init.d.ts +7 -18
  89. package/dist/cli/commands/init.d.ts.map +1 -1
  90. package/dist/cli/commands/init.js +357 -273
  91. package/dist/cli/commands/init.js.map +1 -1
  92. package/dist/cli/commands/replay.d.ts +12 -0
  93. package/dist/cli/commands/replay.d.ts.map +1 -0
  94. package/dist/cli/commands/replay.js +145 -0
  95. package/dist/cli/commands/replay.js.map +1 -0
  96. package/dist/cli/commands/secret.d.ts +6 -0
  97. package/dist/cli/commands/secret.d.ts.map +1 -0
  98. package/dist/cli/commands/secret.js +24 -0
  99. package/dist/cli/commands/secret.js.map +1 -0
  100. package/dist/cli/index.d.ts +0 -5
  101. package/dist/cli/index.d.ts.map +1 -1
  102. package/dist/cli/index.js +52 -95
  103. package/dist/cli/index.js.map +1 -1
  104. package/dist/cli/launch-files.d.ts +10 -0
  105. package/dist/cli/launch-files.d.ts.map +1 -0
  106. package/dist/cli/launch-files.js +74 -0
  107. package/dist/cli/launch-files.js.map +1 -0
  108. package/dist/cli/prompt.d.ts +15 -0
  109. package/dist/cli/prompt.d.ts.map +1 -0
  110. package/dist/cli/prompt.js +64 -0
  111. package/dist/cli/prompt.js.map +1 -0
  112. package/dist/cli/runtime/action-mcp-config.d.ts +15 -0
  113. package/dist/cli/runtime/action-mcp-config.d.ts.map +1 -0
  114. package/dist/cli/runtime/action-mcp-config.js +56 -0
  115. package/dist/cli/runtime/action-mcp-config.js.map +1 -0
  116. package/dist/cli/runtime/claude-caller-config.d.ts +4 -0
  117. package/dist/cli/runtime/claude-caller-config.d.ts.map +1 -0
  118. package/dist/cli/runtime/claude-caller-config.js +46 -0
  119. package/dist/cli/runtime/claude-caller-config.js.map +1 -0
  120. package/dist/cli/secrets.d.ts +9 -0
  121. package/dist/cli/secrets.d.ts.map +1 -0
  122. package/dist/cli/secrets.js +94 -0
  123. package/dist/cli/secrets.js.map +1 -0
  124. package/dist/connectors/calendar/index.d.ts +11 -10
  125. package/dist/connectors/calendar/index.d.ts.map +1 -1
  126. package/dist/connectors/calendar/index.js +171 -97
  127. package/dist/connectors/calendar/index.js.map +1 -1
  128. package/dist/connectors/chatwork/index.d.ts +31 -5
  129. package/dist/connectors/chatwork/index.d.ts.map +1 -1
  130. package/dist/connectors/chatwork/index.js +184 -20
  131. package/dist/connectors/chatwork/index.js.map +1 -1
  132. package/dist/connectors/claude-code/index.d.ts +0 -2
  133. package/dist/connectors/claude-code/index.d.ts.map +1 -1
  134. package/dist/connectors/claude-code/index.js +94 -70
  135. package/dist/connectors/claude-code/index.js.map +1 -1
  136. package/dist/connectors/config-loader.d.ts +1 -6
  137. package/dist/connectors/config-loader.d.ts.map +1 -1
  138. package/dist/connectors/config-loader.js +154 -134
  139. package/dist/connectors/config-loader.js.map +1 -1
  140. package/dist/connectors/discord/index.d.ts +8 -1
  141. package/dist/connectors/discord/index.d.ts.map +1 -1
  142. package/dist/connectors/discord/index.js +110 -32
  143. package/dist/connectors/discord/index.js.map +1 -1
  144. package/dist/connectors/drive/index.d.ts +10 -5
  145. package/dist/connectors/drive/index.d.ts.map +1 -1
  146. package/dist/connectors/drive/index.js +145 -88
  147. package/dist/connectors/drive/index.js.map +1 -1
  148. package/dist/connectors/framework/attachment-io.d.ts +5 -0
  149. package/dist/connectors/framework/attachment-io.d.ts.map +1 -0
  150. package/dist/connectors/framework/attachment-io.js +72 -0
  151. package/dist/connectors/framework/attachment-io.js.map +1 -0
  152. package/dist/connectors/framework/attachments.d.ts +32 -0
  153. package/dist/connectors/framework/attachments.d.ts.map +1 -0
  154. package/dist/connectors/framework/attachments.js +14 -0
  155. package/dist/connectors/framework/attachments.js.map +1 -0
  156. package/dist/connectors/framework/connector-event-types.d.ts +136 -0
  157. package/dist/connectors/framework/connector-event-types.d.ts.map +1 -0
  158. package/dist/connectors/framework/connector-event-types.js +3 -0
  159. package/dist/connectors/framework/connector-event-types.js.map +1 -0
  160. package/dist/connectors/framework/connector-state.d.ts +3 -0
  161. package/dist/connectors/framework/connector-state.d.ts.map +1 -0
  162. package/dist/connectors/framework/connector-state.js +47 -0
  163. package/dist/connectors/framework/connector-state.js.map +1 -0
  164. package/dist/connectors/framework/event-index.d.ts +28 -0
  165. package/dist/connectors/framework/event-index.d.ts.map +1 -0
  166. package/dist/connectors/framework/event-index.js +354 -0
  167. package/dist/connectors/framework/event-index.js.map +1 -0
  168. package/dist/connectors/framework/gws-utils.d.ts +3 -8
  169. package/dist/connectors/framework/gws-utils.d.ts.map +1 -1
  170. package/dist/connectors/framework/gws-utils.js +23 -30
  171. package/dist/connectors/framework/gws-utils.js.map +1 -1
  172. package/dist/connectors/framework/index.d.ts +4 -2
  173. package/dist/connectors/framework/index.d.ts.map +1 -1
  174. package/dist/connectors/framework/index.js +8 -6
  175. package/dist/connectors/framework/index.js.map +1 -1
  176. package/dist/connectors/framework/polling-scheduler.d.ts +71 -52
  177. package/dist/connectors/framework/polling-scheduler.d.ts.map +1 -1
  178. package/dist/connectors/framework/polling-scheduler.js +236 -168
  179. package/dist/connectors/framework/polling-scheduler.js.map +1 -1
  180. package/dist/connectors/framework/raw-query.d.ts +44 -0
  181. package/dist/connectors/framework/raw-query.d.ts.map +1 -0
  182. package/dist/connectors/framework/raw-query.js +584 -0
  183. package/dist/connectors/framework/raw-query.js.map +1 -0
  184. package/dist/connectors/framework/stored-index-read.d.ts +16 -0
  185. package/dist/connectors/framework/stored-index-read.d.ts.map +1 -0
  186. package/dist/connectors/framework/stored-index-read.js +66 -0
  187. package/dist/connectors/framework/stored-index-read.js.map +1 -0
  188. package/dist/connectors/framework/types.d.ts +17 -61
  189. package/dist/connectors/framework/types.d.ts.map +1 -1
  190. package/dist/connectors/framework/types.js +0 -4
  191. package/dist/connectors/framework/types.js.map +1 -1
  192. package/dist/connectors/gmail/index.d.ts +3 -2
  193. package/dist/connectors/gmail/index.d.ts.map +1 -1
  194. package/dist/connectors/gmail/index.js +74 -27
  195. package/dist/connectors/gmail/index.js.map +1 -1
  196. package/dist/connectors/ical/index.d.ts +29 -0
  197. package/dist/connectors/ical/index.d.ts.map +1 -0
  198. package/dist/connectors/ical/index.js +220 -0
  199. package/dist/connectors/ical/index.js.map +1 -0
  200. package/dist/connectors/ical/parser.d.ts +13 -0
  201. package/dist/connectors/ical/parser.d.ts.map +1 -0
  202. package/dist/connectors/ical/parser.js +117 -0
  203. package/dist/connectors/ical/parser.js.map +1 -0
  204. package/dist/connectors/imessage/index.d.ts +3 -1
  205. package/dist/connectors/imessage/index.d.ts.map +1 -1
  206. package/dist/connectors/imessage/index.js +31 -16
  207. package/dist/connectors/imessage/index.js.map +1 -1
  208. package/dist/connectors/index.d.ts +12 -5
  209. package/dist/connectors/index.d.ts.map +1 -1
  210. package/dist/connectors/index.js +67 -18
  211. package/dist/connectors/index.js.map +1 -1
  212. package/dist/connectors/kagemusha/index.d.ts +7 -19
  213. package/dist/connectors/kagemusha/index.d.ts.map +1 -1
  214. package/dist/connectors/kagemusha/index.js +123 -173
  215. package/dist/connectors/kagemusha/index.js.map +1 -1
  216. package/dist/connectors/notion/index.d.ts.map +1 -1
  217. package/dist/connectors/notion/index.js +79 -36
  218. package/dist/connectors/notion/index.js.map +1 -1
  219. package/dist/connectors/obsidian/index.d.ts +1 -1
  220. package/dist/connectors/obsidian/index.d.ts.map +1 -1
  221. package/dist/connectors/obsidian/index.js +59 -57
  222. package/dist/connectors/obsidian/index.js.map +1 -1
  223. package/dist/connectors/sheets/index.d.ts +8 -4
  224. package/dist/connectors/sheets/index.d.ts.map +1 -1
  225. package/dist/connectors/sheets/index.js +155 -143
  226. package/dist/connectors/sheets/index.js.map +1 -1
  227. package/dist/connectors/slack/index.d.ts +24 -5
  228. package/dist/connectors/slack/index.d.ts.map +1 -1
  229. package/dist/connectors/slack/index.js +177 -39
  230. package/dist/connectors/slack/index.js.map +1 -1
  231. package/dist/connectors/telegram/index.d.ts +9 -2
  232. package/dist/connectors/telegram/index.d.ts.map +1 -1
  233. package/dist/connectors/telegram/index.js +119 -70
  234. package/dist/connectors/telegram/index.js.map +1 -1
  235. package/dist/connectors/trello/index.d.ts +10 -3
  236. package/dist/connectors/trello/index.d.ts.map +1 -1
  237. package/dist/connectors/trello/index.js +88 -39
  238. package/dist/connectors/trello/index.js.map +1 -1
  239. package/dist/gateways/base-gateway.d.ts +9 -33
  240. package/dist/gateways/base-gateway.d.ts.map +1 -1
  241. package/dist/gateways/base-gateway.js +7 -28
  242. package/dist/gateways/base-gateway.js.map +1 -1
  243. package/dist/gateways/conversation-record.d.ts +52 -0
  244. package/dist/gateways/conversation-record.d.ts.map +1 -0
  245. package/dist/gateways/conversation-record.js +220 -0
  246. package/dist/gateways/conversation-record.js.map +1 -0
  247. package/dist/gateways/discord.d.ts +33 -135
  248. package/dist/gateways/discord.d.ts.map +1 -1
  249. package/dist/gateways/discord.js +258 -778
  250. package/dist/gateways/discord.js.map +1 -1
  251. package/dist/gateways/session-store.d.ts +28 -9
  252. package/dist/gateways/session-store.d.ts.map +1 -1
  253. package/dist/gateways/session-store.js +192 -60
  254. package/dist/gateways/session-store.js.map +1 -1
  255. package/dist/gateways/slack.d.ts +35 -105
  256. package/dist/gateways/slack.d.ts.map +1 -1
  257. package/dist/gateways/slack.js +282 -440
  258. package/dist/gateways/slack.js.map +1 -1
  259. package/dist/gateways/telegram-attachments.d.ts +32 -0
  260. package/dist/gateways/telegram-attachments.d.ts.map +1 -0
  261. package/dist/gateways/telegram-attachments.js +113 -0
  262. package/dist/gateways/telegram-attachments.js.map +1 -0
  263. package/dist/gateways/telegram-errors.d.ts +3 -0
  264. package/dist/gateways/telegram-errors.d.ts.map +1 -0
  265. package/dist/gateways/telegram-errors.js +10 -0
  266. package/dist/gateways/telegram-errors.js.map +1 -0
  267. package/dist/gateways/telegram-format.d.ts.map +1 -1
  268. package/dist/gateways/telegram-format.js +11 -3
  269. package/dist/gateways/telegram-format.js.map +1 -1
  270. package/dist/gateways/telegram-message-ledger.d.ts +31 -25
  271. package/dist/gateways/telegram-message-ledger.d.ts.map +1 -1
  272. package/dist/gateways/telegram-message-ledger.js +122 -146
  273. package/dist/gateways/telegram-message-ledger.js.map +1 -1
  274. package/dist/gateways/telegram-response-presenter.d.ts +3 -1
  275. package/dist/gateways/telegram-response-presenter.d.ts.map +1 -1
  276. package/dist/gateways/telegram-response-presenter.js +14 -0
  277. package/dist/gateways/telegram-response-presenter.js.map +1 -1
  278. package/dist/gateways/telegram-text-entities.d.ts +2 -3
  279. package/dist/gateways/telegram-text-entities.d.ts.map +1 -1
  280. package/dist/gateways/telegram-text-entities.js +4 -5
  281. package/dist/gateways/telegram-text-entities.js.map +1 -1
  282. package/dist/gateways/telegram.d.ts +39 -101
  283. package/dist/gateways/telegram.d.ts.map +1 -1
  284. package/dist/gateways/telegram.js +406 -919
  285. package/dist/gateways/telegram.js.map +1 -1
  286. package/dist/gateways/turn-contract.d.ts +27 -87
  287. package/dist/gateways/turn-contract.d.ts.map +1 -1
  288. package/dist/gateways/types.d.ts +14 -299
  289. package/dist/gateways/types.d.ts.map +1 -1
  290. package/dist/gateways/types.js +0 -3
  291. package/dist/gateways/types.js.map +1 -1
  292. package/dist/index.d.ts +1 -6
  293. package/dist/index.d.ts.map +1 -1
  294. package/dist/index.js +0 -23
  295. package/dist/index.js.map +1 -1
  296. package/dist/operator/board-read-views.d.ts +8 -10
  297. package/dist/operator/board-read-views.d.ts.map +1 -1
  298. package/dist/operator/board-read-views.js +7 -16
  299. package/dist/operator/board-read-views.js.map +1 -1
  300. package/dist/operator/board-slot-instructions.d.ts +5 -8
  301. package/dist/operator/board-slot-instructions.d.ts.map +1 -1
  302. package/dist/operator/board-slot-instructions.js +12 -24
  303. package/dist/operator/board-slot-instructions.js.map +1 -1
  304. package/dist/replay/import-manifest.d.ts +21 -0
  305. package/dist/replay/import-manifest.d.ts.map +1 -0
  306. package/dist/replay/import-manifest.js +157 -0
  307. package/dist/replay/import-manifest.js.map +1 -0
  308. package/dist/replay/jev-client.d.ts +35 -0
  309. package/dist/replay/jev-client.d.ts.map +1 -0
  310. package/dist/replay/jev-client.js +141 -0
  311. package/dist/replay/jev-client.js.map +1 -0
  312. package/dist/replay/kagemusha-import.d.ts +35 -0
  313. package/dist/replay/kagemusha-import.d.ts.map +1 -0
  314. package/dist/replay/kagemusha-import.js +543 -0
  315. package/dist/replay/kagemusha-import.js.map +1 -0
  316. package/dist/replay/replay-cursor.d.ts +31 -0
  317. package/dist/replay/replay-cursor.d.ts.map +1 -0
  318. package/dist/replay/replay-cursor.js +189 -0
  319. package/dist/replay/replay-cursor.js.map +1 -0
  320. package/dist/replay/replay-feeder.d.ts +55 -0
  321. package/dist/replay/replay-feeder.d.ts.map +1 -0
  322. package/dist/replay/replay-feeder.js +214 -0
  323. package/dist/replay/replay-feeder.js.map +1 -0
  324. package/dist/replay/replay-ledger.d.ts +32 -0
  325. package/dist/replay/replay-ledger.d.ts.map +1 -0
  326. package/dist/replay/replay-ledger.js +91 -0
  327. package/dist/replay/replay-ledger.js.map +1 -0
  328. package/dist/replay/replay-source-catalog.d.ts +66 -0
  329. package/dist/replay/replay-source-catalog.d.ts.map +1 -0
  330. package/dist/replay/replay-source-catalog.js +332 -0
  331. package/dist/replay/replay-source-catalog.js.map +1 -0
  332. package/dist/replay/trello-import.d.ts +33 -0
  333. package/dist/replay/trello-import.d.ts.map +1 -0
  334. package/dist/replay/trello-import.js +204 -0
  335. package/dist/replay/trello-import.js.map +1 -0
  336. package/dist/replay/window-queue.d.ts +116 -0
  337. package/dist/replay/window-queue.d.ts.map +1 -0
  338. package/dist/replay/window-queue.js +497 -0
  339. package/dist/replay/window-queue.js.map +1 -0
  340. package/dist/runtime/action-mcp-server.d.ts +30 -0
  341. package/dist/runtime/action-mcp-server.d.ts.map +1 -0
  342. package/dist/runtime/action-mcp-server.js +178 -0
  343. package/dist/runtime/action-mcp-server.js.map +1 -0
  344. package/dist/runtime/action-surface.d.ts +47 -0
  345. package/dist/runtime/action-surface.d.ts.map +1 -0
  346. package/dist/runtime/action-surface.js +192 -0
  347. package/dist/runtime/action-surface.js.map +1 -0
  348. package/dist/runtime/backend-security.d.ts +7 -0
  349. package/dist/runtime/backend-security.d.ts.map +1 -0
  350. package/dist/runtime/backend-security.js +28 -0
  351. package/dist/runtime/backend-security.js.map +1 -0
  352. package/dist/runtime/claude-caller-hook.d.ts +20 -0
  353. package/dist/runtime/claude-caller-hook.d.ts.map +1 -0
  354. package/dist/runtime/claude-caller-hook.js +41 -0
  355. package/dist/runtime/claude-caller-hook.js.map +1 -0
  356. package/dist/runtime/config.d.ts +84 -0
  357. package/dist/runtime/config.d.ts.map +1 -0
  358. package/dist/runtime/config.js +361 -0
  359. package/dist/runtime/config.js.map +1 -0
  360. package/dist/runtime/connectors.d.ts +41 -0
  361. package/dist/runtime/connectors.d.ts.map +1 -0
  362. package/dist/runtime/connectors.js +187 -0
  363. package/dist/runtime/connectors.js.map +1 -0
  364. package/dist/runtime/core-db.d.ts +8 -0
  365. package/dist/runtime/core-db.d.ts.map +1 -0
  366. package/dist/runtime/core-db.js +19 -0
  367. package/dist/runtime/core-db.js.map +1 -0
  368. package/dist/runtime/model-cache.d.ts +9 -0
  369. package/dist/runtime/model-cache.d.ts.map +1 -0
  370. package/dist/runtime/model-cache.js +22 -0
  371. package/dist/runtime/model-cache.js.map +1 -0
  372. package/dist/runtime/native-session.d.ts +86 -0
  373. package/dist/runtime/native-session.d.ts.map +1 -0
  374. package/dist/runtime/native-session.js +282 -0
  375. package/dist/runtime/native-session.js.map +1 -0
  376. package/dist/runtime/owner-policy.d.ts +10 -0
  377. package/dist/runtime/owner-policy.d.ts.map +1 -0
  378. package/dist/runtime/owner-policy.js +35 -0
  379. package/dist/runtime/owner-policy.js.map +1 -0
  380. package/dist/runtime/owner-runtime.d.ts +89 -0
  381. package/dist/runtime/owner-runtime.d.ts.map +1 -0
  382. package/dist/runtime/owner-runtime.js +319 -0
  383. package/dist/runtime/owner-runtime.js.map +1 -0
  384. package/dist/runtime/owner-system-prompt.d.ts +16 -0
  385. package/dist/runtime/owner-system-prompt.d.ts.map +1 -0
  386. package/dist/runtime/owner-system-prompt.js +118 -0
  387. package/dist/runtime/owner-system-prompt.js.map +1 -0
  388. package/dist/runtime/recent-owner-exchanges.d.ts +8 -0
  389. package/dist/runtime/recent-owner-exchanges.d.ts.map +1 -0
  390. package/dist/runtime/recent-owner-exchanges.js +27 -0
  391. package/dist/runtime/recent-owner-exchanges.js.map +1 -0
  392. package/dist/runtime/record-orders.d.ts +49 -0
  393. package/dist/runtime/record-orders.d.ts.map +1 -0
  394. package/dist/runtime/record-orders.js +152 -0
  395. package/dist/runtime/record-orders.js.map +1 -0
  396. package/dist/runtime/report-scheduler.d.ts +24 -0
  397. package/dist/runtime/report-scheduler.d.ts.map +1 -0
  398. package/dist/runtime/report-scheduler.js +100 -0
  399. package/dist/runtime/report-scheduler.js.map +1 -0
  400. package/dist/runtime/session-credential.d.ts +5 -0
  401. package/dist/runtime/session-credential.d.ts.map +1 -0
  402. package/dist/runtime/session-credential.js +19 -0
  403. package/dist/runtime/session-credential.js.map +1 -0
  404. package/dist/runtime/stimulus-delivery.d.ts +83 -0
  405. package/dist/runtime/stimulus-delivery.d.ts.map +1 -0
  406. package/dist/runtime/stimulus-delivery.js +507 -0
  407. package/dist/runtime/stimulus-delivery.js.map +1 -0
  408. package/dist/runtime/timezone.d.ts +15 -0
  409. package/dist/runtime/timezone.d.ts.map +1 -0
  410. package/dist/runtime/timezone.js +128 -0
  411. package/dist/runtime/timezone.js.map +1 -0
  412. package/dist/runtime/turn-orders.d.ts +86 -0
  413. package/dist/runtime/turn-orders.d.ts.map +1 -0
  414. package/dist/runtime/turn-orders.js +272 -0
  415. package/dist/runtime/turn-orders.js.map +1 -0
  416. package/dist/sqlite.d.ts +7 -32
  417. package/dist/sqlite.d.ts.map +1 -1
  418. package/dist/sqlite.js +10 -48
  419. package/dist/sqlite.js.map +1 -1
  420. package/dist/storage/migrations/raw-item-revisions.d.ts +6 -0
  421. package/dist/storage/migrations/raw-item-revisions.d.ts.map +1 -0
  422. package/dist/storage/migrations/raw-item-revisions.js +109 -0
  423. package/dist/storage/migrations/raw-item-revisions.js.map +1 -0
  424. package/dist/storage/migrations-source.d.ts +5 -0
  425. package/dist/storage/migrations-source.d.ts.map +1 -0
  426. package/dist/storage/migrations-source.js +24 -0
  427. package/dist/storage/migrations-source.js.map +1 -0
  428. package/dist/storage/source-archive.d.ts +123 -0
  429. package/dist/storage/source-archive.d.ts.map +1 -0
  430. package/dist/storage/source-archive.js +595 -0
  431. package/dist/storage/source-archive.js.map +1 -0
  432. package/dist/storage-sqlite.d.ts +59 -0
  433. package/dist/storage-sqlite.d.ts.map +1 -0
  434. package/dist/storage-sqlite.js +75 -0
  435. package/dist/storage-sqlite.js.map +1 -0
  436. package/dist/utils/untrusted-content.d.ts +5 -35
  437. package/dist/utils/untrusted-content.d.ts.map +1 -1
  438. package/dist/utils/untrusted-content.js +16 -75
  439. package/dist/utils/untrusted-content.js.map +1 -1
  440. package/dist/wiki/obsidian-writer.d.ts +4 -2
  441. package/dist/wiki/obsidian-writer.d.ts.map +1 -1
  442. package/dist/wiki/obsidian-writer.js +85 -4
  443. package/dist/wiki/obsidian-writer.js.map +1 -1
  444. package/dist/wiki/path-safety.d.ts +2 -0
  445. package/dist/wiki/path-safety.d.ts.map +1 -1
  446. package/dist/wiki/path-safety.js +11 -3
  447. package/dist/wiki/path-safety.js.map +1 -1
  448. package/dist/wiki/wiki-edits.d.ts +17 -0
  449. package/dist/wiki/wiki-edits.d.ts.map +1 -0
  450. package/dist/wiki/wiki-edits.js +75 -0
  451. package/dist/wiki/wiki-edits.js.map +1 -0
  452. package/dist/wiki/wiki-read.d.ts +20 -11
  453. package/dist/wiki/wiki-read.d.ts.map +1 -1
  454. package/dist/wiki/wiki-read.js +87 -89
  455. package/dist/wiki/wiki-read.js.map +1 -1
  456. package/dist/wiki-artifacts/types.d.ts +1 -1
  457. package/dist/wiki-artifacts/types.d.ts.map +1 -1
  458. package/dist/wiki-artifacts/wiki-publish-adapter.d.ts.map +1 -1
  459. package/dist/wiki-artifacts/wiki-publish-adapter.js +13 -9
  460. package/dist/wiki-artifacts/wiki-publish-adapter.js.map +1 -1
  461. package/package.json +11 -41
  462. package/public/viewer/js/modules/graph.js +111 -41
  463. package/public/viewer/js/modules/memory.js +4 -31
  464. package/public/viewer/js/modules/wiki.js +0 -37
  465. package/public/viewer/js/utils/api.js +4 -50
  466. package/public/viewer/log-viewer.html +46 -0
  467. package/public/viewer/operator/operator.css +1 -1
  468. package/public/viewer/operator/operator.js +10835 -8211
  469. package/public/viewer/src/modules/graph.ts +133 -41
  470. package/public/viewer/src/modules/memory.ts +4 -31
  471. package/public/viewer/src/modules/wiki.ts +0 -42
  472. package/public/viewer/src/types/global.d.ts +1 -1
  473. package/public/viewer/src/utils/api.ts +7 -83
  474. package/public/viewer/viewer.html +7 -96
  475. package/dist/agent/agent-loop.d.ts +0 -289
  476. package/dist/agent/agent-loop.d.ts.map +0 -1
  477. package/dist/agent/agent-loop.js +0 -2842
  478. package/dist/agent/agent-loop.js.map +0 -1
  479. package/dist/agent/attachment-text-extractor.d.ts +0 -2
  480. package/dist/agent/attachment-text-extractor.d.ts.map +0 -1
  481. package/dist/agent/attachment-text-extractor.js +0 -128
  482. package/dist/agent/attachment-text-extractor.js.map +0 -1
  483. package/dist/agent/backend-model-policy.d.ts +0 -58
  484. package/dist/agent/backend-model-policy.d.ts.map +0 -1
  485. package/dist/agent/backend-model-policy.js +0 -167
  486. package/dist/agent/backend-model-policy.js.map +0 -1
  487. package/dist/agent/backend-model-runner-factory.d.ts +0 -27
  488. package/dist/agent/backend-model-runner-factory.d.ts.map +0 -1
  489. package/dist/agent/backend-model-runner-factory.js +0 -88
  490. package/dist/agent/backend-model-runner-factory.js.map +0 -1
  491. package/dist/agent/claude-cli-wrapper.d.ts +0 -144
  492. package/dist/agent/claude-cli-wrapper.d.ts.map +0 -1
  493. package/dist/agent/claude-cli-wrapper.js +0 -382
  494. package/dist/agent/claude-cli-wrapper.js.map +0 -1
  495. package/dist/agent/cli-arg-redaction.d.ts +0 -2
  496. package/dist/agent/cli-arg-redaction.d.ts.map +0 -1
  497. package/dist/agent/cli-arg-redaction.js +0 -18
  498. package/dist/agent/cli-arg-redaction.js.map +0 -1
  499. package/dist/agent/cline-cli-adapter.d.ts +0 -126
  500. package/dist/agent/cline-cli-adapter.d.ts.map +0 -1
  501. package/dist/agent/cline-cli-adapter.js +0 -1042
  502. package/dist/agent/cline-cli-adapter.js.map +0 -1
  503. package/dist/agent/cline-native-tool-policy.d.ts +0 -9
  504. package/dist/agent/cline-native-tool-policy.d.ts.map +0 -1
  505. package/dist/agent/cline-native-tool-policy.js +0 -61
  506. package/dist/agent/cline-native-tool-policy.js.map +0 -1
  507. package/dist/agent/code-act/completed-terminal-result.d.ts +0 -5
  508. package/dist/agent/code-act/completed-terminal-result.d.ts.map +0 -1
  509. package/dist/agent/code-act/completed-terminal-result.js +0 -83
  510. package/dist/agent/code-act/completed-terminal-result.js.map +0 -1
  511. package/dist/agent/code-act/constants.d.ts +0 -11
  512. package/dist/agent/code-act/constants.d.ts.map +0 -1
  513. package/dist/agent/code-act/constants.js +0 -64
  514. package/dist/agent/code-act/constants.js.map +0 -1
  515. package/dist/agent/code-act/host-bridge.d.ts +0 -50
  516. package/dist/agent/code-act/host-bridge.d.ts.map +0 -1
  517. package/dist/agent/code-act/host-bridge.js +0 -1405
  518. package/dist/agent/code-act/host-bridge.js.map +0 -1
  519. package/dist/agent/code-act/index.d.ts +0 -10
  520. package/dist/agent/code-act/index.d.ts.map +0 -1
  521. package/dist/agent/code-act/index.js +0 -22
  522. package/dist/agent/code-act/index.js.map +0 -1
  523. package/dist/agent/code-act/run-context-registry.d.ts +0 -36
  524. package/dist/agent/code-act/run-context-registry.d.ts.map +0 -1
  525. package/dist/agent/code-act/run-context-registry.js +0 -143
  526. package/dist/agent/code-act/run-context-registry.js.map +0 -1
  527. package/dist/agent/code-act/sandbox.d.ts +0 -25
  528. package/dist/agent/code-act/sandbox.d.ts.map +0 -1
  529. package/dist/agent/code-act/sandbox.js +0 -494
  530. package/dist/agent/code-act/sandbox.js.map +0 -1
  531. package/dist/agent/code-act/tool-catalog.d.ts +0 -30
  532. package/dist/agent/code-act/tool-catalog.d.ts.map +0 -1
  533. package/dist/agent/code-act/tool-catalog.js +0 -185
  534. package/dist/agent/code-act/tool-catalog.js.map +0 -1
  535. package/dist/agent/code-act/tool-policy.d.ts +0 -51
  536. package/dist/agent/code-act/tool-policy.d.ts.map +0 -1
  537. package/dist/agent/code-act/tool-policy.js +0 -160
  538. package/dist/agent/code-act/tool-policy.js.map +0 -1
  539. package/dist/agent/code-act/type-definition-generator.d.ts +0 -19
  540. package/dist/agent/code-act/type-definition-generator.d.ts.map +0 -1
  541. package/dist/agent/code-act/type-definition-generator.js +0 -73
  542. package/dist/agent/code-act/type-definition-generator.js.map +0 -1
  543. package/dist/agent/code-act/types.d.ts +0 -57
  544. package/dist/agent/code-act/types.d.ts.map +0 -1
  545. package/dist/agent/code-act/types.js +0 -14
  546. package/dist/agent/code-act/types.js.map +0 -1
  547. package/dist/agent/codex-app-server-process.d.ts +0 -257
  548. package/dist/agent/codex-app-server-process.d.ts.map +0 -1
  549. package/dist/agent/codex-app-server-process.js +0 -2084
  550. package/dist/agent/codex-app-server-process.js.map +0 -1
  551. package/dist/agent/codex-auth.d.ts +0 -2
  552. package/dist/agent/codex-auth.d.ts.map +0 -1
  553. package/dist/agent/codex-auth.js +0 -17
  554. package/dist/agent/codex-auth.js.map +0 -1
  555. package/dist/agent/codex-auxiliary-tools.d.ts +0 -17
  556. package/dist/agent/codex-auxiliary-tools.d.ts.map +0 -1
  557. package/dist/agent/codex-auxiliary-tools.js +0 -267
  558. package/dist/agent/codex-auxiliary-tools.js.map +0 -1
  559. package/dist/agent/codex-home.d.ts +0 -13
  560. package/dist/agent/codex-home.d.ts.map +0 -1
  561. package/dist/agent/codex-home.js +0 -644
  562. package/dist/agent/codex-home.js.map +0 -1
  563. package/dist/agent/codex-thread-registry.d.ts +0 -63
  564. package/dist/agent/codex-thread-registry.d.ts.map +0 -1
  565. package/dist/agent/codex-thread-registry.js +0 -433
  566. package/dist/agent/codex-thread-registry.js.map +0 -1
  567. package/dist/agent/content-dedup.d.ts +0 -86
  568. package/dist/agent/content-dedup.d.ts.map +0 -1
  569. package/dist/agent/content-dedup.js +0 -114
  570. package/dist/agent/content-dedup.js.map +0 -1
  571. package/dist/agent/context-compile-contract.d.ts +0 -5
  572. package/dist/agent/context-compile-contract.d.ts.map +0 -1
  573. package/dist/agent/context-compile-contract.js +0 -8
  574. package/dist/agent/context-compile-contract.js.map +0 -1
  575. package/dist/agent/context-compile-service.d.ts +0 -60
  576. package/dist/agent/context-compile-service.d.ts.map +0 -1
  577. package/dist/agent/context-compile-service.js +0 -481
  578. package/dist/agent/context-compile-service.js.map +0 -1
  579. package/dist/agent/context-prompt-builder.d.ts +0 -24
  580. package/dist/agent/context-prompt-builder.d.ts.map +0 -1
  581. package/dist/agent/context-prompt-builder.js +0 -61
  582. package/dist/agent/context-prompt-builder.js.map +0 -1
  583. package/dist/agent/contract-extractor.d.ts +0 -124
  584. package/dist/agent/contract-extractor.d.ts.map +0 -1
  585. package/dist/agent/contract-extractor.js +0 -465
  586. package/dist/agent/contract-extractor.js.map +0 -1
  587. package/dist/agent/drive-tools.d.ts +0 -83
  588. package/dist/agent/drive-tools.d.ts.map +0 -1
  589. package/dist/agent/drive-tools.js +0 -338
  590. package/dist/agent/drive-tools.js.map +0 -1
  591. package/dist/agent/gateway-tool-catalog.d.ts +0 -14
  592. package/dist/agent/gateway-tool-catalog.d.ts.map +0 -1
  593. package/dist/agent/gateway-tool-catalog.js +0 -41
  594. package/dist/agent/gateway-tool-catalog.js.map +0 -1
  595. package/dist/agent/gateway-tool-executor.d.ts +0 -353
  596. package/dist/agent/gateway-tool-executor.d.ts.map +0 -1
  597. package/dist/agent/gateway-tool-executor.js +0 -5448
  598. package/dist/agent/gateway-tool-executor.js.map +0 -1
  599. package/dist/agent/gateway-tools.md +0 -166
  600. package/dist/agent/image-translation-tools.d.ts +0 -48
  601. package/dist/agent/image-translation-tools.d.ts.map +0 -1
  602. package/dist/agent/image-translation-tools.js +0 -274
  603. package/dist/agent/image-translation-tools.js.map +0 -1
  604. package/dist/agent/index.d.ts +0 -13
  605. package/dist/agent/index.d.ts.map +0 -1
  606. package/dist/agent/index.js +0 -18
  607. package/dist/agent/index.js.map +0 -1
  608. package/dist/agent/mama-tool-handlers.d.ts +0 -11
  609. package/dist/agent/mama-tool-handlers.d.ts.map +0 -1
  610. package/dist/agent/mama-tool-handlers.js +0 -220
  611. package/dist/agent/mama-tool-handlers.js.map +0 -1
  612. package/dist/agent/managed-agent-runtime-sync.d.ts +0 -36
  613. package/dist/agent/managed-agent-runtime-sync.d.ts.map +0 -1
  614. package/dist/agent/managed-agent-runtime-sync.js +0 -245
  615. package/dist/agent/managed-agent-runtime-sync.js.map +0 -1
  616. package/dist/agent/managed-agent-validation.d.ts +0 -4
  617. package/dist/agent/managed-agent-validation.d.ts.map +0 -1
  618. package/dist/agent/managed-agent-validation.js +0 -85
  619. package/dist/agent/managed-agent-validation.js.map +0 -1
  620. package/dist/agent/model-runner.d.ts +0 -180
  621. package/dist/agent/model-runner.d.ts.map +0 -1
  622. package/dist/agent/model-runner.js +0 -54
  623. package/dist/agent/model-runner.js.map +0 -1
  624. package/dist/agent/native-effect-observer.d.ts +0 -20
  625. package/dist/agent/native-effect-observer.d.ts.map +0 -1
  626. package/dist/agent/native-effect-observer.js +0 -86
  627. package/dist/agent/native-effect-observer.js.map +0 -1
  628. package/dist/agent/obsidian-cli-args.d.ts +0 -14
  629. package/dist/agent/obsidian-cli-args.d.ts.map +0 -1
  630. package/dist/agent/obsidian-cli-args.js +0 -57
  631. package/dist/agent/obsidian-cli-args.js.map +0 -1
  632. package/dist/agent/os-agent-capabilities.md +0 -367
  633. package/dist/agent/persistent-cli-adapter.d.ts +0 -173
  634. package/dist/agent/persistent-cli-adapter.d.ts.map +0 -1
  635. package/dist/agent/persistent-cli-adapter.js +0 -506
  636. package/dist/agent/persistent-cli-adapter.js.map +0 -1
  637. package/dist/agent/persistent-cli-process.d.ts +0 -392
  638. package/dist/agent/persistent-cli-process.d.ts.map +0 -1
  639. package/dist/agent/persistent-cli-process.js +0 -1568
  640. package/dist/agent/persistent-cli-process.js.map +0 -1
  641. package/dist/agent/post-tool-handler.d.ts +0 -27
  642. package/dist/agent/post-tool-handler.d.ts.map +0 -1
  643. package/dist/agent/post-tool-handler.js +0 -194
  644. package/dist/agent/post-tool-handler.js.map +0 -1
  645. package/dist/agent/pre-compact-handler.d.ts +0 -36
  646. package/dist/agent/pre-compact-handler.d.ts.map +0 -1
  647. package/dist/agent/pre-compact-handler.js +0 -162
  648. package/dist/agent/pre-compact-handler.js.map +0 -1
  649. package/dist/agent/prompt-enhancer.d.ts +0 -33
  650. package/dist/agent/prompt-enhancer.d.ts.map +0 -1
  651. package/dist/agent/prompt-enhancer.js +0 -811
  652. package/dist/agent/prompt-enhancer.js.map +0 -1
  653. package/dist/agent/prompt-size-monitor.d.ts +0 -104
  654. package/dist/agent/prompt-size-monitor.d.ts.map +0 -1
  655. package/dist/agent/prompt-size-monitor.js +0 -192
  656. package/dist/agent/prompt-size-monitor.js.map +0 -1
  657. package/dist/agent/role-manager.d.ts +0 -122
  658. package/dist/agent/role-manager.d.ts.map +0 -1
  659. package/dist/agent/role-manager.js +0 -300
  660. package/dist/agent/role-manager.js.map +0 -1
  661. package/dist/agent/session-pool.d.ts +0 -176
  662. package/dist/agent/session-pool.d.ts.map +0 -1
  663. package/dist/agent/session-pool.js +0 -368
  664. package/dist/agent/session-pool.js.map +0 -1
  665. package/dist/agent/skill-loader.d.ts +0 -87
  666. package/dist/agent/skill-loader.d.ts.map +0 -1
  667. package/dist/agent/skill-loader.js +0 -461
  668. package/dist/agent/skill-loader.js.map +0 -1
  669. package/dist/agent/stop-continuation-handler.d.ts +0 -106
  670. package/dist/agent/stop-continuation-handler.d.ts.map +0 -1
  671. package/dist/agent/stop-continuation-handler.js +0 -230
  672. package/dist/agent/stop-continuation-handler.js.map +0 -1
  673. package/dist/agent/subagent-run-reconcile.d.ts +0 -23
  674. package/dist/agent/subagent-run-reconcile.d.ts.map +0 -1
  675. package/dist/agent/subagent-run-reconcile.js +0 -56
  676. package/dist/agent/subagent-run-reconcile.js.map +0 -1
  677. package/dist/agent/temporal-code-act-breaker.d.ts +0 -26
  678. package/dist/agent/temporal-code-act-breaker.d.ts.map +0 -1
  679. package/dist/agent/temporal-code-act-breaker.js +0 -94
  680. package/dist/agent/temporal-code-act-breaker.js.map +0 -1
  681. package/dist/agent/token-estimator.d.ts +0 -25
  682. package/dist/agent/token-estimator.d.ts.map +0 -1
  683. package/dist/agent/token-estimator.js +0 -75
  684. package/dist/agent/token-estimator.js.map +0 -1
  685. package/dist/agent/tool-registry.d.ts +0 -81
  686. package/dist/agent/tool-registry.d.ts.map +0 -1
  687. package/dist/agent/tool-registry.js +0 -876
  688. package/dist/agent/tool-registry.js.map +0 -1
  689. package/dist/agent/types.d.ts +0 -1261
  690. package/dist/agent/types.d.ts.map +0 -1
  691. package/dist/agent/types.js +0 -60
  692. package/dist/agent/types.js.map +0 -1
  693. package/dist/agent/yaml-frontmatter.d.ts +0 -75
  694. package/dist/agent/yaml-frontmatter.d.ts.map +0 -1
  695. package/dist/agent/yaml-frontmatter.js +0 -166
  696. package/dist/agent/yaml-frontmatter.js.map +0 -1
  697. package/dist/api/agent-context-handler.d.ts +0 -10
  698. package/dist/api/agent-context-handler.d.ts.map +0 -1
  699. package/dist/api/agent-context-handler.js +0 -216
  700. package/dist/api/agent-context-handler.js.map +0 -1
  701. package/dist/api/agent-graph-handler.d.ts +0 -18
  702. package/dist/api/agent-graph-handler.d.ts.map +0 -1
  703. package/dist/api/agent-graph-handler.js +0 -569
  704. package/dist/api/agent-graph-handler.js.map +0 -1
  705. package/dist/api/agent-handler.d.ts +0 -36
  706. package/dist/api/agent-handler.d.ts.map +0 -1
  707. package/dist/api/agent-handler.js +0 -223
  708. package/dist/api/agent-handler.js.map +0 -1
  709. package/dist/api/agent-raw-handler.d.ts +0 -70
  710. package/dist/api/agent-raw-handler.d.ts.map +0 -1
  711. package/dist/api/agent-raw-handler.js +0 -262
  712. package/dist/api/agent-raw-handler.js.map +0 -1
  713. package/dist/api/agent-situation-handler.d.ts +0 -14
  714. package/dist/api/agent-situation-handler.d.ts.map +0 -1
  715. package/dist/api/agent-situation-handler.js +0 -383
  716. package/dist/api/agent-situation-handler.js.map +0 -1
  717. package/dist/api/connector-feed-handler.d.ts +0 -42
  718. package/dist/api/connector-feed-handler.d.ts.map +0 -1
  719. package/dist/api/connector-feed-handler.js +0 -180
  720. package/dist/api/connector-feed-handler.js.map +0 -1
  721. package/dist/api/cron-handler.d.ts +0 -44
  722. package/dist/api/cron-handler.d.ts.map +0 -1
  723. package/dist/api/cron-handler.js +0 -261
  724. package/dist/api/cron-handler.js.map +0 -1
  725. package/dist/api/entity-audit-handler.d.ts +0 -12
  726. package/dist/api/entity-audit-handler.d.ts.map +0 -1
  727. package/dist/api/entity-audit-handler.js +0 -119
  728. package/dist/api/entity-audit-handler.js.map +0 -1
  729. package/dist/api/entity-audit-queue.d.ts +0 -74
  730. package/dist/api/entity-audit-queue.d.ts.map +0 -1
  731. package/dist/api/entity-audit-queue.js +0 -123
  732. package/dist/api/entity-audit-queue.js.map +0 -1
  733. package/dist/api/entity-audit-runner.d.ts +0 -9
  734. package/dist/api/entity-audit-runner.d.ts.map +0 -1
  735. package/dist/api/entity-audit-runner.js +0 -240
  736. package/dist/api/entity-audit-runner.js.map +0 -1
  737. package/dist/api/entity-review-handler.d.ts +0 -18
  738. package/dist/api/entity-review-handler.d.ts.map +0 -1
  739. package/dist/api/entity-review-handler.js +0 -521
  740. package/dist/api/entity-review-handler.js.map +0 -1
  741. package/dist/api/error-handler.d.ts +0 -22
  742. package/dist/api/error-handler.d.ts.map +0 -1
  743. package/dist/api/error-handler.js +0 -104
  744. package/dist/api/error-handler.js.map +0 -1
  745. package/dist/api/graph-api-types.d.ts +0 -105
  746. package/dist/api/graph-api-types.d.ts.map +0 -1
  747. package/dist/api/graph-api-types.js +0 -6
  748. package/dist/api/graph-api-types.js.map +0 -1
  749. package/dist/api/graph-api.d.ts +0 -42
  750. package/dist/api/graph-api.d.ts.map +0 -1
  751. package/dist/api/graph-api.js +0 -3460
  752. package/dist/api/graph-api.js.map +0 -1
  753. package/dist/api/heartbeat-handler.d.ts +0 -49
  754. package/dist/api/heartbeat-handler.d.ts.map +0 -1
  755. package/dist/api/heartbeat-handler.js +0 -106
  756. package/dist/api/heartbeat-handler.js.map +0 -1
  757. package/dist/api/index.d.ts +0 -145
  758. package/dist/api/index.d.ts.map +0 -1
  759. package/dist/api/index.js +0 -448
  760. package/dist/api/index.js.map +0 -1
  761. package/dist/api/intelligence-handler.d.ts +0 -116
  762. package/dist/api/intelligence-handler.d.ts.map +0 -1
  763. package/dist/api/intelligence-handler.js +0 -280
  764. package/dist/api/intelligence-handler.js.map +0 -1
  765. package/dist/api/memory-provenance-handler.d.ts +0 -3
  766. package/dist/api/memory-provenance-handler.d.ts.map +0 -1
  767. package/dist/api/memory-provenance-handler.js +0 -120
  768. package/dist/api/memory-provenance-handler.js.map +0 -1
  769. package/dist/api/operator-handler.d.ts +0 -19
  770. package/dist/api/operator-handler.d.ts.map +0 -1
  771. package/dist/api/operator-handler.js +0 -106
  772. package/dist/api/operator-handler.js.map +0 -1
  773. package/dist/api/operator-summary.d.ts +0 -3
  774. package/dist/api/operator-summary.d.ts.map +0 -1
  775. package/dist/api/operator-summary.js +0 -72
  776. package/dist/api/operator-summary.js.map +0 -1
  777. package/dist/api/operator-tasks-handler.d.ts +0 -7
  778. package/dist/api/operator-tasks-handler.d.ts.map +0 -1
  779. package/dist/api/operator-tasks-handler.js +0 -192
  780. package/dist/api/operator-tasks-handler.js.map +0 -1
  781. package/dist/api/runtime-status-handler.d.ts +0 -42
  782. package/dist/api/runtime-status-handler.d.ts.map +0 -1
  783. package/dist/api/runtime-status-handler.js +0 -56
  784. package/dist/api/runtime-status-handler.js.map +0 -1
  785. package/dist/api/skills-handler.d.ts +0 -12
  786. package/dist/api/skills-handler.d.ts.map +0 -1
  787. package/dist/api/skills-handler.js +0 -156
  788. package/dist/api/skills-handler.js.map +0 -1
  789. package/dist/api/token-handler.d.ts +0 -33
  790. package/dist/api/token-handler.d.ts.map +0 -1
  791. package/dist/api/token-handler.js +0 -118
  792. package/dist/api/token-handler.js.map +0 -1
  793. package/dist/api/types.d.ts +0 -155
  794. package/dist/api/types.d.ts.map +0 -1
  795. package/dist/api/types.js +0 -49
  796. package/dist/api/types.js.map +0 -1
  797. package/dist/api/ui-command-handler.d.ts +0 -48
  798. package/dist/api/ui-command-handler.d.ts.map +0 -1
  799. package/dist/api/ui-command-handler.js +0 -160
  800. package/dist/api/ui-command-handler.js.map +0 -1
  801. package/dist/api/upload-handler.d.ts +0 -12
  802. package/dist/api/upload-handler.d.ts.map +0 -1
  803. package/dist/api/upload-handler.js +0 -321
  804. package/dist/api/upload-handler.js.map +0 -1
  805. package/dist/api/wiki-handler.d.ts +0 -19
  806. package/dist/api/wiki-handler.d.ts.map +0 -1
  807. package/dist/api/wiki-handler.js +0 -136
  808. package/dist/api/wiki-handler.js.map +0 -1
  809. package/dist/api/worker-envelope.d.ts +0 -26
  810. package/dist/api/worker-envelope.d.ts.map +0 -1
  811. package/dist/api/worker-envelope.js +0 -176
  812. package/dist/api/worker-envelope.js.map +0 -1
  813. package/dist/auth/claude-client.d.ts +0 -12
  814. package/dist/auth/claude-client.d.ts.map +0 -1
  815. package/dist/auth/claude-client.js +0 -36
  816. package/dist/auth/claude-client.js.map +0 -1
  817. package/dist/auth/claude-code-auth.d.ts +0 -12
  818. package/dist/auth/claude-code-auth.d.ts.map +0 -1
  819. package/dist/auth/claude-code-auth.js +0 -85
  820. package/dist/auth/claude-code-auth.js.map +0 -1
  821. package/dist/auth/index.d.ts +0 -9
  822. package/dist/auth/index.d.ts.map +0 -1
  823. package/dist/auth/index.js +0 -13
  824. package/dist/auth/index.js.map +0 -1
  825. package/dist/auth/oauth-manager.d.ts +0 -59
  826. package/dist/auth/oauth-manager.d.ts.map +0 -1
  827. package/dist/auth/oauth-manager.js +0 -252
  828. package/dist/auth/oauth-manager.js.map +0 -1
  829. package/dist/auth/types.d.ts +0 -92
  830. package/dist/auth/types.d.ts.map +0 -1
  831. package/dist/auth/types.js +0 -23
  832. package/dist/auth/types.js.map +0 -1
  833. package/dist/cli/commands/connector.d.ts +0 -14
  834. package/dist/cli/commands/connector.d.ts.map +0 -1
  835. package/dist/cli/commands/connector.js +0 -174
  836. package/dist/cli/commands/connector.js.map +0 -1
  837. package/dist/cli/commands/gateway.d.ts +0 -18
  838. package/dist/cli/commands/gateway.d.ts.map +0 -1
  839. package/dist/cli/commands/gateway.js +0 -144
  840. package/dist/cli/commands/gateway.js.map +0 -1
  841. package/dist/cli/commands/report.d.ts +0 -14
  842. package/dist/cli/commands/report.d.ts.map +0 -1
  843. package/dist/cli/commands/report.js +0 -102
  844. package/dist/cli/commands/report.js.map +0 -1
  845. package/dist/cli/commands/run.d.ts +0 -19
  846. package/dist/cli/commands/run.d.ts.map +0 -1
  847. package/dist/cli/commands/run.js +0 -123
  848. package/dist/cli/commands/run.js.map +0 -1
  849. package/dist/cli/commands/setup.d.ts +0 -3
  850. package/dist/cli/commands/setup.d.ts.map +0 -1
  851. package/dist/cli/commands/setup.js +0 -9
  852. package/dist/cli/commands/setup.js.map +0 -1
  853. package/dist/cli/commands/start.d.ts +0 -263
  854. package/dist/cli/commands/start.d.ts.map +0 -1
  855. package/dist/cli/commands/start.js +0 -2230
  856. package/dist/cli/commands/start.js.map +0 -1
  857. package/dist/cli/commands/status.d.ts +0 -18
  858. package/dist/cli/commands/status.d.ts.map +0 -1
  859. package/dist/cli/commands/status.js +0 -326
  860. package/dist/cli/commands/status.js.map +0 -1
  861. package/dist/cli/commands/stop.d.ts +0 -28
  862. package/dist/cli/commands/stop.d.ts.map +0 -1
  863. package/dist/cli/commands/stop.js +0 -597
  864. package/dist/cli/commands/stop.js.map +0 -1
  865. package/dist/cli/config/config-manager.d.ts +0 -84
  866. package/dist/cli/config/config-manager.d.ts.map +0 -1
  867. package/dist/cli/config/config-manager.js +0 -886
  868. package/dist/cli/config/config-manager.js.map +0 -1
  869. package/dist/cli/config/types.d.ts +0 -633
  870. package/dist/cli/config/types.d.ts.map +0 -1
  871. package/dist/cli/config/types.js +0 -247
  872. package/dist/cli/config/types.js.map +0 -1
  873. package/dist/cli/runtime/agent-loop-init.d.ts +0 -53
  874. package/dist/cli/runtime/agent-loop-init.d.ts.map +0 -1
  875. package/dist/cli/runtime/agent-loop-init.js +0 -368
  876. package/dist/cli/runtime/agent-loop-init.js.map +0 -1
  877. package/dist/cli/runtime/api-routes-init.d.ts +0 -84
  878. package/dist/cli/runtime/api-routes-init.d.ts.map +0 -1
  879. package/dist/cli/runtime/api-routes-init.js +0 -1542
  880. package/dist/cli/runtime/api-routes-init.js.map +0 -1
  881. package/dist/cli/runtime/api-server-init.d.ts +0 -59
  882. package/dist/cli/runtime/api-server-init.d.ts.map +0 -1
  883. package/dist/cli/runtime/api-server-init.js +0 -159
  884. package/dist/cli/runtime/api-server-init.js.map +0 -1
  885. package/dist/cli/runtime/code-act-executor.d.ts +0 -14
  886. package/dist/cli/runtime/code-act-executor.d.ts.map +0 -1
  887. package/dist/cli/runtime/code-act-executor.js +0 -108
  888. package/dist/cli/runtime/code-act-executor.js.map +0 -1
  889. package/dist/cli/runtime/connector-bootstrap.d.ts +0 -8
  890. package/dist/cli/runtime/connector-bootstrap.d.ts.map +0 -1
  891. package/dist/cli/runtime/connector-bootstrap.js +0 -14
  892. package/dist/cli/runtime/connector-bootstrap.js.map +0 -1
  893. package/dist/cli/runtime/connector-init.d.ts +0 -64
  894. package/dist/cli/runtime/connector-init.d.ts.map +0 -1
  895. package/dist/cli/runtime/connector-init.js +0 -237
  896. package/dist/cli/runtime/connector-init.js.map +0 -1
  897. package/dist/cli/runtime/daemon.d.ts +0 -38
  898. package/dist/cli/runtime/daemon.d.ts.map +0 -1
  899. package/dist/cli/runtime/daemon.js +0 -263
  900. package/dist/cli/runtime/daemon.js.map +0 -1
  901. package/dist/cli/runtime/envelope-bootstrap.d.ts +0 -17
  902. package/dist/cli/runtime/envelope-bootstrap.d.ts.map +0 -1
  903. package/dist/cli/runtime/envelope-bootstrap.js +0 -56
  904. package/dist/cli/runtime/envelope-bootstrap.js.map +0 -1
  905. package/dist/cli/runtime/gateway-init.d.ts +0 -55
  906. package/dist/cli/runtime/gateway-init.d.ts.map +0 -1
  907. package/dist/cli/runtime/gateway-init.js +0 -196
  908. package/dist/cli/runtime/gateway-init.js.map +0 -1
  909. package/dist/cli/runtime/gateway-wiring.d.ts +0 -51
  910. package/dist/cli/runtime/gateway-wiring.d.ts.map +0 -1
  911. package/dist/cli/runtime/gateway-wiring.js +0 -215
  912. package/dist/cli/runtime/gateway-wiring.js.map +0 -1
  913. package/dist/cli/runtime/mama-core-init.d.ts +0 -42
  914. package/dist/cli/runtime/mama-core-init.d.ts.map +0 -1
  915. package/dist/cli/runtime/mama-core-init.js +0 -211
  916. package/dist/cli/runtime/mama-core-init.js.map +0 -1
  917. package/dist/cli/runtime/message-router-config.d.ts +0 -4
  918. package/dist/cli/runtime/message-router-config.d.ts.map +0 -1
  919. package/dist/cli/runtime/message-router-config.js +0 -11
  920. package/dist/cli/runtime/message-router-config.js.map +0 -1
  921. package/dist/cli/runtime/metrics-init.d.ts +0 -28
  922. package/dist/cli/runtime/metrics-init.d.ts.map +0 -1
  923. package/dist/cli/runtime/metrics-init.js +0 -131
  924. package/dist/cli/runtime/metrics-init.js.map +0 -1
  925. package/dist/cli/runtime/owner-backfill.d.ts +0 -24
  926. package/dist/cli/runtime/owner-backfill.d.ts.map +0 -1
  927. package/dist/cli/runtime/owner-backfill.js +0 -24
  928. package/dist/cli/runtime/owner-backfill.js.map +0 -1
  929. package/dist/cli/runtime/scheduler-init.d.ts +0 -60
  930. package/dist/cli/runtime/scheduler-init.d.ts.map +0 -1
  931. package/dist/cli/runtime/scheduler-init.js +0 -173
  932. package/dist/cli/runtime/scheduler-init.js.map +0 -1
  933. package/dist/cli/runtime/server-start.d.ts +0 -23
  934. package/dist/cli/runtime/server-start.d.ts.map +0 -1
  935. package/dist/cli/runtime/server-start.js +0 -174
  936. package/dist/cli/runtime/server-start.js.map +0 -1
  937. package/dist/cli/runtime/shutdown.d.ts +0 -46
  938. package/dist/cli/runtime/shutdown.d.ts.map +0 -1
  939. package/dist/cli/runtime/shutdown.js +0 -240
  940. package/dist/cli/runtime/shutdown.js.map +0 -1
  941. package/dist/cli/runtime/temporal-init.d.ts +0 -26
  942. package/dist/cli/runtime/temporal-init.d.ts.map +0 -1
  943. package/dist/cli/runtime/temporal-init.js +0 -57
  944. package/dist/cli/runtime/temporal-init.js.map +0 -1
  945. package/dist/cli/runtime/types.d.ts +0 -127
  946. package/dist/cli/runtime/types.d.ts.map +0 -1
  947. package/dist/cli/runtime/types.js +0 -12
  948. package/dist/cli/runtime/types.js.map +0 -1
  949. package/dist/cli/runtime/utilities.d.ts +0 -72
  950. package/dist/cli/runtime/utilities.d.ts.map +0 -1
  951. package/dist/cli/runtime/utilities.js +0 -472
  952. package/dist/cli/runtime/utilities.js.map +0 -1
  953. package/dist/cli/shutdown-utils.d.ts +0 -6
  954. package/dist/cli/shutdown-utils.d.ts.map +0 -1
  955. package/dist/cli/shutdown-utils.js +0 -11
  956. package/dist/cli/shutdown-utils.js.map +0 -1
  957. package/dist/cli/utils/pid-manager.d.ts +0 -56
  958. package/dist/cli/utils/pid-manager.d.ts.map +0 -1
  959. package/dist/cli/utils/pid-manager.js +0 -141
  960. package/dist/cli/utils/pid-manager.js.map +0 -1
  961. package/dist/concurrency/index.d.ts +0 -13
  962. package/dist/concurrency/index.d.ts.map +0 -1
  963. package/dist/concurrency/index.js +0 -22
  964. package/dist/concurrency/index.js.map +0 -1
  965. package/dist/concurrency/lane-manager.d.ts +0 -113
  966. package/dist/concurrency/lane-manager.d.ts.map +0 -1
  967. package/dist/concurrency/lane-manager.js +0 -248
  968. package/dist/concurrency/lane-manager.js.map +0 -1
  969. package/dist/concurrency/session-key.d.ts +0 -41
  970. package/dist/concurrency/session-key.d.ts.map +0 -1
  971. package/dist/concurrency/session-key.js +0 -61
  972. package/dist/concurrency/session-key.js.map +0 -1
  973. package/dist/concurrency/types.d.ts +0 -73
  974. package/dist/concurrency/types.d.ts.map +0 -1
  975. package/dist/concurrency/types.js +0 -16
  976. package/dist/concurrency/types.js.map +0 -1
  977. package/dist/connectors/framework/raw-store.d.ts +0 -63
  978. package/dist/connectors/framework/raw-store.d.ts.map +0 -1
  979. package/dist/connectors/framework/raw-store.js +0 -356
  980. package/dist/connectors/framework/raw-store.js.map +0 -1
  981. package/dist/connectors/kagemusha/query-tools.d.ts +0 -146
  982. package/dist/connectors/kagemusha/query-tools.d.ts.map +0 -1
  983. package/dist/connectors/kagemusha/query-tools.js +0 -467
  984. package/dist/connectors/kagemusha/query-tools.js.map +0 -1
  985. package/dist/connectors/private-connector-policy.d.ts +0 -174
  986. package/dist/connectors/private-connector-policy.d.ts.map +0 -1
  987. package/dist/connectors/private-connector-policy.js +0 -299
  988. package/dist/connectors/private-connector-policy.js.map +0 -1
  989. package/dist/connectors/private-prompt-overlay.d.ts +0 -17
  990. package/dist/connectors/private-prompt-overlay.d.ts.map +0 -1
  991. package/dist/connectors/private-prompt-overlay.js +0 -156
  992. package/dist/connectors/private-prompt-overlay.js.map +0 -1
  993. package/dist/connectors/trello/query-tools.d.ts +0 -243
  994. package/dist/connectors/trello/query-tools.d.ts.map +0 -1
  995. package/dist/connectors/trello/query-tools.js +0 -661
  996. package/dist/connectors/trello/query-tools.js.map +0 -1
  997. package/dist/db/agent-store.d.ts +0 -145
  998. package/dist/db/agent-store.d.ts.map +0 -1
  999. package/dist/db/agent-store.js +0 -279
  1000. package/dist/db/agent-store.js.map +0 -1
  1001. package/dist/db/migrations/agent-activity-envelope-hash.d.ts +0 -3
  1002. package/dist/db/migrations/agent-activity-envelope-hash.d.ts.map +0 -1
  1003. package/dist/db/migrations/agent-activity-envelope-hash.js +0 -29
  1004. package/dist/db/migrations/agent-activity-envelope-hash.js.map +0 -1
  1005. package/dist/db/migrations/agent-activity-gateway-call-id.d.ts +0 -3
  1006. package/dist/db/migrations/agent-activity-gateway-call-id.d.ts.map +0 -1
  1007. package/dist/db/migrations/agent-activity-gateway-call-id.js +0 -17
  1008. package/dist/db/migrations/agent-activity-gateway-call-id.js.map +0 -1
  1009. package/dist/db/migrations/agent-activity-tool-name.d.ts +0 -8
  1010. package/dist/db/migrations/agent-activity-tool-name.d.ts.map +0 -1
  1011. package/dist/db/migrations/agent-activity-tool-name.js +0 -24
  1012. package/dist/db/migrations/agent-activity-tool-name.js.map +0 -1
  1013. package/dist/db/migrations/agent-activity-validation-columns.d.ts +0 -3
  1014. package/dist/db/migrations/agent-activity-validation-columns.d.ts.map +0 -1
  1015. package/dist/db/migrations/agent-activity-validation-columns.js +0 -22
  1016. package/dist/db/migrations/agent-activity-validation-columns.js.map +0 -1
  1017. package/dist/db/migrations/agent-metrics-response-avg.d.ts +0 -3
  1018. package/dist/db/migrations/agent-metrics-response-avg.d.ts.map +0 -1
  1019. package/dist/db/migrations/agent-metrics-response-avg.js +0 -19
  1020. package/dist/db/migrations/agent-metrics-response-avg.js.map +0 -1
  1021. package/dist/db/migrations/agent-store-tables.d.ts +0 -3
  1022. package/dist/db/migrations/agent-store-tables.d.ts.map +0 -1
  1023. package/dist/db/migrations/agent-store-tables.js +0 -64
  1024. package/dist/db/migrations/agent-store-tables.js.map +0 -1
  1025. package/dist/db/migrations/envelope-tables.d.ts +0 -3
  1026. package/dist/db/migrations/envelope-tables.d.ts.map +0 -1
  1027. package/dist/db/migrations/envelope-tables.js +0 -38
  1028. package/dist/db/migrations/envelope-tables.js.map +0 -1
  1029. package/dist/db/migrations/operator-owner-action-candidates.d.ts +0 -19
  1030. package/dist/db/migrations/operator-owner-action-candidates.d.ts.map +0 -1
  1031. package/dist/db/migrations/operator-owner-action-candidates.js +0 -254
  1032. package/dist/db/migrations/operator-owner-action-candidates.js.map +0 -1
  1033. package/dist/db/migrations/operator-procedures.d.ts +0 -4
  1034. package/dist/db/migrations/operator-procedures.d.ts.map +0 -1
  1035. package/dist/db/migrations/operator-procedures.js +0 -63
  1036. package/dist/db/migrations/operator-procedures.js.map +0 -1
  1037. package/dist/db/migrations/operator-task-classification.d.ts +0 -15
  1038. package/dist/db/migrations/operator-task-classification.d.ts.map +0 -1
  1039. package/dist/db/migrations/operator-task-classification.js +0 -25
  1040. package/dist/db/migrations/operator-task-classification.js.map +0 -1
  1041. package/dist/db/migrations/operator-task-external-lifecycle.d.ts +0 -17
  1042. package/dist/db/migrations/operator-task-external-lifecycle.d.ts.map +0 -1
  1043. package/dist/db/migrations/operator-task-external-lifecycle.js +0 -199
  1044. package/dist/db/migrations/operator-task-external-lifecycle.js.map +0 -1
  1045. package/dist/db/migrations/operator-task-review-lifecycle.d.ts +0 -4
  1046. package/dist/db/migrations/operator-task-review-lifecycle.d.ts.map +0 -1
  1047. package/dist/db/migrations/operator-task-review-lifecycle.js +0 -17
  1048. package/dist/db/migrations/operator-task-review-lifecycle.js.map +0 -1
  1049. package/dist/db/migrations/operator-task-temporal.d.ts +0 -8
  1050. package/dist/db/migrations/operator-task-temporal.d.ts.map +0 -1
  1051. package/dist/db/migrations/operator-task-temporal.js +0 -214
  1052. package/dist/db/migrations/operator-task-temporal.js.map +0 -1
  1053. package/dist/db/migrations/owner-action-effects.d.ts +0 -18
  1054. package/dist/db/migrations/owner-action-effects.d.ts.map +0 -1
  1055. package/dist/db/migrations/owner-action-effects.js +0 -111
  1056. package/dist/db/migrations/owner-action-effects.js.map +0 -1
  1057. package/dist/db/migrations/raw-item-revisions.d.ts +0 -4
  1058. package/dist/db/migrations/raw-item-revisions.d.ts.map +0 -1
  1059. package/dist/db/migrations/raw-item-revisions.js +0 -29
  1060. package/dist/db/migrations/raw-item-revisions.js.map +0 -1
  1061. package/dist/db/migrations/token-usage-agent-version.d.ts +0 -3
  1062. package/dist/db/migrations/token-usage-agent-version.d.ts.map +0 -1
  1063. package/dist/db/migrations/token-usage-agent-version.js +0 -16
  1064. package/dist/db/migrations/token-usage-agent-version.js.map +0 -1
  1065. package/dist/db/migrations/validation-session-tables.d.ts +0 -3
  1066. package/dist/db/migrations/validation-session-tables.d.ts.map +0 -1
  1067. package/dist/db/migrations/validation-session-tables.js +0 -59
  1068. package/dist/db/migrations/validation-session-tables.js.map +0 -1
  1069. package/dist/envelope/authority.d.ts +0 -15
  1070. package/dist/envelope/authority.d.ts.map +0 -1
  1071. package/dist/envelope/authority.js +0 -95
  1072. package/dist/envelope/authority.js.map +0 -1
  1073. package/dist/envelope/canonical.d.ts +0 -14
  1074. package/dist/envelope/canonical.d.ts.map +0 -1
  1075. package/dist/envelope/canonical.js +0 -68
  1076. package/dist/envelope/canonical.js.map +0 -1
  1077. package/dist/envelope/enforcer.d.ts +0 -30
  1078. package/dist/envelope/enforcer.d.ts.map +0 -1
  1079. package/dist/envelope/enforcer.js +0 -286
  1080. package/dist/envelope/enforcer.js.map +0 -1
  1081. package/dist/envelope/expiry.d.ts +0 -2
  1082. package/dist/envelope/expiry.d.ts.map +0 -1
  1083. package/dist/envelope/expiry.js +0 -15
  1084. package/dist/envelope/expiry.js.map +0 -1
  1085. package/dist/envelope/index.d.ts +0 -9
  1086. package/dist/envelope/index.d.ts.map +0 -1
  1087. package/dist/envelope/index.js +0 -25
  1088. package/dist/envelope/index.js.map +0 -1
  1089. package/dist/envelope/key-provider.d.ts +0 -7
  1090. package/dist/envelope/key-provider.d.ts.map +0 -1
  1091. package/dist/envelope/key-provider.js +0 -137
  1092. package/dist/envelope/key-provider.js.map +0 -1
  1093. package/dist/envelope/reactive-config.d.ts +0 -24
  1094. package/dist/envelope/reactive-config.d.ts.map +0 -1
  1095. package/dist/envelope/reactive-config.js +0 -198
  1096. package/dist/envelope/reactive-config.js.map +0 -1
  1097. package/dist/envelope/run-guard.d.ts +0 -10
  1098. package/dist/envelope/run-guard.d.ts.map +0 -1
  1099. package/dist/envelope/run-guard.js +0 -19
  1100. package/dist/envelope/run-guard.js.map +0 -1
  1101. package/dist/envelope/signature.d.ts +0 -15
  1102. package/dist/envelope/signature.d.ts.map +0 -1
  1103. package/dist/envelope/signature.js +0 -75
  1104. package/dist/envelope/signature.js.map +0 -1
  1105. package/dist/envelope/store.d.ts +0 -16
  1106. package/dist/envelope/store.d.ts.map +0 -1
  1107. package/dist/envelope/store.js +0 -118
  1108. package/dist/envelope/store.js.map +0 -1
  1109. package/dist/envelope/tool-connector-scope.d.ts +0 -35
  1110. package/dist/envelope/tool-connector-scope.d.ts.map +0 -1
  1111. package/dist/envelope/tool-connector-scope.js +0 -61
  1112. package/dist/envelope/tool-connector-scope.js.map +0 -1
  1113. package/dist/envelope/types.d.ts +0 -60
  1114. package/dist/envelope/types.d.ts.map +0 -1
  1115. package/dist/envelope/types.js +0 -9
  1116. package/dist/envelope/types.js.map +0 -1
  1117. package/dist/evidence/effects.d.ts +0 -125
  1118. package/dist/evidence/effects.d.ts.map +0 -1
  1119. package/dist/evidence/effects.js +0 -409
  1120. package/dist/evidence/effects.js.map +0 -1
  1121. package/dist/evidence/read.d.ts +0 -130
  1122. package/dist/evidence/read.d.ts.map +0 -1
  1123. package/dist/evidence/read.js +0 -167
  1124. package/dist/evidence/read.js.map +0 -1
  1125. package/dist/gateways/attachment-utils.d.ts +0 -28
  1126. package/dist/gateways/attachment-utils.d.ts.map +0 -1
  1127. package/dist/gateways/attachment-utils.js +0 -489
  1128. package/dist/gateways/attachment-utils.js.map +0 -1
  1129. package/dist/gateways/channel-history.d.ts +0 -148
  1130. package/dist/gateways/channel-history.d.ts.map +0 -1
  1131. package/dist/gateways/channel-history.js +0 -385
  1132. package/dist/gateways/channel-history.js.map +0 -1
  1133. package/dist/gateways/context-injector.d.ts +0 -255
  1134. package/dist/gateways/context-injector.d.ts.map +0 -1
  1135. package/dist/gateways/context-injector.js +0 -285
  1136. package/dist/gateways/context-injector.js.map +0 -1
  1137. package/dist/gateways/image-analyzer.d.ts +0 -28
  1138. package/dist/gateways/image-analyzer.d.ts.map +0 -1
  1139. package/dist/gateways/image-analyzer.js +0 -154
  1140. package/dist/gateways/image-analyzer.js.map +0 -1
  1141. package/dist/gateways/index.d.ts +0 -35
  1142. package/dist/gateways/index.d.ts.map +0 -1
  1143. package/dist/gateways/index.js +0 -55
  1144. package/dist/gateways/index.js.map +0 -1
  1145. package/dist/gateways/member-candidate-store.d.ts +0 -26
  1146. package/dist/gateways/member-candidate-store.d.ts.map +0 -1
  1147. package/dist/gateways/member-candidate-store.js +0 -90
  1148. package/dist/gateways/member-candidate-store.js.map +0 -1
  1149. package/dist/gateways/member-effective-scope.d.ts +0 -25
  1150. package/dist/gateways/member-effective-scope.d.ts.map +0 -1
  1151. package/dist/gateways/member-effective-scope.js +0 -323
  1152. package/dist/gateways/member-effective-scope.js.map +0 -1
  1153. package/dist/gateways/message-router.d.ts +0 -239
  1154. package/dist/gateways/message-router.d.ts.map +0 -1
  1155. package/dist/gateways/message-router.js +0 -1714
  1156. package/dist/gateways/message-router.js.map +0 -1
  1157. package/dist/gateways/plugin-loader.d.ts +0 -80
  1158. package/dist/gateways/plugin-loader.d.ts.map +0 -1
  1159. package/dist/gateways/plugin-loader.js +0 -299
  1160. package/dist/gateways/plugin-loader.js.map +0 -1
  1161. package/dist/gateways/principal.d.ts +0 -37
  1162. package/dist/gateways/principal.d.ts.map +0 -1
  1163. package/dist/gateways/principal.js +0 -95
  1164. package/dist/gateways/principal.js.map +0 -1
  1165. package/dist/gateways/report-projection-v1.d.ts +0 -41
  1166. package/dist/gateways/report-projection-v1.d.ts.map +0 -1
  1167. package/dist/gateways/report-projection-v1.js +0 -160
  1168. package/dist/gateways/report-projection-v1.js.map +0 -1
  1169. package/dist/gateways/telegram-media.d.ts +0 -41
  1170. package/dist/gateways/telegram-media.d.ts.map +0 -1
  1171. package/dist/gateways/telegram-media.js +0 -242
  1172. package/dist/gateways/telegram-media.js.map +0 -1
  1173. package/dist/gateways/telegram-report-context-store.d.ts +0 -131
  1174. package/dist/gateways/telegram-report-context-store.d.ts.map +0 -1
  1175. package/dist/gateways/telegram-report-context-store.js +0 -388
  1176. package/dist/gateways/telegram-report-context-store.js.map +0 -1
  1177. package/dist/gateways/tool-status-tracker.d.ts +0 -87
  1178. package/dist/gateways/tool-status-tracker.d.ts.map +0 -1
  1179. package/dist/gateways/tool-status-tracker.js +0 -284
  1180. package/dist/gateways/tool-status-tracker.js.map +0 -1
  1181. package/dist/mcp/code-act-api-client.d.ts +0 -32
  1182. package/dist/mcp/code-act-api-client.d.ts.map +0 -1
  1183. package/dist/mcp/code-act-api-client.js +0 -80
  1184. package/dist/mcp/code-act-api-client.js.map +0 -1
  1185. package/dist/mcp/code-act-mcp-config.d.ts +0 -49
  1186. package/dist/mcp/code-act-mcp-config.d.ts.map +0 -1
  1187. package/dist/mcp/code-act-mcp-config.js +0 -124
  1188. package/dist/mcp/code-act-mcp-config.js.map +0 -1
  1189. package/dist/mcp/code-act-server.d.ts +0 -14
  1190. package/dist/mcp/code-act-server.d.ts.map +0 -1
  1191. package/dist/mcp/code-act-server.js +0 -204
  1192. package/dist/mcp/code-act-server.js.map +0 -1
  1193. package/dist/mcp/code-act-terminal-transport.d.ts +0 -64
  1194. package/dist/mcp/code-act-terminal-transport.d.ts.map +0 -1
  1195. package/dist/mcp/code-act-terminal-transport.js +0 -176
  1196. package/dist/mcp/code-act-terminal-transport.js.map +0 -1
  1197. package/dist/memory/agent-notice-queue.d.ts +0 -24
  1198. package/dist/memory/agent-notice-queue.d.ts.map +0 -1
  1199. package/dist/memory/agent-notice-queue.js +0 -40
  1200. package/dist/memory/agent-notice-queue.js.map +0 -1
  1201. package/dist/memory/audit-task-queue.d.ts +0 -28
  1202. package/dist/memory/audit-task-queue.d.ts.map +0 -1
  1203. package/dist/memory/audit-task-queue.js +0 -29
  1204. package/dist/memory/audit-task-queue.js.map +0 -1
  1205. package/dist/memory/bootstrap-context.d.ts +0 -12
  1206. package/dist/memory/bootstrap-context.d.ts.map +0 -1
  1207. package/dist/memory/bootstrap-context.js +0 -68
  1208. package/dist/memory/bootstrap-context.js.map +0 -1
  1209. package/dist/memory/history-extractor.d.ts +0 -69
  1210. package/dist/memory/history-extractor.d.ts.map +0 -1
  1211. package/dist/memory/history-extractor.js +0 -210
  1212. package/dist/memory/history-extractor.js.map +0 -1
  1213. package/dist/memory/memory-agent-ack.d.ts +0 -4
  1214. package/dist/memory/memory-agent-ack.d.ts.map +0 -1
  1215. package/dist/memory/memory-agent-ack.js +0 -54
  1216. package/dist/memory/memory-agent-ack.js.map +0 -1
  1217. package/dist/memory/memory-agent-dashboard.d.ts +0 -35
  1218. package/dist/memory/memory-agent-dashboard.d.ts.map +0 -1
  1219. package/dist/memory/memory-agent-dashboard.js +0 -116
  1220. package/dist/memory/memory-agent-dashboard.js.map +0 -1
  1221. package/dist/memory/memory-logger.d.ts +0 -47
  1222. package/dist/memory/memory-logger.d.ts.map +0 -1
  1223. package/dist/memory/memory-logger.js +0 -126
  1224. package/dist/memory/memory-logger.js.map +0 -1
  1225. package/dist/memory/provenance-live.d.ts +0 -111
  1226. package/dist/memory/provenance-live.d.ts.map +0 -1
  1227. package/dist/memory/provenance-live.js +0 -381
  1228. package/dist/memory/provenance-live.js.map +0 -1
  1229. package/dist/memory/provenance-resolver.d.ts +0 -184
  1230. package/dist/memory/provenance-resolver.d.ts.map +0 -1
  1231. package/dist/memory/provenance-resolver.js +0 -152
  1232. package/dist/memory/provenance-resolver.js.map +0 -1
  1233. package/dist/memory/raw-backed-memory-ingest.d.ts +0 -26
  1234. package/dist/memory/raw-backed-memory-ingest.d.ts.map +0 -1
  1235. package/dist/memory/raw-backed-memory-ingest.js +0 -214
  1236. package/dist/memory/raw-backed-memory-ingest.js.map +0 -1
  1237. package/dist/memory/recall-bundle-formatter.d.ts +0 -26
  1238. package/dist/memory/recall-bundle-formatter.d.ts.map +0 -1
  1239. package/dist/memory/recall-bundle-formatter.js +0 -53
  1240. package/dist/memory/recall-bundle-formatter.js.map +0 -1
  1241. package/dist/memory/save-candidate-extractor.d.ts +0 -16
  1242. package/dist/memory/save-candidate-extractor.d.ts.map +0 -1
  1243. package/dist/memory/save-candidate-extractor.js +0 -127
  1244. package/dist/memory/save-candidate-extractor.js.map +0 -1
  1245. package/dist/memory/save-candidate-types.d.ts +0 -16
  1246. package/dist/memory/save-candidate-types.d.ts.map +0 -1
  1247. package/dist/memory/save-candidate-types.js +0 -3
  1248. package/dist/memory/save-candidate-types.js.map +0 -1
  1249. package/dist/memory/scope-context.d.ts +0 -12
  1250. package/dist/memory/scope-context.d.ts.map +0 -1
  1251. package/dist/memory/scope-context.js +0 -18
  1252. package/dist/memory/scope-context.js.map +0 -1
  1253. package/dist/memory/secret-filter.d.ts +0 -23
  1254. package/dist/memory/secret-filter.d.ts.map +0 -1
  1255. package/dist/memory/secret-filter.js +0 -90
  1256. package/dist/memory/secret-filter.js.map +0 -1
  1257. package/dist/multi-agent/agent-event-bus.d.ts +0 -50
  1258. package/dist/multi-agent/agent-event-bus.d.ts.map +0 -1
  1259. package/dist/multi-agent/agent-event-bus.js +0 -101
  1260. package/dist/multi-agent/agent-event-bus.js.map +0 -1
  1261. package/dist/multi-agent/agent-process-manager.d.ts +0 -205
  1262. package/dist/multi-agent/agent-process-manager.d.ts.map +0 -1
  1263. package/dist/multi-agent/agent-process-manager.js +0 -1191
  1264. package/dist/multi-agent/agent-process-manager.js.map +0 -1
  1265. package/dist/multi-agent/bmad-templates.d.ts +0 -49
  1266. package/dist/multi-agent/bmad-templates.d.ts.map +0 -1
  1267. package/dist/multi-agent/bmad-templates.js +0 -121
  1268. package/dist/multi-agent/bmad-templates.js.map +0 -1
  1269. package/dist/multi-agent/runtime-process.d.ts +0 -74
  1270. package/dist/multi-agent/runtime-process.d.ts.map +0 -1
  1271. package/dist/multi-agent/runtime-process.js +0 -160
  1272. package/dist/multi-agent/runtime-process.js.map +0 -1
  1273. package/dist/multi-agent/tool-permission-manager.d.ts +0 -70
  1274. package/dist/multi-agent/tool-permission-manager.d.ts.map +0 -1
  1275. package/dist/multi-agent/tool-permission-manager.js +0 -195
  1276. package/dist/multi-agent/tool-permission-manager.js.map +0 -1
  1277. package/dist/multi-agent/types.d.ts +0 -438
  1278. package/dist/multi-agent/types.d.ts.map +0 -1
  1279. package/dist/multi-agent/types.js +0 -27
  1280. package/dist/multi-agent/types.js.map +0 -1
  1281. package/dist/multi-agent/wiki-agent-persona.d.ts +0 -16
  1282. package/dist/multi-agent/wiki-agent-persona.d.ts.map +0 -1
  1283. package/dist/multi-agent/wiki-agent-persona.js +0 -23
  1284. package/dist/multi-agent/wiki-agent-persona.js.map +0 -1
  1285. package/dist/multi-agent/workflow-types.d.ts +0 -186
  1286. package/dist/multi-agent/workflow-types.d.ts.map +0 -1
  1287. package/dist/multi-agent/workflow-types.js +0 -9
  1288. package/dist/multi-agent/workflow-types.js.map +0 -1
  1289. package/dist/observability/code-audit.d.ts +0 -87
  1290. package/dist/observability/code-audit.d.ts.map +0 -1
  1291. package/dist/observability/code-audit.js +0 -414
  1292. package/dist/observability/code-audit.js.map +0 -1
  1293. package/dist/observability/health-check.d.ts +0 -102
  1294. package/dist/observability/health-check.d.ts.map +0 -1
  1295. package/dist/observability/health-check.js +0 -422
  1296. package/dist/observability/health-check.js.map +0 -1
  1297. package/dist/observability/health-score.d.ts +0 -29
  1298. package/dist/observability/health-score.d.ts.map +0 -1
  1299. package/dist/observability/health-score.js +0 -83
  1300. package/dist/observability/health-score.js.map +0 -1
  1301. package/dist/observability/metrics-cleanup.d.ts +0 -24
  1302. package/dist/observability/metrics-cleanup.d.ts.map +0 -1
  1303. package/dist/observability/metrics-cleanup.js +0 -51
  1304. package/dist/observability/metrics-cleanup.js.map +0 -1
  1305. package/dist/observability/metrics-store.d.ts +0 -52
  1306. package/dist/observability/metrics-store.d.ts.map +0 -1
  1307. package/dist/observability/metrics-store.js +0 -186
  1308. package/dist/observability/metrics-store.js.map +0 -1
  1309. package/dist/observability/operational-issues.d.ts +0 -55
  1310. package/dist/observability/operational-issues.d.ts.map +0 -1
  1311. package/dist/observability/operational-issues.js +0 -170
  1312. package/dist/observability/operational-issues.js.map +0 -1
  1313. package/dist/onboarding/agent-contract.d.ts +0 -42
  1314. package/dist/onboarding/agent-contract.d.ts.map +0 -1
  1315. package/dist/onboarding/agent-contract.js +0 -129
  1316. package/dist/onboarding/agent-contract.js.map +0 -1
  1317. package/dist/onboarding/assess-live.d.ts +0 -22
  1318. package/dist/onboarding/assess-live.d.ts.map +0 -1
  1319. package/dist/onboarding/assess-live.js +0 -200
  1320. package/dist/onboarding/assess-live.js.map +0 -1
  1321. package/dist/onboarding/bootstrap-template.d.ts +0 -5
  1322. package/dist/onboarding/bootstrap-template.d.ts.map +0 -1
  1323. package/dist/onboarding/bootstrap-template.js +0 -34
  1324. package/dist/onboarding/bootstrap-template.js.map +0 -1
  1325. package/dist/operator/action-verifier.d.ts +0 -75
  1326. package/dist/operator/action-verifier.d.ts.map +0 -1
  1327. package/dist/operator/action-verifier.js +0 -149
  1328. package/dist/operator/action-verifier.js.map +0 -1
  1329. package/dist/operator/board-delta-gate.d.ts +0 -131
  1330. package/dist/operator/board-delta-gate.d.ts.map +0 -1
  1331. package/dist/operator/board-delta-gate.js +0 -181
  1332. package/dist/operator/board-delta-gate.js.map +0 -1
  1333. package/dist/operator/board-pipeline-render.d.ts +0 -16
  1334. package/dist/operator/board-pipeline-render.d.ts.map +0 -1
  1335. package/dist/operator/board-pipeline-render.js +0 -69
  1336. package/dist/operator/board-pipeline-render.js.map +0 -1
  1337. package/dist/operator/board-reconcile.d.ts +0 -61
  1338. package/dist/operator/board-reconcile.d.ts.map +0 -1
  1339. package/dist/operator/board-reconcile.js +0 -157
  1340. package/dist/operator/board-reconcile.js.map +0 -1
  1341. package/dist/operator/board-refresh-gate.d.ts +0 -39
  1342. package/dist/operator/board-refresh-gate.d.ts.map +0 -1
  1343. package/dist/operator/board-refresh-gate.js +0 -83
  1344. package/dist/operator/board-refresh-gate.js.map +0 -1
  1345. package/dist/operator/changes-projection.d.ts +0 -72
  1346. package/dist/operator/changes-projection.d.ts.map +0 -1
  1347. package/dist/operator/changes-projection.js +0 -110
  1348. package/dist/operator/changes-projection.js.map +0 -1
  1349. package/dist/operator/connector-delta-repo.d.ts +0 -33
  1350. package/dist/operator/connector-delta-repo.d.ts.map +0 -1
  1351. package/dist/operator/connector-delta-repo.js +0 -0
  1352. package/dist/operator/connector-delta-repo.js.map +0 -1
  1353. package/dist/operator/console-brief.d.ts +0 -40
  1354. package/dist/operator/console-brief.d.ts.map +0 -1
  1355. package/dist/operator/console-brief.js +0 -246
  1356. package/dist/operator/console-brief.js.map +0 -1
  1357. package/dist/operator/experience-evidence.d.ts +0 -18
  1358. package/dist/operator/experience-evidence.d.ts.map +0 -1
  1359. package/dist/operator/experience-evidence.js +0 -82
  1360. package/dist/operator/experience-evidence.js.map +0 -1
  1361. package/dist/operator/experience-hints.d.ts +0 -44
  1362. package/dist/operator/experience-hints.d.ts.map +0 -1
  1363. package/dist/operator/experience-hints.js +0 -98
  1364. package/dist/operator/experience-hints.js.map +0 -1
  1365. package/dist/operator/external-correlation.d.ts +0 -94
  1366. package/dist/operator/external-correlation.d.ts.map +0 -1
  1367. package/dist/operator/external-correlation.js +0 -177
  1368. package/dist/operator/external-correlation.js.map +0 -1
  1369. package/dist/operator/external-lifecycle-candidates.d.ts +0 -70
  1370. package/dist/operator/external-lifecycle-candidates.d.ts.map +0 -1
  1371. package/dist/operator/external-lifecycle-candidates.js +0 -579
  1372. package/dist/operator/external-lifecycle-candidates.js.map +0 -1
  1373. package/dist/operator/external-lifecycle-discovery.d.ts +0 -61
  1374. package/dist/operator/external-lifecycle-discovery.d.ts.map +0 -1
  1375. package/dist/operator/external-lifecycle-discovery.js +0 -103
  1376. package/dist/operator/external-lifecycle-discovery.js.map +0 -1
  1377. package/dist/operator/external-lifecycle.d.ts +0 -105
  1378. package/dist/operator/external-lifecycle.d.ts.map +0 -1
  1379. package/dist/operator/external-lifecycle.js +0 -27
  1380. package/dist/operator/external-lifecycle.js.map +0 -1
  1381. package/dist/operator/file-coordination.d.ts +0 -7
  1382. package/dist/operator/file-coordination.d.ts.map +0 -1
  1383. package/dist/operator/file-coordination.js +0 -84
  1384. package/dist/operator/file-coordination.js.map +0 -1
  1385. package/dist/operator/file-export.d.ts +0 -22
  1386. package/dist/operator/file-export.d.ts.map +0 -1
  1387. package/dist/operator/file-export.js +0 -115
  1388. package/dist/operator/file-export.js.map +0 -1
  1389. package/dist/operator/leg-cadence.d.ts +0 -72
  1390. package/dist/operator/leg-cadence.d.ts.map +0 -1
  1391. package/dist/operator/leg-cadence.js +0 -122
  1392. package/dist/operator/leg-cadence.js.map +0 -1
  1393. package/dist/operator/mama-memory-port.d.ts +0 -13
  1394. package/dist/operator/mama-memory-port.d.ts.map +0 -1
  1395. package/dist/operator/mama-memory-port.js +0 -33
  1396. package/dist/operator/mama-memory-port.js.map +0 -1
  1397. package/dist/operator/operator-interfaces.d.ts +0 -136
  1398. package/dist/operator/operator-interfaces.d.ts.map +0 -1
  1399. package/dist/operator/operator-interfaces.js +0 -15
  1400. package/dist/operator/operator-interfaces.js.map +0 -1
  1401. package/dist/operator/operator-trigger-loop.d.ts +0 -203
  1402. package/dist/operator/operator-trigger-loop.d.ts.map +0 -1
  1403. package/dist/operator/operator-trigger-loop.js +0 -827
  1404. package/dist/operator/operator-trigger-loop.js.map +0 -1
  1405. package/dist/operator/owner-action-effects.d.ts +0 -112
  1406. package/dist/operator/owner-action-effects.d.ts.map +0 -1
  1407. package/dist/operator/owner-action-effects.js +0 -375
  1408. package/dist/operator/owner-action-effects.js.map +0 -1
  1409. package/dist/operator/owner-event-effects.d.ts +0 -65
  1410. package/dist/operator/owner-event-effects.d.ts.map +0 -1
  1411. package/dist/operator/owner-event-effects.js +0 -249
  1412. package/dist/operator/owner-event-effects.js.map +0 -1
  1413. package/dist/operator/owner-event-inbox.d.ts +0 -124
  1414. package/dist/operator/owner-event-inbox.d.ts.map +0 -1
  1415. package/dist/operator/owner-event-inbox.js +0 -440
  1416. package/dist/operator/owner-event-inbox.js.map +0 -1
  1417. package/dist/operator/owner-event-loop.d.ts +0 -99
  1418. package/dist/operator/owner-event-loop.d.ts.map +0 -1
  1419. package/dist/operator/owner-event-loop.js +0 -253
  1420. package/dist/operator/owner-event-loop.js.map +0 -1
  1421. package/dist/operator/owner-event-outcome.d.ts +0 -36
  1422. package/dist/operator/owner-event-outcome.d.ts.map +0 -1
  1423. package/dist/operator/owner-event-outcome.js +0 -174
  1424. package/dist/operator/owner-event-outcome.js.map +0 -1
  1425. package/dist/operator/owner-event-policy.d.ts +0 -40
  1426. package/dist/operator/owner-event-policy.d.ts.map +0 -1
  1427. package/dist/operator/owner-event-policy.js +0 -75
  1428. package/dist/operator/owner-event-policy.js.map +0 -1
  1429. package/dist/operator/owner-event-prompt.d.ts +0 -21
  1430. package/dist/operator/owner-event-prompt.d.ts.map +0 -1
  1431. package/dist/operator/owner-event-prompt.js +0 -69
  1432. package/dist/operator/owner-event-prompt.js.map +0 -1
  1433. package/dist/operator/owner-runtime-journal.d.ts +0 -21
  1434. package/dist/operator/owner-runtime-journal.d.ts.map +0 -1
  1435. package/dist/operator/owner-runtime-journal.js +0 -135
  1436. package/dist/operator/owner-runtime-journal.js.map +0 -1
  1437. package/dist/operator/owner-runtime.d.ts +0 -48
  1438. package/dist/operator/owner-runtime.d.ts.map +0 -1
  1439. package/dist/operator/owner-runtime.js +0 -99
  1440. package/dist/operator/owner-runtime.js.map +0 -1
  1441. package/dist/operator/pending-report-store.d.ts +0 -99
  1442. package/dist/operator/pending-report-store.d.ts.map +0 -1
  1443. package/dist/operator/pending-report-store.js +0 -554
  1444. package/dist/operator/pending-report-store.js.map +0 -1
  1445. package/dist/operator/procedure-activation.d.ts +0 -7
  1446. package/dist/operator/procedure-activation.d.ts.map +0 -1
  1447. package/dist/operator/procedure-activation.js +0 -132
  1448. package/dist/operator/procedure-activation.js.map +0 -1
  1449. package/dist/operator/procedure-projection.d.ts +0 -25
  1450. package/dist/operator/procedure-projection.d.ts.map +0 -1
  1451. package/dist/operator/procedure-projection.js +0 -80
  1452. package/dist/operator/procedure-projection.js.map +0 -1
  1453. package/dist/operator/procedure-runtime.d.ts +0 -45
  1454. package/dist/operator/procedure-runtime.d.ts.map +0 -1
  1455. package/dist/operator/procedure-runtime.js +0 -496
  1456. package/dist/operator/procedure-runtime.js.map +0 -1
  1457. package/dist/operator/procedure-store.d.ts +0 -97
  1458. package/dist/operator/procedure-store.d.ts.map +0 -1
  1459. package/dist/operator/procedure-store.js +0 -368
  1460. package/dist/operator/procedure-store.js.map +0 -1
  1461. package/dist/operator/provenance-lookup.d.ts +0 -18
  1462. package/dist/operator/provenance-lookup.d.ts.map +0 -1
  1463. package/dist/operator/provenance-lookup.js +0 -54
  1464. package/dist/operator/provenance-lookup.js.map +0 -1
  1465. package/dist/operator/repair-request.d.ts +0 -29
  1466. package/dist/operator/repair-request.d.ts.map +0 -1
  1467. package/dist/operator/repair-request.js +0 -115
  1468. package/dist/operator/repair-request.js.map +0 -1
  1469. package/dist/operator/report-carry-delivery.d.ts +0 -35
  1470. package/dist/operator/report-carry-delivery.d.ts.map +0 -1
  1471. package/dist/operator/report-carry-delivery.js +0 -55
  1472. package/dist/operator/report-carry-delivery.js.map +0 -1
  1473. package/dist/operator/report-carry.d.ts +0 -66
  1474. package/dist/operator/report-carry.d.ts.map +0 -1
  1475. package/dist/operator/report-carry.js +0 -352
  1476. package/dist/operator/report-carry.js.map +0 -1
  1477. package/dist/operator/report-delivery-coordinator.d.ts +0 -84
  1478. package/dist/operator/report-delivery-coordinator.d.ts.map +0 -1
  1479. package/dist/operator/report-delivery-coordinator.js +0 -146
  1480. package/dist/operator/report-delivery-coordinator.js.map +0 -1
  1481. package/dist/operator/report-run.d.ts +0 -52
  1482. package/dist/operator/report-run.d.ts.map +0 -1
  1483. package/dist/operator/report-run.js +0 -32
  1484. package/dist/operator/report-run.js.map +0 -1
  1485. package/dist/operator/report-scheduler.d.ts +0 -66
  1486. package/dist/operator/report-scheduler.d.ts.map +0 -1
  1487. package/dist/operator/report-scheduler.js +0 -135
  1488. package/dist/operator/report-scheduler.js.map +0 -1
  1489. package/dist/operator/runtime-config.d.ts +0 -10
  1490. package/dist/operator/runtime-config.d.ts.map +0 -1
  1491. package/dist/operator/runtime-config.js +0 -21
  1492. package/dist/operator/runtime-config.js.map +0 -1
  1493. package/dist/operator/situation-report.d.ts +0 -197
  1494. package/dist/operator/situation-report.d.ts.map +0 -1
  1495. package/dist/operator/situation-report.js +0 -462
  1496. package/dist/operator/situation-report.js.map +0 -1
  1497. package/dist/operator/subagent-stimulus.d.ts +0 -34
  1498. package/dist/operator/subagent-stimulus.d.ts.map +0 -1
  1499. package/dist/operator/subagent-stimulus.js +0 -145
  1500. package/dist/operator/subagent-stimulus.js.map +0 -1
  1501. package/dist/operator/task-ledger.d.ts +0 -879
  1502. package/dist/operator/task-ledger.d.ts.map +0 -1
  1503. package/dist/operator/task-ledger.js +0 -3601
  1504. package/dist/operator/task-ledger.js.map +0 -1
  1505. package/dist/operator/task-list-views.d.ts +0 -91
  1506. package/dist/operator/task-list-views.d.ts.map +0 -1
  1507. package/dist/operator/task-list-views.js +0 -532
  1508. package/dist/operator/task-list-views.js.map +0 -1
  1509. package/dist/operator/task-temporal.d.ts +0 -24
  1510. package/dist/operator/task-temporal.d.ts.map +0 -1
  1511. package/dist/operator/task-temporal.js +0 -123
  1512. package/dist/operator/task-temporal.js.map +0 -1
  1513. package/dist/operator/temporal-effect.d.ts +0 -65
  1514. package/dist/operator/temporal-effect.d.ts.map +0 -1
  1515. package/dist/operator/temporal-effect.js +0 -71
  1516. package/dist/operator/temporal-effect.js.map +0 -1
  1517. package/dist/operator/temporal-reconcile.d.ts +0 -49
  1518. package/dist/operator/temporal-reconcile.d.ts.map +0 -1
  1519. package/dist/operator/temporal-reconcile.js +0 -231
  1520. package/dist/operator/temporal-reconcile.js.map +0 -1
  1521. package/dist/operator/temporal-runtime.d.ts +0 -51
  1522. package/dist/operator/temporal-runtime.d.ts.map +0 -1
  1523. package/dist/operator/temporal-runtime.js +0 -104
  1524. package/dist/operator/temporal-runtime.js.map +0 -1
  1525. package/dist/operator/temporal-worker.d.ts +0 -18
  1526. package/dist/operator/temporal-worker.d.ts.map +0 -1
  1527. package/dist/operator/temporal-worker.js +0 -82
  1528. package/dist/operator/temporal-worker.js.map +0 -1
  1529. package/dist/operator/thread-brief-memory.d.ts +0 -29
  1530. package/dist/operator/thread-brief-memory.d.ts.map +0 -1
  1531. package/dist/operator/thread-brief-memory.js +0 -61
  1532. package/dist/operator/thread-brief-memory.js.map +0 -1
  1533. package/dist/operator/trigger-author.d.ts +0 -63
  1534. package/dist/operator/trigger-author.d.ts.map +0 -1
  1535. package/dist/operator/trigger-author.js +0 -384
  1536. package/dist/operator/trigger-author.js.map +0 -1
  1537. package/dist/operator/trigger-evolve.d.ts +0 -31
  1538. package/dist/operator/trigger-evolve.d.ts.map +0 -1
  1539. package/dist/operator/trigger-evolve.js +0 -51
  1540. package/dist/operator/trigger-evolve.js.map +0 -1
  1541. package/dist/operator/trigger-fire.d.ts +0 -29
  1542. package/dist/operator/trigger-fire.d.ts.map +0 -1
  1543. package/dist/operator/trigger-fire.js +0 -41
  1544. package/dist/operator/trigger-fire.js.map +0 -1
  1545. package/dist/operator/trigger-matcher.d.ts +0 -19
  1546. package/dist/operator/trigger-matcher.d.ts.map +0 -1
  1547. package/dist/operator/trigger-matcher.js +0 -65
  1548. package/dist/operator/trigger-matcher.js.map +0 -1
  1549. package/dist/operator/trigger-registry.d.ts +0 -58
  1550. package/dist/operator/trigger-registry.d.ts.map +0 -1
  1551. package/dist/operator/trigger-registry.js +0 -349
  1552. package/dist/operator/trigger-registry.js.map +0 -1
  1553. package/dist/operator/trigger-review.d.ts +0 -23
  1554. package/dist/operator/trigger-review.d.ts.map +0 -1
  1555. package/dist/operator/trigger-review.js +0 -193
  1556. package/dist/operator/trigger-review.js.map +0 -1
  1557. package/dist/operator/trigger-types.d.ts +0 -95
  1558. package/dist/operator/trigger-types.d.ts.map +0 -1
  1559. package/dist/operator/trigger-types.js +0 -14
  1560. package/dist/operator/trigger-types.js.map +0 -1
  1561. package/dist/operator/wiki-continuity.d.ts +0 -153
  1562. package/dist/operator/wiki-continuity.d.ts.map +0 -1
  1563. package/dist/operator/wiki-continuity.js +0 -221
  1564. package/dist/operator/wiki-continuity.js.map +0 -1
  1565. package/dist/operator/worker-run.d.ts +0 -109
  1566. package/dist/operator/worker-run.d.ts.map +0 -1
  1567. package/dist/operator/worker-run.js +0 -131
  1568. package/dist/operator/worker-run.js.map +0 -1
  1569. package/dist/operator/workorder-consumer.d.ts +0 -294
  1570. package/dist/operator/workorder-consumer.d.ts.map +0 -1
  1571. package/dist/operator/workorder-consumer.js +0 -1108
  1572. package/dist/operator/workorder-consumer.js.map +0 -1
  1573. package/dist/operator/workorder-hooks.d.ts +0 -162
  1574. package/dist/operator/workorder-hooks.d.ts.map +0 -1
  1575. package/dist/operator/workorder-hooks.js +0 -342
  1576. package/dist/operator/workorder-hooks.js.map +0 -1
  1577. package/dist/operator/workorder-publishers.d.ts +0 -117
  1578. package/dist/operator/workorder-publishers.d.ts.map +0 -1
  1579. package/dist/operator/workorder-publishers.js +0 -544
  1580. package/dist/operator/workorder-publishers.js.map +0 -1
  1581. package/dist/runners/cli-runner.d.ts +0 -59
  1582. package/dist/runners/cli-runner.d.ts.map +0 -1
  1583. package/dist/runners/cli-runner.js +0 -191
  1584. package/dist/runners/cli-runner.js.map +0 -1
  1585. package/dist/runners/index.d.ts +0 -11
  1586. package/dist/runners/index.d.ts.map +0 -1
  1587. package/dist/runners/index.js +0 -15
  1588. package/dist/runners/index.js.map +0 -1
  1589. package/dist/runners/types.d.ts +0 -81
  1590. package/dist/runners/types.d.ts.map +0 -1
  1591. package/dist/runners/types.js +0 -31
  1592. package/dist/runners/types.js.map +0 -1
  1593. package/dist/scheduler/cron-result-router.d.ts +0 -24
  1594. package/dist/scheduler/cron-result-router.d.ts.map +0 -1
  1595. package/dist/scheduler/cron-result-router.js +0 -63
  1596. package/dist/scheduler/cron-result-router.js.map +0 -1
  1597. package/dist/scheduler/cron-scheduler.d.ts +0 -115
  1598. package/dist/scheduler/cron-scheduler.d.ts.map +0 -1
  1599. package/dist/scheduler/cron-scheduler.js +0 -336
  1600. package/dist/scheduler/cron-scheduler.js.map +0 -1
  1601. package/dist/scheduler/cron-worker.d.ts +0 -39
  1602. package/dist/scheduler/cron-worker.d.ts.map +0 -1
  1603. package/dist/scheduler/cron-worker.js +0 -94
  1604. package/dist/scheduler/cron-worker.js.map +0 -1
  1605. package/dist/scheduler/heartbeat.d.ts +0 -64
  1606. package/dist/scheduler/heartbeat.d.ts.map +0 -1
  1607. package/dist/scheduler/heartbeat.js +0 -197
  1608. package/dist/scheduler/heartbeat.js.map +0 -1
  1609. package/dist/scheduler/index.d.ts +0 -26
  1610. package/dist/scheduler/index.d.ts.map +0 -1
  1611. package/dist/scheduler/index.js +0 -37
  1612. package/dist/scheduler/index.js.map +0 -1
  1613. package/dist/scheduler/job-lock.d.ts +0 -85
  1614. package/dist/scheduler/job-lock.d.ts.map +0 -1
  1615. package/dist/scheduler/job-lock.js +0 -137
  1616. package/dist/scheduler/job-lock.js.map +0 -1
  1617. package/dist/scheduler/recovery.d.ts +0 -78
  1618. package/dist/scheduler/recovery.d.ts.map +0 -1
  1619. package/dist/scheduler/recovery.js +0 -124
  1620. package/dist/scheduler/recovery.js.map +0 -1
  1621. package/dist/scheduler/schedule-store.d.ts +0 -112
  1622. package/dist/scheduler/schedule-store.d.ts.map +0 -1
  1623. package/dist/scheduler/schedule-store.js +0 -259
  1624. package/dist/scheduler/schedule-store.js.map +0 -1
  1625. package/dist/scheduler/token-keep-alive.d.ts +0 -49
  1626. package/dist/scheduler/token-keep-alive.d.ts.map +0 -1
  1627. package/dist/scheduler/token-keep-alive.js +0 -102
  1628. package/dist/scheduler/token-keep-alive.js.map +0 -1
  1629. package/dist/scheduler/types.d.ts +0 -98
  1630. package/dist/scheduler/types.d.ts.map +0 -1
  1631. package/dist/scheduler/types.js +0 -21
  1632. package/dist/scheduler/types.js.map +0 -1
  1633. package/dist/security/security-monitor.d.ts +0 -56
  1634. package/dist/security/security-monitor.d.ts.map +0 -1
  1635. package/dist/security/security-monitor.js +0 -779
  1636. package/dist/security/security-monitor.js.map +0 -1
  1637. package/dist/security/trusted-proxy.d.ts +0 -9
  1638. package/dist/security/trusted-proxy.d.ts.map +0 -1
  1639. package/dist/security/trusted-proxy.js +0 -36
  1640. package/dist/security/trusted-proxy.js.map +0 -1
  1641. package/dist/skills/index.d.ts +0 -10
  1642. package/dist/skills/index.d.ts.map +0 -1
  1643. package/dist/skills/index.js +0 -26
  1644. package/dist/skills/index.js.map +0 -1
  1645. package/dist/skills/skill-executor.d.ts +0 -48
  1646. package/dist/skills/skill-executor.d.ts.map +0 -1
  1647. package/dist/skills/skill-executor.js +0 -483
  1648. package/dist/skills/skill-executor.js.map +0 -1
  1649. package/dist/skills/skill-loader.d.ts +0 -40
  1650. package/dist/skills/skill-loader.d.ts.map +0 -1
  1651. package/dist/skills/skill-loader.js +0 -233
  1652. package/dist/skills/skill-loader.js.map +0 -1
  1653. package/dist/skills/skill-matcher.d.ts +0 -33
  1654. package/dist/skills/skill-matcher.d.ts.map +0 -1
  1655. package/dist/skills/skill-matcher.js +0 -190
  1656. package/dist/skills/skill-matcher.js.map +0 -1
  1657. package/dist/skills/skill-registry.d.ts +0 -117
  1658. package/dist/skills/skill-registry.d.ts.map +0 -1
  1659. package/dist/skills/skill-registry.js +0 -627
  1660. package/dist/skills/skill-registry.js.map +0 -1
  1661. package/dist/skills/types.d.ts +0 -131
  1662. package/dist/skills/types.d.ts.map +0 -1
  1663. package/dist/skills/types.js +0 -12
  1664. package/dist/skills/types.js.map +0 -1
  1665. package/dist/utils/log-sanitizer.d.ts +0 -79
  1666. package/dist/utils/log-sanitizer.d.ts.map +0 -1
  1667. package/dist/utils/log-sanitizer.js +0 -215
  1668. package/dist/utils/log-sanitizer.js.map +0 -1
  1669. package/dist/validation/session-service.d.ts +0 -72
  1670. package/dist/validation/session-service.d.ts.map +0 -1
  1671. package/dist/validation/session-service.js +0 -298
  1672. package/dist/validation/session-service.js.map +0 -1
  1673. package/dist/validation/store.d.ts +0 -25
  1674. package/dist/validation/store.d.ts.map +0 -1
  1675. package/dist/validation/store.js +0 -200
  1676. package/dist/validation/store.js.map +0 -1
  1677. package/dist/validation/types.d.ts +0 -119
  1678. package/dist/validation/types.d.ts.map +0 -1
  1679. package/dist/validation/types.js +0 -57
  1680. package/dist/validation/types.js.map +0 -1
  1681. package/dist/wiki/wiki-turn-contract.d.ts +0 -19
  1682. package/dist/wiki/wiki-turn-contract.d.ts.map +0 -1
  1683. package/dist/wiki/wiki-turn-contract.js +0 -60
  1684. package/dist/wiki/wiki-turn-contract.js.map +0 -1
  1685. package/public/viewer/js/utils/ui-commands.js +0 -88
  1686. package/public/viewer/src/utils/ui-commands.ts +0 -114
  1687. package/scripts/attachment/extract-office-text.js +0 -179
  1688. package/scripts/attachment/extract-pdf-text.swift +0 -36
  1689. package/scripts/backfill-channel-keys.ts +0 -509
  1690. package/scripts/crack-failure-digests.ts +0 -55
  1691. package/scripts/generate-gateway-tools.ts +0 -131
  1692. package/scripts/image/fb-overlay.py +0 -128
  1693. package/scripts/image/ocr-image.py +0 -38
  1694. package/scripts/postinstall.js +0 -161
  1695. package/scripts/setup-ocr.js +0 -120
  1696. package/templates/AGENTS.claude.md +0 -23
  1697. package/templates/AGENTS.codex.md +0 -11
  1698. package/templates/bmad/LICENSE +0 -28
  1699. package/templates/bmad/architecture.md +0 -343
  1700. package/templates/bmad/bmm-workflow-status.template.yaml +0 -66
  1701. package/templates/bmad/prd.md +0 -198
  1702. package/templates/bmad/product-brief.md +0 -149
  1703. package/templates/bmad/sprint-status.template.yaml +0 -35
  1704. package/templates/bmad/tech-spec.md +0 -151
  1705. package/templates/entity-audit-fixtures/cross-language-aliases.json +0 -28
  1706. package/templates/entity-audit-fixtures/gold-canonical-identities.json +0 -46
  1707. package/templates/skills/danggeun-monitor.md +0 -88
  1708. package/templates/skills/document-analyze.md +0 -63
  1709. package/templates/skills/frontend-design.md +0 -71
  1710. package/templates/skills/image-translate.md +0 -62
  1711. package/templates/skills/multi-agent-collab.md +0 -145
  1712. package/templates/skills/scheduling.md +0 -107
  1713. package/templates/workspace/skill-forge/DESIGN.md +0 -115
  1714. package/templates/workspace/skill-forge/agents/architect.ts +0 -295
  1715. package/templates/workspace/skill-forge/agents/developer.ts +0 -364
  1716. package/templates/workspace/skill-forge/agents/qa.ts +0 -313
  1717. package/templates/workspace/skill-forge/claude-api.ts +0 -353
  1718. package/templates/workspace/skill-forge/discord-ui.ts +0 -580
  1719. package/templates/workspace/skill-forge/error-handler.ts +0 -354
  1720. package/templates/workspace/skill-forge/mama-integration.ts +0 -357
  1721. package/templates/workspace/skill-forge/orchestrator.ts +0 -495
  1722. package/templates/workspace/skill-forge/output/generated-skills/skills/hello-world/README.md +0 -24
  1723. package/templates/workspace/skill-forge/output/generated-skills/skills/hello-world/index.ts +0 -79
  1724. package/templates/workspace/skill-forge/output/generated-skills/skills/hello-world/types.ts +0 -17
  1725. package/templates/workspace/skill-forge/package.json +0 -21
  1726. package/templates/workspace/skill-forge/state/session.json +0 -132
  1727. package/templates/workspace/skill-forge/test-e2e.ts +0 -139
  1728. package/templates/workspace/skill-forge/tsconfig.json +0 -20
  1729. package/templates/workspace/skill-forge/types.ts +0 -159
@@ -1,2842 +0,0 @@
1
- "use strict";
2
- /**
3
- * Agent Loop Engine for MAMA Standalone
4
- *
5
- * Main orchestrator that:
6
- * - Maintains conversation history
7
- * - Calls Claude API via ClaudeClient
8
- * - Parses tool_use blocks from responses
9
- * - Executes tools via MCPExecutor
10
- * - Sends tool_result back to Claude
11
- * - Loops until stop_reason is "end_turn" or max turns reached
12
- */
13
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
- if (k2 === undefined) k2 = k;
15
- var desc = Object.getOwnPropertyDescriptor(m, k);
16
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
- desc = { enumerable: true, get: function() { return m[k]; } };
18
- }
19
- Object.defineProperty(o, k2, desc);
20
- }) : (function(o, m, k, k2) {
21
- if (k2 === undefined) k2 = k;
22
- o[k2] = m[k];
23
- }));
24
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
- Object.defineProperty(o, "default", { enumerable: true, value: v });
26
- }) : function(o, v) {
27
- o["default"] = v;
28
- });
29
- var __importStar = (this && this.__importStar) || (function () {
30
- var ownKeys = function(o) {
31
- ownKeys = Object.getOwnPropertyNames || function (o) {
32
- var ar = [];
33
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
34
- return ar;
35
- };
36
- return ownKeys(o);
37
- };
38
- return function (mod) {
39
- if (mod && mod.__esModule) return mod;
40
- var result = {};
41
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
42
- __setModuleDefault(result, mod);
43
- return result;
44
- };
45
- })();
46
- Object.defineProperty(exports, "__esModule", { value: true });
47
- exports.AgentLoop = exports.SOURCE_GLOBAL_LANES = void 0;
48
- exports.sanitizeLegacyCodexAgentsMd = sanitizeLegacyCodexAgentsMd;
49
- exports.loadBackendAgentsMd = loadBackendAgentsMd;
50
- exports.loadComposedSystemPrompt = loadComposedSystemPrompt;
51
- exports.getGatewayToolsPrompt = getGatewayToolsPrompt;
52
- exports.buildAgentToolExecutionContext = buildAgentToolExecutionContext;
53
- const fs_1 = require("fs");
54
- const native_effect_observer_js_1 = require("./native-effect-observer.js");
55
- const prompt_size_monitor_js_1 = require("./prompt-size-monitor.js");
56
- const skill_loader_js_1 = require("./skill-loader.js");
57
- const persistent_cli_adapter_js_1 = require("./persistent-cli-adapter.js");
58
- const cline_cli_adapter_js_1 = require("./cline-cli-adapter.js");
59
- const cline_native_tool_policy_js_1 = require("./cline-native-tool-policy.js");
60
- const runtime_process_js_1 = require("../multi-agent/runtime-process.js");
61
- const model_runner_js_1 = require("./model-runner.js");
62
- const gateway_tool_executor_js_1 = require("./gateway-tool-executor.js");
63
- const run_guard_js_1 = require("../envelope/run-guard.js");
64
- const tool_registry_js_1 = require("./tool-registry.js");
65
- const gateway_tool_catalog_js_1 = require("./gateway-tool-catalog.js");
66
- const private_connector_policy_js_1 = require("../connectors/private-connector-policy.js");
67
- const index_js_1 = require("./code-act/index.js");
68
- const index_js_2 = require("../concurrency/index.js");
69
- const session_pool_js_1 = require("./session-pool.js");
70
- const principal_js_1 = require("../gateways/principal.js");
71
- const owner_runtime_js_1 = require("../operator/owner-runtime.js");
72
- const owner_event_policy_js_1 = require("../operator/owner-event-policy.js");
73
- const os_1 = require("os");
74
- const path_1 = require("path");
75
- const crypto_1 = require("crypto");
76
- const types_js_1 = require("./types.js");
77
- const context_prompt_builder_js_1 = require("./context-prompt-builder.js");
78
- const telegram_format_js_1 = require("../gateways/telegram-format.js");
79
- const temporal_code_act_breaker_js_1 = require("./temporal-code-act-breaker.js");
80
- const post_tool_handler_js_1 = require("./post-tool-handler.js");
81
- const stop_continuation_handler_js_1 = require("./stop-continuation-handler.js");
82
- const pre_compact_handler_js_1 = require("./pre-compact-handler.js");
83
- const debugLogger = __importStar(require("@jungjaehoon/mama-core/debug-logger"));
84
- const { DebugLogger } = debugLogger;
85
- const logger = new DebugLogger('AgentLoop');
86
- const MODEL_RUNNER_AGENT_ERROR_CODES = {
87
- timeout: 'NETWORK_ERROR',
88
- crash: 'CLI_ERROR',
89
- context_overflow: 'MAX_TOKENS',
90
- auth_failure: 'AUTH_ERROR',
91
- rate_limit: 'RATE_LIMIT',
92
- unknown: 'CLI_ERROR',
93
- };
94
- /**
95
- * Default configuration
96
- */
97
- const DEFAULT_MAX_TURNS = 20; // Increased from 10 to allow more complex tool chains
98
- /**
99
- * Default tools configuration - all tools via Gateway (self-contained)
100
- */
101
- const DEFAULT_TOOLS_CONFIG = {
102
- gateway: ['*'],
103
- mcp: [],
104
- mcp_config: '~/.mama/mama-mcp-config.json',
105
- };
106
- const DEFAULT_PRIVATE_CONNECTOR_POLICY = (0, private_connector_policy_js_1.resolvePrivateConnectorPolicy)({
107
- ok: true,
108
- config: {},
109
- enabledNames: [],
110
- });
111
- // Sources without an entry stay on their per-session lane. Every owner stimulus
112
- // uses owner:runtime, so its session lane serializes chat, events, reports,
113
- // maintenance, and heartbeat before any global-lane choice is considered.
114
- exports.SOURCE_GLOBAL_LANES = {
115
- viewer: 'viewer',
116
- system: 'system',
117
- // Non-owner trigger authoring/review still uses the operator global lane.
118
- operator: 'operator',
119
- };
120
- function applyTemporalCodeActBreakerState(runScope, state) {
121
- runScope.codeActCalls = state.codeActCalls;
122
- runScope.lastDeterministicFingerprint = state.lastDeterministicFingerprint;
123
- runScope.consecutiveDeterministicFailures = state.consecutiveDeterministicFailures;
124
- }
125
- function temporalCodeActTerminalResult(decision) {
126
- return {
127
- success: false,
128
- code: 'TOOL_CONTRACT_REPEAT',
129
- retryable: false,
130
- abort: true,
131
- failureClass: 'deterministic_contract',
132
- ...(decision.fingerprintPrefix
133
- ? { deterministicFingerprintPrefix: decision.fingerprintPrefix }
134
- : {}),
135
- error: decision.reason === 'outer_call_limit'
136
- ? 'Temporal outer Code-Act call limit exceeded before host execution'
137
- : 'Temporal deterministic host-tool contract failure repeated three times',
138
- };
139
- }
140
- function historyToolResult(result) {
141
- const { abort: _abort, terminalCode: _terminalCode, ...block } = result;
142
- return block;
143
- }
144
- /**
145
- * Load CLAUDE.md system prompt
146
- * Tries multiple paths: project root, ~/.mama, /etc/mama
147
- */
148
- function loadSystemPrompt(verbose = false) {
149
- const searchPaths = [
150
- // User home - MAMA standalone config (priority)
151
- (0, path_1.join)((0, os_1.homedir)(), '.mama/CLAUDE.md'),
152
- // System config
153
- '/etc/mama/CLAUDE.md',
154
- // Project root (monorepo) - fallback only for development
155
- (0, path_1.join)(__dirname, '../../../../CLAUDE.md'),
156
- ];
157
- for (const path of searchPaths) {
158
- if ((0, fs_1.existsSync)(path)) {
159
- if (verbose)
160
- console.log(`[AgentLoop] Loaded system prompt from: ${path}`);
161
- return (0, fs_1.readFileSync)(path, 'utf-8');
162
- }
163
- }
164
- console.warn('[AgentLoop] CLAUDE.md not found, using default identity');
165
- return "You are Claude Code, Anthropic's official CLI for Claude.";
166
- }
167
- /**
168
- * Load backend-specific AGENTS.md from ~/.mama/
169
- * Maps backend to file: 'claude' → AGENTS.claude.md, 'codex' → AGENTS.codex.md
170
- */
171
- function sanitizeLegacyCodexAgentsMd(content) {
172
- const nativeGuidance = [
173
- 'MAMA exposes the tools permitted for this run as native host tools. Call those tools directly through the model tool interface.',
174
- '',
175
- 'Do not print Markdown tool blocks or JavaScript as a substitute for a tool call. The available native tool set is injected for each run and already reflects the current role and channel permissions.',
176
- ].join('\n');
177
- const knownLegacySections = [
178
- {
179
- heading: '## Tool protocol',
180
- nextHeading: '## Behavioural traits to know about yourself',
181
- signature: 'Gateway tools via `tool_call` JSON blocks:',
182
- },
183
- {
184
- heading: '## Tool Usage',
185
- nextHeading: '### Skills',
186
- signature: 'Use gateway tools via `tool_call` JSON blocks.',
187
- },
188
- ];
189
- const knownLegacyLines = [
190
- '### How to Call Tools',
191
- '### Available Gateway Tools',
192
- '### Important',
193
- '- **mama_search**(query?, type?, limit?) — Search decisions in MAMA memory',
194
- '- **mama_save**(type, topic?, decision?, reasoning?) — Save decision or checkpoint',
195
- '- **mama_update**(id, outcome, reason?) — Update decision outcome',
196
- '- **mama_load_checkpoint**() — Load last checkpoint',
197
- '- **discord_send**(channel_id, message?) — Send message to Discord channel',
198
- '- **slack_send**(channel_id, message?) — Send message to Slack channel',
199
- '- **Read**(path) — Read file',
200
- '- **Write**(path, content) — Write file',
201
- '- **Bash**(command) — Execute shell command',
202
- '- Do NOT use `exec_command` or `apply_patch` — use gateway tools instead',
203
- '- Tool calls are executed automatically. No need to use curl or Bash for these.',
204
- "Do NOT use `exec_command` or `apply_patch` — those are Codex defaults but bypass MAMA's gateway. Tool calls are executed automatically; do not wrap in `curl` or `Bash`.",
205
- '## Available gateway tools',
206
- '`mama_search`, `mama_save`, `mama_recall`, `mama_update`, `mama_load_checkpoint`, `discord_send`, `slack_send`, `Read`, `Write`, `Bash`. Check the skill `SKILL.md` for skill-provided extras.',
207
- ];
208
- const removeExactLine = (section, line) => section
209
- .split(/(\r?\n)/)
210
- .filter((part) => part !== line)
211
- .join('');
212
- let sanitized = content;
213
- for (const legacy of knownLegacySections) {
214
- const start = sanitized.indexOf(legacy.heading);
215
- if (start === -1) {
216
- continue;
217
- }
218
- const end = sanitized.indexOf(legacy.nextHeading, start + legacy.heading.length);
219
- if (end === -1) {
220
- continue;
221
- }
222
- const section = sanitized.slice(start, end);
223
- if (!section.includes(legacy.signature) || !section.includes('```tool_call')) {
224
- continue;
225
- }
226
- let transformed = section.replace(legacy.signature, nativeGuidance);
227
- const toolCallExample = [
228
- '```tool_call',
229
- '{"name": "tool_name", "input": {"param1": "value1"}}',
230
- '```',
231
- ].join('\n');
232
- transformed = transformed
233
- .replaceAll(toolCallExample, '')
234
- .replaceAll(toolCallExample.replaceAll('\n', '\r\n'), '');
235
- for (const line of knownLegacyLines) {
236
- transformed = removeExactLine(transformed, line);
237
- }
238
- sanitized = `${sanitized.slice(0, start)}${transformed}${sanitized.slice(end)}`;
239
- }
240
- return sanitized;
241
- }
242
- function loadBackendAgentsMd(backend, verbose = false) {
243
- if (!backend) {
244
- return '';
245
- }
246
- const keyMap = {
247
- claude: 'claude',
248
- codex: 'codex',
249
- };
250
- const key = keyMap[backend];
251
- if (!key) {
252
- return '';
253
- }
254
- const filePath = (0, path_1.join)((0, os_1.homedir)(), '.mama', `AGENTS.${key}.md`);
255
- if ((0, fs_1.existsSync)(filePath)) {
256
- if (verbose) {
257
- console.log(`[AgentLoop] Loaded backend AGENTS.md: AGENTS.${key}.md`);
258
- }
259
- const content = (0, fs_1.readFileSync)(filePath, 'utf-8');
260
- return key === 'codex' ? sanitizeLegacyCodexAgentsMd(content) : content;
261
- }
262
- if (verbose) {
263
- console.log(`[AgentLoop] Backend AGENTS.md not found: AGENTS.${key}.md`);
264
- }
265
- return '';
266
- }
267
- function loadComposedSystemPrompt(verbose = false, context) {
268
- const layers = [];
269
- // Load skill catalog (on-demand mode — full content injected per-message by PromptEnhancer)
270
- const skillCatalog = (0, skill_loader_js_1.filterSkillCatalogForContext)((0, skill_loader_js_1.loadInstalledSkills)(verbose, { includePaths: context?.roleName === 'owner_console' }), context);
271
- if (skillCatalog.length > 0) {
272
- const skillDirective = [
273
- '# Installed Skills',
274
- '',
275
- 'Choose relevant skills from their descriptions and the current task; keywords are optional hints.',
276
- 'Read the selected instructions (source path when listed) before applying them. Learned procedures use procedure_list/read.',
277
- '',
278
- ...skillCatalog,
279
- ].join('\n');
280
- layers.push(skillDirective);
281
- if (verbose)
282
- console.log(`[AgentLoop] Skill catalog: ${skillCatalog.length} skills`);
283
- }
284
- // Add minimal context if AgentContext is provided (role awareness)
285
- if (context) {
286
- layers.push((0, context_prompt_builder_js_1.buildMinimalContext)(context));
287
- }
288
- // Load CLAUDE.md (base instructions)
289
- const claudeMd = loadSystemPrompt(verbose);
290
- layers.push(claudeMd);
291
- const result = layers.join('\n\n---\n\n');
292
- // Debug: log each layer's size to find what's consuming context
293
- logger.debug(`[SystemPrompt] Total: ${result.length} chars, layers: ${layers.map((l, i) => `L${i}=${l.length}`).join(', ')}`);
294
- return result;
295
- }
296
- /**
297
- * Load Gateway Tools prompt from MD file
298
- * These tools are executed by GatewayToolExecutor, NOT MCP
299
- */
300
- function getGatewayToolsPrompt(disallowed) {
301
- return (0, gateway_tool_catalog_js_1.buildGatewayToolCatalog)({
302
- surface: 'multi-agent-generic',
303
- allowedTools: ['*'],
304
- blockedTools: disallowed,
305
- privateConnectorPolicy: DEFAULT_PRIVATE_CONNECTOR_POLICY,
306
- }).prompt;
307
- }
308
- function getRunGatewayToolsPrompt(context, disallowed) {
309
- return (0, gateway_tool_catalog_js_1.buildGatewayToolCatalog)({
310
- surface: context
311
- ? (0, private_connector_policy_js_1.resolvePrivatePrincipalSurface)({ agentContext: context })
312
- : 'multi-agent-generic',
313
- allowedTools: context?.role.allowedTools ?? ['*'],
314
- blockedTools: [...(context?.role.blockedTools ?? []), ...(disallowed ?? [])],
315
- privateConnectorPolicy: DEFAULT_PRIVATE_CONNECTOR_POLICY,
316
- }).prompt;
317
- }
318
- /** Korean/English phrasings that assert a correction, save, update or send has happened. */
319
- const COMPLETION_CLAIM_PATTERN = /(?:반영|저장|기록|등록|갱신|적용|수정|전송|발송)\s*(?:완료|했습니다|됐습니다|되었습니다|하였습니다)|\b(?:saved|updated|applied|recorded|sent)\b/i;
320
- const CANONICAL_CODE_ACT_HEADING = '## Code-Act: Gateway Tool Execution via Sandbox';
321
- const CODE_ACT_MCP_COMPAT_NAME = 'mcp__code-act__code_act';
322
- const GENERATED_CODE_ACT_START = '<!-- MAMA_GENERATED_CODE_ACT_START -->';
323
- const GENERATED_CODE_ACT_END = '<!-- MAMA_GENERATED_CODE_ACT_END -->';
324
- const GENERATED_GATEWAY_TOOLS_START = '<!-- MAMA_GENERATED_GATEWAY_TOOLS_START -->';
325
- const GENERATED_GATEWAY_TOOLS_END = '<!-- MAMA_GENERATED_GATEWAY_TOOLS_END -->';
326
- function removePromptSection(systemPrompt, sectionStart, sectionEnd) {
327
- const prefix = systemPrompt.slice(0, sectionStart);
328
- const separator = prefix.match(/\r?\n\r?\n---[ \t]*\r?\n\r?\n$/);
329
- const removalStart = separator?.index ?? sectionStart;
330
- return `${systemPrompt.slice(0, removalStart)}${systemPrompt.slice(sectionEnd)}`;
331
- }
332
- function stripMarkedPromptSection(systemPrompt, startMarker, endMarker) {
333
- let stripped = systemPrompt;
334
- let sectionStart = stripped.lastIndexOf(startMarker);
335
- while (sectionStart >= 0) {
336
- const markerEnd = stripped.indexOf(endMarker, sectionStart + startMarker.length);
337
- if (markerEnd < 0) {
338
- return stripped;
339
- }
340
- stripped = removePromptSection(stripped, sectionStart, markerEnd + endMarker.length);
341
- sectionStart = stripped.lastIndexOf(startMarker);
342
- }
343
- return stripped;
344
- }
345
- function wrapGeneratedPromptSection(kind, content) {
346
- const [start, end] = kind === 'codeAct'
347
- ? [GENERATED_CODE_ACT_START, GENERATED_CODE_ACT_END]
348
- : [GENERATED_GATEWAY_TOOLS_START, GENERATED_GATEWAY_TOOLS_END];
349
- return `${start}\n${content}\n${end}`;
350
- }
351
- function stripGenericGatewayToolsCatalog(systemPrompt) {
352
- const withoutMarked = stripMarkedPromptSection(systemPrompt, GENERATED_GATEWAY_TOOLS_START, GENERATED_GATEWAY_TOOLS_END);
353
- const generatedCatalog = getGatewayToolsPrompt();
354
- const catalogStart = withoutMarked.lastIndexOf(generatedCatalog);
355
- if (catalogStart < 0) {
356
- return withoutMarked;
357
- }
358
- const catalogEnd = catalogStart + generatedCatalog.length;
359
- const startsAtLayerBoundary = catalogStart === 0 ||
360
- /\r?\n\r?\n---[ \t]*\r?\n\r?\n$/.test(withoutMarked.slice(0, catalogStart));
361
- const endsAtLayerBoundary = catalogEnd === withoutMarked.length ||
362
- /^\r?\n\r?\n---[ \t]*\r?\n\r?\n/.test(withoutMarked.slice(catalogEnd));
363
- if (!startsAtLayerBoundary || !endsAtLayerBoundary) {
364
- return withoutMarked;
365
- }
366
- return removePromptSection(withoutMarked, catalogStart, catalogEnd);
367
- }
368
- function stripTrailingCanonicalCodeActSection(systemPrompt) {
369
- const withoutMarked = stripMarkedPromptSection(systemPrompt, GENERATED_CODE_ACT_START, GENERATED_CODE_ACT_END);
370
- const sectionStart = withoutMarked.lastIndexOf(CANONICAL_CODE_ACT_HEADING);
371
- if (sectionStart < 0) {
372
- return withoutMarked;
373
- }
374
- const section = withoutMarked.slice(sectionStart);
375
- const typeFenceStart = section.indexOf('```typescript');
376
- if (typeFenceStart >= 0) {
377
- const typeFenceEnd = section.indexOf('```', typeFenceStart + '```typescript'.length);
378
- if (typeFenceEnd >= 0) {
379
- return removePromptSection(withoutMarked, sectionStart, sectionStart + typeFenceEnd + 3);
380
- }
381
- }
382
- const boundedSeparator = section.match(/\r?\n\r?\n---[ \t]*\r?\n\r?\n/);
383
- const sectionEnd = boundedSeparator?.index ?? section.length;
384
- return removePromptSection(withoutMarked, sectionStart, sectionStart + sectionEnd);
385
- }
386
- function stripDisabledCodeActGuidance(systemPrompt) {
387
- return stripTrailingCanonicalCodeActSection(systemPrompt).replace(/^- \*\*(?:code_act|mcp__code-act__code_act)\*\*.*$/gm, '');
388
- }
389
- function combineCodeActSessionPolicyFingerprint(callerFingerprint, policy) {
390
- return JSON.stringify({
391
- version: 1,
392
- callerFingerprint: callerFingerprint ?? null,
393
- codeActPolicy: policy.fingerprintPayload,
394
- });
395
- }
396
- function ownerRuntimeSessionPolicyFingerprint(role, model, supportsNativeSubagents, backend) {
397
- return JSON.stringify({
398
- version: 1,
399
- subject: owner_runtime_js_1.OWNER_RUNTIME_SESSION_KEY,
400
- // The fingerprint names the policy the session actually carries: a runner without
401
- // native subagents is never told to delegate, so it must not be pinned to that text.
402
- subagentPolicy: supportsNativeSubagents ? (0, owner_runtime_js_1.ownerSubagentInstructions)(backend) : null,
403
- telegramFormatPolicy: telegram_format_js_1.TELEGRAM_FORMAT_GUIDE,
404
- model: model ?? null,
405
- allowedTools: [...(role?.allowedTools ?? [])].sort(),
406
- blockedTools: [...(role?.blockedTools ?? [])].sort(),
407
- allowedPaths: [...(role?.allowedPaths ?? [])].sort(),
408
- systemControl: role?.systemControl === true,
409
- sensitiveAccess: role?.sensitiveAccess === true,
410
- });
411
- }
412
- function roleAllowsOuterCodeAct(role, disallowedTools) {
413
- if (!role) {
414
- return false;
415
- }
416
- return tool_registry_js_1.ToolRegistry.getHostToolDefinitions({
417
- allowedTools: role.allowedTools,
418
- blockedTools: role.blockedTools,
419
- disallowedTools: disallowedTools ? [...disallowedTools] : undefined,
420
- }).some((tool) => tool.name === index_js_1.CODE_ACT_MARKER);
421
- }
422
- function buildAgentToolExecutionContext(options) {
423
- if (!options ||
424
- (options.agentContext === undefined &&
425
- options.source === undefined &&
426
- options.channelId === undefined &&
427
- options.envelope === undefined &&
428
- options.sourceTurnId === undefined &&
429
- options.sourceMessageRef === undefined &&
430
- options.modelRunId === undefined &&
431
- options.workorderAttemptId === undefined &&
432
- options.temporalWorkContext === undefined &&
433
- options.wikiTaskRange === undefined &&
434
- options.ownerEventEffects === undefined)) {
435
- return null;
436
- }
437
- const agentContext = options.agentContext;
438
- const context = {
439
- agentContext,
440
- agentId: options.actorId ??
441
- (agentContext
442
- ? agentContext.source === 'viewer'
443
- ? 'os-agent'
444
- : agentContext.roleName
445
- : undefined),
446
- source: options.source,
447
- channelId: options.channelId,
448
- envelope: options.envelope,
449
- executionSurface: 'model_tool',
450
- channelGrantSnapshot: options.memberEffectiveScope?.channelGrant,
451
- memberScopeRequired: options.memberScopeRequired,
452
- };
453
- if (options.sourceTurnId !== undefined) {
454
- context.sourceTurnId = options.sourceTurnId;
455
- }
456
- if (options.sourceMessageRef !== undefined) {
457
- context.sourceMessageRef = options.sourceMessageRef;
458
- }
459
- if (options.modelRunId !== undefined) {
460
- context.modelRunId = options.modelRunId;
461
- }
462
- if (options.workorderAttemptId !== undefined) {
463
- context.workorderAttemptId = options.workorderAttemptId;
464
- }
465
- if (options.causeEventIds !== undefined) {
466
- context.causeEventIds = options.causeEventIds;
467
- }
468
- if (options.ownerEventEffects !== undefined) {
469
- context.ownerEventEffects = options.ownerEventEffects;
470
- }
471
- if (options.temporalWorkContext !== undefined) {
472
- context.temporalWorkContext = options.temporalWorkContext;
473
- }
474
- if (options.wikiTaskRange !== undefined) {
475
- context.wikiTaskRange = options.wikiTaskRange;
476
- }
477
- return context;
478
- }
479
- function withExecutionSurface(executionContext, executionSurface) {
480
- if (!executionContext) {
481
- return null;
482
- }
483
- if (executionContext.executionSurface === executionSurface) {
484
- return executionContext;
485
- }
486
- return {
487
- ...executionContext,
488
- executionSurface,
489
- };
490
- }
491
- /** Normal coding tasks often need 10+ consecutive Bash calls; 5 was too low. */
492
- const MAX_CONSECUTIVE_SAME_HOST_TOOL = 15;
493
- /**
494
- * The parent run's shape, kept only so a child announced mid-run (or after it) can be
495
- * given an authority of its OWN: its own model run under the parent's, its own envelope,
496
- * its own bridge with its own counters.
497
- */
498
- /**
499
- * The options a native child of this run inherits. Everything is carried EXCEPT the role,
500
- * which is projected onto the unattended surface: the owner's 1:1 chat turn holds the
501
- * gateway shell and file writer, and a child answers to no one inside the turn.
502
- */
503
- function withUnattendedSubagentRole(options) {
504
- const agentContext = options?.agentContext;
505
- if (!agentContext) {
506
- return { ...options };
507
- }
508
- const role = (0, owner_event_policy_js_1.projectUnattendedRole)(agentContext.role);
509
- return {
510
- ...options,
511
- agentContext: {
512
- ...agentContext,
513
- role,
514
- capabilities: [...role.allowedTools],
515
- limitations: (role.blockedTools ?? []).map((tool) => `Cannot use ${tool}`),
516
- },
517
- };
518
- }
519
- class AgentLoop {
520
- /**
521
- * Construction-wide child-runtime tool capability.
522
- *
523
- * Claude's persistent CLI cannot narrow native or MCP tools per turn, so a
524
- * public lane may run only when both surfaces were disabled at construction.
525
- * Codex native multi-agent and Claude built-ins are construction-wide, so
526
- * public lanes must use another tool-free runtime. Cline can gate spawn per role.
527
- */
528
- childRuntimeToolCapable;
529
- probesDurableSession;
530
- ownerRecoveryJournalEnabled;
531
- agent;
532
- /**
533
- * Whether the ACTIVE runner can spawn a native subagent the host can observe.
534
- *
535
- * Read by the owner prompt path and forwarded to the scheduled work-order contract, so
536
- * neither has to string-match a backend name. A mocked runner that predates this field
537
- * is treated as incapable rather than silently promised delegation.
538
- */
539
- get supportsNativeSubagents() {
540
- return this.agent.supportsNativeSubagents === true;
541
- }
542
- /**
543
- * What a native child started by a run on this session needs to be given its own
544
- * authority. Keyed by session key, overwritten by each run on that session, and dropped
545
- * once the run finished and no child of it is still registered.
546
- */
547
- subagentRunContexts = new Map();
548
- persistentCLI = null;
549
- mcpExecutor;
550
- maxTurns;
551
- model;
552
- onTurn;
553
- onToolUse;
554
- runTokenBudget;
555
- onBudgetStop;
556
- onTokenUsage;
557
- onMetric;
558
- laneManager;
559
- useLanes;
560
- sessionKey;
561
- sessionPool;
562
- toolsConfig;
563
- isGatewayMode;
564
- useCodeAct;
565
- backend;
566
- defaultSystemPrompt;
567
- postToolHandler;
568
- stopContinuationHandler;
569
- preCompactHandler;
570
- // Per-run state (stream callbacks, tier) lives in a RunScope threaded through
571
- // runWithContentInternal -> executeTools, NEVER on the
572
- // instance: concurrent runs on separate global lanes (operator report/worker
573
- // overlapping owner chat) would steal each other's callbacks and leak tiers
574
- // if these were instance fields.
575
- disallowedTools;
576
- clineNativeAllowedTools;
577
- clineNativeDisallowedTools;
578
- clineNativePolicyConfigured;
579
- clineAllowSpawnAgent;
580
- clineAllowAgentTeams;
581
- ownerRuntimeJournal;
582
- createNativeEffectObserver;
583
- constructor(_oauthManager, options = {}, _clientOptions, executorOptions) {
584
- // Initialize tools config (hybrid Gateway/MCP routing)
585
- this.toolsConfig = {
586
- ...DEFAULT_TOOLS_CONFIG,
587
- ...options.toolsConfig,
588
- };
589
- const mcpConfigPath = this.toolsConfig.mcp_config?.replace('~', (0, os_1.homedir)()) ||
590
- (0, path_1.join)((0, os_1.homedir)(), '.mama/mama-mcp-config.json');
591
- const sessionId = (0, crypto_1.randomUUID)();
592
- // Determine tool mode: Gateway, MCP, or Hybrid
593
- // - gateway: ['*'] → Use internal GatewayToolExecutor for mama_*, discord_send, etc.
594
- // - mcp: ['*'] or [...] → Use MCP servers for external tools (brave-devtools, etc.)
595
- // - Both can be enabled for hybrid mode
596
- const mcpTools = this.toolsConfig.mcp || [];
597
- const gatewayTools = this.toolsConfig.gateway || [];
598
- // Hybrid mode: Gateway + MCP both enabled
599
- const useGatewayMode = gatewayTools.includes('*') || gatewayTools.length > 0;
600
- const useMCPMode = mcpTools.includes('*') || mcpTools.length > 0;
601
- this.useCodeAct = options.useCodeAct ?? false;
602
- this.isGatewayMode =
603
- useGatewayMode ||
604
- ((options.backend === 'codex' || options.backend === 'cline') && this.useCodeAct);
605
- this.disallowedTools = this.useCodeAct
606
- ? options.disallowedTools
607
- : [
608
- ...new Set([
609
- ...(options.disallowedTools ?? []),
610
- index_js_1.CODE_ACT_MARKER,
611
- CODE_ACT_MCP_COMPAT_NAME,
612
- ]),
613
- ];
614
- this.clineNativeAllowedTools = [...(options.clineNativeAllowedTools ?? [])];
615
- this.clineNativeDisallowedTools = [...(options.clineNativeDisallowedTools ?? [])];
616
- this.clineNativePolicyConfigured =
617
- options.clineNativeAllowedTools !== undefined ||
618
- options.clineNativeDisallowedTools !== undefined;
619
- this.clineAllowSpawnAgent = options.clineAllowSpawnAgent ?? false;
620
- this.clineAllowAgentTeams = options.clineAllowAgentTeams ?? false;
621
- this.ownerRuntimeJournal = options.ownerRuntimeJournal;
622
- this.ownerRecoveryJournalEnabled = this.ownerRuntimeJournal !== undefined;
623
- if (useGatewayMode && useMCPMode) {
624
- logger.debug('🔀 Hybrid mode: Gateway + MCP tools enabled');
625
- }
626
- else if (useMCPMode) {
627
- logger.debug('🔌 MCP-only mode');
628
- }
629
- else {
630
- logger.debug('⚙️ Gateway-only mode');
631
- }
632
- // Build system prompt with layered truncation support
633
- const monitor = new prompt_size_monitor_js_1.PromptSizeMonitor();
634
- let promptLayers;
635
- if (options.systemPrompt) {
636
- // Custom system prompt (e.g., multi-agent): treat as a single critical layer
637
- promptLayers = [{ name: 'custom', content: options.systemPrompt, priority: 1 }];
638
- }
639
- else {
640
- // Composed prompt: build layers with individual priorities for graceful truncation
641
- // Priority 1 (never cut): CLAUDE.md base instructions
642
- // Priority 2 (cut if extreme): personas (SOUL, IDENTITY, USER) + gateway tools
643
- // Priority 3 (cut first): context prompt + skills + onboarding
644
- const claudeMd = loadSystemPrompt();
645
- const skillCatalog = (0, skill_loader_js_1.filterSkillCatalogForContext)((0, skill_loader_js_1.loadInstalledSkills)(false, {
646
- includePaths: options.agentContext?.roleName === 'owner_console',
647
- }), options.agentContext ?? null);
648
- promptLayers = [
649
- { name: 'claudeMd', content: claudeMd, priority: 1 },
650
- ...(skillCatalog.length > 0
651
- ? [
652
- {
653
- name: 'skills',
654
- content: [
655
- '# Installed Skills',
656
- '',
657
- 'Choose skills by their purpose and the current task, not only literal keywords.',
658
- '',
659
- ...skillCatalog,
660
- ].join('\n'),
661
- priority: 3,
662
- },
663
- ]
664
- : []),
665
- ];
666
- }
667
- const backend = options.backend ?? 'claude';
668
- this.probesDurableSession = backend === 'codex';
669
- if (this.useCodeAct && options.systemPrompt) {
670
- promptLayers = [
671
- {
672
- name: 'custom',
673
- content: stripTrailingCanonicalCodeActSection(stripGenericGatewayToolsCatalog(options.systemPrompt)),
674
- priority: 1,
675
- },
676
- ];
677
- }
678
- if (this.isGatewayMode) {
679
- if (this.useCodeAct &&
680
- roleAllowsOuterCodeAct(options.agentContext?.role, this.disallowedTools)) {
681
- // Code-Act mode: expose the compact progressive-discovery bootstrap.
682
- const tierForTypeDefs = options.agentContext?.tier ?? 1;
683
- const policy = (0, index_js_1.projectCodeActToolPolicy)({
684
- tier: tierForTypeDefs,
685
- roleName: options.agentContext?.roleName,
686
- role: options.agentContext?.role,
687
- disallowedTools: this.disallowedTools,
688
- envelopeDestinationKinds: options.envelope?.scope.allowed_destinations.map((destination) => destination.kind) ??
689
- [],
690
- envelopeRawConnectors: options.envelope?.scope.raw_connectors ?? [],
691
- });
692
- const codeActPrompt = wrapGeneratedPromptSection('codeAct', (0, index_js_1.getCodeActInstructions)(backend, policy.names));
693
- promptLayers.push({
694
- name: 'codeAct',
695
- content: codeActPrompt,
696
- priority: 1,
697
- protectedPrefix: GENERATED_CODE_ACT_START,
698
- protectedSuffix: GENERATED_CODE_ACT_END,
699
- });
700
- }
701
- else if (!this.useCodeAct && backend !== 'codex') {
702
- const gatewayToolsPrompt = getRunGatewayToolsPrompt(options.agentContext, this.disallowedTools);
703
- if (gatewayToolsPrompt) {
704
- promptLayers.push({
705
- name: 'gatewayTools',
706
- content: wrapGeneratedPromptSection('gatewayTools', gatewayToolsPrompt),
707
- priority: 2,
708
- protectedPrefix: GENERATED_GATEWAY_TOOLS_START,
709
- protectedSuffix: GENERATED_GATEWAY_TOOLS_END,
710
- });
711
- }
712
- }
713
- }
714
- const checkResult = monitor.check(promptLayers);
715
- if (checkResult.warning) {
716
- logger.warn(checkResult.warning);
717
- }
718
- // Enforce truncation if over budget (priority > 1 layers trimmed first)
719
- if (!checkResult.withinBudget) {
720
- const { layers: trimmedLayers, result: enforceResult } = monitor.enforce(promptLayers);
721
- if (enforceResult.truncatedLayers.length > 0) {
722
- logger.warn(`Truncated layers: ${enforceResult.truncatedLayers.join(', ')}`);
723
- }
724
- promptLayers = trimmedLayers;
725
- logger.debug(`System prompt truncated: ${checkResult.totalChars} → ${enforceResult.totalChars} chars`);
726
- }
727
- const defaultSystemPrompt = promptLayers
728
- .filter((l) => l.content.length > 0)
729
- .map((l) => l.content)
730
- .join('\n\n---\n\n');
731
- this.defaultSystemPrompt = defaultSystemPrompt;
732
- // Choose backend (default: claude)
733
- this.backend = backend;
734
- this.childRuntimeToolCapable =
735
- backend === 'codex' || (backend === 'claude' && (useMCPMode || options.builtinTools !== ''));
736
- if (this.backend === 'codex') {
737
- // Codex app-server mode
738
- const workspaceDir = options.codexCwd ?? (0, path_1.join)((0, os_1.homedir)(), '.mama', 'workspace');
739
- // Ensure workspace directory exists
740
- if (!(0, fs_1.existsSync)(workspaceDir)) {
741
- (0, fs_1.mkdirSync)(workspaceDir, { recursive: true });
742
- }
743
- this.agent = new runtime_process_js_1.CodexRuntimeProcess({
744
- model: options.model,
745
- cwd: workspaceDir,
746
- sandbox: options.codexSandbox ?? 'workspace-write',
747
- systemPrompt: defaultSystemPrompt,
748
- command: options.codexCommand,
749
- requestTimeout: options.timeoutMs,
750
- codexHome: options.codexHome,
751
- isolatedHome: options.codexIsolatedHome,
752
- registryRoot: options.codexRegistryRoot,
753
- effort: options.codexEffort,
754
- mcpConfigPath: this.useCodeAct
755
- ? undefined
756
- : (options.mcpConfigPath ?? (useMCPMode ? mcpConfigPath : undefined)),
757
- // A Codex-native child outlives the parent turn. The host - not the child's
758
- // parent bridge - issues its authority: own model run, own envelope, own counters.
759
- createSubagentBridge: (info) => this.createSubagentBridge(info),
760
- });
761
- logger.debug('Codex app-server backend enabled');
762
- }
763
- else if (this.backend === 'cline') {
764
- const workspaceDir = options.clineCwd ?? (0, path_1.join)((0, os_1.homedir)(), '.mama', 'workspace');
765
- if (!(0, fs_1.existsSync)(workspaceDir)) {
766
- (0, fs_1.mkdirSync)(workspaceDir, { recursive: true });
767
- }
768
- this.agent = new cline_cli_adapter_js_1.ClineCLIAdapter({
769
- command: options.clineCommand,
770
- provider: options.clineProvider ?? 'cline',
771
- model: options.model,
772
- systemPrompt: defaultSystemPrompt,
773
- cwd: workspaceDir,
774
- // Cline receives MAMA CodeAct as a session-bound Hub custom tool.
775
- // Its shared daemon owns native MCP settings independently.
776
- dataDir: options.clineDataDir,
777
- requestTimeout: options.timeoutMs,
778
- sessionId,
779
- });
780
- logger.debug('Cline CLI backend enabled');
781
- }
782
- else {
783
- // Claude backend: always use PersistentCLI for fast responses (~2-3s vs ~16-30s)
784
- this.persistentCLI = new persistent_cli_adapter_js_1.PersistentCLIAdapter({
785
- model: options.model,
786
- sessionId,
787
- systemPrompt: defaultSystemPrompt,
788
- // MCP config: only pass when MCP mode is enabled (gateway mode uses GatewayToolExecutor)
789
- mcpConfigPath: useMCPMode ? mcpConfigPath : undefined,
790
- // MAMA OS is a headless daemon (no TTY) — Claude CLI's interactive permission prompts
791
- // cannot work. Security is enforced by MAMA's own RoleManager layer (config.yaml roles).
792
- // DO NOT gate this on env vars — MAMA manages permissions via its config, not Claude CLI.
793
- dangerouslySkipPermissions: options.dangerouslySkipPermissions ?? true,
794
- // Gateway tools are processed by GatewayToolExecutor (hybrid with MCP)
795
- useGatewayTools: useGatewayMode,
796
- // Structurally disallow specific tools (e.g., Bash/Read for restricted agents)
797
- disallowedTools: this.disallowedTools,
798
- // Native built-ins cross with text-parsed gateway calls (hallucinated
799
- // ToolSearch/Agent, native gathering that bypasses report verification).
800
- // Callers opt in per loop; agent-loop-init locks down the main persona.
801
- tools: options.builtinTools,
802
- // agent.effort: the boot gate already proved it is a level this backend accepts.
803
- effort: options.codexEffort,
804
- // Pass configured timeout (default in PersistentCLI: 120s — too short for complex tasks)
805
- requestTimeout: options.timeoutMs,
806
- });
807
- this.agent = this.persistentCLI;
808
- logger.debug('🚀 Claude PersistentCLI mode enabled - faster responses');
809
- }
810
- logger.debug('Config: gateway=' +
811
- JSON.stringify(this.toolsConfig.gateway) +
812
- ' mcp=' +
813
- JSON.stringify(this.toolsConfig.mcp));
814
- // Root fix (2026-07-16): the daemon persona shares the boot-wired executor so
815
- // every dependency wiring (task ledger, report publisher, event bus, gateways,
816
- // wiki, obsidian, ...) reaches persona lanes by construction. Constructing a
817
- // second instance here is allowed ONLY for deliberately isolated loops
818
- // (memory agent, mama run CLI) that own their dep set.
819
- this.mcpExecutor = options.executor ?? new gateway_tool_executor_js_1.GatewayToolExecutor(executorOptions);
820
- // Persona tool blocks are per-call policy, not executor state - a shared
821
- // executor must never inherit one caller's blocks (see buildToolExecutionContext).
822
- this.maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
823
- this.model = options.model;
824
- this.onTurn = options.onTurn;
825
- this.onToolUse = options.onToolUse;
826
- this.createNativeEffectObserver = options.createNativeEffectObserver;
827
- this.onTokenUsage = options.onTokenUsage;
828
- this.runTokenBudget =
829
- options.runTokenBudget && options.runTokenBudget > 0 ? options.runTokenBudget : 0;
830
- this.onBudgetStop = options.onBudgetStop;
831
- this.onMetric = options.onMetric;
832
- this.laneManager = (0, index_js_2.getGlobalLaneManager)();
833
- this.useLanes = options.useLanes ?? false;
834
- this.sessionKey = options.sessionKey ?? 'default';
835
- this.sessionPool = (0, session_pool_js_1.getSessionPool)();
836
- // Initialize PostToolHandler (fire-and-forget after tool execution)
837
- if (options.postToolUse?.enabled) {
838
- this.postToolHandler = new post_tool_handler_js_1.PostToolHandler((name, input, executionContext) => this.mcpExecutor.execute(name, input, executionContext ?? undefined), { enabled: true, contractSaveLimit: options.postToolUse.contractSaveLimit });
839
- console.log('[AgentLoop] PostToolHandler enabled');
840
- }
841
- else {
842
- this.postToolHandler = null;
843
- }
844
- // Initialize PreCompactHandler (unsaved decision detection)
845
- if (options.preCompact?.enabled) {
846
- this.preCompactHandler = new pre_compact_handler_js_1.PreCompactHandler((name, input, executionContext) => this.mcpExecutor.execute(name, input, executionContext ?? undefined), { enabled: true, maxDecisionsToDetect: options.preCompact.maxDecisionsToDetect });
847
- console.log('[AgentLoop] PreCompactHandler enabled');
848
- }
849
- else {
850
- this.preCompactHandler = null;
851
- }
852
- // Initialize StopContinuationHandler (opt-in auto-resume)
853
- if (options.stopContinuation?.enabled) {
854
- this.stopContinuationHandler = new stop_continuation_handler_js_1.StopContinuationHandler({
855
- enabled: true,
856
- maxRetries: options.stopContinuation.maxRetries ?? 3,
857
- completionMarkers: options.stopContinuation.completionMarkers ?? [
858
- 'DONE',
859
- 'FINISHED',
860
- '✅',
861
- 'TASK_COMPLETE',
862
- ],
863
- });
864
- console.log('[AgentLoop] StopContinuationHandler enabled');
865
- }
866
- else {
867
- this.stopContinuationHandler = null;
868
- }
869
- }
870
- setContextCompileService(service) {
871
- this.mcpExecutor.setContextCompileService(service);
872
- }
873
- /**
874
- * Set session key for lane-based concurrency
875
- * Use format: "{source}:{channelId}:{userId}"
876
- */
877
- setSessionKey(key) {
878
- this.sessionKey = key;
879
- }
880
- /**
881
- * Get current session key
882
- */
883
- getSessionKey() {
884
- return this.sessionKey;
885
- }
886
- resolveGlobalLaneForSession(sessionKey) {
887
- const source = sessionKey.split(':', 1)[0]?.trim().toLowerCase();
888
- if (!source) {
889
- return undefined;
890
- }
891
- return exports.SOURCE_GLOBAL_LANES[source];
892
- }
893
- buildToolExecutionContext(options) {
894
- const base = buildAgentToolExecutionContext(options);
895
- if (!base) {
896
- return null; // no context fields - out-of-scope loops keep today's semantics
897
- }
898
- return {
899
- ...base,
900
- // Persona blocks are per-call policy - never executor instance state.
901
- disallowedGatewayTools: this.disallowedTools,
902
- // Never let optional multi-agent persona calls inherit the code-act
903
- // route's fallback identity. `conductor` remains the legacy persona
904
- // fallback and is unrelated to the removed background event subject.
905
- // (Persona lanes always pass source/channelId, so base is non-null for them
906
- // and the disallowed list travels on every persona run.)
907
- agentId: base.agentId || 'conductor',
908
- };
909
- }
910
- /**
911
- * Set system prompt override (for per-message context injection)
912
- */
913
- setSystemPrompt(prompt) {
914
- this.agent.setSystemPrompt(prompt ?? this.defaultSystemPrompt);
915
- }
916
- /**
917
- * Set Discord gateway for discord_send tool
918
- */
919
- setDiscordGateway(gateway) {
920
- this.mcpExecutor.setDiscordGateway(gateway);
921
- }
922
- /**
923
- * Set Telegram gateway for telegram_send tool
924
- */
925
- setTelegramGateway(gateway) {
926
- this.mcpExecutor.setTelegramGateway(gateway);
927
- }
928
- /**
929
- * Set shared sessions DB for agent management and validation-aware tools.
930
- */
931
- setSessionsDb(db) {
932
- this.mcpExecutor.setSessionsDb(db);
933
- }
934
- /**
935
- * Set validation service for agent validation flows.
936
- */
937
- setValidationService(svc) {
938
- this.mcpExecutor.setValidationService(svc);
939
- }
940
- /**
941
- * Set raw store for connector-backed agent_test input gathering.
942
- */
943
- setRawStore(store) {
944
- this.mcpExecutor.setRawStore(store);
945
- }
946
- /**
947
- * Set report publisher for report_publish tool (Dashboard Agent)
948
- */
949
- setReportPublisher(fn) {
950
- this.mcpExecutor.setReportPublisher(fn);
951
- }
952
- /**
953
- * Set wiki publisher for wiki_publish tool (Wiki Agent)
954
- */
955
- setWikiPublisher(fn) {
956
- this.mcpExecutor.setWikiPublisher(fn);
957
- }
958
- /**
959
- * Set AgentEventBus for agent_notices tool
960
- */
961
- setAgentEventBus(eventBus) {
962
- this.mcpExecutor.setAgentEventBus(eventBus);
963
- }
964
- /**
965
- * The model runner backing this loop, for host adapters that subscribe to runner
966
- * lifecycle events (e.g. native subagent completion waking the standing owner).
967
- * Returned as `unknown` on purpose: the runner surface differs per backend, so the
968
- * caller must feature-detect rather than assume an emitter.
969
- */
970
- getModelRunner() {
971
- return this.agent;
972
- }
973
- /**
974
- * Run the agent loop with a user prompt
975
- *
976
- * Uses lane-based concurrency when useLanes is enabled:
977
- * - Same session messages are processed in order
978
- * - Different sessions can run in parallel
979
- * - Global lane limits total concurrent API calls
980
- *
981
- * @param prompt - User prompt to process
982
- * @param options - Execution options (systemPrompt, disableAutoRecall, etc.)
983
- * @returns Agent loop result with final response and history
984
- * @throws AgentError on errors
985
- */
986
- async run(prompt, options) {
987
- // Convert string prompt to text content block
988
- const content = [{ type: 'text', text: prompt }];
989
- // Per-call session key wins over the instance default (same contract as
990
- // runWithContent): overlapping runs on a shared AgentLoop must never
991
- // depend on a mutated this.sessionKey to pick their lane.
992
- const sessionKey = options?.sessionKey || this.sessionKey;
993
- // Use lane-based queueing if enabled
994
- if (this.useLanes) {
995
- const globalLane = this.resolveGlobalLaneForSession(sessionKey);
996
- return this.laneManager.enqueueWithSession(sessionKey, () => this.runWithContentInternal(content, options), globalLane, { priority: options?.lanePriority ?? 0 });
997
- }
998
- // Direct execution for backward compatibility
999
- return this.runWithContentInternal(content, options);
1000
- }
1001
- /**
1002
- * Run the agent loop with multimodal content blocks
1003
- *
1004
- * Uses lane-based concurrency when useLanes is enabled.
1005
- *
1006
- * @param content - Array of content blocks (text, images, documents)
1007
- * @param options - Execution options (systemPrompt, disableAutoRecall, etc.)
1008
- * @returns Agent loop result with final response and history
1009
- * @throws AgentError on errors
1010
- */
1011
- async runWithContent(content, options) {
1012
- const sessionKey = options?.sessionKey || this.sessionKey;
1013
- // Use lane-based queueing if enabled
1014
- if (this.useLanes) {
1015
- const globalLane = this.resolveGlobalLaneForSession(sessionKey);
1016
- return this.laneManager.enqueueWithSession(sessionKey, () => this.runWithContentInternal(content, options), globalLane, { priority: options?.lanePriority ?? 0 });
1017
- }
1018
- // Direct execution for backward compatibility
1019
- return this.runWithContentInternal(content, options);
1020
- }
1021
- /**
1022
- * Internal implementation of runWithContent (without lane queueing)
1023
- */
1024
- async runWithContentInternal(content, options) {
1025
- if (this.stopped) {
1026
- throw new types_js_1.AgentError('Agent loop is stopping', 'AGENT_STOPPED', undefined, false);
1027
- }
1028
- // Queue wait consumes no execution authority. Never renew a signed envelope implicitly:
1029
- // only a host-supplied issuer can prepare the current grant after both lane waits.
1030
- if (options?.prepareEnvelope) {
1031
- const runEnvelopeIssuer = options.prepareEnvelope;
1032
- options = {
1033
- ...options,
1034
- envelope: await runEnvelopeIssuer(),
1035
- prepareEnvelope: undefined,
1036
- // A native child outlives this envelope and needs one of its OWN. The run's issuer
1037
- // is the fallback when the host supplied no dedicated subagent issuer, so it is kept
1038
- // reachable here instead of being lost with this rewrite - without it a child would
1039
- // silently get no authority at all.
1040
- prepareSubagentEnvelope: options.prepareSubagentEnvelope ?? (async () => await runEnvelopeIssuer()),
1041
- };
1042
- if (this.stopped) {
1043
- throw new types_js_1.AgentError('Agent loop is stopping', 'AGENT_STOPPED', undefined, false);
1044
- }
1045
- }
1046
- if (options?.prepareContent) {
1047
- const admitted = await options.prepareContent();
1048
- content = admitted.content;
1049
- options = { ...options, procedureRefs: admitted.procedureRefs, prepareContent: undefined };
1050
- if (this.stopped) {
1051
- throw new types_js_1.AgentError('Agent loop is stopping', 'AGENT_STOPPED', undefined, false);
1052
- }
1053
- }
1054
- if (options?.agentContext) {
1055
- options = {
1056
- ...options,
1057
- agentContext: this.mcpExecutor.projectPrivateAgentContext(options.agentContext),
1058
- };
1059
- }
1060
- const runScope = {
1061
- streamCallbacks: options?.streamCallbacks,
1062
- tier: 1,
1063
- onTurn: options?.onTurn ?? this.onTurn,
1064
- onToolUse: options?.onToolUse ?? this.onToolUse,
1065
- ...(0, temporal_code_act_breaker_js_1.createTemporalCodeActBreakerState)(),
1066
- };
1067
- const history = [];
1068
- const ownerJournalPrompt = options?.ownerJournalPrompt ??
1069
- content.map((block) => (block.type === 'text' ? block.text : `[${block.type}]`)).join('\n');
1070
- const totalUsage = { input_tokens: 0, output_tokens: 0 };
1071
- // Budget accounting is separate from totalUsage (a published field): it includes cache
1072
- // creation and cache reads, which are the bulk of a re-sent context and the cost being
1073
- // bounded - a budget that ignored them would not have stopped a 4.28M-token run.
1074
- let budgetTokens = 0;
1075
- let stoppedBy;
1076
- let turn = 0;
1077
- let stopReason = 'end_turn';
1078
- let ownedModelRunId = null;
1079
- let ownedModelRunCommitted = false;
1080
- let nativeEffects = new native_effect_observer_js_1.NativeEffectReplayBoundary();
1081
- const pendingBackgroundTasks = [];
1082
- const backgroundTasks = {
1083
- register(task) {
1084
- const observedTask = Promise.resolve(task);
1085
- observedTask.catch(() => {
1086
- // Re-thrown later by drainBackgroundTasks; attach now to prevent unhandled rejections.
1087
- });
1088
- pendingBackgroundTasks.push(observedTask);
1089
- },
1090
- };
1091
- let toolExecutionContext = this.withBackgroundTaskRegistry(this.buildToolExecutionContext(options), backgroundTasks);
1092
- if (toolExecutionContext) {
1093
- toolExecutionContext = {
1094
- ...toolExecutionContext,
1095
- procedureStimulus: ownerJournalPrompt,
1096
- procedureRefs: options?.procedureRefs,
1097
- };
1098
- }
1099
- // Track this run's tier for code-act execution and prompt sizing.
1100
- if (options?.agentContext) {
1101
- const rawTier = options.agentContext.tier ?? 1;
1102
- runScope.tier = this.useCodeAct
1103
- ? (0, index_js_1.requireCodeActTier)(rawTier)
1104
- : rawTier === 1 || rawTier === 2 || rawTier === 3
1105
- ? rawTier
1106
- : 1;
1107
- }
1108
- // Infinite loop prevention
1109
- let consecutiveToolCalls = 0;
1110
- let lastToolName = '';
1111
- const MAX_CONSECUTIVE_SAME_TOOL = MAX_CONSECUTIVE_SAME_HOST_TOOL;
1112
- const EMERGENCY_MAX_TURNS = this.emergencyMaxCalls(); // Always above maxTurns
1113
- // Track channel key for session release
1114
- const channelKey = options?.sessionKey ??
1115
- (0, session_pool_js_1.buildChannelKey)(options?.source ?? 'default', (0, principal_js_1.laneChannelId)(options?.channelId ?? this.sessionKey, 'owner'));
1116
- // The context object THIS run created, compared by identity before the finally marks
1117
- // it finished: a later run on the same session key replaces the map entry.
1118
- let ownedSubagentRunContext;
1119
- // Use session pool for conversation continuity
1120
- // IMPORTANT: If caller passes cliSessionId, use it directly to avoid double-locking
1121
- // MessageRouter already calls getSession() and passes the result via options
1122
- let sessionIsNew = options?.resumeSession === undefined ? true : !options.resumeSession;
1123
- let ownedSession = false;
1124
- // Set session ID on the agent
1125
- // Claude PersistentCLI: process alive → CONTINUE (stdin message), process dead → NEW (spawn with --session-id)
1126
- // Codex/Cline: durable runtime session alive → CONTINUE, missing → NEW.
1127
- const isCodex = this.backend === 'codex';
1128
- const isCline = this.backend === 'cline';
1129
- const isDurableRuntime = isCodex || isCline;
1130
- const tracksSessionPolicy = isDurableRuntime || this.backend === 'claude';
1131
- const clineRole = options?.agentContext?.role;
1132
- // The main persona's gateway Bash/Write run through MAMA's executor; Cline's native
1133
- // shell/editor would bypass it, so they stay disallowed whatever the role grants.
1134
- const clineAllowedTools = this.clineNativePolicyConfigured
1135
- ? this.clineNativeAllowedTools
1136
- : (0, cline_native_tool_policy_js_1.projectClineNativeTools)(clineRole?.allowedTools).filter((tool) => !cline_native_tool_policy_js_1.CLINE_NATIVE_GUARD_BYPASS.includes(tool));
1137
- const clineDisallowedTools = this.clineNativePolicyConfigured
1138
- ? this.clineNativeDisallowedTools
1139
- : [
1140
- ...new Set([
1141
- ...(0, cline_native_tool_policy_js_1.projectClineNativeTools)(clineRole?.blockedTools),
1142
- ...cline_native_tool_policy_js_1.CLINE_NATIVE_GUARD_BYPASS,
1143
- ]),
1144
- ];
1145
- const clineDelegationGranted = clineRole?.allowedTools.some((pattern) => pattern === '*' || pattern === 'native_subagent') ??
1146
- false;
1147
- const clineDelegationBlocked = clineRole?.blockedTools?.some((pattern) => pattern === '*' || pattern === 'native_subagent') ?? false;
1148
- const clineAllowSpawnAgent = this.clineAllowSpawnAgent && clineDelegationGranted && !clineDelegationBlocked;
1149
- const clineAllowAgentTeams = this.clineAllowAgentTeams && clineDelegationGranted && !clineDelegationBlocked;
1150
- const ownerRuntime = channelKey === owner_runtime_js_1.OWNER_RUNTIME_SESSION_KEY;
1151
- const sessionPolicyRole = ownerRuntime
1152
- ? (options?.sessionPolicyRole ?? options?.agentContext?.role)
1153
- : options?.agentContext?.role;
1154
- const codeActPolicy = this.useCodeAct
1155
- ? (0, index_js_1.projectCodeActToolPolicy)({
1156
- tier: ownerRuntime ? 1 : runScope.tier,
1157
- roleName: ownerRuntime ? 'owner_console' : options?.agentContext?.roleName,
1158
- role: sessionPolicyRole,
1159
- disallowedTools: this.disallowedTools,
1160
- ...(ownerRuntime
1161
- ? {}
1162
- : {
1163
- envelopeDestinationKinds: options?.envelope?.scope.allowed_destinations.map((destination) => destination.kind) ?? [],
1164
- envelopeRawConnectors: options?.envelope?.scope.raw_connectors ?? [],
1165
- }),
1166
- })
1167
- : undefined;
1168
- const outerCodeActAllowed = this.useCodeAct && roleAllowsOuterCodeAct(options?.agentContext?.role, this.disallowedTools);
1169
- const ownerPolicyFingerprint = ownerRuntime
1170
- ? ownerRuntimeSessionPolicyFingerprint(sessionPolicyRole, options?.model ?? this.model, this.supportsNativeSubagents, this.backend)
1171
- : undefined;
1172
- const effectiveSessionPolicyFingerprint = isDurableRuntime && codeActPolicy
1173
- ? combineCodeActSessionPolicyFingerprint(ownerPolicyFingerprint ?? options?.sessionPolicyFingerprint, codeActPolicy)
1174
- : (ownerPolicyFingerprint ?? options?.sessionPolicyFingerprint);
1175
- let resolvedCliSessionId = options?.cliSessionId ?? null;
1176
- const sessionLabel = (isNew) => {
1177
- if (isDurableRuntime) {
1178
- return isNew ? 'NEW thread' : 'CONTINUE thread';
1179
- }
1180
- return isNew ? 'NEW process' : 'CONTINUE session';
1181
- };
1182
- if (options?.cliSessionId) {
1183
- // Session routing travels per prompt() call via resolvedCliSessionId - no
1184
- // shared-adapter mutation (setSessionId re-pointed channelKey/currentProcess
1185
- // across awaits, cross-wiring concurrent lanes).
1186
- console.log(`[AgentLoop] [${this.backend}] ${channelKey} (${sessionLabel(sessionIsNew)})`);
1187
- }
1188
- else if (options?.freshSession) {
1189
- // Stateless lanes (operator reports): session context is a cache, not
1190
- // persistence - every run self-gathers and recalls; carrying prior runs'
1191
- // gather dumps only grows the context until runs outlive their envelope
1192
- // (measured 146s -> 521s over 3 days; owner decision 2026-07-16).
1193
- const cliSessionId = this.sessionPool.resetSession(channelKey);
1194
- sessionIsNew = true;
1195
- ownedSession = true;
1196
- resolvedCliSessionId = cliSessionId;
1197
- console.log(`[AgentLoop] [${this.backend}] ${channelKey} (FRESH session - stateless lane)`);
1198
- }
1199
- else {
1200
- // Fallback: get session from pool (for direct AgentLoop usage)
1201
- // getSession() returns immediately - if busy, we create a new session
1202
- const { sessionId: cliSessionId, isNew, busy } = this.sessionPool.getSession(channelKey);
1203
- if (busy) {
1204
- console.log(`[AgentLoop] Session busy for ${channelKey}, will be queued by Lane`);
1205
- }
1206
- sessionIsNew = isNew;
1207
- ownedSession = true;
1208
- resolvedCliSessionId = cliSessionId;
1209
- // Per-call routing via resolvedCliSessionId - no shared-adapter mutation.
1210
- console.log(`[AgentLoop] [${this.backend}] ${channelKey} (${sessionLabel(isNew)})`);
1211
- }
1212
- try {
1213
- if (this.shouldBeginModelRun(options)) {
1214
- const modelRun = await this.mcpExecutor.beginRuntimeModelRun(this.buildModelRunInput(options, resolvedCliSessionId));
1215
- ownedModelRunId = modelRun.model_run_id;
1216
- toolExecutionContext = this.withBackgroundTaskRegistry(this.buildToolExecutionContext({
1217
- ...options,
1218
- modelRunId: ownedModelRunId,
1219
- }), backgroundTasks);
1220
- if (toolExecutionContext) {
1221
- toolExecutionContext = {
1222
- ...toolExecutionContext,
1223
- procedureStimulus: ownerJournalPrompt,
1224
- procedureRefs: options?.procedureRefs,
1225
- };
1226
- }
1227
- }
1228
- nativeEffects = new native_effect_observer_js_1.NativeEffectReplayBoundary(this.createNativeEffectObserver?.(toolExecutionContext));
1229
- // This run's bridge is ITS OWN: the loop guards, the emergency budget, the history
1230
- // writes and the turn observers all belong to this run. A Codex-native child gets a
1231
- // separate bridge from `createSubagentBridge` - sharing this closure let a child trip
1232
- // the parent's loop guard and append its traces to the parent's committed model run.
1233
- const hostToolDefinitions = this.hostToolDefinitionsFor(options, outerCodeActAllowed);
1234
- const hostToolBridge = isDurableRuntime && this.isGatewayMode
1235
- ? this.buildHostToolBridge({
1236
- tools: hostToolDefinitions,
1237
- runScope,
1238
- executionContext: () => toolExecutionContext,
1239
- stopAfterSuccessfulTools: options?.stopAfterSuccessfulTools ?? [],
1240
- emergencyMaxCalls: EMERGENCY_MAX_TURNS,
1241
- maxConsecutiveSameTool: MAX_CONSECUTIVE_SAME_TOOL,
1242
- // Codex does not return completed host exchanges, so record them here. Cline
1243
- // reports the paired custom-tool exchange from its Hub event stream and
1244
- // AgentLoop appends it exactly once below.
1245
- ...(isCodex
1246
- ? {
1247
- recordExchange: {
1248
- assistant: (toolUse) => {
1249
- history.push({ role: 'assistant', content: [toolUse] });
1250
- runScope.onTurn?.({
1251
- turn,
1252
- role: 'assistant',
1253
- content: [toolUse],
1254
- stopReason: 'tool_use',
1255
- });
1256
- },
1257
- result: (toolResult) => {
1258
- const persistedToolResult = historyToolResult(toolResult);
1259
- history.push({ role: 'user', content: [persistedToolResult] });
1260
- runScope.onTurn?.({
1261
- turn,
1262
- role: 'user',
1263
- content: [persistedToolResult],
1264
- });
1265
- },
1266
- },
1267
- }
1268
- : {}),
1269
- })
1270
- : undefined;
1271
- if (hostToolBridge && isCodex) {
1272
- // A child can be announced during this run and outlive it, so what its authority
1273
- // needs is recorded now, per session key, and dropped when nothing needs it.
1274
- // A previous run's context object stays referenced by ITS still-live children, so
1275
- // this run starts its own count rather than inheriting one it can never settle.
1276
- // The child NEVER inherits this turn's role verbatim: an owner 1:1 chat turn holds
1277
- // the gateway shell and file writer, and a child is unattended by definition.
1278
- const childOptions = withUnattendedSubagentRole(options);
1279
- ownedSubagentRunContext = {
1280
- options: childOptions,
1281
- parentModelRunId: ownedModelRunId ?? options?.modelRunId ?? null,
1282
- cliSessionId: resolvedCliSessionId,
1283
- tools: this.hostToolDefinitionsFor(childOptions),
1284
- tier: runScope.tier,
1285
- activeChildren: 0,
1286
- runFinished: false,
1287
- };
1288
- this.subagentRunContexts.set(channelKey, ownedSubagentRunContext);
1289
- }
1290
- const prepareSystemPrompt = (requestedSystemPrompt, isResumingSession, includeOwnerRecovery = false) => {
1291
- let baseSystemPrompt = requestedSystemPrompt ?? this.defaultSystemPrompt;
1292
- if (ownerRuntime &&
1293
- this.supportsNativeSubagents &&
1294
- !baseSystemPrompt.includes(owner_runtime_js_1.OWNER_SUBAGENT_INSTRUCTIONS)) {
1295
- // Per-runner: the shared rule plus that runtime's own spawn mechanics.
1296
- // On a runner with no native subagent (persistent Claude persona, Cline) the
1297
- // delegation policy asks for something the runtime cannot do. It is omitted, and
1298
- // nothing replaces it: the turn's own result contract already says what must exist.
1299
- baseSystemPrompt = `${baseSystemPrompt}\n\n${(0, owner_runtime_js_1.ownerSubagentInstructions)(this.backend)}`;
1300
- }
1301
- if (ownerRuntime && !baseSystemPrompt.includes(telegram_format_js_1.TELEGRAM_FORMAT_GUIDE)) {
1302
- baseSystemPrompt = `${baseSystemPrompt}\n\n${telegram_format_js_1.TELEGRAM_FORMAT_GUIDE}`;
1303
- }
1304
- if (ownerRuntime && !baseSystemPrompt.includes(owner_runtime_js_1.OWNER_RUNTIME_RULES)) {
1305
- baseSystemPrompt = `${baseSystemPrompt}\n\n${owner_runtime_js_1.OWNER_RUNTIME_RULES}`;
1306
- }
1307
- let gatewayToolsPrompt = '';
1308
- if (this.isGatewayMode && this.useCodeAct) {
1309
- baseSystemPrompt = stripTrailingCanonicalCodeActSection(stripGenericGatewayToolsCatalog(baseSystemPrompt));
1310
- if (outerCodeActAllowed) {
1311
- const policy = codeActPolicy;
1312
- gatewayToolsPrompt = wrapGeneratedPromptSection('codeAct', (0, index_js_1.getCodeActInstructions)(this.backend, policy.names));
1313
- }
1314
- }
1315
- else if (this.isGatewayMode && !isCodex) {
1316
- baseSystemPrompt = stripDisabledCodeActGuidance(baseSystemPrompt);
1317
- if (!isResumingSession) {
1318
- if (options?.gatewayToolsPrompt !== undefined) {
1319
- // A short-lived caller may carry a more specific final policy than
1320
- // the process-wide default. Replace the host-generated constructor
1321
- // catalog with that exact policy-keyed catalog for this run.
1322
- baseSystemPrompt = stripGenericGatewayToolsCatalog(baseSystemPrompt);
1323
- if (options.gatewayToolsPrompt) {
1324
- gatewayToolsPrompt = wrapGeneratedPromptSection('gatewayTools', options.gatewayToolsPrompt);
1325
- }
1326
- }
1327
- else {
1328
- // Non-CodeAct callers may already embed the generic gateway catalog.
1329
- const alreadyHasTools = baseSystemPrompt.includes('# Gateway Tools') ||
1330
- baseSystemPrompt.includes('# Code Execution') ||
1331
- baseSystemPrompt.includes('## Code-Act');
1332
- if (!alreadyHasTools) {
1333
- gatewayToolsPrompt = wrapGeneratedPromptSection('gatewayTools', getRunGatewayToolsPrompt(options?.agentContext, this.disallowedTools));
1334
- }
1335
- }
1336
- }
1337
- }
1338
- const ownerRecovery = includeOwnerRecovery && ownerRuntime && this.ownerRuntimeJournal
1339
- ? this.ownerRuntimeJournal.recoveryBlock()
1340
- : '';
1341
- const joinLayers = (base, tools, recovery) => [base, tools, recovery].filter(Boolean).join('\n\n---\n\n');
1342
- const fullPrompt = joinLayers(baseSystemPrompt, gatewayToolsPrompt, ownerRecovery);
1343
- // Monitor and enforce prompt size
1344
- const monitor = new prompt_size_monitor_js_1.PromptSizeMonitor();
1345
- const runLayers = [
1346
- { name: 'systemPrompt', content: baseSystemPrompt, priority: 1 },
1347
- ...(gatewayToolsPrompt
1348
- ? [
1349
- {
1350
- name: 'gatewayTools',
1351
- content: gatewayToolsPrompt,
1352
- priority: gatewayToolsPrompt.startsWith(GENERATED_CODE_ACT_START) ? 1 : 2,
1353
- protectedPrefix: gatewayToolsPrompt.startsWith(GENERATED_CODE_ACT_START)
1354
- ? GENERATED_CODE_ACT_START
1355
- : GENERATED_GATEWAY_TOOLS_START,
1356
- protectedSuffix: gatewayToolsPrompt.startsWith(GENERATED_CODE_ACT_START)
1357
- ? GENERATED_CODE_ACT_END
1358
- : GENERATED_GATEWAY_TOOLS_END,
1359
- },
1360
- ]
1361
- : []),
1362
- ...(ownerRecovery
1363
- ? [{ name: 'ownerRecovery', content: ownerRecovery, priority: 3 }]
1364
- : []),
1365
- ];
1366
- const checkResult = monitor.check(runLayers);
1367
- if (checkResult.warning) {
1368
- console.warn(`[AgentLoop] ${checkResult.warning}`);
1369
- }
1370
- let effectivePrompt = fullPrompt;
1371
- if (!checkResult.withinBudget) {
1372
- const { layers: trimmed, result: enforceResult } = monitor.enforce(runLayers);
1373
- const truncatedLayers = enforceResult.truncatedLayers;
1374
- if (truncatedLayers.length > 0) {
1375
- console.warn(`[AgentLoop] Truncated layers: ${truncatedLayers.join(', ')}`);
1376
- }
1377
- const tBase = trimmed.find((l) => l.name === 'systemPrompt')?.content || baseSystemPrompt;
1378
- const tTools = trimmed.find((l) => l.name === 'gatewayTools')?.content || '';
1379
- const tRecovery = trimmed.find((l) => l.name === 'ownerRecovery')?.content || '';
1380
- effectivePrompt = joinLayers(tBase, tTools, tRecovery);
1381
- logger.debug(`[AgentLoop] System prompt truncated: ${fullPrompt.length} → ${effectivePrompt.length} chars`);
1382
- }
1383
- logger.debug(`[AgentLoop] Prepared systemPrompt for this call: ${effectivePrompt.length} chars ` +
1384
- `(base: ${baseSystemPrompt.length}, tools: ${gatewayToolsPrompt.length}, recovery: ${ownerRecovery.length})`);
1385
- return effectivePrompt;
1386
- };
1387
- let perCallSystemPrompt;
1388
- if (isCline && this.isGatewayMode && this.useCodeAct && !sessionIsNew) {
1389
- // TG-05: a compatible Cline Hub session ignores the per-call system prompt.
1390
- // Keep the continuation stub cheap; missing/mismatched sessions rebuild the
1391
- // complete policy lazily through freshSessionSystemPrompt below.
1392
- perCallSystemPrompt = options?.systemPrompt ?? this.defaultSystemPrompt;
1393
- }
1394
- else if (ownerRuntime ||
1395
- options?.systemPrompt ||
1396
- options?.gatewayToolsPrompt !== undefined ||
1397
- (this.isGatewayMode && this.useCodeAct)) {
1398
- perCallSystemPrompt = prepareSystemPrompt(options?.systemPrompt, options?.resumeSession === true, false);
1399
- }
1400
- else {
1401
- perCallSystemPrompt = this.defaultSystemPrompt;
1402
- console.log(`[AgentLoop] No systemPrompt in options - using spawn default for this call`);
1403
- }
1404
- // Durable backends re-anchor a lost session with the complete current policy.
1405
- // A CONTINUE
1406
- // turn's per-call prompt is deliberately minimal (message-router
1407
- // buildMinimalResumePrompt), so resuming with it would REPLACE the thread's full
1408
- // policy with a stub - only freshSessionSystemPrompt rebuilds the complete one.
1409
- // That rebuild costs an embedding search, so hand the backend a lazy builder it
1410
- // invokes only inside the resume branch; a live thread never pays for it.
1411
- const freshSystemPromptBuilder = options?.freshSessionSystemPrompt;
1412
- // The owner-event and scheduled lanes carry no per-call systemPrompt at all: their
1413
- // perCallSystemPrompt IS the complete composed owner policy (the ownerRuntime branch
1414
- // above). Without a resume builder those lanes fell back to the turn-text
1415
- // <system-reminder> replay - the same full prompt, but billed as USER text on the
1416
- // first turn after every daemon restart. Re-anchor it through baseInstructions
1417
- // instead; the reminder is then never needed.
1418
- const resumeInstructions = !isDurableRuntime
1419
- ? undefined
1420
- : freshSystemPromptBuilder
1421
- ? async () => prepareSystemPrompt(await freshSystemPromptBuilder(), false, false)
1422
- : ownerRuntime
1423
- ? async () => perCallSystemPrompt
1424
- : undefined;
1425
- // Reset StopContinuation state for this channel to prevent leaking
1426
- // retry counts from previous invocations
1427
- if (this.stopContinuationHandler) {
1428
- this.stopContinuationHandler.resetChannel(channelKey);
1429
- }
1430
- // Add initial user message with content blocks
1431
- history.push({
1432
- role: 'user',
1433
- content,
1434
- });
1435
- while (turn < this.maxTurns) {
1436
- turn++;
1437
- // A run whose envelope is (about to be) expired cannot commit ANY write -
1438
- // every gateway call from here on is denied '[expired]' (enforcer.ts:73).
1439
- if (options?.envelope && (0, run_guard_js_1.envelopeExpired)(options.envelope, Date.now(), 30_000)) {
1440
- const envId = String(options.envelope.instance_id ?? 'unknown');
1441
- if (options?.source === 'operator') {
1442
- // Non-interactive lane: abort loudly now instead of burning doomed turns.
1443
- // The trigger loop keeps its digest buffer and retries next cadence.
1444
- throw new types_js_1.AgentError(`Envelope ${envId} expired mid-run at turn ${turn}; aborting doomed run`, 'ENVELOPE_EXPIRED', undefined, false);
1445
- }
1446
- // Interactive lanes (chat): never abort a live conversation - deliver the
1447
- // text; individual writes will be denied loudly by the enforcer as today.
1448
- console.error(`[AgentLoop] envelope ${envId} expired mid-run (turn ${turn}, source ${options?.source ?? 'unknown'}); ` +
1449
- `subsequent gateway writes will be denied`);
1450
- }
1451
- // Emergency brake: prevent infinite loops
1452
- if (turn >= EMERGENCY_MAX_TURNS) {
1453
- throw new types_js_1.AgentError(`Emergency stop: Agent loop exceeded emergency maximum turns (${EMERGENCY_MAX_TURNS})`, 'EMERGENCY_MAX_TURNS', undefined, false);
1454
- }
1455
- let response;
1456
- const ext = runScope.streamCallbacks;
1457
- let attemptReportedError;
1458
- const callbacks = {
1459
- onDelta: (text) => {
1460
- ext?.onDelta?.(text);
1461
- },
1462
- onToolUse: (name, input) => {
1463
- nativeEffects.started(name, input);
1464
- ext?.onToolUse?.(name, input);
1465
- },
1466
- onToolComplete: (name, toolUseId, isError) => {
1467
- nativeEffects.settled(name, toolUseId, isError);
1468
- ext?.onToolComplete?.(name, toolUseId, isError);
1469
- },
1470
- // A spawn is an admission, not an external effect: forwarded verbatim with NO
1471
- // nativeEffects call, so it never writes a `native_tool` ledger row and never
1472
- // makes the occurrence unsafe to replay.
1473
- onSubagentStart: (info) => {
1474
- ext?.onSubagentStart?.(info);
1475
- },
1476
- onFinal: (finalResponse) => {
1477
- ext?.onFinal?.(finalResponse);
1478
- },
1479
- onError: (error) => {
1480
- // A model runner can emit onError before rejecting. Hold it until
1481
- // AgentLoop knows whether the attempt is terminal so a successful
1482
- // one-time session recovery does not leak a false failure event.
1483
- attemptReportedError = error;
1484
- },
1485
- };
1486
- let piResult;
1487
- // Claude: First turn → --session-id (inject system prompt), subsequent → --resume
1488
- // Codex/Cline: resumeSession controls durable session reset/continuation.
1489
- let shouldResume = isDurableRuntime
1490
- ? turn > 1 || (options?.freshSession === true ? false : (options?.resumeSession ?? true))
1491
- : !sessionIsNew || turn > 1 || (ownerRuntime && options?.resumeSession === true);
1492
- let requestSystemPrompt = perCallSystemPrompt;
1493
- let provisionalDurableSessionId;
1494
- // All three backends preserve context and receive only the new user message.
1495
- const basePromptText = this.formatLastMessageOnly(history);
1496
- let promptText = basePromptText;
1497
- const promptStart = Date.now();
1498
- const throwFinalCliError = (error) => {
1499
- const normalizedError = error instanceof Error ? error : new Error(String(error));
1500
- const modelRunnerErrorCode = normalizedError instanceof model_runner_js_1.ModelRunnerError
1501
- ? MODEL_RUNNER_AGENT_ERROR_CODES[normalizedError.code]
1502
- : undefined;
1503
- const errorType = normalizedError instanceof types_js_1.McpResultMissingError ||
1504
- normalizedError instanceof types_js_1.McpCompletedMutationInterruptedError ||
1505
- normalizedError instanceof types_js_1.ClaudeToolStreamProtocolError
1506
- ? normalizedError.code
1507
- : normalizedError instanceof model_runner_js_1.HostToolTerminalError
1508
- ? normalizedError.terminalCode
1509
- : (modelRunnerErrorCode ?? 'CLI_ERROR');
1510
- this.onMetric?.('prompt_error', 1, {
1511
- backend: this.backend,
1512
- error_type: errorType,
1513
- });
1514
- try {
1515
- ext?.onError?.(attemptReportedError ?? normalizedError);
1516
- }
1517
- catch (callbackError) {
1518
- logger.warn(`External onError callback failed: ${callbackError instanceof Error ? callbackError.message : String(callbackError)}`);
1519
- }
1520
- if (normalizedError instanceof model_runner_js_1.HostToolTerminalError) {
1521
- throw new types_js_1.AgentError(normalizedError.message, normalizedError.terminalCode, normalizedError, false);
1522
- }
1523
- if (normalizedError instanceof model_runner_js_1.HostToolAbortError) {
1524
- throw new types_js_1.AgentError(normalizedError.message, 'CLI_ERROR', normalizedError, false);
1525
- }
1526
- if (normalizedError instanceof types_js_1.McpResultMissingError ||
1527
- normalizedError instanceof types_js_1.McpCompletedMutationInterruptedError ||
1528
- normalizedError instanceof types_js_1.ClaudeToolStreamProtocolError) {
1529
- throw new types_js_1.AgentError(normalizedError.message, normalizedError.code, normalizedError, false);
1530
- }
1531
- throw new types_js_1.AgentError(`CLI error: ${normalizedError.message}`, modelRunnerErrorCode ?? 'CLI_ERROR', normalizedError, normalizedError instanceof model_runner_js_1.ModelRunnerError ? normalizedError.retryable : true);
1532
- };
1533
- const appendCompletedToolExchanges = (exchanges) => {
1534
- for (const exchange of exchanges) {
1535
- history.push({ role: 'assistant', content: [exchange.toolUse] });
1536
- runScope.onTurn?.({
1537
- turn,
1538
- role: 'assistant',
1539
- content: [exchange.toolUse],
1540
- stopReason: 'tool_use',
1541
- });
1542
- history.push({ role: 'user', content: [exchange.toolResult] });
1543
- runScope.onTurn?.({
1544
- turn,
1545
- role: 'user',
1546
- content: [exchange.toolResult],
1547
- });
1548
- }
1549
- };
1550
- try {
1551
- const durablePolicyStatus = tracksSessionPolicy && turn === 1 && (shouldResume || ownerRuntime)
1552
- ? this.agent.getSessionPolicyStatus?.({
1553
- model: options?.model,
1554
- resumeSession: true,
1555
- systemPrompt: requestSystemPrompt,
1556
- sessionKey: channelKey,
1557
- sessionPolicyFingerprint: effectiveSessionPolicyFingerprint,
1558
- sessionId: resolvedCliSessionId ?? undefined,
1559
- requestTimeout: options?.requestTimeoutMs,
1560
- // Enforced INSIDE the codex turn (usage events), see CodexAppServerProcess.
1561
- runTokenBudget: this.runTokenBudget,
1562
- hostToolBridge,
1563
- ...(isCline
1564
- ? {
1565
- allowedTools: clineAllowedTools,
1566
- disallowedTools: clineDisallowedTools,
1567
- allowSpawnAgent: clineAllowSpawnAgent,
1568
- allowAgentTeams: clineAllowAgentTeams,
1569
- }
1570
- : {}),
1571
- })
1572
- : undefined;
1573
- if (durablePolicyStatus === 'mismatch' || durablePolicyStatus === 'missing') {
1574
- console.log(`[AgentLoop] ${this.backend} durable session ${durablePolicyStatus}; ` +
1575
- 'opening the full policy before model request');
1576
- if (this.backend === 'claude' && durablePolicyStatus === 'mismatch') {
1577
- if (!this.agent.resetSession) {
1578
- throw new Error('Claude model runner cannot retire a stale policy session');
1579
- }
1580
- await this.agent.resetSession(resolvedCliSessionId ?? undefined);
1581
- }
1582
- const newSessionId = this.sessionPool.resetSession(channelKey);
1583
- options?.onCliSessionReset?.(newSessionId);
1584
- resolvedCliSessionId = newSessionId;
1585
- provisionalDurableSessionId = newSessionId;
1586
- try {
1587
- if (options?.freshSessionSystemPrompt) {
1588
- requestSystemPrompt = prepareSystemPrompt(await options.freshSessionSystemPrompt(), false, true);
1589
- }
1590
- else if (ownerRuntime) {
1591
- // Background stimuli use the standing base policy. Recover their journal only
1592
- // after the backend proves replacement is required, never from host pool state.
1593
- requestSystemPrompt = prepareSystemPrompt(options?.systemPrompt, false, true);
1594
- }
1595
- }
1596
- catch (rebuildError) {
1597
- this.sessionPool.invalidateSession(channelKey, newSessionId);
1598
- provisionalDurableSessionId = undefined;
1599
- attemptReportedError =
1600
- rebuildError instanceof Error ? rebuildError : new Error(String(rebuildError));
1601
- throw rebuildError;
1602
- }
1603
- shouldResume = false;
1604
- }
1605
- promptText = this.withProcedureHints(basePromptText, turn, {
1606
- threadId: resolvedCliSessionId ?? channelKey,
1607
- // A NEW pool session has no prior thread to carry procedures forward from, even
1608
- // when the durable runtime is asked to resume: fresh is about the thread.
1609
- fresh: !shouldResume || sessionIsNew,
1610
- context: toolExecutionContext,
1611
- });
1612
- piResult = await this.agent.prompt(promptText, callbacks, {
1613
- model: options?.model,
1614
- resumeSession: shouldResume,
1615
- systemPrompt: requestSystemPrompt,
1616
- resumeInstructions,
1617
- promptTelemetry: {
1618
- kind: options?.promptKind ?? (options?.source === 'operator' ? 'scheduled' : 'chat'),
1619
- brief: options?.promptBrief ?? 'omitted',
1620
- },
1621
- sessionKey: channelKey,
1622
- sessionPolicyFingerprint: effectiveSessionPolicyFingerprint,
1623
- sessionId: resolvedCliSessionId ?? undefined,
1624
- // Per-run request timeout (operator worker runs); undefined leaves
1625
- // the pool's construction-time default untouched (chat).
1626
- requestTimeout: options?.requestTimeoutMs,
1627
- runTokenBudget: this.runTokenBudget,
1628
- hostToolBridge,
1629
- toolExecutionContext,
1630
- ...(isCline
1631
- ? {
1632
- allowedTools: clineAllowedTools,
1633
- disallowedTools: clineDisallowedTools,
1634
- allowSpawnAgent: clineAllowSpawnAgent,
1635
- allowAgentTeams: clineAllowAgentTeams,
1636
- }
1637
- : {}),
1638
- });
1639
- provisionalDurableSessionId = undefined;
1640
- }
1641
- catch (error) {
1642
- if (provisionalDurableSessionId) {
1643
- this.sessionPool.invalidateSession(channelKey, provisionalDurableSessionId);
1644
- provisionalDurableSessionId = undefined;
1645
- }
1646
- const errorMessage = error instanceof Error ? error.message : String(error);
1647
- console.error(`[AgentLoop] ${this.backend} CLI error:`, errorMessage);
1648
- // A codex turn interrupted by the run budget is a host decision, not a failure:
1649
- // stop here with what was collected and let the host record the receipt.
1650
- if (error?.code === 'RUN_BUDGET_STOP' ||
1651
- errorMessage.startsWith('run budget stop:')) {
1652
- stoppedBy = 'budget';
1653
- const stoppedUsage = error.usage;
1654
- if (stoppedUsage) {
1655
- totalUsage.input_tokens += stoppedUsage.input_tokens;
1656
- totalUsage.output_tokens += stoppedUsage.output_tokens;
1657
- budgetTokens += this.countBudgetTokens(stoppedUsage);
1658
- try {
1659
- this.onTokenUsage?.({
1660
- channel_key: channelKey,
1661
- agent_id: options?.agentContext?.roleName || this.model,
1662
- input_tokens: stoppedUsage.input_tokens,
1663
- output_tokens: stoppedUsage.output_tokens,
1664
- cache_read_tokens: stoppedUsage.cache_read_input_tokens || 0,
1665
- cost_usd: 0,
1666
- });
1667
- }
1668
- catch {
1669
- // Recording failures must never mask the stop itself.
1670
- }
1671
- }
1672
- budgetTokens = Math.max(budgetTokens, this.runTokenBudget);
1673
- try {
1674
- this.onBudgetStop?.({
1675
- channelKey,
1676
- modelRunId: ownedModelRunId ?? options?.modelRunId ?? null,
1677
- agentId: options?.agentContext?.roleName,
1678
- budgetTokens,
1679
- runTokenBudget: this.runTokenBudget,
1680
- turns: turn,
1681
- });
1682
- }
1683
- catch {
1684
- // Receipt failures must never mask the stop itself.
1685
- }
1686
- break;
1687
- }
1688
- if (error instanceof types_js_1.McpCompletedMutationInterruptedError) {
1689
- appendCompletedToolExchanges(error.completedToolExchanges);
1690
- throwFinalCliError(error);
1691
- }
1692
- if (error instanceof model_runner_js_1.HostToolTerminalError && error.completedToolExchanges?.length) {
1693
- appendCompletedToolExchanges(error.completedToolExchanges);
1694
- throwFinalCliError(error);
1695
- }
1696
- if (error instanceof model_runner_js_1.HostToolAbortError && error.completedToolExchanges.length > 0) {
1697
- appendCompletedToolExchanges(error.completedToolExchanges);
1698
- throwFinalCliError(error);
1699
- }
1700
- // Check if this is a recoverable session error
1701
- // 1. "No conversation found" - CLI session was lost (daemon restart, timeout)
1702
- // 2. "Session ID already in use" - concurrent request conflict
1703
- // 3. "Prompt is too long" - session context exceeded API limits
1704
- const isSessionNotFound = errorMessage.includes('No conversation found with session ID');
1705
- const isSessionInUse = errorMessage.includes('is already in use');
1706
- const isPromptTooLong = (error instanceof model_runner_js_1.ModelRunnerError && error.code === 'context_overflow') ||
1707
- errorMessage.includes('Prompt is too long') ||
1708
- errorMessage.includes('prompt is too long') ||
1709
- errorMessage.includes('request_too_large') ||
1710
- errorMessage.includes('context window') ||
1711
- errorMessage.includes('context_length_exceeded');
1712
- const isCodexPolicyMismatch = errorMessage.includes('Codex app-server thread policy mismatch; reset the session explicitly');
1713
- // 4. API 400 on a resumed session whose stored transcript carries an
1714
- // empty content block (live incident 2026-07-27: sonnet emitted an
1715
- // empty thinking block, the CLI persisted it, and every subsequent
1716
- // replay of that session died with this 400). The transcript is
1717
- // unrecoverable - only a fresh session heals it.
1718
- const isCorruptTranscript = errorMessage.includes('text content blocks must be non-empty');
1719
- const canRecoverSession = (isCodex && isCodexPolicyMismatch) ||
1720
- (!isCodex &&
1721
- (isSessionNotFound || isSessionInUse || isPromptTooLong || isCorruptTranscript));
1722
- const nativeFailure = nativeEffects.failure(error, canRecoverSession);
1723
- if (nativeFailure !== error) {
1724
- throw nativeFailure;
1725
- }
1726
- if (canRecoverSession) {
1727
- const reason = isCodexPolicyMismatch
1728
- ? 'policy mismatch'
1729
- : isSessionNotFound
1730
- ? 'not found in CLI'
1731
- : isSessionInUse
1732
- ? 'already in use'
1733
- : isCorruptTranscript
1734
- ? 'transcript corrupt (empty content block)'
1735
- : 'prompt too long (context overflow)';
1736
- console.log(`[AgentLoop] Session ${reason}, retrying with new session`);
1737
- // Reset session in pool so it creates a new one
1738
- const newSessionId = this.sessionPool.resetSession(channelKey);
1739
- options?.onCliSessionReset?.(newSessionId);
1740
- // Per-call routing: hand the new id to this prompt() and update the
1741
- // resolved id so later turns follow it - no shared-adapter mutation.
1742
- resolvedCliSessionId = newSessionId;
1743
- // A recoverable durable-session error can occur on a resumed
1744
- // MessageRouter session whose per-call prompt is intentionally minimal.
1745
- // Rebuild the full policy before opening every replacement session.
1746
- let resetSystemPrompt = perCallSystemPrompt;
1747
- try {
1748
- // Discard the recoverable first-attempt error before any reset
1749
- // preparation. A prompt rebuild or retry failure must surface
1750
- // its own final error, never the mismatch that triggered it.
1751
- attemptReportedError = undefined;
1752
- if (options?.freshSessionSystemPrompt) {
1753
- resetSystemPrompt = prepareSystemPrompt(await options.freshSessionSystemPrompt(), false, true);
1754
- }
1755
- else if (ownerRuntime) {
1756
- resetSystemPrompt = prepareSystemPrompt(options?.systemPrompt, false, true);
1757
- }
1758
- promptText = this.withProcedureHints(basePromptText, turn, {
1759
- threadId: newSessionId,
1760
- fresh: true,
1761
- context: toolExecutionContext,
1762
- });
1763
- piResult = await this.agent.prompt(promptText, callbacks, {
1764
- model: options?.model,
1765
- resumeSession: false, // Force new session
1766
- systemPrompt: resetSystemPrompt,
1767
- sessionKey: channelKey,
1768
- sessionPolicyFingerprint: effectiveSessionPolicyFingerprint,
1769
- sessionId: newSessionId,
1770
- // Carry the per-run timeout onto the reset session too.
1771
- requestTimeout: options?.requestTimeoutMs,
1772
- runTokenBudget: this.runTokenBudget,
1773
- hostToolBridge,
1774
- toolExecutionContext,
1775
- ...(isCline
1776
- ? {
1777
- allowedTools: clineAllowedTools,
1778
- disallowedTools: clineDisallowedTools,
1779
- allowSpawnAgent: clineAllowSpawnAgent,
1780
- allowAgentTeams: clineAllowAgentTeams,
1781
- }
1782
- : {}),
1783
- });
1784
- }
1785
- catch (retryError) {
1786
- console.error(`[AgentLoop] ${this.backend} reset retry failed:`, retryError instanceof Error ? retryError.message : String(retryError));
1787
- // resetSession() creates and locks a replacement pool entry.
1788
- // A failed rebuild/retry must remove it entirely; otherwise the
1789
- // next MessageRouter turn sees isNew=false and can persist a
1790
- // minimal resume prompt as the replacement thread's base policy.
1791
- this.sessionPool.invalidateSession(channelKey, newSessionId);
1792
- throwFinalCliError(retryError);
1793
- }
1794
- // Prepend reset notice so user knows context was lost
1795
- if (isPromptTooLong && piResult?.response) {
1796
- piResult.response = `⚠️ Session reset: The previous conversation was too long, starting a new session.\n\n${piResult.response}`;
1797
- }
1798
- console.log(`[AgentLoop] Retry successful with new session: ${newSessionId}`);
1799
- }
1800
- else {
1801
- throwFinalCliError(error);
1802
- }
1803
- }
1804
- if (!piResult) {
1805
- return throwFinalCliError(new Error('Model runner returned no prompt result'));
1806
- }
1807
- // Emit one terminal metric per prompt turn, including recovered calls.
1808
- this.onMetric?.('prompt_latency_ms', Date.now() - promptStart, {
1809
- backend: this.backend,
1810
- turn: String(turn),
1811
- });
1812
- // After first successful call, mark session as not new for subsequent turns
1813
- if (turn === 1) {
1814
- sessionIsNew = false;
1815
- }
1816
- // Build content blocks - include tool_use blocks if present
1817
- const contentBlocks = [];
1818
- let parsedToolCalls = [];
1819
- // Parse tool_call / code_act blocks from text response (Gateway Tools mode ONLY)
1820
- if (this.isGatewayMode && !isDurableRuntime) {
1821
- parsedToolCalls = this.parseToolCallsFromText(piResult.response || '');
1822
- // Code-Act: parse ```js blocks only if enabled
1823
- if (this.useCodeAct) {
1824
- const codeActCalls = this.parseCodeActBlocks(piResult.response || '');
1825
- if (codeActCalls.length > 0) {
1826
- parsedToolCalls.push(...codeActCalls);
1827
- }
1828
- }
1829
- const textWithoutToolCalls = this.removeToolCallBlocks(piResult.response || '');
1830
- if (textWithoutToolCalls.trim()) {
1831
- contentBlocks.push({ type: 'text', text: textWithoutToolCalls });
1832
- }
1833
- // Add parsed tool_use blocks from text (Gateway Tools - prompt-based)
1834
- if (parsedToolCalls.length > 0) {
1835
- for (const toolCall of parsedToolCalls) {
1836
- contentBlocks.push({
1837
- type: 'tool_use',
1838
- id: toolCall.id,
1839
- name: toolCall.name,
1840
- input: toolCall.input,
1841
- });
1842
- }
1843
- console.log(`[AgentLoop] Parsed ${parsedToolCalls.length} tool calls from text (Gateway Tools mode)`);
1844
- }
1845
- }
1846
- else {
1847
- // MCP mode: use response text as-is
1848
- if (piResult.response?.trim()) {
1849
- contentBlocks.push({ type: 'text', text: piResult.response });
1850
- }
1851
- }
1852
- // Add tool_use blocks from Claude CLI if present (MCP mode)
1853
- if ('toolUseBlocks' in piResult && Array.isArray(piResult.toolUseBlocks)) {
1854
- const toolUseBlocks = piResult.toolUseBlocks;
1855
- for (const toolUse of toolUseBlocks) {
1856
- contentBlocks.push({
1857
- type: 'tool_use',
1858
- id: toolUse.id,
1859
- name: toolUse.name,
1860
- input: toolUse.input,
1861
- });
1862
- }
1863
- console.log(`[AgentLoop] Detected ${toolUseBlocks.length} tool calls from MCP`);
1864
- }
1865
- // Both parsed gateway calls and native/MCP tool blocks share executeTools.
1866
- const hasToolUse = contentBlocks.some((block) => block.type === 'tool_use');
1867
- // eslint-disable-next-line prefer-const
1868
- response = {
1869
- id: `msg_${Date.now()}`,
1870
- type: 'message',
1871
- role: 'assistant',
1872
- content: contentBlocks,
1873
- model: this.model,
1874
- stop_reason: hasToolUse ? 'tool_use' : 'end_turn',
1875
- stop_sequence: null,
1876
- usage: piResult.usage,
1877
- };
1878
- // Update usage
1879
- totalUsage.input_tokens += response.usage.input_tokens;
1880
- totalUsage.output_tokens += response.usage.output_tokens;
1881
- budgetTokens += this.countBudgetTokens(response.usage);
1882
- // Record token usage
1883
- if (this.onTokenUsage) {
1884
- try {
1885
- this.onTokenUsage({
1886
- channel_key: channelKey,
1887
- agent_id: options?.agentContext?.roleName || this.model, // Use roleName if available, else model
1888
- input_tokens: response.usage.input_tokens,
1889
- output_tokens: response.usage.output_tokens,
1890
- cache_read_tokens: response.usage.cache_read_input_tokens || 0, // No longer needs 'as any' cast
1891
- cost_usd: piResult.cost_usd || 0,
1892
- });
1893
- }
1894
- catch {
1895
- // Ignore recording errors - never break the agent loop
1896
- }
1897
- }
1898
- // Preserve the SessionPool usage-status contract. Billing telemetry is
1899
- // recorded above; durable runtimes own model-aware compaction.
1900
- const tokenStatus = this.sessionPool.updateTokens(channelKey, response.usage.input_tokens, this.backend);
1901
- // Claude's MCP server may already have executed these tool calls while the
1902
- // prompt was streaming. Preserve the observed exchange in conversation
1903
- // order, but never put the completed tool_use back into executeTools().
1904
- // Replaying a completed mutation would turn a transport observation into a
1905
- // second host-side effect.
1906
- if (Array.isArray(piResult.completedToolExchanges)) {
1907
- appendCompletedToolExchanges(piResult.completedToolExchanges);
1908
- }
1909
- // The local MCP server can complete a mutation and still report an
1910
- // indeterminate terminal outcome. Preserve the paired exchange above
1911
- // for auditability, then fail this turn without sending it through the
1912
- // ordinary host-tool loop or retrying the prompt.
1913
- if (piResult.terminalError) {
1914
- throwFinalCliError(new model_runner_js_1.HostToolTerminalError(piResult.terminalError.code, piResult.terminalError.message));
1915
- }
1916
- // PreCompact remains available for a future authoritative occupancy
1917
- // signal. Runtime-owned sessions do not infer one from usage telemetry.
1918
- if (tokenStatus.nearThreshold && this.preCompactHandler && !runScope.preCompactInjected) {
1919
- runScope.preCompactInjected = true;
1920
- try {
1921
- const historyText = history.map((msg) => {
1922
- if (typeof msg.content === 'string')
1923
- return msg.content;
1924
- return msg.content
1925
- .filter((b) => b.type === 'text')
1926
- .map((b) => b.text)
1927
- .join('\n');
1928
- });
1929
- const compactResult = await this.preCompactHandler.process(historyText, withExecutionSurface(toolExecutionContext, 'reactive_internal'));
1930
- if (compactResult.compactionPrompt) {
1931
- history.push({
1932
- role: 'user',
1933
- content: [{ type: 'text', text: compactResult.compactionPrompt }],
1934
- });
1935
- console.log(`[AgentLoop] PreCompact: injected compaction summary (${compactResult.unsavedDecisions.length} unsaved decisions detected)`);
1936
- }
1937
- }
1938
- catch (error) {
1939
- const message = error instanceof Error ? error.message : String(error);
1940
- console.error(`[AgentLoop] PreCompact error (non-blocking):`, message);
1941
- }
1942
- }
1943
- // Add assistant response to history
1944
- history.push({
1945
- role: 'assistant',
1946
- content: response.content,
1947
- });
1948
- // Notify turn callback
1949
- runScope.onTurn?.({
1950
- turn,
1951
- role: 'assistant',
1952
- content: response.content,
1953
- stopReason: response.stop_reason,
1954
- usage: response.usage,
1955
- });
1956
- stopReason = response.stop_reason;
1957
- // Per-run budget: checked after this turn's usage and before the next dispatch, so
1958
- // the budget is never exceeded by more than one turn. The partial response so far is
1959
- // returned, and the host records the receipt.
1960
- if (this.runTokenBudget > 0 && budgetTokens >= this.runTokenBudget) {
1961
- stoppedBy = 'budget';
1962
- console.warn(`[AgentLoop] run budget stop: ${budgetTokens} >= ${this.runTokenBudget} tokens after turn ${turn} (${channelKey})`);
1963
- try {
1964
- this.onBudgetStop?.({
1965
- channelKey,
1966
- modelRunId: ownedModelRunId ?? options?.modelRunId ?? null,
1967
- agentId: options?.agentContext?.roleName,
1968
- budgetTokens,
1969
- runTokenBudget: this.runTokenBudget,
1970
- turns: turn,
1971
- });
1972
- }
1973
- catch {
1974
- // Receipt failures must never mask the stop itself.
1975
- }
1976
- break;
1977
- }
1978
- // Check stop conditions
1979
- if (response.stop_reason === 'end_turn') {
1980
- // StopContinuation: check if response looks incomplete before breaking
1981
- if (this.stopContinuationHandler) {
1982
- const finalText = this.extractTextFromContent(response.content);
1983
- const decision = this.stopContinuationHandler.analyzeResponse(channelKey, finalText);
1984
- if (decision.shouldContinue && decision.continuationPrompt) {
1985
- console.log(`[AgentLoop] StopContinuation: auto-continuing (attempt ${decision.attempt}, reason: ${decision.reason})`);
1986
- history.push({
1987
- role: 'user',
1988
- content: [{ type: 'text', text: decision.continuationPrompt }],
1989
- });
1990
- continue;
1991
- }
1992
- }
1993
- break;
1994
- }
1995
- if (response.stop_reason === 'max_tokens') {
1996
- throw new types_js_1.AgentError('Response truncated due to max tokens limit', 'MAX_TOKENS', undefined, false);
1997
- }
1998
- // Handle tool use
1999
- if (response.stop_reason === 'tool_use') {
2000
- // Check for infinite loop patterns in tool usage
2001
- const toolUseBlocks = response.content.filter((block) => block.type === 'tool_use');
2002
- if (toolUseBlocks.length > 0) {
2003
- const currentToolName = toolUseBlocks[0].name;
2004
- if (currentToolName === lastToolName) {
2005
- consecutiveToolCalls++;
2006
- if (consecutiveToolCalls >= MAX_CONSECUTIVE_SAME_TOOL) {
2007
- throw new types_js_1.AgentError(`Infinite loop detected: Tool "${currentToolName}" called ${consecutiveToolCalls} times consecutively`, 'INFINITE_LOOP_DETECTED', undefined, false);
2008
- }
2009
- }
2010
- else {
2011
- consecutiveToolCalls = 1;
2012
- lastToolName = currentToolName;
2013
- }
2014
- }
2015
- const internalToolResults = await this.executeTools(response.content, options?.stopAfterSuccessfulTools ?? [], toolExecutionContext, runScope);
2016
- const toolResults = internalToolResults.map(historyToolResult);
2017
- // Add tool results to history
2018
- history.push({
2019
- role: 'user',
2020
- content: toolResults,
2021
- });
2022
- // Notify turn callback for tool results
2023
- runScope.onTurn?.({
2024
- turn,
2025
- role: 'user',
2026
- content: toolResults,
2027
- });
2028
- const terminalToolResult = internalToolResults.find((result) => result.abort === true);
2029
- if (terminalToolResult) {
2030
- throw new types_js_1.AgentError(terminalToolResult.content, terminalToolResult.terminalCode ?? 'TOOL_ERROR', undefined, false);
2031
- }
2032
- const stopAfterSuccessfulTools = options?.stopAfterSuccessfulTools ?? [];
2033
- const shouldStopAfterTool = stopAfterSuccessfulTools.length > 0 &&
2034
- toolUseBlocks.some((toolUse) => stopAfterSuccessfulTools.includes(toolUse.name) &&
2035
- toolResults.some((result) => result.tool_use_id === toolUse.id && !result.is_error));
2036
- if (shouldStopAfterTool) {
2037
- stopReason = 'end_turn';
2038
- break;
2039
- }
2040
- }
2041
- }
2042
- // Check if we hit max turns
2043
- // A budget stop on the last allowed turn is a budget stop, not MAX_TURNS.
2044
- if (turn >= this.maxTurns && stopReason === 'tool_use' && stoppedBy !== 'budget') {
2045
- throw new types_js_1.AgentError(`Agent loop exceeded maximum turns (${this.maxTurns})`, 'MAX_TURNS', undefined, false);
2046
- }
2047
- // Extract final text response
2048
- const finalResponse = this.extractTextResponse(history);
2049
- const result = {
2050
- ...(stoppedBy ? { stoppedBy } : {}),
2051
- response: finalResponse,
2052
- turns: turn,
2053
- history,
2054
- totalUsage,
2055
- stopReason,
2056
- modelRunId: ownedModelRunId ?? options?.modelRunId ?? null,
2057
- modelRunProvenance: ((ownedModelRunId ?? options?.modelRunId)
2058
- ? 'available'
2059
- : 'backend_no_run'),
2060
- };
2061
- // Draining background work and committing the run are separate failures and get
2062
- // separate catches. Sharing one meant a rejected background task skipped the commit
2063
- // and was then reported as `commit_failed` - naming a failure that was never even
2064
- // attempted, which is the exact habit this provenance state exists to break.
2065
- try {
2066
- await this.drainBackgroundTasks(pendingBackgroundTasks);
2067
- }
2068
- catch (backgroundError) {
2069
- logger.warn(`AgentLoop background task drain failed: ${backgroundError instanceof Error ? backgroundError.message : String(backgroundError)}`);
2070
- }
2071
- try {
2072
- if (ownedModelRunId) {
2073
- await this.mcpExecutor.commitRuntimeModelRun(ownedModelRunId, 'agent_loop completed');
2074
- ownedModelRunCommitted = true;
2075
- }
2076
- }
2077
- catch (commitError) {
2078
- logger.warn(`AgentLoop model run commit failed: ${commitError instanceof Error ? commitError.message : String(commitError)}`);
2079
- }
2080
- if (ownedModelRunId && !ownedModelRunCommitted) {
2081
- // The response still stands - the turn happened and the owner should get it.
2082
- // What does NOT stand is the handle: the run record may be left uncommitted, so
2083
- // returning its id would hand out provenance that cannot be resolved. Report the
2084
- // answer, withhold the claim, and say which kind of absence this is - an
2085
- // uncommitted record is a durability failure to repair, not the ordinary case of
2086
- // a backend that reports no run at all.
2087
- //
2088
- // Deliberately NOT marked failed. The run did not fail; writing its completion
2089
- // did. Relabelling a successful run as failed would tidy the state by recording
2090
- // something untrue, and an existing test pins that decision. The orphan stays
2091
- // visible, and the reason below is what a repair pass keys on.
2092
- result.modelRunId = null;
2093
- result.modelRunProvenance = 'commit_failed';
2094
- logger.error(`Model run ${ownedModelRunId} may remain uncommitted; provenance reported as commit_failed`);
2095
- }
2096
- if (ownerRuntime && finalResponse.trim()) {
2097
- // Observation only: a completion claim with no durable write in this run is the
2098
- // failure the owner sees as "corrected" work that never persisted (2026-09-09).
2099
- void this.observeCompletionClaim(ownedModelRunId, finalResponse);
2100
- }
2101
- if (ownerRuntime && this.ownerRuntimeJournal && finalResponse.trim()) {
2102
- try {
2103
- this.ownerRuntimeJournal.append({
2104
- trust: options?.ownerJournalTrust ?? 'untrusted',
2105
- source: options?.source ?? 'owner',
2106
- channelId: options?.channelId ?? owner_runtime_js_1.OWNER_RUNTIME_SESSION_KEY,
2107
- prompt: ownerJournalPrompt,
2108
- response: finalResponse,
2109
- ...(options?.sourceMessageRef ? { sourceMessageRef: options.sourceMessageRef } : {}),
2110
- committedAt: new Date().toISOString(),
2111
- });
2112
- }
2113
- catch (journalError) {
2114
- result.ownerJournalProvenance = 'commit_failed';
2115
- logger.warn(`Owner runtime journal append failed: ${journalError instanceof Error ? journalError.message : String(journalError)}`);
2116
- }
2117
- }
2118
- if (stoppedBy) {
2119
- // Budget interruption is returned structurally; keep admission uncertain.
2120
- nativeEffects.failure(new Error('Native run stopped by token budget'));
2121
- }
2122
- else {
2123
- nativeEffects.finished();
2124
- }
2125
- return result;
2126
- }
2127
- catch (error) {
2128
- if (ownedModelRunId && !ownedModelRunCommitted) {
2129
- try {
2130
- const summary = error instanceof Error ? error.message : String(error);
2131
- await this.mcpExecutor.failRuntimeModelRun(ownedModelRunId, summary);
2132
- }
2133
- catch (failError) {
2134
- logger.warn(`Failed to mark model run ${ownedModelRunId} failed: ${failError instanceof Error ? failError.message : String(failError)}`);
2135
- }
2136
- }
2137
- throw nativeEffects.failure(error);
2138
- }
2139
- finally {
2140
- this.mcpExecutor.releaseProcedureRun?.(toolExecutionContext);
2141
- // A child that outlives this run still needs its authority recipe, so the context is
2142
- // dropped only once the run finished AND no child of it is still registered.
2143
- if (ownedSubagentRunContext) {
2144
- ownedSubagentRunContext.runFinished = true;
2145
- if (ownedSubagentRunContext.activeChildren === 0 &&
2146
- this.subagentRunContexts.get(channelKey) === ownedSubagentRunContext) {
2147
- this.subagentRunContexts.delete(channelKey);
2148
- }
2149
- }
2150
- // Always release session lock, even on error
2151
- // BUT only if we own the session (not passed by caller)
2152
- if (ownedSession) {
2153
- this.sessionPool.releaseSession(channelKey);
2154
- }
2155
- }
2156
- }
2157
- shouldBeginModelRun(options) {
2158
- return this.isGatewayMode && !options?.modelRunId;
2159
- }
2160
- withBackgroundTaskRegistry(context, backgroundTasks) {
2161
- if (!context) {
2162
- return null;
2163
- }
2164
- return {
2165
- ...context,
2166
- backgroundTasks,
2167
- };
2168
- }
2169
- async drainBackgroundTasks(tasks) {
2170
- for (let index = 0; index < tasks.length; index += 1) {
2171
- await tasks[index];
2172
- }
2173
- }
2174
- buildModelRunInput(options, resolvedCliSessionId) {
2175
- const agentContext = options?.agentContext;
2176
- return {
2177
- model_id: options?.model ?? this.model ?? null,
2178
- model_provider: this.backend,
2179
- agent_id: options?.envelope?.agent_id ??
2180
- (agentContext?.source === 'viewer'
2181
- ? 'os-agent'
2182
- : (agentContext?.roleName ?? options?.source ?? 'agent')),
2183
- instance_id: options?.envelope?.instance_id ?? agentContext?.session?.sessionId ?? null,
2184
- envelope_hash: options?.envelope?.envelope_hash ?? null,
2185
- parent_model_run_id: options?.parentModelRunId ?? null,
2186
- status: 'running',
2187
- input_refs: {
2188
- source: options?.source ?? agentContext?.source ?? 'default',
2189
- channelId: options?.channelId ?? agentContext?.session?.channelId ?? this.sessionKey,
2190
- entrypoint: 'agent_loop',
2191
- ...(options?.sourceTurnId ? { sourceTurnId: options.sourceTurnId } : {}),
2192
- ...(options?.sourceMessageRef ? { sourceMessageRef: options.sourceMessageRef } : {}),
2193
- ...(resolvedCliSessionId ? { cliSessionId: resolvedCliSessionId } : {}),
2194
- ...(options?.workorderAttemptId !== undefined
2195
- ? { workorderAttemptId: options.workorderAttemptId }
2196
- : {}),
2197
- },
2198
- };
2199
- }
2200
- /** Always above maxTurns: the last-resort stop for a runaway native tool loop. */
2201
- emergencyMaxCalls() {
2202
- return Math.max(this.maxTurns + 10, 50);
2203
- }
2204
- /**
2205
- * The host tool surface the given options' role grants.
2206
- *
2207
- * The Code-Act gate is derived from THOSE options by default, never from the caller's
2208
- * own role: a child runs under a projected unattended role, so a parent that may hold
2209
- * outer Code-Act must not hand that marker to a child whose role forbids it.
2210
- */
2211
- hostToolDefinitionsFor(options, outerCodeActAllowed = this.useCodeAct &&
2212
- roleAllowsOuterCodeAct(options?.agentContext?.role, this.disallowedTools)) {
2213
- return this.useCodeAct
2214
- ? outerCodeActAllowed
2215
- ? tool_registry_js_1.ToolRegistry.getHostToolDefinitions({ allowedTools: [index_js_1.CODE_ACT_MARKER] })
2216
- : []
2217
- : tool_registry_js_1.ToolRegistry.getHostToolDefinitions({
2218
- allowedTools: options?.agentContext?.role.allowedTools,
2219
- blockedTools: options?.agentContext?.role.blockedTools,
2220
- disallowedTools: this.disallowedTools,
2221
- viewer: options?.agentContext?.platform === 'viewer',
2222
- });
2223
- }
2224
- /**
2225
- * One dynamic-tool bridge. Every guard it applies - the emergency call budget and the
2226
- * same-signature loop guard - is private to the bridge, so a parent and its children
2227
- * never share a counter. `recordExchange` is the ONLY way a bridge writes to a
2228
- * conversation: a child passes none and therefore cannot touch the parent's history.
2229
- */
2230
- buildHostToolBridge(params) {
2231
- let toolCallCount = 0;
2232
- let consecutiveToolCalls = 0;
2233
- let lastToolSignature = '';
2234
- return {
2235
- tools: params.tools,
2236
- execute: async (call) => {
2237
- const callSignal = call.signal ?? new AbortController().signal;
2238
- callSignal.throwIfAborted();
2239
- if (toolCallCount >= params.emergencyMaxCalls) {
2240
- return {
2241
- content: `Native tool call budget exceeded emergency maximum turns (${params.emergencyMaxCalls})`,
2242
- isError: true,
2243
- abort: true,
2244
- };
2245
- }
2246
- const toolSignature = call.name === index_js_1.CODE_ACT_MARKER && typeof call.input.code === 'string'
2247
- ? `${call.name}:${call.input.code.trim()}`
2248
- : call.name;
2249
- const nextConsecutiveCount = toolSignature === lastToolSignature ? consecutiveToolCalls + 1 : 1;
2250
- if (nextConsecutiveCount >= params.maxConsecutiveSameTool) {
2251
- return {
2252
- content: `Infinite loop detected: Tool "${call.name}" called ${nextConsecutiveCount} times consecutively`,
2253
- isError: true,
2254
- abort: true,
2255
- };
2256
- }
2257
- toolCallCount += 1;
2258
- consecutiveToolCalls = nextConsecutiveCount;
2259
- lastToolSignature = toolSignature;
2260
- const toolUse = {
2261
- type: 'tool_use',
2262
- id: call.callId,
2263
- name: call.name,
2264
- input: call.input,
2265
- };
2266
- params.recordExchange?.assistant(toolUse);
2267
- const executionContext = params.executionContext();
2268
- const callExecutionContext = executionContext
2269
- ? {
2270
- ...executionContext,
2271
- gatewayCallId: call.callId,
2272
- signal: callSignal,
2273
- }
2274
- : null;
2275
- const [toolResult] = await this.executeTools([toolUse], [...params.stopAfterSuccessfulTools], callExecutionContext, params.runScope);
2276
- if (!toolResult) {
2277
- callSignal.throwIfAborted();
2278
- return {
2279
- content: `Native tool "${call.name}" returned no result`,
2280
- isError: true,
2281
- abort: true,
2282
- };
2283
- }
2284
- if (!toolResult.terminalCode) {
2285
- callSignal.throwIfAborted();
2286
- }
2287
- params.recordExchange?.result(toolResult);
2288
- return {
2289
- content: toolResult.content,
2290
- isError: toolResult.is_error === true,
2291
- abort: toolResult.abort === true,
2292
- terminalCode: toolResult.terminalCode,
2293
- stop: toolResult.is_error !== true && params.stopAfterSuccessfulTools.includes(call.name),
2294
- };
2295
- },
2296
- };
2297
- }
2298
- /**
2299
- * Give one Codex-native child its OWN authority.
2300
- *
2301
- * The parent's bridge closes over an envelope issued for the PARENT's wall, which the
2302
- * child cannot renew - inheriting it meant a long delegated run losing every tool
2303
- * mid-flight and still reporting "done". So the child gets: its own model run under the
2304
- * parent's, its own envelope from a host issuer, its own execution context, and its own
2305
- * bridge counters. When no issuer is reachable it gets nothing and says so - the process
2306
- * refuses its calls with `subagent authority unavailable` rather than quietly borrowing.
2307
- */
2308
- async createSubagentBridge(info) {
2309
- const context = this.subagentRunContexts.get(info.sessionKey);
2310
- if (!context) {
2311
- console.warn(`[AgentLoop] subagent authority unavailable: no run context for session ${info.sessionKey} ` +
2312
- `(thread=${info.agentThreadId})`);
2313
- return null;
2314
- }
2315
- if (context.runFinished) {
2316
- // Only a child announced DURING the run inherits that run's issuer. A finished run
2317
- // stays reachable while a sibling is live; it must not mint authority hours later.
2318
- console.warn(`[AgentLoop] subagent authority refused: run for session ${info.sessionKey} already ended ` +
2319
- `(thread=${info.agentThreadId})`);
2320
- return null;
2321
- }
2322
- // Claimed synchronously: the parent's finally must not drop the context while this
2323
- // factory is still awaiting an envelope or a model run.
2324
- context.activeChildren += 1;
2325
- const abandon = (reason) => {
2326
- console.warn(reason);
2327
- this.releaseSubagentRunContext(info.sessionKey, context);
2328
- return null;
2329
- };
2330
- const issuer = context.options.prepareSubagentEnvelope ?? context.options.prepareEnvelope;
2331
- if (!issuer) {
2332
- return abandon(`[AgentLoop] subagent authority unavailable: no host envelope issuer for ${info.sessionKey} ` +
2333
- `(thread=${info.agentThreadId})`);
2334
- }
2335
- let envelope;
2336
- try {
2337
- envelope = await issuer();
2338
- }
2339
- catch (error) {
2340
- return abandon(`[AgentLoop] subagent authority issuance failed thread=${info.agentThreadId}: ${error instanceof Error ? error.message : String(error)}`);
2341
- }
2342
- if (!envelope) {
2343
- return abandon(`[AgentLoop] subagent authority unavailable: issuer returned no envelope ` +
2344
- `(thread=${info.agentThreadId})`);
2345
- }
2346
- const childOptions = {
2347
- ...context.options,
2348
- envelope,
2349
- prepareEnvelope: undefined,
2350
- parentModelRunId: context.parentModelRunId,
2351
- sourceMessageRef: `subagent:${info.agentThreadId}`,
2352
- };
2353
- let modelRunId;
2354
- try {
2355
- const modelRun = await this.mcpExecutor.beginRuntimeModelRun(this.buildModelRunInput(childOptions, context.cliSessionId));
2356
- modelRunId = modelRun.model_run_id;
2357
- }
2358
- catch (error) {
2359
- return abandon(`[AgentLoop] subagent model run could not begin thread=${info.agentThreadId}: ${error instanceof Error ? error.message : String(error)}`);
2360
- }
2361
- const childTasks = [];
2362
- const backgroundTasks = {
2363
- register(task) {
2364
- const observedTask = Promise.resolve(task);
2365
- observedTask.catch(() => {
2366
- // Re-thrown later by the child's release drain.
2367
- });
2368
- childTasks.push(observedTask);
2369
- },
2370
- };
2371
- let childContext;
2372
- let bridge;
2373
- // The child's model run is already OPEN. Anything that throws while assembling its
2374
- // context or bridge must fail that run and release the parent's context, or the run
2375
- // stays `running` forever and the context stays pinned by a child that never existed.
2376
- try {
2377
- childContext = this.withBackgroundTaskRegistry(this.buildToolExecutionContext({ ...childOptions, modelRunId }), backgroundTasks);
2378
- if (childContext) {
2379
- childContext = { ...childContext, subagentThreadId: info.agentThreadId };
2380
- }
2381
- // The child's own run scope: no stream callbacks, no onTurn, no onToolUse. Its work
2382
- // is not this run's turns, and the parent's model run is already committed by then.
2383
- const runScope = { tier: context.tier, ...(0, temporal_code_act_breaker_js_1.createTemporalCodeActBreakerState)() };
2384
- bridge = this.buildHostToolBridge({
2385
- tools: context.tools,
2386
- runScope,
2387
- executionContext: () => childContext,
2388
- stopAfterSuccessfulTools: [],
2389
- emergencyMaxCalls: this.emergencyMaxCalls(),
2390
- maxConsecutiveSameTool: MAX_CONSECUTIVE_SAME_HOST_TOOL,
2391
- });
2392
- }
2393
- catch (error) {
2394
- const summary = error instanceof Error ? error.message : String(error);
2395
- try {
2396
- await this.mcpExecutor.failRuntimeModelRun(modelRunId, `subagent authority could not be assembled: ${summary}`);
2397
- }
2398
- catch (failError) {
2399
- logger.warn(`Failed to mark subagent model run ${modelRunId} failed: ${failError instanceof Error ? failError.message : String(failError)}`);
2400
- }
2401
- return abandon(`[AgentLoop] subagent authority could not be assembled thread=${info.agentThreadId}: ${summary}`);
2402
- }
2403
- let released = false;
2404
- return {
2405
- bridge,
2406
- release: async (outcome) => {
2407
- if (released) {
2408
- return;
2409
- }
2410
- released = true;
2411
- try {
2412
- await this.drainBackgroundTasks(childTasks);
2413
- }
2414
- catch (error) {
2415
- logger.warn(`AgentLoop subagent background drain failed: ${error instanceof Error ? error.message : String(error)}`);
2416
- }
2417
- try {
2418
- if (outcome.status === 'completed') {
2419
- await this.mcpExecutor.commitRuntimeModelRun(modelRunId, `agent_loop subagent ${info.agentPath || info.agentThreadId} completed`);
2420
- }
2421
- else {
2422
- // `unknown` is not success: the run is marked failed with the reason so the
2423
- // ledger never carries a completion nobody confirmed.
2424
- await this.mcpExecutor.failRuntimeModelRun(modelRunId, outcome.error ?? `subagent ${outcome.status}`);
2425
- }
2426
- }
2427
- catch (error) {
2428
- logger.warn(`AgentLoop subagent model run ${modelRunId} could not be closed: ${error instanceof Error ? error.message : String(error)}`);
2429
- }
2430
- this.mcpExecutor.releaseProcedureRun?.(childContext);
2431
- this.releaseSubagentRunContext(info.sessionKey, context);
2432
- },
2433
- };
2434
- }
2435
- /** Drop a run's subagent context once the run finished and no child still holds it. */
2436
- releaseSubagentRunContext(sessionKey, context) {
2437
- context.activeChildren = Math.max(0, context.activeChildren - 1);
2438
- if (context.runFinished &&
2439
- context.activeChildren === 0 &&
2440
- this.subagentRunContexts.get(sessionKey) === context) {
2441
- this.subagentRunContexts.delete(sessionKey);
2442
- }
2443
- }
2444
- /**
2445
- * Execute tools from response content blocks
2446
- */
2447
- async executeTools(content, stopAfterSuccessfulTools = [], executionContext = null, runScope = { tier: 1, ...(0, temporal_code_act_breaker_js_1.createTemporalCodeActBreakerState)() }) {
2448
- const modelToolContext = withExecutionSurface(executionContext, 'model_tool');
2449
- const reactiveInternalContext = withExecutionSurface(executionContext, 'reactive_internal');
2450
- const toolUseBlocks = content.filter((block) => block.type === 'tool_use');
2451
- const results = [];
2452
- for (const toolUse of toolUseBlocks) {
2453
- let result;
2454
- let isError = false;
2455
- let abort = false;
2456
- let terminalCode;
2457
- const executionToolName = toolUse.name === CODE_ACT_MCP_COMPAT_NAME ? index_js_1.CODE_ACT_MARKER : toolUse.name;
2458
- // Notify stream: tool execution starting
2459
- runScope.streamCallbacks?.onToolUse?.(executionToolName, toolUse.input);
2460
- const toolStart = Date.now();
2461
- try {
2462
- // PreToolUse: search MAMA for contracts before Write operations
2463
- let contractContext = '';
2464
- if (executionToolName === 'Write' && toolUse.input) {
2465
- contractContext = await this.searchContractsForTool(executionToolName, toolUse.input, reactiveInternalContext);
2466
- }
2467
- const temporalCodeAct = executionToolName === index_js_1.CODE_ACT_MARKER &&
2468
- modelToolContext?.temporalWorkContext !== undefined;
2469
- let codeActExecuted = false;
2470
- let toolResult;
2471
- if (temporalCodeAct) {
2472
- const callDecision = (0, temporal_code_act_breaker_js_1.beginTemporalCodeActCall)(runScope);
2473
- applyTemporalCodeActBreakerState(runScope, callDecision.state);
2474
- if (callDecision.terminal) {
2475
- toolResult = temporalCodeActTerminalResult(callDecision);
2476
- }
2477
- else {
2478
- codeActExecuted = true;
2479
- toolResult = await this.mcpExecutor.execute(executionToolName, toolUse.input, modelToolContext);
2480
- }
2481
- }
2482
- else {
2483
- toolResult = await this.mcpExecutor.execute(executionToolName, toolUse.input, modelToolContext ?? undefined);
2484
- }
2485
- let toolResultRecord = toolResult;
2486
- const existingTerminal = toolResultRecord.abort === true &&
2487
- toolResultRecord.retryable === false &&
2488
- (0, model_runner_js_1.isHostToolTerminalCode)(toolResultRecord.code);
2489
- if (temporalCodeAct && codeActExecuted && !existingTerminal) {
2490
- const resultDecision = (0, temporal_code_act_breaker_js_1.observeTemporalCodeActResult)(runScope, {
2491
- success: toolResult.success,
2492
- hostToolExecutions: toolResultRecord.hostToolExecutions,
2493
- });
2494
- applyTemporalCodeActBreakerState(runScope, resultDecision.state);
2495
- if (resultDecision.terminal) {
2496
- toolResult = temporalCodeActTerminalResult(resultDecision);
2497
- toolResultRecord = toolResult;
2498
- }
2499
- }
2500
- result =
2501
- executionToolName === index_js_1.CODE_ACT_MARKER
2502
- ? (0, gateway_tool_executor_js_1.serializeCodeActModelResult)(toolResult)
2503
- : JSON.stringify(toolResult, null, 2);
2504
- // Check if tool execution failed
2505
- const hasSuccess = 'success' in toolResult;
2506
- const toolFailed = hasSuccess && !toolResult.success;
2507
- if (toolFailed) {
2508
- isError = true;
2509
- }
2510
- abort = toolResultRecord.abort === true;
2511
- terminalCode =
2512
- abort &&
2513
- toolResultRecord.retryable === false &&
2514
- (0, model_runner_js_1.isHostToolTerminalCode)(toolResultRecord.code)
2515
- ? toolResultRecord.code
2516
- : undefined;
2517
- if (contractContext) {
2518
- result = `${contractContext}\n\n---\n\n${result}`;
2519
- }
2520
- // Notify tool use callback
2521
- runScope.onToolUse?.(executionToolName, toolUse.input, toolResult);
2522
- // PostToolUse: auto-extract contracts (fire-and-forget)
2523
- this.postToolHandler?.processInBackground(executionToolName, toolUse.input, toolResult, reactiveInternalContext);
2524
- // Notify stream: tool completed (check actual status)
2525
- runScope.streamCallbacks?.onToolComplete?.(executionToolName, toolUse.id, isError);
2526
- // Emit tool execution metric
2527
- this.onMetric?.('tool_duration_ms', Date.now() - toolStart, {
2528
- tool: executionToolName,
2529
- error: String(isError),
2530
- });
2531
- }
2532
- catch (error) {
2533
- isError = true;
2534
- result = error instanceof Error ? error.message : String(error);
2535
- // Notify tool use callback with error
2536
- runScope.onToolUse?.(executionToolName, toolUse.input, { error: result });
2537
- this.onMetric?.('tool_duration_ms', Date.now() - toolStart, {
2538
- tool: executionToolName,
2539
- error: 'true',
2540
- });
2541
- // Notify stream: tool completed with error
2542
- runScope.streamCallbacks?.onToolComplete?.(executionToolName, toolUse.id, true);
2543
- }
2544
- results.push({
2545
- type: 'tool_result',
2546
- tool_use_id: toolUse.id,
2547
- content: result,
2548
- is_error: isError,
2549
- ...(abort ? { abort: true } : {}),
2550
- ...(terminalCode ? { terminalCode } : {}),
2551
- });
2552
- if (abort) {
2553
- break;
2554
- }
2555
- if (!isError && stopAfterSuccessfulTools.includes(executionToolName)) {
2556
- break;
2557
- }
2558
- }
2559
- return results;
2560
- }
2561
- /**
2562
- * Search MAMA for contracts related to a tool operation.
2563
- * Used as PreToolUse interceptor — searches for contract_* topics
2564
- * related to the file being written/edited.
2565
- *
2566
- * Non-blocking: returns empty string if search fails or no contracts found.
2567
- */
2568
- async searchContractsForTool(_toolName, input, executionContext = null) {
2569
- try {
2570
- const filePath = input.path;
2571
- if (!filePath) {
2572
- return '';
2573
- }
2574
- const fileName = filePath.split('/').pop() || filePath;
2575
- const searchQuery = `contract ${fileName}`;
2576
- const searchResult = await this.mcpExecutor.execute('mama_search', {
2577
- query: searchQuery,
2578
- limit: 3,
2579
- }, executionContext ?? undefined);
2580
- if (searchResult && typeof searchResult === 'object' && 'results' in searchResult) {
2581
- const typedResult = searchResult;
2582
- const contractResults = typedResult.results.filter((r) => r.topic?.startsWith('contract_'));
2583
- if (contractResults.length > 0) {
2584
- const lines = contractResults.map((r) => `- **${r.topic}**: ${r.decision} (confidence: ${r.confidence ?? 'unknown'})`);
2585
- return (`## PreToolUse: Related Contracts Found\n\n` +
2586
- `Before writing to \`${fileName}\`, review these existing contracts:\n\n` +
2587
- `${lines.join('\n')}\n\n` +
2588
- `Ensure your changes are consistent with these contracts.`);
2589
- }
2590
- }
2591
- return '';
2592
- }
2593
- catch {
2594
- // Non-blocking: silently return empty on any error
2595
- return '';
2596
- }
2597
- }
2598
- /**
2599
- * Parse tool_call blocks from text response (Gateway Tools mode)
2600
- * Format: ```tool_call\n{"name": "...", "input": {...}}\n```
2601
- */
2602
- parseToolCallsFromText(text) {
2603
- const toolCalls = [];
2604
- const toolCallRegex = /```tool_call\s*\n([\s\S]*?)\n```/g;
2605
- let match;
2606
- while ((match = toolCallRegex.exec(text)) !== null) {
2607
- try {
2608
- const jsonStr = match[1].trim();
2609
- const parsed = JSON.parse(jsonStr);
2610
- if (parsed.name && typeof parsed.name === 'string') {
2611
- toolCalls.push({
2612
- type: 'tool_use',
2613
- id: `gateway_tool_${(0, crypto_1.randomUUID)()}`,
2614
- name: parsed.name,
2615
- input: parsed.input || {},
2616
- });
2617
- }
2618
- }
2619
- catch (e) {
2620
- console.warn(`[AgentLoop] Failed to parse tool_call block: ${e}`);
2621
- }
2622
- }
2623
- return toolCalls;
2624
- }
2625
- /**
2626
- * Parse ```js code blocks as code_act tool calls (Code-Act mode)
2627
- */
2628
- parseCodeActBlocks(text) {
2629
- const blocks = [];
2630
- const codeActRegex = /```(?:js|javascript)\s*\n([\s\S]*?)\n```/g;
2631
- let match;
2632
- while ((match = codeActRegex.exec(text)) !== null) {
2633
- const code = match[1].trim();
2634
- if (code) {
2635
- blocks.push({
2636
- type: 'tool_use',
2637
- id: `code_act_${(0, crypto_1.randomUUID)()}`,
2638
- name: index_js_1.CODE_ACT_MARKER,
2639
- input: { code },
2640
- });
2641
- }
2642
- }
2643
- return blocks;
2644
- }
2645
- /**
2646
- * Remove tool_call and code_act blocks from text (to avoid duplication in response)
2647
- */
2648
- removeToolCallBlocks(text) {
2649
- let result = text.replace(/```tool_call\s*\n[\s\S]*?\n```/g, '');
2650
- if (this.useCodeAct) {
2651
- result = result.replace(/```(?:js|javascript)\s*\n[\s\S]*?\n```/g, '');
2652
- }
2653
- return result.trim();
2654
- }
2655
- extractTextFromContent(content) {
2656
- return content
2657
- .filter((block) => block.type === 'text')
2658
- .map((block) => block.text)
2659
- .join('\n');
2660
- }
2661
- /**
2662
- * Extract text response from the last assistant message
2663
- */
2664
- /**
2665
- * Tokens a turn counts against the run budget. Anthropic reports cache reads and
2666
- * cache creation OUTSIDE input_tokens; codex (OpenAI usage) reports inputTokens
2667
- * inclusive of cachedInputTokens. Adding cache reads for codex doubled every count
2668
- * in 0.44.0 (a 2.8M wiki turn read as 5.5M and was stopped).
2669
- */
2670
- countBudgetTokens(usage) {
2671
- const base = usage.input_tokens + usage.output_tokens;
2672
- if (this.backend === 'codex') {
2673
- return base;
2674
- }
2675
- return base + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
2676
- }
2677
- extractTextResponse(history) {
2678
- // Find the last assistant message
2679
- for (let i = history.length - 1; i >= 0; i--) {
2680
- const message = history[i];
2681
- if (message.role === 'assistant') {
2682
- const content = message.content;
2683
- if (typeof content === 'string') {
2684
- return content;
2685
- }
2686
- // Extract text blocks
2687
- const textBlocks = content.filter((block) => block.type === 'text');
2688
- return textBlocks.map((block) => block.text).join('\n');
2689
- }
2690
- }
2691
- return '';
2692
- }
2693
- /**
2694
- * Format only the last user message for persistent CLI
2695
- * Persistent CLI maintains context automatically, so we only send the new message
2696
- */
2697
- /**
2698
- * Turn 1 only, once the backend has said whether the thread is live: a fresh or re-opened
2699
- * thread is told the relevant procedures once, a live thread only what it has not been
2700
- * told (procedure-runtime.ts). Later turns of a run carry tool results, not hints.
2701
- */
2702
- withProcedureHints(basePromptText, turn, input) {
2703
- if (turn !== 1)
2704
- return basePromptText;
2705
- const hints = this.mcpExecutor.prepareProcedureContext?.(input.context, {
2706
- threadId: input.threadId,
2707
- fresh: input.fresh,
2708
- });
2709
- // Logged even when empty: with no procedures stored, this is the only sign the
2710
- // assembler ran and the thread decision it saw.
2711
- console.log(`[experience] thread=${input.threadId} fresh=${input.fresh} hints=${hints?.hints.length ?? 0}${hints?.hints.length ? `(${hints.hints.join(',')})` : ''} chars=${hints?.text.length ?? 0}`);
2712
- if (!hints?.text)
2713
- return basePromptText;
2714
- return `${hints.text}\n\n${basePromptText}`;
2715
- }
2716
- async observeCompletionClaim(modelRunId, finalResponse) {
2717
- const claim = finalResponse.match(COMPLETION_CLAIM_PATTERN)?.[0];
2718
- if (!claim || !modelRunId)
2719
- return;
2720
- try {
2721
- const wrote = await this.mcpExecutor.runHadDurableWrite?.(modelRunId);
2722
- if (wrote === false) {
2723
- console.warn(`[evidence] completion claim without a durable write: run=${modelRunId} claim="${claim}"`);
2724
- }
2725
- }
2726
- catch (error) {
2727
- console.warn(`[evidence] claim check unavailable: ${error instanceof Error ? error.message : String(error)}`);
2728
- }
2729
- }
2730
- formatLastMessageOnly(history) {
2731
- const imageReaderTool = this.backend === 'cline' ? 'read_files' : this.backend === 'codex' ? 'view_image' : 'Read';
2732
- // Find the last user message in the history
2733
- for (let i = history.length - 1; i >= 0; i--) {
2734
- const msg = history[i];
2735
- if (msg.role === 'user') {
2736
- const content = msg.content;
2737
- let text;
2738
- if (typeof content === 'string') {
2739
- text = content;
2740
- }
2741
- else if (Array.isArray(content)) {
2742
- const parts = [];
2743
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
2744
- for (const block of content) {
2745
- if (block.type === 'text') {
2746
- parts.push(block.text);
2747
- }
2748
- else if (block.type === 'image' && block.localPath) {
2749
- parts.push(`⚠️ CRITICAL: The user has uploaded an image file.\n` +
2750
- `Image path: ${block.localPath}\n` +
2751
- `You MUST call the ${imageReaderTool} tool on "${block.localPath}" to view this image FIRST.\n` +
2752
- `DO NOT describe or guess the image contents without reading it.\n` +
2753
- `DO NOT say you cannot read images - ${imageReaderTool} supports image files.`);
2754
- }
2755
- else if (block.type === 'image' && block.source?.data) {
2756
- // Base64-encoded image — save to disk so persistent CLI can read it
2757
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2758
- const fs = require('fs');
2759
- // eslint-disable-next-line @typescript-eslint/no-require-imports
2760
- const path = require('path');
2761
- const mediaDir = path.join((0, os_1.homedir)(), '.mama', 'workspace', 'media', 'inbound');
2762
- fs.mkdirSync(mediaDir, { recursive: true });
2763
- // Map MIME type to file extension (support PNG, JPEG, GIF, WebP)
2764
- const mimeToExt = {
2765
- 'image/png': '.png',
2766
- 'image/jpeg': '.jpg',
2767
- 'image/jpg': '.jpg',
2768
- 'image/gif': '.gif',
2769
- 'image/webp': '.webp',
2770
- };
2771
- const ext = mimeToExt[block.source.media_type?.toLowerCase() || ''] || '.jpg';
2772
- const imagePath = path.join(mediaDir, `${Date.now()}-${(0, crypto_1.randomUUID)().slice(0, 8)}${ext}`);
2773
- try {
2774
- fs.writeFileSync(imagePath, Buffer.from(block.source.data, 'base64'));
2775
- parts.push(`⚠️ CRITICAL: The user has uploaded an image file.\n` +
2776
- `Image path: ${imagePath}\n` +
2777
- `You MUST call the ${imageReaderTool} tool on "${imagePath}" to view this image FIRST.\n` +
2778
- `DO NOT describe or guess the image contents without reading it.\n` +
2779
- `DO NOT say you cannot read images - ${imageReaderTool} supports image files.`);
2780
- }
2781
- catch {
2782
- parts.push('[Image attached but could not be processed]');
2783
- }
2784
- }
2785
- else if (block.type === 'tool_result') {
2786
- const status = block.is_error ? 'ERROR' : 'SUCCESS';
2787
- parts.push(`[Tool Result: ${status}]\n${block.content}`);
2788
- }
2789
- else if (block.type === 'tool_use') {
2790
- parts.push(`[Tool Call: ${block.name}]\nInput: ${JSON.stringify(block.input, null, 2)}`);
2791
- }
2792
- }
2793
- text = parts.join('\n');
2794
- }
2795
- else {
2796
- text = '';
2797
- }
2798
- return text;
2799
- }
2800
- }
2801
- // Fallback: if no user message found, return empty string
2802
- return '';
2803
- }
2804
- /**
2805
- * Get the MAMA tool definitions
2806
- */
2807
- static getToolDefinitions() {
2808
- return [];
2809
- }
2810
- /**
2811
- * Get the default system prompt (verbose logging)
2812
- */
2813
- static getDefaultSystemPrompt() {
2814
- return loadSystemPrompt(true);
2815
- }
2816
- /**
2817
- * Stop and cleanup the AgentLoop resources
2818
- */
2819
- stopped = false;
2820
- async stop() {
2821
- if (this.stopped)
2822
- return;
2823
- this.stopped = true;
2824
- try {
2825
- // Stop the model runner
2826
- await this.agent.stop();
2827
- const waitUntil = Date.now() + 5000;
2828
- while (this.laneManager.getTotalQueueSize() > 0 && Date.now() < waitUntil) {
2829
- await new Promise((resolve) => setTimeout(resolve, 50));
2830
- }
2831
- // NOTE: sessionPool is a shared global singleton — do NOT dispose here.
2832
- // It will be cleaned up when the process exits or via a global shutdown handler.
2833
- // Lane manager doesn't have explicit stop method
2834
- // Let it be cleaned up by garbage collection
2835
- }
2836
- catch (error) {
2837
- console.error('Error during AgentLoop cleanup:', error);
2838
- }
2839
- }
2840
- }
2841
- exports.AgentLoop = AgentLoop;
2842
- //# sourceMappingURL=agent-loop.js.map