@armadra/agent 0.0.0-stage → 0.2.1

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 (407) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE +21 -0
  3. package/README.md +426 -2
  4. package/dist/agent/agent.d.ts +56 -0
  5. package/dist/agent/agent.js +129 -0
  6. package/dist/agent/loop.d.ts +51 -0
  7. package/dist/agent/loop.js +158 -0
  8. package/dist/agent/queue.d.ts +25 -0
  9. package/dist/agent/queue.js +55 -0
  10. package/dist/agent/retry.d.ts +22 -0
  11. package/dist/agent/retry.js +92 -0
  12. package/dist/agent/schema.d.ts +27 -0
  13. package/dist/agent/schema.js +186 -0
  14. package/dist/agent/session-cache.d.ts +100 -0
  15. package/dist/agent/session-cache.js +511 -0
  16. package/dist/agent/session-compaction.d.ts +49 -0
  17. package/dist/agent/session-compaction.js +251 -0
  18. package/dist/agent/session-core.d.ts +103 -0
  19. package/dist/agent/session-core.js +7 -0
  20. package/dist/agent/session-run.d.ts +55 -0
  21. package/dist/agent/session-run.js +246 -0
  22. package/dist/agent/session-state.d.ts +39 -0
  23. package/dist/agent/session-state.js +118 -0
  24. package/dist/agent/session-subagent.d.ts +54 -0
  25. package/dist/agent/session-subagent.js +157 -0
  26. package/dist/agent/session-sync.d.ts +20 -0
  27. package/dist/agent/session-sync.js +104 -0
  28. package/dist/agent/session-tools.d.ts +24 -0
  29. package/dist/agent/session-tools.js +277 -0
  30. package/dist/agent/session.d.ts +117 -0
  31. package/dist/agent/session.js +484 -0
  32. package/dist/agent/system-prompt.d.ts +49 -0
  33. package/dist/agent/system-prompt.js +121 -0
  34. package/dist/agent/tool-runner.d.ts +64 -0
  35. package/dist/agent/tool-runner.js +309 -0
  36. package/dist/agent/transform.d.ts +26 -0
  37. package/dist/agent/transform.js +171 -0
  38. package/dist/agent/types.d.ts +378 -0
  39. package/dist/agent/types.js +21 -0
  40. package/dist/ai/apis/anthropic-messages.d.ts +26 -0
  41. package/dist/ai/apis/anthropic-messages.js +214 -0
  42. package/dist/ai/apis/anthropic-request.d.ts +42 -0
  43. package/dist/ai/apis/anthropic-request.js +282 -0
  44. package/dist/ai/apis/api.d.ts +28 -0
  45. package/dist/ai/apis/api.js +102 -0
  46. package/dist/ai/apis/cache-params.d.ts +48 -0
  47. package/dist/ai/apis/cache-params.js +163 -0
  48. package/dist/ai/apis/google-generative-ai.d.ts +32 -0
  49. package/dist/ai/apis/google-generative-ai.js +249 -0
  50. package/dist/ai/apis/google-request.d.ts +40 -0
  51. package/dist/ai/apis/google-request.js +255 -0
  52. package/dist/ai/apis/openai-compat.d.ts +35 -0
  53. package/dist/ai/apis/openai-compat.js +142 -0
  54. package/dist/ai/apis/openai-completions.d.ts +28 -0
  55. package/dist/ai/apis/openai-completions.js +246 -0
  56. package/dist/ai/apis/openai-request.d.ts +35 -0
  57. package/dist/ai/apis/openai-request.js +303 -0
  58. package/dist/ai/apis/openai-responses-request.d.ts +52 -0
  59. package/dist/ai/apis/openai-responses-request.js +266 -0
  60. package/dist/ai/apis/openai-responses.d.ts +28 -0
  61. package/dist/ai/apis/openai-responses.js +303 -0
  62. package/dist/ai/apis/shared.d.ts +56 -0
  63. package/dist/ai/apis/shared.js +179 -0
  64. package/dist/ai/cache/economics.d.ts +24 -0
  65. package/dist/ai/cache/economics.js +69 -0
  66. package/dist/ai/cache/fingerprint.d.ts +17 -0
  67. package/dist/ai/cache/fingerprint.js +39 -0
  68. package/dist/ai/cache/miss.d.ts +49 -0
  69. package/dist/ai/cache/miss.js +96 -0
  70. package/dist/ai/cache/reporting.d.ts +39 -0
  71. package/dist/ai/cache/reporting.js +102 -0
  72. package/dist/ai/cache/types.d.ts +94 -0
  73. package/dist/ai/cache/types.js +19 -0
  74. package/dist/ai/cache/warmer.d.ts +94 -0
  75. package/dist/ai/cache/warmer.js +224 -0
  76. package/dist/ai/context.d.ts +35 -0
  77. package/dist/ai/context.js +114 -0
  78. package/dist/ai/cost.d.ts +21 -0
  79. package/dist/ai/cost.js +60 -0
  80. package/dist/ai/event-stream.d.ts +33 -0
  81. package/dist/ai/event-stream.js +101 -0
  82. package/dist/ai/fake/fake-provider.d.ts +68 -0
  83. package/dist/ai/fake/fake-provider.js +278 -0
  84. package/dist/ai/fake/fake-script.d.ts +69 -0
  85. package/dist/ai/fake/fake-script.js +142 -0
  86. package/dist/ai/http.d.ts +54 -0
  87. package/dist/ai/http.js +212 -0
  88. package/dist/ai/json-partial.d.ts +17 -0
  89. package/dist/ai/json-partial.js +243 -0
  90. package/dist/ai/overflow.d.ts +22 -0
  91. package/dist/ai/overflow.js +61 -0
  92. package/dist/ai/providers/auth.d.ts +71 -0
  93. package/dist/ai/providers/auth.js +202 -0
  94. package/dist/ai/providers/builtin.d.ts +23 -0
  95. package/dist/ai/providers/builtin.js +148 -0
  96. package/dist/ai/providers/catalog-data.d.ts +5 -0
  97. package/dist/ai/providers/catalog-data.js +19 -0
  98. package/dist/ai/providers/catalog.d.ts +28 -0
  99. package/dist/ai/providers/catalog.js +166 -0
  100. package/dist/ai/providers/registry.d.ts +83 -0
  101. package/dist/ai/providers/registry.js +305 -0
  102. package/dist/ai/sse.d.ts +32 -0
  103. package/dist/ai/sse.js +140 -0
  104. package/dist/ai/thinking.d.ts +42 -0
  105. package/dist/ai/thinking.js +101 -0
  106. package/dist/ai/types.d.ts +428 -0
  107. package/dist/ai/types.js +19 -0
  108. package/dist/bundle/ama-sandbox.cjs +324 -0
  109. package/dist/bundle/ama.cjs +25770 -0
  110. package/dist/bundle.d.ts +9 -0
  111. package/dist/bundle.js +15 -0
  112. package/dist/cli/args.d.ts +82 -0
  113. package/dist/cli/args.js +381 -0
  114. package/dist/cli/bootstrap.d.ts +18 -0
  115. package/dist/cli/bootstrap.js +398 -0
  116. package/dist/cli/compose-providers.d.ts +37 -0
  117. package/dist/cli/compose-providers.js +104 -0
  118. package/dist/cli/compose-session.d.ts +69 -0
  119. package/dist/cli/compose-session.js +370 -0
  120. package/dist/cli/compose-store.d.ts +24 -0
  121. package/dist/cli/compose-store.js +125 -0
  122. package/dist/cli/compose.d.ts +106 -0
  123. package/dist/cli/compose.js +206 -0
  124. package/dist/cli/default-model.d.ts +16 -0
  125. package/dist/cli/default-model.js +24 -0
  126. package/dist/cli/deps.d.ts +205 -0
  127. package/dist/cli/deps.js +12 -0
  128. package/dist/cli/exit-codes.d.ts +29 -0
  129. package/dist/cli/exit-codes.js +40 -0
  130. package/dist/cli/main.d.ts +26 -0
  131. package/dist/cli/main.js +165 -0
  132. package/dist/cli/runtime.d.ts +90 -0
  133. package/dist/cli/runtime.js +8 -0
  134. package/dist/cli/startup-screen.d.ts +15 -0
  135. package/dist/cli/startup-screen.js +56 -0
  136. package/dist/cli/startup-steps.d.ts +35 -0
  137. package/dist/cli/startup-steps.js +197 -0
  138. package/dist/cli/subcommands/auth.d.ts +12 -0
  139. package/dist/cli/subcommands/auth.js +91 -0
  140. package/dist/cli/subcommands/config.d.ts +44 -0
  141. package/dist/cli/subcommands/config.js +201 -0
  142. package/dist/cli/subcommands/context.d.ts +21 -0
  143. package/dist/cli/subcommands/context.js +41 -0
  144. package/dist/cli/subcommands/doctor.d.ts +11 -0
  145. package/dist/cli/subcommands/doctor.js +246 -0
  146. package/dist/cli/subcommands/models-cache-probe.d.ts +34 -0
  147. package/dist/cli/subcommands/models-cache-probe.js +190 -0
  148. package/dist/cli/subcommands/models-discover.d.ts +40 -0
  149. package/dist/cli/subcommands/models-discover.js +204 -0
  150. package/dist/cli/subcommands/models.d.ts +40 -0
  151. package/dist/cli/subcommands/models.js +144 -0
  152. package/dist/cli/subcommands/sessions.d.ts +11 -0
  153. package/dist/cli/subcommands/sessions.js +100 -0
  154. package/dist/codemode/capability.d.ts +37 -0
  155. package/dist/codemode/capability.js +55 -0
  156. package/dist/codemode/declarations.d.ts +44 -0
  157. package/dist/codemode/declarations.js +111 -0
  158. package/dist/codemode/host-side.d.ts +59 -0
  159. package/dist/codemode/host-side.js +253 -0
  160. package/dist/codemode/modes.d.ts +23 -0
  161. package/dist/codemode/modes.js +40 -0
  162. package/dist/codemode/protocol.d.ts +91 -0
  163. package/dist/codemode/protocol.js +114 -0
  164. package/dist/codemode/sandbox-entry.d.ts +25 -0
  165. package/dist/codemode/sandbox-entry.js +323 -0
  166. package/dist/codemode/store.d.ts +26 -0
  167. package/dist/codemode/store.js +53 -0
  168. package/dist/codemode/tool.d.ts +105 -0
  169. package/dist/codemode/tool.js +283 -0
  170. package/dist/compaction/branch-summary.d.ts +30 -0
  171. package/dist/compaction/branch-summary.js +79 -0
  172. package/dist/compaction/breaker.d.ts +32 -0
  173. package/dist/compaction/breaker.js +65 -0
  174. package/dist/compaction/cut-point.d.ts +23 -0
  175. package/dist/compaction/cut-point.js +70 -0
  176. package/dist/compaction/estimate.d.ts +30 -0
  177. package/dist/compaction/estimate.js +114 -0
  178. package/dist/compaction/prune-tier.d.ts +31 -0
  179. package/dist/compaction/prune-tier.js +83 -0
  180. package/dist/compaction/serialize.d.ts +20 -0
  181. package/dist/compaction/serialize.js +115 -0
  182. package/dist/compaction/summarize-tier.d.ts +111 -0
  183. package/dist/compaction/summarize-tier.js +305 -0
  184. package/dist/config/auth-file.d.ts +39 -0
  185. package/dist/config/auth-file.js +92 -0
  186. package/dist/config/context-files.d.ts +30 -0
  187. package/dist/config/context-files.js +77 -0
  188. package/dist/config/load.d.ts +45 -0
  189. package/dist/config/load.js +97 -0
  190. package/dist/config/merge.d.ts +73 -0
  191. package/dist/config/merge.js +248 -0
  192. package/dist/config/paths.d.ts +38 -0
  193. package/dist/config/paths.js +108 -0
  194. package/dist/config/profile.d.ts +27 -0
  195. package/dist/config/profile.js +65 -0
  196. package/dist/config/schema.d.ts +34 -0
  197. package/dist/config/schema.js +413 -0
  198. package/dist/config/trust.d.ts +42 -0
  199. package/dist/config/trust.js +122 -0
  200. package/dist/config/types.d.ts +172 -0
  201. package/dist/config/types.js +27 -0
  202. package/dist/config/write.d.ts +10 -0
  203. package/dist/config/write.js +25 -0
  204. package/dist/errors.d.ts +28 -0
  205. package/dist/errors.js +30 -0
  206. package/dist/hooks/config.d.ts +49 -0
  207. package/dist/hooks/config.js +102 -0
  208. package/dist/hooks/dispatcher.d.ts +41 -0
  209. package/dist/hooks/dispatcher.js +104 -0
  210. package/dist/hooks/matcher.d.ts +22 -0
  211. package/dist/hooks/matcher.js +108 -0
  212. package/dist/hooks/protocol.d.ts +33 -0
  213. package/dist/hooks/protocol.js +240 -0
  214. package/dist/hooks/runner.d.ts +30 -0
  215. package/dist/hooks/runner.js +143 -0
  216. package/dist/hooks/types.d.ts +147 -0
  217. package/dist/hooks/types.js +20 -0
  218. package/dist/host/api-impl.d.ts +75 -0
  219. package/dist/host/api-impl.js +173 -0
  220. package/dist/host/loader.d.ts +31 -0
  221. package/dist/host/loader.js +147 -0
  222. package/dist/host/types.d.ts +169 -0
  223. package/dist/host/types.js +14 -0
  224. package/dist/host.d.ts +5 -0
  225. package/dist/host.js +4 -0
  226. package/dist/index.d.ts +41 -0
  227. package/dist/index.js +28 -0
  228. package/dist/modes/commands-core.d.ts +44 -0
  229. package/dist/modes/commands-core.js +171 -0
  230. package/dist/modes/interactive/approval-dialog.d.ts +48 -0
  231. package/dist/modes/interactive/approval-dialog.js +202 -0
  232. package/dist/modes/interactive/commands.d.ts +41 -0
  233. package/dist/modes/interactive/commands.js +202 -0
  234. package/dist/modes/interactive/completion.d.ts +53 -0
  235. package/dist/modes/interactive/completion.js +157 -0
  236. package/dist/modes/interactive/interactive-mode.d.ts +46 -0
  237. package/dist/modes/interactive/interactive-mode.js +487 -0
  238. package/dist/modes/interactive/key-dispatch.d.ts +29 -0
  239. package/dist/modes/interactive/key-dispatch.js +107 -0
  240. package/dist/modes/interactive/line/line-editor.d.ts +50 -0
  241. package/dist/modes/interactive/line/line-editor.js +232 -0
  242. package/dist/modes/interactive/line/line-mode.d.ts +20 -0
  243. package/dist/modes/interactive/line/line-mode.js +216 -0
  244. package/dist/modes/interactive/line/line-render.d.ts +35 -0
  245. package/dist/modes/interactive/line/line-render.js +171 -0
  246. package/dist/modes/interactive/line/paste-state.d.ts +26 -0
  247. package/dist/modes/interactive/line/paste-state.js +72 -0
  248. package/dist/modes/interactive/message-view.d.ts +77 -0
  249. package/dist/modes/interactive/message-view.js +269 -0
  250. package/dist/modes/interactive/pickers.d.ts +42 -0
  251. package/dist/modes/interactive/pickers.js +115 -0
  252. package/dist/modes/interactive/startup-ui.d.ts +28 -0
  253. package/dist/modes/interactive/startup-ui.js +238 -0
  254. package/dist/modes/interactive/status-bar.d.ts +48 -0
  255. package/dist/modes/interactive/status-bar.js +139 -0
  256. package/dist/modes/interactive/tool-view.d.ts +95 -0
  257. package/dist/modes/interactive/tool-view.js +344 -0
  258. package/dist/modes/print/json-event.d.ts +15 -0
  259. package/dist/modes/print/json-event.js +39 -0
  260. package/dist/modes/print/print-mode.d.ts +15 -0
  261. package/dist/modes/print/print-mode.js +96 -0
  262. package/dist/modes/rpc/commands.d.ts +40 -0
  263. package/dist/modes/rpc/commands.js +258 -0
  264. package/dist/modes/rpc/jsonl.d.ts +16 -0
  265. package/dist/modes/rpc/jsonl.js +55 -0
  266. package/dist/modes/rpc/rpc-mode.d.ts +22 -0
  267. package/dist/modes/rpc/rpc-mode.js +153 -0
  268. package/dist/modes/session-report.d.ts +55 -0
  269. package/dist/modes/session-report.js +278 -0
  270. package/dist/modes/shared.d.ts +13 -0
  271. package/dist/modes/shared.js +52 -0
  272. package/dist/modes/startup-ui-text.d.ts +16 -0
  273. package/dist/modes/startup-ui-text.js +103 -0
  274. package/dist/permissions/broker.d.ts +47 -0
  275. package/dist/permissions/broker.js +107 -0
  276. package/dist/permissions/dangerous.d.ts +47 -0
  277. package/dist/permissions/dangerous.js +370 -0
  278. package/dist/permissions/pipeline.d.ts +51 -0
  279. package/dist/permissions/pipeline.js +181 -0
  280. package/dist/permissions/preview.d.ts +43 -0
  281. package/dist/permissions/preview.js +463 -0
  282. package/dist/permissions/rules.d.ts +58 -0
  283. package/dist/permissions/rules.js +249 -0
  284. package/dist/permissions/types.d.ts +100 -0
  285. package/dist/permissions/types.js +18 -0
  286. package/dist/rpc.d.ts +171 -0
  287. package/dist/rpc.js +13 -0
  288. package/dist/sdk.d.ts +98 -0
  289. package/dist/sdk.js +195 -0
  290. package/dist/session/manager.d.ts +70 -0
  291. package/dist/session/manager.js +278 -0
  292. package/dist/session/migrate.d.ts +19 -0
  293. package/dist/session/migrate.js +53 -0
  294. package/dist/session/projection.d.ts +50 -0
  295. package/dist/session/projection.js +180 -0
  296. package/dist/session/store.d.ts +47 -0
  297. package/dist/session/store.js +210 -0
  298. package/dist/session/tree.d.ts +21 -0
  299. package/dist/session/tree.js +88 -0
  300. package/dist/session/types.d.ts +199 -0
  301. package/dist/session/types.js +18 -0
  302. package/dist/skills/discover.d.ts +60 -0
  303. package/dist/skills/discover.js +160 -0
  304. package/dist/skills/expand.d.ts +35 -0
  305. package/dist/skills/expand.js +46 -0
  306. package/dist/skills/frontmatter.d.ts +27 -0
  307. package/dist/skills/frontmatter.js +157 -0
  308. package/dist/skills/index-prompt.d.ts +13 -0
  309. package/dist/skills/index-prompt.js +42 -0
  310. package/dist/skills/templates.d.ts +52 -0
  311. package/dist/skills/templates.js +177 -0
  312. package/dist/tools/bash.d.ts +49 -0
  313. package/dist/tools/bash.js +222 -0
  314. package/dist/tools/edit-fuzzy.d.ts +36 -0
  315. package/dist/tools/edit-fuzzy.js +129 -0
  316. package/dist/tools/edit.d.ts +38 -0
  317. package/dist/tools/edit.js +241 -0
  318. package/dist/tools/file-mutex.d.ts +8 -0
  319. package/dist/tools/file-mutex.js +29 -0
  320. package/dist/tools/glob.d.ts +44 -0
  321. package/dist/tools/glob.js +217 -0
  322. package/dist/tools/grep.d.ts +39 -0
  323. package/dist/tools/grep.js +179 -0
  324. package/dist/tools/ignore.d.ts +40 -0
  325. package/dist/tools/ignore.js +174 -0
  326. package/dist/tools/ls.d.ts +21 -0
  327. package/dist/tools/ls.js +96 -0
  328. package/dist/tools/output-accumulator.d.ts +48 -0
  329. package/dist/tools/output-accumulator.js +106 -0
  330. package/dist/tools/paths.d.ts +20 -0
  331. package/dist/tools/paths.js +58 -0
  332. package/dist/tools/presets.d.ts +71 -0
  333. package/dist/tools/presets.js +128 -0
  334. package/dist/tools/process-tree.d.ts +35 -0
  335. package/dist/tools/process-tree.js +125 -0
  336. package/dist/tools/read.d.ts +28 -0
  337. package/dist/tools/read.js +181 -0
  338. package/dist/tools/registry.d.ts +43 -0
  339. package/dist/tools/registry.js +106 -0
  340. package/dist/tools/shell.d.ts +38 -0
  341. package/dist/tools/shell.js +91 -0
  342. package/dist/tools/task.d.ts +29 -0
  343. package/dist/tools/task.js +107 -0
  344. package/dist/tools/todo.d.ts +28 -0
  345. package/dist/tools/todo.js +107 -0
  346. package/dist/tools/truncate.d.ts +44 -0
  347. package/dist/tools/truncate.js +175 -0
  348. package/dist/tools/types.d.ts +135 -0
  349. package/dist/tools/types.js +19 -0
  350. package/dist/tools/write.d.ts +20 -0
  351. package/dist/tools/write.js +84 -0
  352. package/dist/tui/ansi.d.ts +29 -0
  353. package/dist/tui/ansi.js +420 -0
  354. package/dist/tui/component.d.ts +38 -0
  355. package/dist/tui/component.js +13 -0
  356. package/dist/tui/components/box.d.ts +26 -0
  357. package/dist/tui/components/box.js +65 -0
  358. package/dist/tui/components/container.d.ts +14 -0
  359. package/dist/tui/components/container.js +39 -0
  360. package/dist/tui/components/editor-buffer.d.ts +67 -0
  361. package/dist/tui/components/editor-buffer.js +300 -0
  362. package/dist/tui/components/editor-paste.d.ts +29 -0
  363. package/dist/tui/components/editor-paste.js +64 -0
  364. package/dist/tui/components/editor.d.ts +114 -0
  365. package/dist/tui/components/editor.js +530 -0
  366. package/dist/tui/components/key-value.d.ts +29 -0
  367. package/dist/tui/components/key-value.js +48 -0
  368. package/dist/tui/components/loader.d.ts +35 -0
  369. package/dist/tui/components/loader.js +71 -0
  370. package/dist/tui/components/markdown.d.ts +90 -0
  371. package/dist/tui/components/markdown.js +462 -0
  372. package/dist/tui/components/meter.d.ts +29 -0
  373. package/dist/tui/components/meter.js +47 -0
  374. package/dist/tui/components/overlay.d.ts +24 -0
  375. package/dist/tui/components/overlay.js +52 -0
  376. package/dist/tui/components/select-list.d.ts +57 -0
  377. package/dist/tui/components/select-list.js +179 -0
  378. package/dist/tui/components/spacer.d.ts +11 -0
  379. package/dist/tui/components/spacer.js +16 -0
  380. package/dist/tui/components/text.d.ts +30 -0
  381. package/dist/tui/components/text.js +65 -0
  382. package/dist/tui/keybindings.d.ts +66 -0
  383. package/dist/tui/keybindings.js +120 -0
  384. package/dist/tui/keys.d.ts +38 -0
  385. package/dist/tui/keys.js +275 -0
  386. package/dist/tui/stdin-buffer.d.ts +41 -0
  387. package/dist/tui/stdin-buffer.js +206 -0
  388. package/dist/tui/terminal.d.ts +79 -0
  389. package/dist/tui/terminal.js +153 -0
  390. package/dist/tui/theme.d.ts +31 -0
  391. package/dist/tui/theme.js +199 -0
  392. package/dist/tui/tui.d.ts +103 -0
  393. package/dist/tui/tui.js +363 -0
  394. package/dist/tui/vt-screen.d.ts +46 -0
  395. package/dist/tui/vt-screen.js +251 -0
  396. package/dist/tui.d.ts +30 -0
  397. package/dist/tui.js +31 -0
  398. package/dist/version.d.ts +8 -0
  399. package/dist/version.js +24 -0
  400. package/docs/codemode.md +102 -0
  401. package/docs/hooks.md +196 -0
  402. package/docs/host-api.md +161 -0
  403. package/docs/providers.md +316 -0
  404. package/docs/rpc.md +253 -0
  405. package/docs/session-format.md +119 -0
  406. package/docs/tui.md +168 -0
  407. package/package.json +101 -4
@@ -0,0 +1,484 @@
1
+ /**
2
+ * AgentSessionImpl(设计 §4.2–§4.3、§9、§11.1 第 16 步、§13.1)。[B2]
3
+ *
4
+ * 会话 = SessionManager(JSONL 树,事实来源)+ Agent(上下文消息、队列、run)+ 压缩 / 重试 / Hook 调度。
5
+ * - 每条 message_end 落盘为条目;Agent 的上下文 = 活动分支的投影(压缩 / context_edit 后重建)。
6
+ * - 首次模型请求前把系统提示 + 工具表作为首条 `system` 消息落盘并 `flush()`(此时才创建文件);
7
+ * 之后节或工具表变化落 system 补丁。
8
+ * - `prompt()`:运行中且无 streamingBehavior → `AmaError{code:"busy"}`;否则展开(expandPrompt)→
9
+ * UserPromptSubmit Hook → 阈值压缩检查 → 会话周期(session-run.ts);周期结束后 resolve。
10
+ * - `steer()` / `followUp()`:运行中入队(返回 "queued");空闲时直接以该消息开始一个周期("handled")。
11
+ * - `abort()`:中断供应商流、工具、重试等待与压缩;回到 idle 后 resolve;不清队列。
12
+ */
13
+ import { join } from "node:path";
14
+ import { AmaError } from "../errors.js";
15
+ import { buildProjection } from "../session/projection.js";
16
+ import { Agent } from "./agent.js";
17
+ import { queuedText } from "./queue.js";
18
+ import { resolveRetrySettings } from "./retry.js";
19
+ import { SessionCacheController, resolveCacheSettings } from "./session-cache.js";
20
+ import { CompactionController } from "./session-compaction.js";
21
+ import { makeUserMessage, runPrompt } from "./session-run.js";
22
+ import { buildSessionState, computeStats, lastAssistantText } from "./session-state.js";
23
+ import { DEFAULT_SUBAGENT_CONCURRENCY, SubagentPool, runSubagent } from "./session-subagent.js";
24
+ import { persistMessage, runHookWithEvents, syncSystemMessage } from "./session-sync.js";
25
+ import { createToolRunnerOptions } from "./session-tools.js";
26
+ import { convertToLlm } from "./transform.js";
27
+ /** `"user"` = 普通用户输入,不写 origin。 */
28
+ function normalizeOrigin(origin) {
29
+ return origin === undefined || origin === "user" ? undefined : origin;
30
+ }
31
+ export class AgentSessionImpl {
32
+ options;
33
+ manager;
34
+ agent;
35
+ cwd;
36
+ depth;
37
+ readFiles = new Set();
38
+ stream;
39
+ cache;
40
+ currentModel;
41
+ currentThinking;
42
+ allTools = new Map();
43
+ activeNames;
44
+ listeners = new Set();
45
+ compaction;
46
+ retrySettings;
47
+ cycle;
48
+ retrying = false;
49
+ stopReason;
50
+ stopFlag = false;
51
+ turns = 0;
52
+ systemInput;
53
+ subagentPool;
54
+ disposed = false;
55
+ /** 已入队、尚未投递的消息(投递时发 queue_update)。 */
56
+ queuedMessages = new WeakSet();
57
+ constructor(options) {
58
+ this.options = options;
59
+ this.manager = options.sessionManager;
60
+ this.cwd = this.manager.cwd;
61
+ this.depth = options.depth ?? 0;
62
+ this.currentModel = options.model;
63
+ this.currentThinking = options.thinkingLevel ?? "off";
64
+ for (const tool of options.tools ?? [])
65
+ this.allTools.set(tool.name, tool);
66
+ this.activeNames = [...(options.activeTools ?? this.allTools.keys())].filter((name) => this.allTools.has(name));
67
+ this.systemInput = { ...(options.system ?? {}) };
68
+ this.retrySettings = resolveRetrySettings(options.retry);
69
+ this.cache = new SessionCacheController(this, resolveCacheSettings(options.cache), {
70
+ decider: () => options.warmingDecider?.(),
71
+ });
72
+ this.stream = this.cache.wrapStream((model, context, streamOptions) => {
73
+ const api = options.providers.getApi(model.api);
74
+ if (api === undefined) {
75
+ throw new AmaError("provider_not_found", `no implementation registered for api ${model.api}`);
76
+ }
77
+ return api.stream(model, context, streamOptions);
78
+ });
79
+ const runner = createToolRunnerOptions(this);
80
+ const agentOptions = {
81
+ hooks: {
82
+ convertToLlm: (messages) => convertToLlm(messages, {
83
+ provider: this.currentModel.provider,
84
+ model: this.currentModel.id,
85
+ }),
86
+ beforeToolCall: runner.beforeToolCall,
87
+ prepareNextTurn: async () => {
88
+ const signal = this.agent.signal ?? this.cycle?.controller.signal;
89
+ if (signal !== undefined)
90
+ await this.compaction.checkThreshold(signal);
91
+ },
92
+ finishTurn: async () => {
93
+ this.turns++;
94
+ if (this.stopFlag)
95
+ return "end";
96
+ const maxTurns = options.maxTurns;
97
+ return maxTurns !== undefined && this.turns >= maxTurns ? "end" : "continue";
98
+ },
99
+ },
100
+ stream: this.stream,
101
+ getModel: () => this.currentModel,
102
+ getThinkingLevel: () => this.currentThinking,
103
+ streamOptions: async () => {
104
+ const apiKey = await this.resolveApiKey();
105
+ return apiKey === undefined
106
+ ? { sessionId: this.manager.id }
107
+ : { apiKey, sessionId: this.manager.id };
108
+ },
109
+ beforeRequest: async () => {
110
+ this.syncSystem();
111
+ this.manager.flush();
112
+ },
113
+ tools: runner,
114
+ messages: buildProjection(this.manager.branch()).messages,
115
+ onListenerError: (error, event) => this.log("warn", `listener failed on ${event.type}: ${String(error)}`),
116
+ };
117
+ if (options.steeringMode !== undefined)
118
+ agentOptions.steeringMode = options.steeringMode;
119
+ if (options.followUpMode !== undefined)
120
+ agentOptions.followUpMode = options.followUpMode;
121
+ this.agent = new Agent(agentOptions);
122
+ this.agent.subscribe((event) => this.onAgentEvent(event));
123
+ this.compaction = new CompactionController(this, options.compaction);
124
+ const subagents = options.subagents === false ? undefined : options.subagents;
125
+ this.subagentPool = new SubagentPool(subagents?.maxConcurrent ?? DEFAULT_SUBAGENT_CONCURRENCY);
126
+ }
127
+ // -------------------------------------------------------------------------
128
+ // SessionCore
129
+ // -------------------------------------------------------------------------
130
+ model() {
131
+ return this.currentModel;
132
+ }
133
+ thinkingLevel() {
134
+ return this.currentThinking;
135
+ }
136
+ outputDir() {
137
+ if (this.options.outputDir !== undefined)
138
+ return this.options.outputDir;
139
+ const dir = this.manager.directory();
140
+ return dir === undefined ? undefined : join(dir, "outputs");
141
+ }
142
+ async resolveApiKey() {
143
+ try {
144
+ return (await this.options.providers.resolveApiKey(this.currentModel.provider)).apiKey;
145
+ }
146
+ catch {
147
+ return undefined;
148
+ }
149
+ }
150
+ emit(event) {
151
+ this.cache.onEvent(event);
152
+ for (const listener of this.listeners) {
153
+ try {
154
+ listener(event);
155
+ }
156
+ catch (error) {
157
+ this.log("warn", `session listener failed on ${event.type}: ${String(error)}`);
158
+ }
159
+ }
160
+ }
161
+ appendEntry(input) {
162
+ const entry = this.manager.append(input);
163
+ this.emit({ type: "entry_appended", entry });
164
+ return entry;
165
+ }
166
+ reloadMessages() {
167
+ this.agent.messages = buildProjection(this.manager.branch()).messages;
168
+ }
169
+ activeTool(name) {
170
+ return this.activeNames.includes(name) ? this.allTools.get(name) : undefined;
171
+ }
172
+ tool(name) {
173
+ return this.allTools.get(name);
174
+ }
175
+ activeToolNames() {
176
+ return [...this.activeNames];
177
+ }
178
+ runHook(event, payload, signal) {
179
+ return runHookWithEvents(this, event, payload, signal);
180
+ }
181
+ requestStop(reason) {
182
+ this.stopFlag = true;
183
+ this.stopReason = reason;
184
+ }
185
+ log(level, message) {
186
+ this.options.log?.(level, message);
187
+ }
188
+ // -------------------------------------------------------------------------
189
+ // 事件与落盘
190
+ // -------------------------------------------------------------------------
191
+ onAgentEvent(event) {
192
+ if (event.type === "message_end")
193
+ persistMessage(this, event.message);
194
+ else if (event.type === "agent_start")
195
+ this.compaction.breaker.startRun();
196
+ this.emit(event);
197
+ if (event.type === "message_start" &&
198
+ event.message.role === "user" &&
199
+ this.queuedMessages.delete(event.message)) {
200
+ this.emitQueue();
201
+ }
202
+ }
203
+ emitQueue() {
204
+ this.emit({
205
+ type: "queue_update",
206
+ steering: this.agent.steeringQueue.snapshot().map(queuedText),
207
+ followUp: this.agent.followUpQueue.snapshot().map(queuedText),
208
+ });
209
+ }
210
+ syncSystem() {
211
+ syncSystemMessage(this, this.systemInput, this.getTools());
212
+ }
213
+ // -------------------------------------------------------------------------
214
+ // 周期
215
+ // -------------------------------------------------------------------------
216
+ assertUsable() {
217
+ if (this.disposed)
218
+ throw new AmaError("session_closed", "session is disposed");
219
+ }
220
+ startCycle(work) {
221
+ const controller = new AbortController();
222
+ let done = () => { };
223
+ const promise = new Promise((resolve) => {
224
+ done = resolve;
225
+ });
226
+ this.cycle = { controller, promise };
227
+ this.turns = 0;
228
+ this.stopFlag = false;
229
+ this.stopReason = undefined;
230
+ return (async () => {
231
+ try {
232
+ return await work(controller.signal);
233
+ }
234
+ finally {
235
+ this.cycle = undefined;
236
+ this.retrying = false;
237
+ done();
238
+ }
239
+ })();
240
+ }
241
+ runDeps() {
242
+ return {
243
+ core: this,
244
+ compaction: this.compaction,
245
+ retry: () => this.retrySettings,
246
+ syncSystem: () => this.syncSystem(),
247
+ stopRequested: () => this.stopFlag,
248
+ setRetrying: (value) => {
249
+ this.retrying = value;
250
+ },
251
+ lastAssistantText: () => this.getLastAssistantText(),
252
+ };
253
+ }
254
+ // -------------------------------------------------------------------------
255
+ // AgentSession
256
+ // -------------------------------------------------------------------------
257
+ async prompt(text, options = {}) {
258
+ this.assertUsable();
259
+ if (this.cycle !== undefined) {
260
+ const behavior = options.streamingBehavior;
261
+ if (behavior === undefined) {
262
+ throw new AmaError("busy", "a run is in progress; pass streamingBehavior or use steer()/followUp()");
263
+ }
264
+ this.enqueue(makeUserMessage(text, options.images, normalizeOrigin(options.origin ?? behavior)), behavior);
265
+ return "queued";
266
+ }
267
+ const origin = normalizeOrigin(options.origin);
268
+ return this.startCycle((signal) => runPrompt(this.runDeps(), text, options.images, origin, signal));
269
+ }
270
+ enqueue(message, queue) {
271
+ this.queuedMessages.add(message);
272
+ if (queue === "steer")
273
+ this.agent.steer(message);
274
+ else
275
+ this.agent.followUp(message);
276
+ this.emitQueue();
277
+ }
278
+ async enqueueOrRun(text, queue, options) {
279
+ this.assertUsable();
280
+ const origin = normalizeOrigin(options.origin ?? queue);
281
+ if (this.cycle === undefined) {
282
+ await this.startCycle((signal) => runPrompt(this.runDeps(), text, undefined, origin, signal));
283
+ return "handled";
284
+ }
285
+ this.enqueue(makeUserMessage(text, undefined, origin), queue);
286
+ return "queued";
287
+ }
288
+ steer(text, options = {}) {
289
+ return this.enqueueOrRun(text, "steer", options);
290
+ }
291
+ followUp(text, options = {}) {
292
+ return this.enqueueOrRun(text, "followUp", options);
293
+ }
294
+ async abort() {
295
+ const cycle = this.cycle;
296
+ if (cycle === undefined)
297
+ return;
298
+ cycle.controller.abort();
299
+ this.agent.abort();
300
+ await cycle.promise;
301
+ }
302
+ waitForIdle() {
303
+ return this.cycle?.promise ?? Promise.resolve();
304
+ }
305
+ clearQueue() {
306
+ const cleared = {
307
+ steering: this.agent.steeringQueue.clear().map(queuedText),
308
+ followUp: this.agent.followUpQueue.clear().map(queuedText),
309
+ };
310
+ this.emitQueue();
311
+ return cleared;
312
+ }
313
+ subscribe(listener) {
314
+ this.listeners.add(listener);
315
+ return () => this.listeners.delete(listener);
316
+ }
317
+ /** 手动压缩;运行中 → busy。 */
318
+ compact(instructions) {
319
+ this.assertUsable();
320
+ if (this.cycle !== undefined)
321
+ return Promise.reject(new AmaError("busy", "cannot compact while running"));
322
+ return this.startCycle((signal) => this.compaction.compactManual(instructions, signal));
323
+ }
324
+ async fork(entryId) {
325
+ this.assertUsable();
326
+ if (this.cycle !== undefined)
327
+ throw new AmaError("busy", "cannot fork while running");
328
+ return new AgentSessionImpl({
329
+ ...this.options,
330
+ ...this.childBase(),
331
+ sessionManager: this.manager.fork(entryId),
332
+ });
333
+ }
334
+ /**
335
+ * `/tree`:同文件换叶子;`summarize` 时为离开的分支写 branch_summary(挂在新叶子下)。
336
+ */
337
+ async navigate(targetId, options = {}) {
338
+ this.assertUsable();
339
+ if (this.cycle !== undefined)
340
+ throw new AmaError("busy", "cannot navigate while running");
341
+ let entry;
342
+ if (options.summarize === true) {
343
+ entry = await this.startCycle((signal) => this.compaction.leaveBranch(targetId, options.instructions, signal));
344
+ }
345
+ else
346
+ this.manager.setLeaf(targetId);
347
+ this.reloadMessages();
348
+ this.cache.onContextChanged();
349
+ return entry;
350
+ }
351
+ async setModel(ref) {
352
+ this.assertUsable();
353
+ const lookup = this.options.providers.findModel(ref);
354
+ if (!lookup.ok) {
355
+ throw new AmaError("model_not_found", `model ${ref} not found`, {
356
+ detail: lookup.candidates,
357
+ });
358
+ }
359
+ this.currentModel = lookup.model;
360
+ this.compaction.refresh();
361
+ this.appendEntry({
362
+ type: "model_change",
363
+ provider: lookup.model.provider,
364
+ modelId: lookup.model.id,
365
+ });
366
+ this.emit({
367
+ type: "model_changed",
368
+ model: { provider: lookup.model.provider, id: lookup.model.id },
369
+ });
370
+ }
371
+ setThinkingLevel(level) {
372
+ this.currentThinking = level;
373
+ this.appendEntry({ type: "thinking_level_change", thinkingLevel: level });
374
+ this.emit({ type: "thinking_level_changed", level });
375
+ }
376
+ setPermissionMode(mode) {
377
+ this.options.permission?.setMode(mode);
378
+ this.emit({ type: "permission_mode_changed", mode });
379
+ }
380
+ setActiveTools(names) {
381
+ const unknown = names.filter((name) => !this.allTools.has(name));
382
+ if (unknown.length > 0)
383
+ throw new AmaError("tool_not_found", `unknown tools: ${unknown.join(", ")}`);
384
+ this.activeNames = [...new Set(names)];
385
+ }
386
+ /** 宿主 / SDK 在会话创建后追加工具(下次请求前以 system 补丁声明)。 */
387
+ addTool(tool, active = true) {
388
+ if (this.allTools.has(tool.name))
389
+ throw new AmaError("tool_exists", `tool ${tool.name} already exists`);
390
+ this.allTools.set(tool.name, tool);
391
+ if (active)
392
+ this.activeNames.push(tool.name);
393
+ }
394
+ /** 更新系统提示的静态部分(SessionStart Hook 的 hookContext、宿主 instructions 等)。 */
395
+ updateSystem(patch) {
396
+ this.systemInput = { ...this.systemInput, ...patch };
397
+ }
398
+ setAutoCompaction(enabled) {
399
+ this.compaction.setAuto(enabled);
400
+ }
401
+ setAutoRetry(enabled) {
402
+ this.retrySettings = { ...this.retrySettings, enabled };
403
+ }
404
+ getTools() {
405
+ return this.activeNames
406
+ .map((name) => this.allTools.get(name))
407
+ .filter((tool) => tool !== undefined)
408
+ .sort((a, b) => a.name.localeCompare(b.name));
409
+ }
410
+ /** 发 session_start(bootstrap / SDK 在会话就绪后调用一次)。 */
411
+ announceStart(reason) {
412
+ const event = {
413
+ type: "session_start",
414
+ sessionId: this.manager.id,
415
+ cwd: this.cwd,
416
+ reason,
417
+ };
418
+ const file = this.manager.file();
419
+ if (file !== undefined)
420
+ event.sessionFile = file;
421
+ this.emit(event);
422
+ }
423
+ get state() {
424
+ return buildSessionState({
425
+ agent: this.agent,
426
+ manager: this.manager,
427
+ model: this.currentModel,
428
+ thinkingLevel: this.currentThinking,
429
+ permissionMode: this.options.permission?.mode ?? "default",
430
+ isCompacting: this.compaction.isCompacting,
431
+ isRetrying: this.retrying,
432
+ autoCompaction: this.compaction.settings.enabled,
433
+ autoRetry: this.retrySettings.enabled,
434
+ });
435
+ }
436
+ get messages() {
437
+ return this.agent.messages;
438
+ }
439
+ get entries() {
440
+ return this.manager.entries();
441
+ }
442
+ /** run 被 Hook 的 continue:false 结束时的说明。 */
443
+ get stopHookReason() {
444
+ return this.stopReason;
445
+ }
446
+ getLastAssistantText() {
447
+ return lastAssistantText(this.manager.branch());
448
+ }
449
+ getStats() {
450
+ const contextTokens = this.compaction.estimate().tokens;
451
+ const contextWindow = this.currentModel.contextWindow;
452
+ return computeStats({
453
+ sessionId: this.manager.id,
454
+ sessionFile: this.manager.file(),
455
+ branch: this.manager.branch(),
456
+ contextTokens,
457
+ contextWindow,
458
+ cache: this.cache.stats({ tokens: contextTokens, window: contextWindow }),
459
+ });
460
+ }
461
+ async dispose() {
462
+ if (this.disposed)
463
+ return;
464
+ await this.abort();
465
+ this.cache.dispose();
466
+ this.disposed = true;
467
+ this.manager.close();
468
+ this.listeners.clear();
469
+ }
470
+ // -------------------------------------------------------------------------
471
+ // 子 Agent(ToolContext.spawnSubagent,供 B3 的 task 工具)
472
+ // -------------------------------------------------------------------------
473
+ childBase() {
474
+ return {
475
+ model: this.currentModel,
476
+ thinkingLevel: this.currentThinking,
477
+ activeTools: this.activeNames,
478
+ system: this.systemInput,
479
+ };
480
+ }
481
+ spawnSubagent(request) {
482
+ return runSubagent(this, request, this.subagentPool, (options) => new AgentSessionImpl(options));
483
+ }
484
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * 系统提示的命名节装配与补丁 diff(设计 §1.2 system-prompt.ts、§9「缓存」)。[B2]
3
+ *
4
+ * 节顺序固定:preamble → tools → rules → project_context → skills → hooks → cwd → host
5
+ * (`hooks` = SessionStart Hook 的 additionalContext;`host` = 宿主 instructions.add,最后)。
6
+ * 不含时间戳等易变内容,保证前缀缓存稳定。
7
+ *
8
+ * 首次请求前,整份节 + 工具表作为首条 `system` 消息落盘;之后节或工具表变化时只落补丁
9
+ * (节名级替换、`null` 删除;`toolsAdded` / `toolsRemoved`),请求时由协议层重装全量。
10
+ */
11
+ import type { SystemMessage, ToolDecl } from "../ai/types.js";
12
+ import { type SystemState } from "../session/projection.js";
13
+ import type { AgentMessage } from "../session/types.js";
14
+ import type { ToolDefinition } from "../tools/types.js";
15
+ export declare const SECTION_ORDER: readonly ["preamble", "tools", "rules", "project_context", "skills", "hooks", "cwd", "host"];
16
+ export type SectionName = (typeof SECTION_ORDER)[number];
17
+ export declare const DEFAULT_PREAMBLE: string;
18
+ export interface SystemPromptInput {
19
+ preamble?: string;
20
+ tools: readonly ToolDefinition[];
21
+ extraRules?: readonly string[];
22
+ contextFiles?: readonly {
23
+ path: string;
24
+ content: string;
25
+ }[];
26
+ /** 预渲染的 `<available_skills>` 索引(B3 的 index-prompt.ts);缺省时由 skills 列表生成最小索引。 */
27
+ skillsIndex?: string;
28
+ skills?: readonly {
29
+ name: string;
30
+ description: string;
31
+ location: string;
32
+ }[];
33
+ /** SessionStart Hook 的 additionalContext。 */
34
+ hookContext?: string;
35
+ cwd: string;
36
+ /** 宿主 instructions(已读入的文本),按添加顺序。 */
37
+ hostInstructions?: readonly string[];
38
+ }
39
+ export declare function toolDecl(tool: ToolDefinition): ToolDecl;
40
+ /** 按名排序的工具声明(与 ToolRegistry.active() 的顺序一致)。 */
41
+ export declare function toolDecls(tools: readonly ToolDefinition[]): ToolDecl[];
42
+ export declare function assembleSections(input: SystemPromptInput): Record<SectionName, string | undefined>;
43
+ /** 去掉 undefined 的有序节表。 */
44
+ export declare function definedSections(sections: Record<SectionName, string | undefined>): Record<string, string>;
45
+ export declare function currentSystemState(messages: Iterable<AgentMessage>): SystemState | undefined;
46
+ /**
47
+ * 当前状态 → 目标状态的 system 消息:无当前状态 → 全量;有差异 → 补丁;无差异 → undefined。
48
+ */
49
+ export declare function diffSystem(current: SystemState | undefined, sections: Record<string, string>, tools: readonly ToolDecl[], timestamp?: number): SystemMessage | undefined;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * 系统提示的命名节装配与补丁 diff(设计 §1.2 system-prompt.ts、§9「缓存」)。[B2]
3
+ *
4
+ * 节顺序固定:preamble → tools → rules → project_context → skills → hooks → cwd → host
5
+ * (`hooks` = SessionStart Hook 的 additionalContext;`host` = 宿主 instructions.add,最后)。
6
+ * 不含时间戳等易变内容,保证前缀缓存稳定。
7
+ *
8
+ * 首次请求前,整份节 + 工具表作为首条 `system` 消息落盘;之后节或工具表变化时只落补丁
9
+ * (节名级替换、`null` 删除;`toolsAdded` / `toolsRemoved`),请求时由协议层重装全量。
10
+ */
11
+ import { replaySystem } from "../session/projection.js";
12
+ import { escapeXml } from "../skills/index-prompt.js";
13
+ export const SECTION_ORDER = [
14
+ "preamble",
15
+ "tools",
16
+ "rules",
17
+ "project_context",
18
+ "skills",
19
+ "hooks",
20
+ "cwd",
21
+ "host",
22
+ ];
23
+ export const DEFAULT_PREAMBLE = "You are ama, a coding agent working in the user's project through tools. Read files before " +
24
+ "changing them, make focused changes, and verify your work. Be concise.";
25
+ function firstLine(text) {
26
+ return text.split("\n", 1)[0]?.trim() ?? "";
27
+ }
28
+ export function toolDecl(tool) {
29
+ return { name: tool.name, description: tool.description, parameters: tool.parameters };
30
+ }
31
+ /** 按名排序的工具声明(与 ToolRegistry.active() 的顺序一致)。 */
32
+ export function toolDecls(tools) {
33
+ return [...tools].sort((a, b) => a.name.localeCompare(b.name)).map(toolDecl);
34
+ }
35
+ export function assembleSections(input) {
36
+ const tools = [...input.tools].sort((a, b) => a.name.localeCompare(b.name));
37
+ const toolLines = tools.map((tool) => {
38
+ const snippet = tool.promptSnippet ?? firstLine(tool.description);
39
+ // 内置工具的 promptSnippet 已以「name: 」开头(B3 约定),不再重复工具名。
40
+ return snippet.startsWith(`${tool.name}:`) ? `- ${snippet}` : `- ${tool.name}: ${snippet}`;
41
+ });
42
+ const rules = [
43
+ ...tools.flatMap((tool) => tool.promptGuidelines ?? []),
44
+ ...(input.extraRules ?? []),
45
+ ];
46
+ const projectContext = (input.contextFiles ?? [])
47
+ .map((file) => `<file path="${escapeXml(file.path)}">\n${file.content.trim()}\n</file>`)
48
+ .join("\n\n");
49
+ let skills = input.skillsIndex;
50
+ if (skills === undefined && input.skills !== undefined && input.skills.length > 0) {
51
+ skills = [
52
+ "<available_skills>",
53
+ ...input.skills.map((skill) => `<skill name="${escapeXml(skill.name)}" location="${escapeXml(skill.location)}">${escapeXml(skill.description)}</skill>`),
54
+ "</available_skills>",
55
+ ].join("\n");
56
+ }
57
+ const host = (input.hostInstructions ?? []).map((text) => text.trim()).filter(Boolean);
58
+ const nonEmpty = (text) => text === undefined || text.trim() === "" ? undefined : text;
59
+ return {
60
+ preamble: input.preamble ?? DEFAULT_PREAMBLE,
61
+ tools: toolLines.length > 0 ? `Available tools:\n${toolLines.join("\n")}` : undefined,
62
+ rules: rules.length > 0 ? `Rules:\n${rules.map((rule) => `- ${rule}`).join("\n")}` : undefined,
63
+ project_context: nonEmpty(projectContext),
64
+ skills: nonEmpty(skills),
65
+ hooks: nonEmpty(input.hookContext),
66
+ cwd: `Current working directory: ${input.cwd}`,
67
+ host: host.length > 0 ? host.join("\n\n") : undefined,
68
+ };
69
+ }
70
+ /** 去掉 undefined 的有序节表。 */
71
+ export function definedSections(sections) {
72
+ const out = {};
73
+ for (const name of SECTION_ORDER) {
74
+ const text = sections[name];
75
+ if (text !== undefined)
76
+ out[name] = text;
77
+ }
78
+ return out;
79
+ }
80
+ export function currentSystemState(messages) {
81
+ return replaySystem(messages);
82
+ }
83
+ function sameTool(a, b) {
84
+ return (a.description === b.description && JSON.stringify(a.parameters) === JSON.stringify(b.parameters));
85
+ }
86
+ /**
87
+ * 当前状态 → 目标状态的 system 消息:无当前状态 → 全量;有差异 → 补丁;无差异 → undefined。
88
+ */
89
+ export function diffSystem(current, sections, tools, timestamp = Date.now()) {
90
+ if (current === undefined) {
91
+ const full = { role: "system", sections: { ...sections }, timestamp };
92
+ if (tools.length > 0)
93
+ full.toolsAdded = tools.map((tool) => ({ ...tool }));
94
+ return full;
95
+ }
96
+ const patch = {};
97
+ for (const [name, text] of Object.entries(sections)) {
98
+ if (current.sections[name] !== text)
99
+ patch[name] = text;
100
+ }
101
+ for (const name of Object.keys(current.sections)) {
102
+ if (!(name in sections))
103
+ patch[name] = null;
104
+ }
105
+ const before = new Map(current.tools.map((tool) => [tool.name, tool]));
106
+ const after = new Map(tools.map((tool) => [tool.name, tool]));
107
+ const toolsAdded = tools.filter((tool) => {
108
+ const old = before.get(tool.name);
109
+ return old === undefined || !sameTool(old, tool);
110
+ });
111
+ const toolsRemoved = [...before.keys()].filter((name) => !after.has(name));
112
+ if (Object.keys(patch).length === 0 && toolsAdded.length === 0 && toolsRemoved.length === 0) {
113
+ return undefined;
114
+ }
115
+ const message = { role: "system", sections: patch, timestamp };
116
+ if (toolsAdded.length > 0)
117
+ message.toolsAdded = toolsAdded.map((tool) => ({ ...tool }));
118
+ if (toolsRemoved.length > 0)
119
+ message.toolsRemoved = toolsRemoved;
120
+ return message;
121
+ }