@downcity/agent 1.1.430 → 1.1.437

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 (488) hide show
  1. package/README.md +13 -11
  2. package/bin/agent/Agent.d.ts +3 -3
  3. package/bin/agent/Agent.d.ts.map +1 -1
  4. package/bin/agent/Agent.js +38 -8
  5. package/bin/agent/Agent.js.map +1 -1
  6. package/bin/agent/AgentInstructions.js +2 -2
  7. package/bin/agent/AgentInstructions.js.map +1 -1
  8. package/bin/agent/AgentMemoryStorage.d.ts.map +1 -1
  9. package/bin/agent/AgentMemoryStorage.js +1 -0
  10. package/bin/agent/AgentMemoryStorage.js.map +1 -1
  11. package/bin/agent/AgentSessions.d.ts +5 -1
  12. package/bin/agent/AgentSessions.d.ts.map +1 -1
  13. package/bin/agent/AgentSessions.js +17 -9
  14. package/bin/agent/AgentSessions.js.map +1 -1
  15. package/bin/executor/Executor.d.ts +9 -27
  16. package/bin/executor/Executor.d.ts.map +1 -1
  17. package/bin/executor/Executor.js +32 -127
  18. package/bin/executor/Executor.js.map +1 -1
  19. package/bin/executor/composer/system/default/SystemPromptAssets.d.ts +0 -4
  20. package/bin/executor/composer/system/default/SystemPromptAssets.d.ts.map +1 -1
  21. package/bin/executor/composer/system/default/SystemPromptAssets.js +0 -5
  22. package/bin/executor/composer/system/default/SystemPromptAssets.js.map +1 -1
  23. package/bin/executor/core-engine/CoreEngineContextCompaction.d.ts +3 -9
  24. package/bin/executor/core-engine/CoreEngineContextCompaction.d.ts.map +1 -1
  25. package/bin/executor/core-engine/CoreEngineContextCompaction.js +4 -130
  26. package/bin/executor/core-engine/CoreEngineContextCompaction.js.map +1 -1
  27. package/bin/executor/core-engine/CoreEngineRunner.d.ts +3 -30
  28. package/bin/executor/core-engine/CoreEngineRunner.d.ts.map +1 -1
  29. package/bin/executor/core-engine/CoreEngineRunner.js +38 -194
  30. package/bin/executor/core-engine/CoreEngineRunner.js.map +1 -1
  31. package/bin/executor/core-engine/CoreEngineSignals.d.ts +6 -6
  32. package/bin/executor/core-engine/CoreEngineSignals.d.ts.map +1 -1
  33. package/bin/executor/core-engine/CoreEngineSignals.js +1 -1
  34. package/bin/executor/core-engine/CoreEngineSignals.js.map +1 -1
  35. package/bin/executor/messages/SessionAttachmentMapper.d.ts +2 -2
  36. package/bin/executor/messages/SessionAttachmentMapper.d.ts.map +1 -1
  37. package/bin/executor/messages/SessionAttachmentMapper.js.map +1 -1
  38. package/bin/executor/messages/SessionMessageLog.d.ts +3 -3
  39. package/bin/executor/messages/SessionMessageLog.d.ts.map +1 -1
  40. package/bin/executor/messages/SessionMessageLog.js.map +1 -1
  41. package/bin/executor/messages/SessionModelMessages.d.ts +0 -3
  42. package/bin/executor/messages/SessionModelMessages.d.ts.map +1 -1
  43. package/bin/executor/messages/SessionModelMessages.js +80 -97
  44. package/bin/executor/messages/SessionModelMessages.js.map +1 -1
  45. package/bin/executor/model/ModelStepRunner.d.ts +2 -6
  46. package/bin/executor/model/ModelStepRunner.d.ts.map +1 -1
  47. package/bin/executor/model/ModelStepRunner.js +0 -28
  48. package/bin/executor/model/ModelStepRunner.js.map +1 -1
  49. package/bin/executor/services/ExecutorRecoveryPolicy.d.ts +7 -64
  50. package/bin/executor/services/ExecutorRecoveryPolicy.d.ts.map +1 -1
  51. package/bin/executor/services/ExecutorRecoveryPolicy.js +29 -45
  52. package/bin/executor/services/ExecutorRecoveryPolicy.js.map +1 -1
  53. package/bin/executor/types/SessionHistoryMeta.d.ts +1 -3
  54. package/bin/executor/types/SessionHistoryMeta.d.ts.map +1 -1
  55. package/bin/executor/types/SessionHistoryMeta.js +1 -1
  56. package/bin/index.d.ts +9 -13
  57. package/bin/index.d.ts.map +1 -1
  58. package/bin/index.js +2 -4
  59. package/bin/index.js.map +1 -1
  60. package/bin/session/DefaultSessionComposer.d.ts +13 -7
  61. package/bin/session/DefaultSessionComposer.d.ts.map +1 -1
  62. package/bin/session/DefaultSessionComposer.js +26 -21
  63. package/bin/session/DefaultSessionComposer.js.map +1 -1
  64. package/bin/session/Session.d.ts +12 -19
  65. package/bin/session/Session.d.ts.map +1 -1
  66. package/bin/session/Session.js +70 -202
  67. package/bin/session/Session.js.map +1 -1
  68. package/bin/session/SessionComposition.d.ts +0 -2
  69. package/bin/session/SessionComposition.d.ts.map +1 -1
  70. package/bin/session/SessionComposition.js +30 -54
  71. package/bin/session/SessionComposition.js.map +1 -1
  72. package/bin/session/SessionLoop.d.ts +17 -16
  73. package/bin/session/SessionLoop.d.ts.map +1 -1
  74. package/bin/session/SessionLoop.js +217 -320
  75. package/bin/session/SessionLoop.js.map +1 -1
  76. package/bin/session/SessionMessages.d.ts +52 -44
  77. package/bin/session/SessionMessages.d.ts.map +1 -1
  78. package/bin/session/SessionMessages.js +285 -187
  79. package/bin/session/SessionMessages.js.map +1 -1
  80. package/bin/session/SessionQueue.d.ts +1 -1
  81. package/bin/session/SessionQueue.d.ts.map +1 -1
  82. package/bin/session/SessionQueue.js +2 -1
  83. package/bin/session/SessionQueue.js.map +1 -1
  84. package/bin/session/SessionState.d.ts +3 -7
  85. package/bin/session/SessionState.d.ts.map +1 -1
  86. package/bin/session/SessionState.js +50 -89
  87. package/bin/session/SessionState.js.map +1 -1
  88. package/bin/session/SessionSystem.d.ts +5 -1
  89. package/bin/session/SessionSystem.d.ts.map +1 -1
  90. package/bin/session/SessionSystem.js +40 -0
  91. package/bin/session/SessionSystem.js.map +1 -1
  92. package/bin/session/SessionTitle.d.ts +3 -3
  93. package/bin/session/SessionTitle.d.ts.map +1 -1
  94. package/bin/session/SessionTitle.js +2 -2
  95. package/bin/session/browse/Browse.d.ts +32 -46
  96. package/bin/session/browse/Browse.d.ts.map +1 -1
  97. package/bin/session/browse/Browse.js +104 -360
  98. package/bin/session/browse/Browse.js.map +1 -1
  99. package/bin/session/browse/SessionMessageTimeline.d.ts.map +1 -1
  100. package/bin/session/browse/SessionMessageTimeline.js +61 -37
  101. package/bin/session/browse/SessionMessageTimeline.js.map +1 -1
  102. package/bin/session/composer/policies/AdaptivePartContextPolicy.d.ts +35 -0
  103. package/bin/session/composer/policies/AdaptivePartContextPolicy.d.ts.map +1 -0
  104. package/bin/session/composer/policies/AdaptivePartContextPolicy.js +256 -0
  105. package/bin/session/composer/policies/AdaptivePartContextPolicy.js.map +1 -0
  106. package/bin/session/composer/policies/FullHistoryContextPolicy.d.ts +24 -0
  107. package/bin/session/composer/policies/FullHistoryContextPolicy.d.ts.map +1 -0
  108. package/bin/session/composer/policies/FullHistoryContextPolicy.js +31 -0
  109. package/bin/session/composer/policies/FullHistoryContextPolicy.js.map +1 -0
  110. package/bin/session/composer/policies/SessionSummaryPrompts.d.ts +16 -0
  111. package/bin/session/composer/policies/SessionSummaryPrompts.d.ts.map +1 -0
  112. package/bin/session/composer/policies/SessionSummaryPrompts.js +32 -0
  113. package/bin/session/composer/policies/SessionSummaryPrompts.js.map +1 -0
  114. package/bin/session/execution/SessionAssistantOutputAdapter.d.ts +15 -4
  115. package/bin/session/execution/SessionAssistantOutputAdapter.d.ts.map +1 -1
  116. package/bin/session/execution/SessionAssistantOutputAdapter.js +7 -3
  117. package/bin/session/execution/SessionAssistantOutputAdapter.js.map +1 -1
  118. package/bin/session/messages/{SessionActionMessageWriter.d.ts → SessionAgentActionPartWriter.d.ts} +7 -7
  119. package/bin/session/messages/SessionAgentActionPartWriter.d.ts.map +1 -0
  120. package/bin/session/messages/{SessionActionMessageWriter.js → SessionAgentActionPartWriter.js} +7 -7
  121. package/bin/session/messages/SessionAgentActionPartWriter.js.map +1 -0
  122. package/bin/session/messages/SessionAgentContent.d.ts +10 -0
  123. package/bin/session/messages/SessionAgentContent.d.ts.map +1 -0
  124. package/bin/session/messages/SessionAgentContent.js +44 -0
  125. package/bin/session/messages/SessionAgentContent.js.map +1 -0
  126. package/bin/session/messages/SessionAgentMessageState.d.ts +50 -0
  127. package/bin/session/messages/SessionAgentMessageState.d.ts.map +1 -0
  128. package/bin/session/messages/SessionAgentMessageState.js +283 -0
  129. package/bin/session/messages/SessionAgentMessageState.js.map +1 -0
  130. package/bin/session/messages/{SessionAssistantMessageWriter.d.ts → SessionAgentMessageWriter.d.ts} +22 -8
  131. package/bin/session/messages/SessionAgentMessageWriter.d.ts.map +1 -0
  132. package/bin/session/messages/{SessionAssistantMessageWriter.js → SessionAgentMessageWriter.js} +54 -42
  133. package/bin/session/messages/SessionAgentMessageWriter.js.map +1 -0
  134. package/bin/session/messages/SessionForkMessageFiles.d.ts +11 -0
  135. package/bin/session/messages/SessionForkMessageFiles.d.ts.map +1 -1
  136. package/bin/session/messages/SessionForkMessageFiles.js +8 -2
  137. package/bin/session/messages/SessionForkMessageFiles.js.map +1 -1
  138. package/bin/session/messages/SessionMessageInteractionWriter.d.ts +6 -6
  139. package/bin/session/messages/SessionMessageInteractionWriter.d.ts.map +1 -1
  140. package/bin/session/messages/SessionMessageInteractionWriter.js +4 -4
  141. package/bin/session/messages/SessionMessageInteractionWriter.js.map +1 -1
  142. package/bin/session/messages/SessionMessageText.d.ts +3 -3
  143. package/bin/session/messages/SessionMessageText.d.ts.map +1 -1
  144. package/bin/session/messages/SessionMessageText.js +0 -2
  145. package/bin/session/messages/SessionMessageText.js.map +1 -1
  146. package/bin/session/messages/SessionTurnFileDiffData.d.ts +3 -3
  147. package/bin/session/messages/SessionTurnFileDiffData.d.ts.map +1 -1
  148. package/bin/session/messages/SessionTurnFileDiffData.js.map +1 -1
  149. package/bin/session/messages/SessionUserMessage.d.ts +3 -3
  150. package/bin/session/messages/SessionUserMessage.d.ts.map +1 -1
  151. package/bin/session/messages/SessionUserMessage.js +6 -3
  152. package/bin/session/messages/SessionUserMessage.js.map +1 -1
  153. package/bin/session/preview/SessionMessagePreview.d.ts.map +1 -1
  154. package/bin/session/preview/SessionMessagePreview.js +25 -9
  155. package/bin/session/preview/SessionMessagePreview.js.map +1 -1
  156. package/bin/session/runtime/SessionTurnCompletion.d.ts +15 -0
  157. package/bin/session/runtime/SessionTurnCompletion.d.ts.map +1 -0
  158. package/bin/session/runtime/SessionTurnCompletion.js +126 -0
  159. package/bin/session/runtime/SessionTurnCompletion.js.map +1 -0
  160. package/bin/session/runtime/SessionTurnContext.d.ts.map +1 -1
  161. package/bin/session/runtime/SessionTurnContext.js +14 -19
  162. package/bin/session/runtime/SessionTurnContext.js.map +1 -1
  163. package/bin/session/runtime/SessionTurnFileDiff.d.ts +12 -0
  164. package/bin/session/runtime/SessionTurnFileDiff.d.ts.map +1 -0
  165. package/bin/session/runtime/SessionTurnFileDiff.js +71 -0
  166. package/bin/session/runtime/SessionTurnFileDiff.js.map +1 -0
  167. package/bin/session/storage/LocalSessionDataStore.d.ts +6 -41
  168. package/bin/session/storage/LocalSessionDataStore.d.ts.map +1 -1
  169. package/bin/session/storage/LocalSessionDataStore.js +19 -101
  170. package/bin/session/storage/LocalSessionDataStore.js.map +1 -1
  171. package/bin/session/storage/LocalSessionStore.d.ts +13 -5
  172. package/bin/session/storage/LocalSessionStore.d.ts.map +1 -1
  173. package/bin/session/storage/LocalSessionStore.js +153 -30
  174. package/bin/session/storage/LocalSessionStore.js.map +1 -1
  175. package/bin/session/storage/LocalStorePaths.d.ts +4 -16
  176. package/bin/session/storage/LocalStorePaths.d.ts.map +1 -1
  177. package/bin/session/storage/LocalStorePaths.js +7 -31
  178. package/bin/session/storage/LocalStorePaths.js.map +1 -1
  179. package/bin/session/storage/Metadata.d.ts +4 -4
  180. package/bin/session/storage/Metadata.d.ts.map +1 -1
  181. package/bin/session/storage/Metadata.js +3 -11
  182. package/bin/session/storage/Metadata.js.map +1 -1
  183. package/bin/session/storage/RuntimeSessionPort.d.ts +4 -4
  184. package/bin/session/storage/RuntimeSessionPort.d.ts.map +1 -1
  185. package/bin/session/storage/RuntimeSessionPort.js +3 -3
  186. package/bin/session/storage/RuntimeSessionPort.js.map +1 -1
  187. package/bin/session/storage/SessionStorageCodec.d.ts +59 -0
  188. package/bin/session/storage/SessionStorageCodec.d.ts.map +1 -0
  189. package/bin/session/storage/SessionStorageCodec.js +331 -0
  190. package/bin/session/storage/SessionStorageCodec.js.map +1 -0
  191. package/bin/session/storage/SessionStorageSchema.d.ts +11 -0
  192. package/bin/session/storage/SessionStorageSchema.d.ts.map +1 -0
  193. package/bin/session/storage/SessionStorageSchema.js +131 -0
  194. package/bin/session/storage/SessionStorageSchema.js.map +1 -0
  195. package/bin/session/storage/SqliteSessionStorage.d.ts +120 -0
  196. package/bin/session/storage/SqliteSessionStorage.d.ts.map +1 -0
  197. package/bin/session/storage/SqliteSessionStorage.js +581 -0
  198. package/bin/session/storage/SqliteSessionStorage.js.map +1 -0
  199. package/bin/tools/ask/AskQuestionsTool.d.ts.map +1 -1
  200. package/bin/tools/ask/AskQuestionsTool.js +3 -1
  201. package/bin/tools/ask/AskQuestionsTool.js.map +1 -1
  202. package/bin/types/action/ActionResult.d.ts +9 -9
  203. package/bin/types/action/ActionResult.d.ts.map +1 -1
  204. package/bin/types/action/ActionResult.js +1 -1
  205. package/bin/types/agent/AgentOptions.d.ts +10 -0
  206. package/bin/types/agent/AgentOptions.d.ts.map +1 -1
  207. package/bin/types/agent/AgentStorage.d.ts +3 -1
  208. package/bin/types/agent/AgentStorage.d.ts.map +1 -1
  209. package/bin/types/agent/SessionActor.d.ts +0 -9
  210. package/bin/types/agent/SessionActor.d.ts.map +1 -1
  211. package/bin/types/agent/SessionTypes.d.ts +5 -5
  212. package/bin/types/agent/SessionTypes.d.ts.map +1 -1
  213. package/bin/types/executor/SessionAssistantOutput.d.ts +15 -4
  214. package/bin/types/executor/SessionAssistantOutput.d.ts.map +1 -1
  215. package/bin/types/executor/SessionTurnContext.d.ts +17 -19
  216. package/bin/types/executor/SessionTurnContext.d.ts.map +1 -1
  217. package/bin/types/sdk/AgentSessionAction.d.ts +1 -1
  218. package/bin/types/sdk/AgentSessionAction.js +1 -1
  219. package/bin/types/sdk/AgentSessionPrompt.d.ts +14 -5
  220. package/bin/types/sdk/AgentSessionPrompt.d.ts.map +1 -1
  221. package/bin/types/sdk/AgentSessionPrompt.js +1 -1
  222. package/bin/types/sdk/AgentSessionPrompt.js.map +1 -1
  223. package/bin/types/session/AdaptivePartContextPolicy.d.ts +31 -0
  224. package/bin/types/session/AdaptivePartContextPolicy.d.ts.map +1 -0
  225. package/bin/types/session/AdaptivePartContextPolicy.js +7 -0
  226. package/bin/types/session/AdaptivePartContextPolicy.js.map +1 -0
  227. package/bin/types/session/{SessionAssistantMessageState.d.ts → SessionAgentMessageState.d.ts} +7 -7
  228. package/bin/types/session/SessionAgentMessageState.d.ts.map +1 -0
  229. package/bin/types/session/{SessionAssistantMessageState.js → SessionAgentMessageState.js} +1 -1
  230. package/bin/types/session/SessionAgentMessageState.js.map +1 -0
  231. package/bin/types/session/SessionCommand.d.ts +19 -7
  232. package/bin/types/session/SessionCommand.d.ts.map +1 -1
  233. package/bin/types/session/SessionComposer.d.ts +43 -43
  234. package/bin/types/session/SessionComposer.d.ts.map +1 -1
  235. package/bin/types/session/SessionComposer.js +2 -2
  236. package/bin/types/session/SessionComposition.d.ts +2 -5
  237. package/bin/types/session/SessionComposition.d.ts.map +1 -1
  238. package/bin/types/session/SessionContextPolicy.d.ts +70 -0
  239. package/bin/types/session/SessionContextPolicy.d.ts.map +1 -0
  240. package/bin/types/session/SessionContextPolicy.js +8 -0
  241. package/bin/types/session/SessionContextPolicy.js.map +1 -0
  242. package/bin/types/session/SessionExecution.d.ts +5 -32
  243. package/bin/types/session/SessionExecution.d.ts.map +1 -1
  244. package/bin/types/session/SessionLoop.d.ts +3 -5
  245. package/bin/types/session/SessionLoop.d.ts.map +1 -1
  246. package/bin/types/session/SessionMessages.d.ts +18 -28
  247. package/bin/types/session/SessionMessages.d.ts.map +1 -1
  248. package/bin/types/session/SessionOptions.d.ts +5 -5
  249. package/bin/types/session/SessionOptions.d.ts.map +1 -1
  250. package/bin/types/session/SessionPort.d.ts +8 -9
  251. package/bin/types/session/SessionPort.d.ts.map +1 -1
  252. package/bin/types/session/SessionState.d.ts +2 -5
  253. package/bin/types/session/SessionState.d.ts.map +1 -1
  254. package/bin/types/session/SessionSystem.d.ts +14 -0
  255. package/bin/types/session/SessionSystem.d.ts.map +1 -1
  256. package/bin/types/session/SessionTool.d.ts +2 -2
  257. package/bin/types/session/SessionTool.d.ts.map +1 -1
  258. package/bin/types/session/SessionTurnCompletion.d.ts +23 -0
  259. package/bin/types/session/SessionTurnCompletion.d.ts.map +1 -0
  260. package/bin/types/session/SessionTurnCompletion.js +8 -0
  261. package/bin/types/session/SessionTurnCompletion.js.map +1 -0
  262. package/bin/types/session/SessionTurnFileDiff.d.ts +42 -0
  263. package/bin/types/session/SessionTurnFileDiff.d.ts.map +1 -0
  264. package/bin/types/session/SessionTurnFileDiff.js +8 -0
  265. package/bin/types/session/SessionTurnFileDiff.js.map +1 -0
  266. package/bin/types/store/LocalStore.d.ts +6 -13
  267. package/bin/types/store/LocalStore.d.ts.map +1 -1
  268. package/bin/types/store/LocalStore.js +1 -1
  269. package/bin/types/store/SessionStorage.d.ts +103 -0
  270. package/bin/types/store/SessionStorage.d.ts.map +1 -0
  271. package/bin/types/store/SessionStorage.js +8 -0
  272. package/bin/types/store/SessionStorage.js.map +1 -0
  273. package/bin/types/store/SessionStore.d.ts +5 -3
  274. package/bin/types/store/SessionStore.d.ts.map +1 -1
  275. package/package.json +2 -2
  276. package/scripts/core-engine-context-compaction.test.mjs +96 -219
  277. package/scripts/core-engine-model-stream.test.mjs +2 -4
  278. package/scripts/executor-failure-result.test.mjs +14 -17
  279. package/scripts/session-agent-message-part-order.test.mjs +63 -0
  280. package/scripts/session-initialization.test.mjs +141 -0
  281. package/scripts/session-message-timeline.test.mjs +5 -6
  282. package/scripts/session-messages-error-part.test.mjs +175 -0
  283. package/scripts/session-messages-error.test.mjs +47 -6
  284. package/scripts/session-prompt-idempotency.test.mjs +91 -0
  285. package/scripts/session-queue.test.mjs +13 -12
  286. package/scripts/session-storage-sqlite.test.mjs +209 -0
  287. package/scripts/session-turn-context.test.mjs +21 -33
  288. package/src/agent/Agent.ts +48 -12
  289. package/src/agent/AgentInstructions.ts +2 -2
  290. package/src/agent/AgentMemoryStorage.ts +1 -0
  291. package/src/agent/AgentSessions.ts +31 -12
  292. package/src/executor/Executor.ts +47 -184
  293. package/src/executor/README.md +12 -13
  294. package/src/executor/composer/system/default/SystemPromptAssets.ts +0 -6
  295. package/src/executor/core-engine/CoreEngineContextCompaction.ts +3 -135
  296. package/src/executor/core-engine/CoreEngineRunner.ts +51 -273
  297. package/src/executor/core-engine/CoreEngineSignals.ts +9 -9
  298. package/src/executor/messages/SessionAttachmentMapper.ts +4 -4
  299. package/src/executor/messages/SessionMessageLog.ts +3 -3
  300. package/src/executor/messages/SessionModelMessages.ts +85 -103
  301. package/src/executor/model/ModelStepRunner.ts +9 -41
  302. package/src/executor/services/ExecutorRecoveryPolicy.ts +34 -127
  303. package/src/executor/types/SessionHistoryMeta.ts +1 -3
  304. package/src/index.ts +39 -47
  305. package/src/session/DefaultSessionComposer.ts +33 -30
  306. package/src/session/Session.ts +96 -227
  307. package/src/session/SessionComposition.ts +28 -65
  308. package/src/session/SessionLoop.ts +267 -370
  309. package/src/session/SessionMessages.ts +363 -242
  310. package/src/session/SessionQueue.ts +3 -2
  311. package/src/session/SessionState.ts +55 -101
  312. package/src/session/SessionSystem.ts +51 -1
  313. package/src/session/SessionTitle.ts +4 -4
  314. package/src/session/browse/Browse.ts +182 -468
  315. package/src/session/browse/SessionMessageTimeline.ts +63 -38
  316. package/src/session/composer/policies/AdaptivePartContextPolicy.ts +307 -0
  317. package/src/session/composer/policies/FullHistoryContextPolicy.ts +36 -0
  318. package/src/session/composer/policies/SessionSummaryPrompts.ts +42 -0
  319. package/src/session/execution/SessionAssistantOutputAdapter.ts +25 -11
  320. package/src/session/messages/{SessionActionMessageWriter.ts → SessionAgentActionPartWriter.ts} +8 -8
  321. package/src/session/messages/SessionAgentContent.ts +56 -0
  322. package/src/session/messages/SessionAgentMessageState.ts +378 -0
  323. package/src/session/messages/{SessionAssistantMessageWriter.ts → SessionAgentMessageWriter.ts} +89 -60
  324. package/src/session/messages/SessionForkMessageFiles.ts +25 -1
  325. package/src/session/messages/SessionMessageInteractionWriter.ts +19 -19
  326. package/src/session/messages/SessionMessageText.ts +3 -4
  327. package/src/session/messages/SessionTurnFileDiffData.ts +3 -3
  328. package/src/session/messages/SessionUserMessage.ts +10 -7
  329. package/src/session/preview/SessionMessagePreview.ts +26 -9
  330. package/src/session/runtime/SessionTurnCompletion.ts +159 -0
  331. package/src/session/runtime/SessionTurnContext.ts +20 -21
  332. package/src/session/runtime/SessionTurnFileDiff.ts +105 -0
  333. package/src/session/storage/LocalSessionDataStore.ts +27 -176
  334. package/src/session/storage/LocalSessionStore.ts +170 -38
  335. package/src/session/storage/LocalStorePaths.ts +14 -86
  336. package/src/session/storage/Metadata.ts +4 -13
  337. package/src/session/storage/RuntimeSessionPort.ts +7 -7
  338. package/src/session/storage/SessionStorageCodec.ts +465 -0
  339. package/src/session/storage/SessionStorageSchema.ts +132 -0
  340. package/src/session/storage/SqliteSessionStorage.ts +776 -0
  341. package/src/tools/ask/AskQuestionsTool.ts +3 -1
  342. package/src/types/action/ActionResult.ts +10 -10
  343. package/src/types/agent/AgentOptions.ts +11 -0
  344. package/src/types/agent/AgentStorage.ts +3 -1
  345. package/src/types/agent/SessionActor.ts +0 -10
  346. package/src/types/agent/SessionTypes.ts +5 -5
  347. package/src/types/executor/SessionAssistantOutput.ts +15 -4
  348. package/src/types/executor/SessionTurnContext.ts +25 -22
  349. package/src/types/sdk/AgentSessionAction.ts +1 -1
  350. package/src/types/sdk/AgentSessionPrompt.ts +15 -5
  351. package/src/types/session/AdaptivePartContextPolicy.ts +37 -0
  352. package/src/types/session/{SessionAssistantMessageState.ts → SessionAgentMessageState.ts} +6 -6
  353. package/src/types/session/SessionCommand.ts +21 -7
  354. package/src/types/session/SessionComposer.ts +48 -48
  355. package/src/types/session/SessionComposition.ts +2 -5
  356. package/src/types/session/SessionContextPolicy.ts +77 -0
  357. package/src/types/session/SessionExecution.ts +11 -36
  358. package/src/types/session/SessionLoop.ts +3 -8
  359. package/src/types/session/SessionMessages.ts +19 -29
  360. package/src/types/session/SessionOptions.ts +5 -5
  361. package/src/types/session/SessionPort.ts +10 -10
  362. package/src/types/session/SessionState.ts +2 -5
  363. package/src/types/session/SessionSystem.ts +19 -0
  364. package/src/types/session/SessionTool.ts +2 -2
  365. package/src/types/session/SessionTurnCompletion.ts +24 -0
  366. package/src/types/session/SessionTurnFileDiff.ts +44 -0
  367. package/src/types/store/LocalStore.ts +6 -14
  368. package/src/types/store/SessionStorage.ts +121 -0
  369. package/src/types/store/SessionStore.ts +6 -3
  370. package/tsconfig.tsbuildinfo +1 -1
  371. package/bin/executor/composer/compaction/jsonl/JsonlSessionCompactionPrompts.d.ts +0 -45
  372. package/bin/executor/composer/compaction/jsonl/JsonlSessionCompactionPrompts.d.ts.map +0 -1
  373. package/bin/executor/composer/compaction/jsonl/JsonlSessionCompactionPrompts.js +0 -144
  374. package/bin/executor/composer/compaction/jsonl/JsonlSessionCompactionPrompts.js.map +0 -1
  375. package/bin/executor/composer/system/SessionSystemComposer.d.ts +0 -23
  376. package/bin/executor/composer/system/SessionSystemComposer.d.ts.map +0 -1
  377. package/bin/executor/composer/system/SessionSystemComposer.js +0 -9
  378. package/bin/executor/composer/system/SessionSystemComposer.js.map +0 -1
  379. package/bin/executor/composer/system/default/DefaultSessionSystemComposer.d.ts +0 -43
  380. package/bin/executor/composer/system/default/DefaultSessionSystemComposer.d.ts.map +0 -1
  381. package/bin/executor/composer/system/default/DefaultSessionSystemComposer.js +0 -42
  382. package/bin/executor/composer/system/default/DefaultSessionSystemComposer.js.map +0 -1
  383. package/bin/executor/composer/system/default/PromptRenderer.d.ts +0 -35
  384. package/bin/executor/composer/system/default/PromptRenderer.d.ts.map +0 -1
  385. package/bin/executor/composer/system/default/PromptRenderer.js +0 -23
  386. package/bin/executor/composer/system/default/PromptRenderer.js.map +0 -1
  387. package/bin/executor/composer/system/default/SystemDomain.d.ts +0 -151
  388. package/bin/executor/composer/system/default/SystemDomain.d.ts.map +0 -1
  389. package/bin/executor/composer/system/default/SystemDomain.js +0 -162
  390. package/bin/executor/composer/system/default/SystemDomain.js.map +0 -1
  391. package/bin/executor/composer/system/default/assets/task.prompt.d.ts +0 -7
  392. package/bin/executor/composer/system/default/assets/task.prompt.d.ts.map +0 -1
  393. package/bin/executor/composer/system/default/assets/task.prompt.js +0 -8
  394. package/bin/executor/composer/system/default/assets/task.prompt.js.map +0 -1
  395. package/bin/executor/composer/system/default/variables/GeoContext.d.ts +0 -14
  396. package/bin/executor/composer/system/default/variables/GeoContext.d.ts.map +0 -1
  397. package/bin/executor/composer/system/default/variables/GeoContext.js +0 -150
  398. package/bin/executor/composer/system/default/variables/GeoContext.js.map +0 -1
  399. package/bin/executor/composer/system/default/variables/PromptTypes.d.ts +0 -36
  400. package/bin/executor/composer/system/default/variables/PromptTypes.d.ts.map +0 -1
  401. package/bin/executor/composer/system/default/variables/PromptTypes.js +0 -9
  402. package/bin/executor/composer/system/default/variables/PromptTypes.js.map +0 -1
  403. package/bin/executor/composer/system/default/variables/VariableReplacer.d.ts +0 -61
  404. package/bin/executor/composer/system/default/variables/VariableReplacer.d.ts.map +0 -1
  405. package/bin/executor/composer/system/default/variables/VariableReplacer.js +0 -93
  406. package/bin/executor/composer/system/default/variables/VariableReplacer.js.map +0 -1
  407. package/bin/executor/core-engine/CoreEngineMessageState.d.ts +0 -63
  408. package/bin/executor/core-engine/CoreEngineMessageState.d.ts.map +0 -1
  409. package/bin/executor/core-engine/CoreEngineMessageState.js +0 -81
  410. package/bin/executor/core-engine/CoreEngineMessageState.js.map +0 -1
  411. package/bin/session/SessionCommand.d.ts +0 -24
  412. package/bin/session/SessionCommand.d.ts.map +0 -1
  413. package/bin/session/SessionCommand.js +0 -35
  414. package/bin/session/SessionCommand.js.map +0 -1
  415. package/bin/session/messages/SessionActionMessageWriter.d.ts.map +0 -1
  416. package/bin/session/messages/SessionActionMessageWriter.js.map +0 -1
  417. package/bin/session/messages/SessionAssistantMessageState.d.ts +0 -49
  418. package/bin/session/messages/SessionAssistantMessageState.d.ts.map +0 -1
  419. package/bin/session/messages/SessionAssistantMessageState.js +0 -296
  420. package/bin/session/messages/SessionAssistantMessageState.js.map +0 -1
  421. package/bin/session/messages/SessionAssistantMessageWriter.d.ts.map +0 -1
  422. package/bin/session/messages/SessionAssistantMessageWriter.js.map +0 -1
  423. package/bin/session/messages/SessionMessageCompaction.d.ts +0 -29
  424. package/bin/session/messages/SessionMessageCompaction.d.ts.map +0 -1
  425. package/bin/session/messages/SessionMessageCompaction.js +0 -128
  426. package/bin/session/messages/SessionMessageCompaction.js.map +0 -1
  427. package/bin/session/runtime/SessionCompactOperation.d.ts +0 -29
  428. package/bin/session/runtime/SessionCompactOperation.d.ts.map +0 -1
  429. package/bin/session/runtime/SessionCompactOperation.js +0 -66
  430. package/bin/session/runtime/SessionCompactOperation.js.map +0 -1
  431. package/bin/session/runtime/SessionHistoryCompaction.d.ts +0 -22
  432. package/bin/session/runtime/SessionHistoryCompaction.d.ts.map +0 -1
  433. package/bin/session/runtime/SessionHistoryCompaction.js +0 -31
  434. package/bin/session/runtime/SessionHistoryCompaction.js.map +0 -1
  435. package/bin/session/storage/JsonlSessionMessageStore.d.ts +0 -77
  436. package/bin/session/storage/JsonlSessionMessageStore.d.ts.map +0 -1
  437. package/bin/session/storage/JsonlSessionMessageStore.js +0 -419
  438. package/bin/session/storage/JsonlSessionMessageStore.js.map +0 -1
  439. package/bin/session/storage/SessionMessageStoreFactory.d.ts +0 -12
  440. package/bin/session/storage/SessionMessageStoreFactory.d.ts.map +0 -1
  441. package/bin/session/storage/SessionMessageStoreFactory.js +0 -13
  442. package/bin/session/storage/SessionMessageStoreFactory.js.map +0 -1
  443. package/bin/types/common/Template.d.ts +0 -9
  444. package/bin/types/common/Template.d.ts.map +0 -1
  445. package/bin/types/common/Template.js +0 -9
  446. package/bin/types/common/Template.js.map +0 -1
  447. package/bin/types/sdk/AgentSessionCompact.d.ts +0 -30
  448. package/bin/types/sdk/AgentSessionCompact.d.ts.map +0 -1
  449. package/bin/types/sdk/AgentSessionCompact.js +0 -8
  450. package/bin/types/sdk/AgentSessionCompact.js.map +0 -1
  451. package/bin/types/session/SessionAssistantMessageState.d.ts.map +0 -1
  452. package/bin/types/session/SessionAssistantMessageState.js.map +0 -1
  453. package/bin/types/session/SessionSegment.d.ts +0 -57
  454. package/bin/types/session/SessionSegment.d.ts.map +0 -1
  455. package/bin/types/session/SessionSegment.js +0 -8
  456. package/bin/types/session/SessionSegment.js.map +0 -1
  457. package/bin/types/store/SessionDataStore.d.ts +0 -88
  458. package/bin/types/store/SessionDataStore.d.ts.map +0 -1
  459. package/bin/types/store/SessionDataStore.js +0 -9
  460. package/bin/types/store/SessionDataStore.js.map +0 -1
  461. package/bin/utils/Template.d.ts +0 -17
  462. package/bin/utils/Template.d.ts.map +0 -1
  463. package/bin/utils/Template.js +0 -24
  464. package/bin/utils/Template.js.map +0 -1
  465. package/scripts/session-compaction-prompts.test.mjs +0 -49
  466. package/src/executor/composer/compaction/jsonl/JsonlSessionCompactionPrompts.ts +0 -162
  467. package/src/executor/composer/system/SessionSystemComposer.ts +0 -25
  468. package/src/executor/composer/system/default/DefaultSessionSystemComposer.ts +0 -76
  469. package/src/executor/composer/system/default/PromptRenderer.ts +0 -52
  470. package/src/executor/composer/system/default/SystemDomain.ts +0 -301
  471. package/src/executor/composer/system/default/assets/task.prompt.ts +0 -9
  472. package/src/executor/composer/system/default/assets/task.prompt.ts.txt +0 -33
  473. package/src/executor/composer/system/default/variables/GeoContext.ts +0 -180
  474. package/src/executor/composer/system/default/variables/PromptTypes.ts +0 -37
  475. package/src/executor/composer/system/default/variables/VariableReplacer.ts +0 -154
  476. package/src/executor/core-engine/CoreEngineMessageState.ts +0 -117
  477. package/src/session/SessionCommand.ts +0 -42
  478. package/src/session/messages/SessionAssistantMessageState.ts +0 -392
  479. package/src/session/messages/SessionMessageCompaction.ts +0 -160
  480. package/src/session/runtime/SessionCompactOperation.ts +0 -93
  481. package/src/session/runtime/SessionHistoryCompaction.ts +0 -45
  482. package/src/session/storage/JsonlSessionMessageStore.ts +0 -513
  483. package/src/session/storage/SessionMessageStoreFactory.ts +0 -18
  484. package/src/types/common/Template.ts +0 -9
  485. package/src/types/sdk/AgentSessionCompact.ts +0 -32
  486. package/src/types/session/SessionSegment.ts +0 -62
  487. package/src/types/store/SessionDataStore.ts +0 -113
  488. package/src/utils/Template.ts +0 -28
@@ -1,154 +0,0 @@
1
- /**
2
- * VariableReplacer:prompt 变量替换模块。
3
- *
4
- * 关键点(中文)
5
- * - 专职负责模板变量构建与文本替换。
6
- * - 与 message 组装解耦,便于独立复用与测试。
7
- */
8
-
9
- import { resolve_prompt_geo_context } from "@executor/composer/system/default/variables/GeoContext.js";
10
- import type { PromptVariables } from "@executor/composer/system/default/variables/PromptTypes.js";
11
- import { render_template_variables } from "@/utils/Template.js";
12
- import {
13
- format_date_in_timezone,
14
- format_date_time_in_timezone,
15
- format_year_in_timezone,
16
- resolve_runtime_timezone,
17
- } from "@/utils/Time.js";
18
-
19
- /**
20
- * Prompt 变量替换模式。
21
- *
22
- * 关键点(中文)
23
- * - `full`:完整替换(包含时间/地点等上下文动态变量)。
24
- * - `stable`:仅保留稳定替换;但 `current_year` 属于低频年度变量,仍保留真实值。
25
- */
26
- export type PromptVariableMode = "full" | "stable";
27
-
28
- async function buildPromptVariables(options?: {
29
- /**
30
- * 项目路径(用于 `project_path/project_root`)。
31
- */
32
- projectPath?: string;
33
-
34
- /**
35
- * 会话 ID(用于 `session_id`)。
36
- */
37
- session_id?: string;
38
-
39
- /**
40
- * 变量替换模式(默认 full)。
41
- */
42
- mode?: PromptVariableMode;
43
- }): Promise<PromptVariables> {
44
- const mode = options?.mode === "stable" ? "stable" : "full";
45
- const projectPath = String(options?.projectPath || "").trim() || process.cwd();
46
- const safeLocalTimezone = resolve_runtime_timezone();
47
- const now = new Date();
48
- if (mode === "stable") {
49
- return {
50
- currentDate: "[See runtime clock tail message]",
51
- currentTime: "[See runtime clock tail message]",
52
- currentYear: format_year_in_timezone(now, safeLocalTimezone),
53
- timezone: safeLocalTimezone,
54
- location: "[See runtime clock tail message]",
55
- projectPath,
56
- project_root: projectPath,
57
- session_id: "[Runtime session id]",
58
- };
59
- }
60
-
61
- const geo = await resolve_prompt_geo_context();
62
- const session_id = String(options?.session_id || "").trim() || "unknown";
63
- return {
64
- // 关键点(中文):时间字段只使用本机 runtime 时区,避免代理/IP 地理推断改变 cron 与相对时间口径。
65
- currentDate: format_date_in_timezone(now, safeLocalTimezone),
66
- currentTime: format_date_time_in_timezone(now, safeLocalTimezone),
67
- currentYear: format_year_in_timezone(now, safeLocalTimezone),
68
- timezone: safeLocalTimezone,
69
- location: geo.location,
70
- projectPath,
71
- project_root: projectPath,
72
- session_id,
73
- };
74
- }
75
-
76
- /**
77
- * 替换 prompt 模板变量。
78
- *
79
- * 当前支持(中文)
80
- * - `{{current_time}}`
81
- * - `{{current_date}}`
82
- * - `{{current_year}}`
83
- * - `{{timezone}}`
84
- * - `{{location}}`
85
- * - `{{project_path}}`
86
- * - `{{project_root}}`
87
- * - `{{session_id}}`
88
- */
89
- export async function replace_variables_in_prompts(
90
- prompt: string,
91
- options?: {
92
- /**
93
- * 项目路径(用于 `project_path/project_root`)。
94
- */
95
- projectPath?: string;
96
-
97
- /**
98
- * 会话 ID(用于 `session_id`)。
99
- */
100
- session_id?: string;
101
-
102
- /**
103
- * 变量替换模式(默认 full)。
104
- */
105
- mode?: PromptVariableMode;
106
- },
107
- ): Promise<string> {
108
- if (!prompt) return prompt;
109
- const variables = await buildPromptVariables(options);
110
- return render_template_variables(prompt, {
111
- current_date: variables.currentDate,
112
- current_time: variables.currentTime,
113
- current_year: variables.currentYear,
114
- timezone: variables.timezone,
115
- location: variables.location,
116
- project_path: variables.projectPath,
117
- project_root: variables.project_root,
118
- session_id: variables.session_id,
119
- });
120
- }
121
-
122
- /**
123
- * 构建每轮运行末尾的 runtime clock system prompt。
124
- *
125
- * 关键点(中文)
126
- * - system/static prompt 使用 stable 模式,不能直接承载每轮变化的时间。
127
- * - 这里在 messages 尾部补齐 `current_date/current_time/timezone`,让 chat、task、prompt 的时间语义统一。
128
- * - 只使用本机 runtime 时区,避免每轮为了地理位置进行网络请求。
129
- */
130
- export function build_runtime_clock_system_prompt(options?: {
131
- /**
132
- * 项目路径(用于 `project_root`)。
133
- */
134
- projectPath?: string;
135
-
136
- /**
137
- * 会话 ID(用于 `session_id`)。
138
- */
139
- session_id?: string;
140
- }): string {
141
- const timezone = resolve_runtime_timezone();
142
- const projectPath = String(options?.projectPath || "").trim() || process.cwd();
143
- const session_id = String(options?.session_id || "").trim() || "unknown";
144
- const now = new Date();
145
- return [
146
- "# Runtime Clock Context",
147
- "The following fields are the authoritative time context for this run. Prefer them when resolving relative time expressions such as today, tomorrow, or a specific hour:",
148
- `- current_date: ${format_date_in_timezone(now, timezone)}`,
149
- `- current_time: ${format_date_time_in_timezone(now, timezone)}`,
150
- `- timezone: ${timezone}`,
151
- `- session_id: ${session_id}`,
152
- `- project_root: ${projectPath}`,
153
- ].join("\n");
154
- }
@@ -1,117 +0,0 @@
1
- /**
2
- * CoreEngine 模型消息运行态。
3
- *
4
- * 关键点(中文)
5
- * - CoreEngine 只维护本 Turn 后续模型 Step 需要的标准 ModelMessage。
6
- * - canonical SessionMessage 的持久化由 SessionMessages 独立拥有。
7
- */
8
-
9
- import type { ModelMessage } from "@downcity/type";
10
- import { session_messages_to_model_messages } from "@executor/messages/SessionModelMessages.js";
11
- import type { SessionMessage, SessionUserMessage } from "@downcity/type";
12
-
13
- /**
14
- * CoreEngine 单轮执行期间的消息基线。
15
- */
16
- export class CoreEngineMessageState {
17
- /**
18
- * 当前模型侧消息基线。
19
- */
20
- private current_model_messages: ModelMessage[];
21
-
22
- /**
23
- * 当前项目根目录,用于解析历史中的相对路径 file part。
24
- */
25
- private readonly project_root?: string;
26
-
27
- private constructor(params: {
28
- /**
29
- * 当前模型侧消息基线。
30
- */
31
- model_messages: ModelMessage[];
32
- /**
33
- * 当前项目根目录。
34
- */
35
- project_root?: string;
36
- }) {
37
- this.current_model_messages = params.model_messages;
38
- this.project_root = params.project_root;
39
- }
40
-
41
- /**
42
- * 基于初始模型消息创建运行态。
43
- */
44
- static async create(params: {
45
- /**
46
- * 初始标准模型消息。
47
- */
48
- messages: ModelMessage[];
49
- /**
50
- * 当前项目根目录。
51
- */
52
- project_root?: string;
53
- }): Promise<CoreEngineMessageState> {
54
- return new CoreEngineMessageState({
55
- model_messages: Array.isArray(params.messages) ? [...params.messages] : [],
56
- project_root: params.project_root,
57
- });
58
- }
59
-
60
- /**
61
- * 读取当前模型消息。
62
- */
63
- get model_messages(): ModelMessage[] {
64
- return this.current_model_messages;
65
- }
66
-
67
- /**
68
- * 把 Step 间新增的 canonical User Message 并入模型基线。
69
- */
70
- async append_merged_user_messages(
71
- messages: SessionUserMessage[],
72
- ): Promise<ModelMessage[]> {
73
- if (messages.length === 0) return [];
74
- return await this.append_session_messages(messages);
75
- }
76
-
77
- /**
78
- * 追加内部生成的 user nudge 消息。
79
- */
80
- async append_user_message(message: SessionUserMessage): Promise<void> {
81
- await this.append_session_messages([message]);
82
- }
83
-
84
- /**
85
- * 追加 SDK 返回的模型 response messages。
86
- */
87
- append_model_messages(messages: ModelMessage[]): void {
88
- if (!Array.isArray(messages) || messages.length === 0) return;
89
- this.current_model_messages = [...this.current_model_messages, ...messages];
90
- }
91
-
92
- /**
93
- * 原子替换当前模型侧消息基线。
94
- *
95
- * 关键点(中文):compact 只替换 Provider 后续可见的 ModelMessage,
96
- * Session 语义消息与持久化历史仍保持完整,等待 turn 收口后再单独归档。
97
- */
98
- replace_model_messages(messages: ModelMessage[]): void {
99
- this.current_model_messages = Array.isArray(messages) ? [...messages] : [];
100
- }
101
-
102
- /** 使用 Composer 重新生成的模型历史原子替换当前基线。 */
103
- replace_model_history(messages: ModelMessage[]): void {
104
- this.current_model_messages = Array.isArray(messages) ? [...messages] : [];
105
- }
106
-
107
- private async append_session_messages(
108
- messages: SessionMessage[],
109
- ): Promise<ModelMessage[]> {
110
- const model_messages = await session_messages_to_model_messages(
111
- messages,
112
- this.project_root,
113
- );
114
- this.current_model_messages = [...this.current_model_messages, ...model_messages];
115
- return model_messages;
116
- }
117
- }
@@ -1,42 +0,0 @@
1
- /**
2
- * Session 有序输入队列中的可执行 Command。
3
- *
4
- * Command 对象封装一次需要遵守 Session FIFO 与检查点顺序的行为。Queue 只保存
5
- * 对象和维护顺序,不识别 Prompt、配置、Compact 等业务种类。
6
- */
7
-
8
- import type {
9
- SessionCommandCompletion,
10
- SessionCommandOptions,
11
- } from "@/types/session/SessionCommand.js";
12
-
13
- /** 一次等待在 Session 检查点执行的 Command。 */
14
- export class SessionCommand {
15
- private readonly execute_command: SessionCommandOptions["execute"];
16
- private readonly cancel_command?: SessionCommandOptions["cancel"];
17
- private readonly completion_info?: SessionCommandOptions["completion"];
18
-
19
- /** @param options 当前 Command 的执行与可选取消行为。 */
20
- constructor(options: SessionCommandOptions) {
21
- this.execute_command = options.execute;
22
- this.cancel_command = options.cancel;
23
- this.completion_info = options.completion;
24
- }
25
-
26
- /** 执行当前 Command,并返回成功后需要持久化的完成信息。 */
27
- async execute(): Promise<SessionCommandCompletion | undefined> {
28
- await this.execute_command();
29
- return this.completion_info;
30
- }
31
-
32
- /**
33
- * 在 Session stop 时尝试取消当前 Command。
34
- *
35
- * @returns true 表示 Command 已取消并应从 Queue 移除;false 表示继续保留。
36
- */
37
- cancel(): boolean {
38
- if (!this.cancel_command) return false;
39
- this.cancel_command();
40
- return true;
41
- }
42
- }
@@ -1,392 +0,0 @@
1
- /**
2
- * canonical Assistant Message 的串行状态转换器。
3
- *
4
- * 关键点(中文)
5
- * - 只拥有每条 Assistant Message 的临时写事务链,不拥有 Message 事实源。
6
- * - 所有草稿、Part、Interaction 与终态都先持久化,再交回 SessionMessages 接受。
7
- * - 同一 Assistant Message 的 revision 严格串行,不同 Message 可以并行推进。
8
- */
9
-
10
- import { generate_id } from "@/utils/Id.js";
11
- import { SessionMessageInteractionWriter } from "@/session/messages/SessionMessageInteractionWriter.js";
12
- import type {
13
- SessionAssistantInteractionPart,
14
- SessionAssistantMessage,
15
- SessionAssistantMessagePart,
16
- SessionAssistantToolPart,
17
- SessionMessage,
18
- } from "@downcity/type";
19
- import type {
20
- SessionInteractionCloseInput,
21
- SessionInteractionRequest,
22
- SessionInteractionResponse,
23
- } from "@downcity/type";
24
- import type { SessionStreamingToolLocation } from "@/types/session/SessionTool.js";
25
- import type { SessionMutation } from "@downcity/type";
26
- import type { SessionAssistantMessageStateOptions } from "@/types/session/SessionAssistantMessageState.js";
27
-
28
- /** 管理 Assistant 草稿、Part 与 Interaction 的原子状态转换。 */
29
- export class SessionAssistantMessageState {
30
- private readonly session_id: string;
31
- private readonly options: SessionAssistantMessageStateOptions;
32
- /** 按 Assistant Message 隔离的完整写事务链。 */
33
- private readonly write_chains = new Map<string, Promise<void>>();
34
- /** Assistant Message 内 Interaction Part 的原子状态写入器。 */
35
- private readonly interaction_writer: SessionMessageInteractionWriter;
36
-
37
- constructor(options: SessionAssistantMessageStateOptions) {
38
- this.session_id = options.session_id;
39
- this.options = options;
40
- this.interaction_writer = new SessionMessageInteractionWriter({
41
- list_messages: options.list_messages,
42
- find_streaming_tool: (tool_call_id) => this.find_streaming_tool(tool_call_id),
43
- enqueue_assistant_write: (message_id, operation) =>
44
- this.enqueue_write(message_id, operation),
45
- commit_assistant_snapshot: (current, parts) =>
46
- this.commit_snapshot(current, parts),
47
- });
48
- }
49
-
50
- /** 写入 Assistant 原始文本 delta。 */
51
- async append_delta(
52
- message_id: string,
53
- part_id: string,
54
- type: "text" | "reasoning",
55
- delta: string,
56
- ): Promise<void> {
57
- if (!delta) return;
58
- await this.enqueue_write(message_id, async () => {
59
- const current = this.require_streaming_assistant(message_id);
60
- const part = current.parts.find((item) => item.part_id === part_id);
61
- if (!part || (part.type !== "text" && part.type !== "reasoning")) {
62
- throw new Error(`Delta target Part does not exist: ${part_id}`);
63
- }
64
- if (part.type !== type) {
65
- throw new Error(`Delta type changed for Part: ${part_id}`);
66
- }
67
- const created_at = Date.now();
68
- const message: SessionAssistantMessage = {
69
- ...current,
70
- revision: current.revision + 1,
71
- updated_at: created_at,
72
- parts: current.parts.map((item) =>
73
- item.part_id === part_id &&
74
- (item.type === "text" || item.type === "reasoning")
75
- ? { ...item, text: item.text + delta }
76
- : item,
77
- ),
78
- };
79
- await this.options.store.write_assistant_message(message);
80
- this.options.accept_mutation({
81
- mutation_id: generate_id(),
82
- variant: "delta",
83
- type,
84
- message_id,
85
- revision: message.revision,
86
- session_id: this.session_id,
87
- turn_id: message.turn_id,
88
- created_at,
89
- part_id,
90
- delta,
91
- }, message);
92
- });
93
- }
94
-
95
- /** 写入 Assistant Tool 输入原始 delta。 */
96
- async append_tool_input_delta(
97
- message_id: string,
98
- part_id: string,
99
- tool_call_id: string,
100
- delta: string,
101
- ): Promise<void> {
102
- if (!delta) return;
103
- await this.enqueue_write(message_id, async () => {
104
- const current = this.require_streaming_assistant(message_id);
105
- const part = current.parts.find((item) => item.part_id === part_id);
106
- if (!part || part.type !== "tool") {
107
- throw new Error(`Tool input Delta target Part does not exist: ${part_id}`);
108
- }
109
- if (part.tool_call_id !== tool_call_id) {
110
- throw new Error(`Tool input Delta tool_call_id changed for Part: ${part_id}`);
111
- }
112
- if (part.state !== "input-streaming") {
113
- throw new Error(`Tool input Delta cannot update ${part.state} Part: ${part_id}`);
114
- }
115
- const created_at = Date.now();
116
- const message: SessionAssistantMessage = {
117
- ...current,
118
- revision: current.revision + 1,
119
- updated_at: created_at,
120
- parts: current.parts.map((item) =>
121
- item.part_id === part_id && item.type === "tool"
122
- ? { ...item, input_text: `${item.input_text || ""}${delta}` }
123
- : item,
124
- ),
125
- };
126
- await this.options.store.write_assistant_message(message);
127
- this.options.accept_mutation({
128
- mutation_id: generate_id(),
129
- variant: "delta",
130
- type: "tool_input",
131
- message_id,
132
- revision: message.revision,
133
- session_id: this.session_id,
134
- turn_id: message.turn_id,
135
- created_at,
136
- part_id,
137
- tool_call_id,
138
- delta,
139
- }, message);
140
- });
141
- }
142
-
143
- /** 提交一个完整 canonical Assistant Part。 */
144
- async update_part(
145
- message_id: string,
146
- part: SessionAssistantMessagePart,
147
- ): Promise<void> {
148
- await this.enqueue_write(message_id, async () => {
149
- const current = this.require_streaming_assistant(message_id);
150
- const existing = current.parts.find((item) => item.part_id === part.part_id);
151
- if (existing && existing.sequence !== part.sequence) {
152
- throw new Error(`Assistant Part sequence changed: ${part.part_id}`);
153
- }
154
- const created_at = Date.now();
155
- const next_part = structuredClone(part);
156
- const message: SessionAssistantMessage = {
157
- ...current,
158
- revision: current.revision + 1,
159
- updated_at: created_at,
160
- parts: (existing
161
- ? current.parts.map((item) =>
162
- item.part_id === part.part_id ? next_part : item)
163
- : [...current.parts, next_part]
164
- ).sort((left, right) => left.sequence - right.sequence),
165
- };
166
- await this.options.store.write_assistant_message(message);
167
- this.options.accept_mutation({
168
- mutation_id: generate_id(),
169
- variant: "part",
170
- type: next_part.type,
171
- message_id,
172
- revision: message.revision,
173
- session_id: this.session_id,
174
- turn_id: message.turn_id,
175
- created_at,
176
- part_id: next_part.part_id,
177
- part: next_part,
178
- } as SessionMutation, message);
179
- });
180
- }
181
-
182
- /** 原子提交当前 Assistant step 的 metadata 快照。 */
183
- async commit_step(
184
- message_id: string,
185
- parts: SessionAssistantMessagePart[],
186
- ): Promise<void> {
187
- await this.enqueue_write(message_id, async () => {
188
- const current = this.require_streaming_assistant(message_id);
189
- if (
190
- parts.length !== current.parts.length ||
191
- parts.some((part, index) =>
192
- part.part_id !== current.parts[index]?.part_id ||
193
- part.sequence !== current.parts[index]?.sequence
194
- )
195
- ) {
196
- throw new Error(
197
- `Assistant step changed canonical Part identity: ${message_id}`,
198
- );
199
- }
200
- const message: SessionAssistantMessage = {
201
- ...current,
202
- revision: current.revision + 1,
203
- updated_at: Date.now(),
204
- parts: structuredClone(parts),
205
- };
206
- await this.options.store.write_assistant_message(message);
207
- this.options.accept_message(message);
208
- });
209
- }
210
-
211
- /** 收口 Assistant Message,并把草稿提交到 Active。 */
212
- async complete(
213
- message_id: string,
214
- status: "completed" | "stopped" | "failed",
215
- error?: string,
216
- ): Promise<void> {
217
- await this.enqueue_write(message_id, async () => {
218
- const current = this.require_streaming_assistant(message_id);
219
- const created_at = Date.now();
220
- const interrupted_interactions = status === "stopped"
221
- ? current.parts.filter(
222
- (part): part is SessionAssistantInteractionPart =>
223
- part.type === "interaction" && part.status === "pending",
224
- )
225
- : [];
226
- const interrupted_tool_ids = new Set(
227
- interrupted_interactions.flatMap((part) =>
228
- part.request.source.tool_call_id
229
- ? [part.request.source.tool_call_id]
230
- : [],
231
- ),
232
- );
233
- const message: SessionAssistantMessage = {
234
- ...current,
235
- revision: current.revision + 1,
236
- status,
237
- updated_at: created_at,
238
- parts: current.parts.map((part) => {
239
- if (part.type === "text" || part.type === "reasoning") {
240
- return { ...part, state: "done" as const };
241
- }
242
- if (part.type === "interaction" && part.status === "pending") {
243
- return {
244
- ...part,
245
- status: "cancelled" as const,
246
- cancel_reason: "runtime_interrupted" as const,
247
- resolved_at: created_at,
248
- };
249
- }
250
- if (
251
- part.type === "tool" &&
252
- part.state !== "completed" &&
253
- part.state !== "failed"
254
- ) {
255
- return {
256
- ...part,
257
- state: "failed" as const,
258
- error:
259
- status === "stopped" &&
260
- part.state === "waiting-user" &&
261
- interrupted_tool_ids.has(part.tool_call_id)
262
- ? "Interaction cancelled"
263
- : error || "Tool did not complete before Assistant Message closed",
264
- };
265
- }
266
- return part;
267
- }),
268
- };
269
- await this.options.store.finalize_assistant_message(message);
270
- this.options.accept_message(message);
271
- });
272
- }
273
-
274
- /** 读取当前流式 Assistant 中的指定 Tool Part。 */
275
- find_streaming_tool(
276
- tool_call_id: string,
277
- ): SessionStreamingToolLocation | undefined {
278
- for (const message of this.options.list_messages()) {
279
- if (message.type !== "assistant" || message.status !== "streaming") continue;
280
- const part = message.parts.find(
281
- (item): item is SessionAssistantToolPart =>
282
- item.type === "tool" && item.tool_call_id === tool_call_id,
283
- );
284
- if (part) return { message_id: message.message_id, part };
285
- }
286
- return undefined;
287
- }
288
-
289
- /** 返回当前 Session 中全部等待用户响应的 canonical Interaction。 */
290
- list_pending_interactions(): SessionAssistantInteractionPart[] {
291
- return this.interaction_writer.list_pending();
292
- }
293
-
294
- /** 原子创建 Interaction,并把关联 Tool 转为 waiting-user。 */
295
- async request_interaction(
296
- request: SessionInteractionRequest,
297
- ): Promise<SessionAssistantInteractionPart> {
298
- return await this.interaction_writer.request(request);
299
- }
300
-
301
- /** 原子保存用户响应,并按 Interaction 结果恢复或终止关联 Tool。 */
302
- async resolve_interaction(
303
- interaction_id: string,
304
- response: SessionInteractionResponse,
305
- ): Promise<SessionAssistantInteractionPart> {
306
- return await this.interaction_writer.resolve(interaction_id, response);
307
- }
308
-
309
- /** 原子结束未响应 Interaction,并把关联 Tool 标记为失败。 */
310
- async close_interaction(
311
- interaction_id: string,
312
- input: SessionInteractionCloseInput,
313
- ): Promise<SessionAssistantInteractionPart> {
314
- return await this.interaction_writer.close(interaction_id, input);
315
- }
316
-
317
- /** 串行执行同一 Assistant Message 的完整写事务。 */
318
- private async enqueue_write<T>(
319
- message_id: string,
320
- operation: () => Promise<T>,
321
- ): Promise<T> {
322
- const previous = this.write_chains.get(message_id) || Promise.resolve();
323
- const result = previous.then(operation, operation);
324
- const chain = result.then(() => undefined, () => undefined);
325
- this.write_chains.set(message_id, chain);
326
- try {
327
- return await result;
328
- } finally {
329
- if (this.write_chains.get(message_id) === chain) {
330
- this.write_chains.delete(message_id);
331
- }
332
- }
333
- }
334
-
335
- /** 原子提交包含多个 Part 状态变化的 Assistant 完整快照。 */
336
- private async commit_snapshot(
337
- current: SessionAssistantMessage,
338
- parts: SessionAssistantMessagePart[],
339
- ): Promise<void> {
340
- const created_at = Date.now();
341
- const message: SessionAssistantMessage = {
342
- ...current,
343
- revision: current.revision + 1,
344
- updated_at: created_at,
345
- parts: structuredClone(parts).sort(
346
- (left, right) => left.sequence - right.sequence,
347
- ),
348
- };
349
- await this.options.store.write_assistant_message(message);
350
- const current_by_id = new Map(
351
- current.parts.map((part) => [part.part_id, part]),
352
- );
353
- const changed_parts = message.parts.filter((part) => {
354
- const previous = current_by_id.get(part.part_id);
355
- return !previous || JSON.stringify(previous) !== JSON.stringify(part);
356
- });
357
- if (changed_parts.length === 0) {
358
- this.options.accept_message(message);
359
- return;
360
- }
361
- for (const part of changed_parts) {
362
- this.options.accept_mutation({
363
- mutation_id: generate_id(),
364
- variant: "part",
365
- type: part.type,
366
- message_id: message.message_id,
367
- revision: message.revision,
368
- session_id: this.session_id,
369
- turn_id: message.turn_id,
370
- created_at,
371
- part_id: part.part_id,
372
- part: structuredClone(part),
373
- } as SessionMutation, message);
374
- }
375
- }
376
-
377
- /** 读取指定的流式 Assistant Message,否则抛出稳定领域错误。 */
378
- private require_streaming_assistant(
379
- message_id: string,
380
- ): SessionAssistantMessage {
381
- const message = [...this.options.list_messages()].find(
382
- (item) => item.message_id === message_id,
383
- );
384
- if (!message || message.type !== "assistant") {
385
- throw new Error(`Session assistant Message not found: ${message_id}`);
386
- }
387
- if (message.status !== "streaming") {
388
- throw new Error(`Assistant Message is already closed: ${message_id}`);
389
- }
390
- return message;
391
- }
392
- }