@orion-agents/orion-code 0.1.4 → 0.1.6

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 (540) hide show
  1. package/README.md +73 -38
  2. package/README.zh-CN.md +32 -10
  3. package/dist/agents/coder.d.ts.map +1 -1
  4. package/dist/agents/coder.js.map +1 -1
  5. package/dist/agents/fork.d.ts +12 -4
  6. package/dist/agents/fork.d.ts.map +1 -1
  7. package/dist/agents/fork.js +28 -32
  8. package/dist/agents/fork.js.map +1 -1
  9. package/dist/agents/leader.d.ts.map +1 -1
  10. package/dist/agents/leader.js.map +1 -1
  11. package/dist/agents/worker-pool.d.ts.map +1 -1
  12. package/dist/agents/worker-pool.js +38 -29
  13. package/dist/agents/worker-pool.js.map +1 -1
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +4 -1
  17. package/dist/cli.js.map +1 -1
  18. package/dist/commands/context-commands.d.ts +4 -0
  19. package/dist/commands/context-commands.d.ts.map +1 -0
  20. package/dist/commands/context-commands.js +74 -0
  21. package/dist/commands/context-commands.js.map +1 -0
  22. package/dist/commands/context-tool-command-handlers.d.ts +13 -0
  23. package/dist/commands/context-tool-command-handlers.d.ts.map +1 -0
  24. package/dist/commands/context-tool-command-handlers.js +617 -0
  25. package/dist/commands/context-tool-command-handlers.js.map +1 -0
  26. package/dist/commands/core-command-handlers.d.ts +12 -0
  27. package/dist/commands/core-command-handlers.d.ts.map +1 -0
  28. package/dist/commands/core-command-handlers.js +805 -0
  29. package/dist/commands/core-command-handlers.js.map +1 -0
  30. package/dist/commands/diagnostic-command-handlers.d.ts +14 -0
  31. package/dist/commands/diagnostic-command-handlers.d.ts.map +1 -0
  32. package/dist/commands/diagnostic-command-handlers.js +1043 -0
  33. package/dist/commands/diagnostic-command-handlers.js.map +1 -0
  34. package/dist/commands/diagnostic-commands.d.ts +4 -0
  35. package/dist/commands/diagnostic-commands.d.ts.map +1 -0
  36. package/dist/commands/diagnostic-commands.js +175 -0
  37. package/dist/commands/diagnostic-commands.js.map +1 -0
  38. package/dist/commands/index.d.ts +9 -10
  39. package/dist/commands/index.d.ts.map +1 -1
  40. package/dist/commands/index.js +42 -3563
  41. package/dist/commands/index.js.map +1 -1
  42. package/dist/commands/legacy-commands.d.ts +4 -0
  43. package/dist/commands/legacy-commands.d.ts.map +1 -0
  44. package/dist/commands/legacy-commands.js +44 -0
  45. package/dist/commands/legacy-commands.js.map +1 -0
  46. package/dist/commands/model-command-handlers.d.ts +15 -0
  47. package/dist/commands/model-command-handlers.d.ts.map +1 -0
  48. package/dist/commands/model-command-handlers.js +526 -0
  49. package/dist/commands/model-command-handlers.js.map +1 -0
  50. package/dist/commands/model-commands.d.ts +4 -0
  51. package/dist/commands/model-commands.d.ts.map +1 -0
  52. package/dist/commands/model-commands.js +85 -0
  53. package/dist/commands/model-commands.js.map +1 -0
  54. package/dist/commands/parser.d.ts +12 -0
  55. package/dist/commands/parser.d.ts.map +1 -1
  56. package/dist/commands/parser.js +48 -7
  57. package/dist/commands/parser.js.map +1 -1
  58. package/dist/commands/registry.d.ts +4 -0
  59. package/dist/commands/registry.d.ts.map +1 -0
  60. package/dist/commands/registry.js +566 -0
  61. package/dist/commands/registry.js.map +1 -0
  62. package/dist/commands/session-command-handlers.d.ts +10 -0
  63. package/dist/commands/session-command-handlers.d.ts.map +1 -0
  64. package/dist/commands/session-command-handlers.js +626 -0
  65. package/dist/commands/session-command-handlers.js.map +1 -0
  66. package/dist/commands/session-commands.d.ts +4 -0
  67. package/dist/commands/session-commands.d.ts.map +1 -0
  68. package/dist/commands/session-commands.js +102 -0
  69. package/dist/commands/session-commands.js.map +1 -0
  70. package/dist/commands/system-commands.d.ts +4 -0
  71. package/dist/commands/system-commands.d.ts.map +1 -0
  72. package/dist/commands/system-commands.js +80 -0
  73. package/dist/commands/system-commands.js.map +1 -0
  74. package/dist/commands/target-command.d.ts +1 -1
  75. package/dist/commands/target-command.d.ts.map +1 -1
  76. package/dist/commands/target-command.js +42 -6
  77. package/dist/commands/target-command.js.map +1 -1
  78. package/dist/commands/tool-commands.d.ts +4 -0
  79. package/dist/commands/tool-commands.d.ts.map +1 -0
  80. package/dist/commands/tool-commands.js +49 -0
  81. package/dist/commands/tool-commands.js.map +1 -0
  82. package/dist/commands/types.d.ts +69 -5
  83. package/dist/commands/types.d.ts.map +1 -1
  84. package/dist/commands/types.js +3 -4
  85. package/dist/commands/types.js.map +1 -1
  86. package/dist/commands/workflow-command-handlers.d.ts +7 -0
  87. package/dist/commands/workflow-command-handlers.d.ts.map +1 -0
  88. package/dist/commands/workflow-command-handlers.js +32 -0
  89. package/dist/commands/workflow-command-handlers.js.map +1 -0
  90. package/dist/commands/workflow-commands.d.ts +4 -0
  91. package/dist/commands/workflow-commands.d.ts.map +1 -0
  92. package/dist/commands/workflow-commands.js +124 -0
  93. package/dist/commands/workflow-commands.js.map +1 -0
  94. package/dist/core/checkpoint.d.ts +12 -4
  95. package/dist/core/checkpoint.d.ts.map +1 -1
  96. package/dist/core/checkpoint.js +114 -28
  97. package/dist/core/checkpoint.js.map +1 -1
  98. package/dist/core/cost-tracker.d.ts +17 -1
  99. package/dist/core/cost-tracker.d.ts.map +1 -1
  100. package/dist/core/cost-tracker.js +24 -8
  101. package/dist/core/cost-tracker.js.map +1 -1
  102. package/dist/core/warn-dedup.d.ts +3 -0
  103. package/dist/core/warn-dedup.d.ts.map +1 -1
  104. package/dist/core/warn-dedup.js +6 -6
  105. package/dist/core/warn-dedup.js.map +1 -1
  106. package/dist/framework/index.d.ts +1 -1
  107. package/dist/framework/index.d.ts.map +1 -1
  108. package/dist/framework/index.js.map +1 -1
  109. package/dist/framework/prompt.d.ts +2 -2
  110. package/dist/framework/query.d.ts +2 -2
  111. package/dist/framework/query.d.ts.map +1 -1
  112. package/dist/framework/query.js +57 -10
  113. package/dist/framework/query.js.map +1 -1
  114. package/dist/framework/store.d.ts +15 -6
  115. package/dist/framework/store.d.ts.map +1 -1
  116. package/dist/framework/store.js +18 -0
  117. package/dist/framework/store.js.map +1 -1
  118. package/dist/framework/tool-scheduler.d.ts +16 -13
  119. package/dist/framework/tool-scheduler.d.ts.map +1 -1
  120. package/dist/framework/tool-scheduler.js +155 -38
  121. package/dist/framework/tool-scheduler.js.map +1 -1
  122. package/dist/framework/tool.d.ts +39 -2
  123. package/dist/framework/tool.d.ts.map +1 -1
  124. package/dist/framework/tool.js +27 -1
  125. package/dist/framework/tool.js.map +1 -1
  126. package/dist/harness/assembler.d.ts.map +1 -1
  127. package/dist/harness/assembler.js +4 -2
  128. package/dist/harness/assembler.js.map +1 -1
  129. package/dist/harness/drift-guard.d.ts.map +1 -1
  130. package/dist/harness/drift-guard.js +9 -1
  131. package/dist/harness/drift-guard.js.map +1 -1
  132. package/dist/harness/evidence.d.ts.map +1 -1
  133. package/dist/harness/evidence.js +3 -2
  134. package/dist/harness/evidence.js.map +1 -1
  135. package/dist/harness/safety.d.ts +11 -1
  136. package/dist/harness/safety.d.ts.map +1 -1
  137. package/dist/harness/safety.js +112 -16
  138. package/dist/harness/safety.js.map +1 -1
  139. package/dist/index.d.ts +1 -4
  140. package/dist/index.d.ts.map +1 -1
  141. package/dist/index.js.map +1 -1
  142. package/dist/init.d.ts +4 -8
  143. package/dist/init.d.ts.map +1 -1
  144. package/dist/init.js +4 -4
  145. package/dist/init.js.map +1 -1
  146. package/dist/ink-ui/App.d.ts +2 -2
  147. package/dist/ink-ui/components/Markdown.d.ts.map +1 -1
  148. package/dist/ink-ui/components/Markdown.js.map +1 -1
  149. package/dist/ink-ui/components/PixelHorseBanner.d.ts +2 -2
  150. package/dist/ink-ui/components/StatusLine.d.ts +2 -2
  151. package/dist/ink-ui/launch.d.ts +2 -2
  152. package/dist/ink-ui/screens/ReplScreen.d.ts +4 -3
  153. package/dist/ink-ui/screens/ReplScreen.d.ts.map +1 -1
  154. package/dist/ink-ui/screens/ReplScreen.js +103 -31
  155. package/dist/ink-ui/screens/ReplScreen.js.map +1 -1
  156. package/dist/memory/relevant-finder.d.ts +2 -1
  157. package/dist/memory/relevant-finder.d.ts.map +1 -1
  158. package/dist/memory/relevant-finder.js +17 -8
  159. package/dist/memory/relevant-finder.js.map +1 -1
  160. package/dist/memory/semantic-config.d.ts +9 -0
  161. package/dist/memory/semantic-config.d.ts.map +1 -0
  162. package/dist/memory/semantic-config.js +16 -0
  163. package/dist/memory/semantic-config.js.map +1 -0
  164. package/dist/memory/semantic-search.d.ts +1 -6
  165. package/dist/memory/semantic-search.d.ts.map +1 -1
  166. package/dist/memory/semantic-search.js +3 -15
  167. package/dist/memory/semantic-search.js.map +1 -1
  168. package/dist/memory/storage.d.ts +23 -0
  169. package/dist/memory/storage.d.ts.map +1 -1
  170. package/dist/memory/storage.js +116 -9
  171. package/dist/memory/storage.js.map +1 -1
  172. package/dist/memory/validation.d.ts +3 -0
  173. package/dist/memory/validation.d.ts.map +1 -1
  174. package/dist/memory/validation.js +123 -10
  175. package/dist/memory/validation.js.map +1 -1
  176. package/dist/memory/vector-store.d.ts +30 -0
  177. package/dist/memory/vector-store.d.ts.map +1 -1
  178. package/dist/memory/vector-store.js +160 -21
  179. package/dist/memory/vector-store.js.map +1 -1
  180. package/dist/migration/command.d.ts.map +1 -1
  181. package/dist/migration/command.js +0 -1
  182. package/dist/migration/command.js.map +1 -1
  183. package/dist/migration/migrate.d.ts.map +1 -1
  184. package/dist/migration/migrate.js +59 -107
  185. package/dist/migration/migrate.js.map +1 -1
  186. package/dist/migration/types.d.ts +0 -1
  187. package/dist/migration/types.d.ts.map +1 -1
  188. package/dist/print-ui/launch.d.ts +13 -3
  189. package/dist/print-ui/launch.d.ts.map +1 -1
  190. package/dist/print-ui/launch.js +28 -3
  191. package/dist/print-ui/launch.js.map +1 -1
  192. package/dist/product/environment.d.ts +3 -5
  193. package/dist/product/environment.d.ts.map +1 -1
  194. package/dist/product/environment.js +4 -32
  195. package/dist/product/environment.js.map +1 -1
  196. package/dist/product/index.d.ts +1 -1
  197. package/dist/product/index.d.ts.map +1 -1
  198. package/dist/product/index.js +1 -3
  199. package/dist/product/index.js.map +1 -1
  200. package/dist/product/paths.d.ts.map +1 -1
  201. package/dist/product/paths.js +16 -11
  202. package/dist/product/paths.js.map +1 -1
  203. package/dist/runtime/agent-runtime-controller.d.ts +4 -2
  204. package/dist/runtime/agent-runtime-controller.d.ts.map +1 -1
  205. package/dist/runtime/agent-runtime-controller.js +129 -15
  206. package/dist/runtime/agent-runtime-controller.js.map +1 -1
  207. package/dist/runtime/agent-runtime-protocol.d.ts +15 -0
  208. package/dist/runtime/agent-runtime-protocol.d.ts.map +1 -1
  209. package/dist/runtime/agent-runtime-protocol.js +6 -0
  210. package/dist/runtime/agent-runtime-protocol.js.map +1 -1
  211. package/dist/runtime/chat-checkpoint.d.ts +17 -0
  212. package/dist/runtime/chat-checkpoint.d.ts.map +1 -0
  213. package/dist/runtime/chat-checkpoint.js +108 -0
  214. package/dist/runtime/chat-checkpoint.js.map +1 -0
  215. package/dist/runtime/chat-controller.d.ts +10 -51
  216. package/dist/runtime/chat-controller.d.ts.map +1 -1
  217. package/dist/runtime/chat-controller.js +256 -1070
  218. package/dist/runtime/chat-controller.js.map +1 -1
  219. package/dist/runtime/chat-effort.d.ts +5 -0
  220. package/dist/runtime/chat-effort.d.ts.map +1 -0
  221. package/dist/runtime/chat-effort.js +47 -0
  222. package/dist/runtime/chat-effort.js.map +1 -0
  223. package/dist/runtime/chat-presentation.d.ts +60 -0
  224. package/dist/runtime/chat-presentation.d.ts.map +1 -0
  225. package/dist/runtime/chat-presentation.js +537 -0
  226. package/dist/runtime/chat-presentation.js.map +1 -0
  227. package/dist/runtime/chat-trace.d.ts +52 -0
  228. package/dist/runtime/chat-trace.d.ts.map +1 -0
  229. package/dist/runtime/chat-trace.js +234 -0
  230. package/dist/runtime/chat-trace.js.map +1 -0
  231. package/dist/runtime/chat-workspace.d.ts +22 -0
  232. package/dist/runtime/chat-workspace.d.ts.map +1 -0
  233. package/dist/runtime/chat-workspace.js +154 -0
  234. package/dist/runtime/chat-workspace.js.map +1 -0
  235. package/dist/runtime/goals/accounting.js +1 -1
  236. package/dist/runtime/goals/accounting.js.map +1 -1
  237. package/dist/runtime/goals/completion-audit.d.ts.map +1 -1
  238. package/dist/runtime/goals/completion-audit.js +5 -4
  239. package/dist/runtime/goals/completion-audit.js.map +1 -1
  240. package/dist/runtime/goals/coordinator.d.ts +3 -0
  241. package/dist/runtime/goals/coordinator.d.ts.map +1 -1
  242. package/dist/runtime/goals/coordinator.js +56 -2
  243. package/dist/runtime/goals/coordinator.js.map +1 -1
  244. package/dist/runtime/goals/prompt.d.ts +1 -1
  245. package/dist/runtime/goals/prompt.d.ts.map +1 -1
  246. package/dist/runtime/goals/prompt.js +4 -3
  247. package/dist/runtime/goals/prompt.js.map +1 -1
  248. package/dist/runtime/goals/tools.d.ts +32 -8
  249. package/dist/runtime/goals/tools.d.ts.map +1 -1
  250. package/dist/runtime/goals/tools.js +187 -11
  251. package/dist/runtime/goals/tools.js.map +1 -1
  252. package/dist/runtime/goals/types.d.ts +9 -0
  253. package/dist/runtime/goals/types.d.ts.map +1 -1
  254. package/dist/runtime/goals/types.js +1 -0
  255. package/dist/runtime/goals/types.js.map +1 -1
  256. package/dist/runtime/loop-budget.d.ts +2 -2
  257. package/dist/runtime/rich-text/markdown-parser.d.ts +2 -0
  258. package/dist/runtime/rich-text/markdown-parser.d.ts.map +1 -1
  259. package/dist/runtime/rich-text/markdown-parser.js +50 -10
  260. package/dist/runtime/rich-text/markdown-parser.js.map +1 -1
  261. package/dist/runtime/subagents/index.d.ts +2 -2
  262. package/dist/runtime/subagents/index.d.ts.map +1 -1
  263. package/dist/runtime/subagents/index.js +2 -1
  264. package/dist/runtime/subagents/index.js.map +1 -1
  265. package/dist/runtime/subagents/policy.d.ts +1 -1
  266. package/dist/runtime/subagents/policy.d.ts.map +1 -1
  267. package/dist/runtime/subagents/policy.js.map +1 -1
  268. package/dist/runtime/subagents/presets.d.ts +2 -2
  269. package/dist/runtime/subagents/research-artifact.d.ts +7 -0
  270. package/dist/runtime/subagents/research-artifact.d.ts.map +1 -1
  271. package/dist/runtime/subagents/research-artifact.js +73 -27
  272. package/dist/runtime/subagents/research-artifact.js.map +1 -1
  273. package/dist/runtime/subagents/research-contract.d.ts +18 -4
  274. package/dist/runtime/subagents/research-contract.d.ts.map +1 -1
  275. package/dist/runtime/subagents/research-contract.js +122 -17
  276. package/dist/runtime/subagents/research-contract.js.map +1 -1
  277. package/dist/runtime/subagents/research-renderer.d.ts +27 -11
  278. package/dist/runtime/subagents/research-renderer.d.ts.map +1 -1
  279. package/dist/runtime/subagents/research-renderer.js +34 -2
  280. package/dist/runtime/subagents/research-renderer.js.map +1 -1
  281. package/dist/runtime/subagents/result-parser.d.ts +1 -5
  282. package/dist/runtime/subagents/result-parser.d.ts.map +1 -1
  283. package/dist/runtime/subagents/result-parser.js +5 -72
  284. package/dist/runtime/subagents/result-parser.js.map +1 -1
  285. package/dist/runtime/subagents/runtime-integration.d.ts +13 -7
  286. package/dist/runtime/subagents/runtime-integration.d.ts.map +1 -1
  287. package/dist/runtime/subagents/runtime-integration.js +112 -2
  288. package/dist/runtime/subagents/runtime-integration.js.map +1 -1
  289. package/dist/runtime/subagents/supervisor.d.ts +15 -1
  290. package/dist/runtime/subagents/supervisor.d.ts.map +1 -1
  291. package/dist/runtime/subagents/supervisor.js +58 -3
  292. package/dist/runtime/subagents/supervisor.js.map +1 -1
  293. package/dist/runtime/subagents/tool.d.ts +2 -2
  294. package/dist/runtime/subagents/tool.d.ts.map +1 -1
  295. package/dist/runtime/subagents/tool.js +129 -9
  296. package/dist/runtime/subagents/tool.js.map +1 -1
  297. package/dist/runtime/subagents/types.d.ts +20 -0
  298. package/dist/runtime/subagents/types.d.ts.map +1 -1
  299. package/dist/runtime/subagents/types.js.map +1 -1
  300. package/dist/runtime/subagents/web-research-adapter.d.ts +4 -2
  301. package/dist/runtime/subagents/web-research-adapter.d.ts.map +1 -1
  302. package/dist/runtime/subagents/web-research-adapter.js +81 -15
  303. package/dist/runtime/subagents/web-research-adapter.js.map +1 -1
  304. package/dist/runtime/ui-events.d.ts +36 -8
  305. package/dist/runtime/ui-events.d.ts.map +1 -1
  306. package/dist/runtime/ui-events.js.map +1 -1
  307. package/dist/runtime/ui-view-model.d.ts +53 -4
  308. package/dist/runtime/ui-view-model.d.ts.map +1 -1
  309. package/dist/runtime/ui-view-model.js +190 -10
  310. package/dist/runtime/ui-view-model.js.map +1 -1
  311. package/dist/services/agent-runner.d.ts +5 -2
  312. package/dist/services/agent-runner.d.ts.map +1 -1
  313. package/dist/services/agent-runner.js +18 -18
  314. package/dist/services/agent-runner.js.map +1 -1
  315. package/dist/services/atomic-write.d.ts +9 -1
  316. package/dist/services/atomic-write.d.ts.map +1 -1
  317. package/dist/services/atomic-write.js +55 -2
  318. package/dist/services/atomic-write.js.map +1 -1
  319. package/dist/services/auth/auth.d.ts +11 -7
  320. package/dist/services/auth/auth.d.ts.map +1 -1
  321. package/dist/services/auth/auth.js +117 -31
  322. package/dist/services/auth/auth.js.map +1 -1
  323. package/dist/services/auth/aws.d.ts +2 -0
  324. package/dist/services/auth/aws.d.ts.map +1 -1
  325. package/dist/services/auth/aws.js +126 -12
  326. package/dist/services/auth/aws.js.map +1 -1
  327. package/dist/services/auth/index.d.ts +1 -1
  328. package/dist/services/auth/index.d.ts.map +1 -1
  329. package/dist/services/auth/index.js +2 -1
  330. package/dist/services/auth/index.js.map +1 -1
  331. package/dist/services/auto-fix/autoFixConfig.d.ts +0 -3
  332. package/dist/services/auto-fix/autoFixConfig.d.ts.map +1 -1
  333. package/dist/services/auto-fix/autoFixConfig.js +25 -8
  334. package/dist/services/auto-fix/autoFixConfig.js.map +1 -1
  335. package/dist/services/auto-fix/autoFixHook.d.ts +7 -0
  336. package/dist/services/auto-fix/autoFixHook.d.ts.map +1 -1
  337. package/dist/services/auto-fix/autoFixHook.js +10 -1
  338. package/dist/services/auto-fix/autoFixHook.js.map +1 -1
  339. package/dist/services/compact/auto-compact.d.ts +2 -0
  340. package/dist/services/compact/auto-compact.d.ts.map +1 -1
  341. package/dist/services/compact/auto-compact.js +15 -1
  342. package/dist/services/compact/auto-compact.js.map +1 -1
  343. package/dist/services/compact/compact.d.ts.map +1 -1
  344. package/dist/services/compact/compact.js +9 -11
  345. package/dist/services/compact/compact.js.map +1 -1
  346. package/dist/services/compact/summary-generator.d.ts.map +1 -1
  347. package/dist/services/compact/summary-generator.js +28 -4
  348. package/dist/services/compact/summary-generator.js.map +1 -1
  349. package/dist/services/compact/tool-call-groups.d.ts +19 -0
  350. package/dist/services/compact/tool-call-groups.d.ts.map +1 -0
  351. package/dist/services/compact/tool-call-groups.js +105 -0
  352. package/dist/services/compact/tool-call-groups.js.map +1 -0
  353. package/dist/services/concurrent-sessions.d.ts +4 -0
  354. package/dist/services/concurrent-sessions.d.ts.map +1 -1
  355. package/dist/services/concurrent-sessions.js +59 -12
  356. package/dist/services/concurrent-sessions.js.map +1 -1
  357. package/dist/services/config.d.ts +8 -4
  358. package/dist/services/config.d.ts.map +1 -1
  359. package/dist/services/config.js +15 -71
  360. package/dist/services/config.js.map +1 -1
  361. package/dist/services/doctor.d.ts +2 -2
  362. package/dist/services/doctor.js.map +1 -1
  363. package/dist/services/effort.d.ts +40 -0
  364. package/dist/services/effort.d.ts.map +1 -0
  365. package/dist/services/effort.js +88 -0
  366. package/dist/services/effort.js.map +1 -0
  367. package/dist/services/file-glob.d.ts.map +1 -1
  368. package/dist/services/file-glob.js +22 -2
  369. package/dist/services/file-glob.js.map +1 -1
  370. package/dist/services/file-lock.d.ts +7 -0
  371. package/dist/services/file-lock.d.ts.map +1 -0
  372. package/dist/services/file-lock.js +193 -0
  373. package/dist/services/file-lock.js.map +1 -0
  374. package/dist/services/global-config.d.ts +9 -0
  375. package/dist/services/global-config.d.ts.map +1 -1
  376. package/dist/services/global-config.js +79 -4
  377. package/dist/services/global-config.js.map +1 -1
  378. package/dist/services/goal-storage.d.ts.map +1 -1
  379. package/dist/services/goal-storage.js +35 -11
  380. package/dist/services/goal-storage.js.map +1 -1
  381. package/dist/services/llm.d.ts +35 -17
  382. package/dist/services/llm.d.ts.map +1 -1
  383. package/dist/services/llm.js +249 -113
  384. package/dist/services/llm.js.map +1 -1
  385. package/dist/services/mcp/transports.d.ts +0 -1
  386. package/dist/services/mcp/transports.d.ts.map +1 -1
  387. package/dist/services/mcp/transports.js +12 -13
  388. package/dist/services/mcp/transports.js.map +1 -1
  389. package/dist/services/model-context.d.ts +8 -0
  390. package/dist/services/model-context.d.ts.map +1 -1
  391. package/dist/services/model-context.js +111 -7
  392. package/dist/services/model-context.js.map +1 -1
  393. package/dist/services/model-registry.d.ts +3 -0
  394. package/dist/services/model-registry.d.ts.map +1 -1
  395. package/dist/services/model-registry.js +59 -2
  396. package/dist/services/model-registry.js.map +1 -1
  397. package/dist/services/provider-diagnostics.d.ts +1 -1
  398. package/dist/services/provider-diagnostics.d.ts.map +1 -1
  399. package/dist/services/provider-diagnostics.js +30 -16
  400. package/dist/services/provider-diagnostics.js.map +1 -1
  401. package/dist/services/provider-resilience/coordinator.d.ts +8 -3
  402. package/dist/services/provider-resilience/coordinator.d.ts.map +1 -1
  403. package/dist/services/provider-resilience/coordinator.js +86 -19
  404. package/dist/services/provider-resilience/coordinator.js.map +1 -1
  405. package/dist/services/provider-resilience/error-classifier.d.ts +1 -0
  406. package/dist/services/provider-resilience/error-classifier.d.ts.map +1 -1
  407. package/dist/services/provider-resilience/error-classifier.js +50 -26
  408. package/dist/services/provider-resilience/error-classifier.js.map +1 -1
  409. package/dist/services/provider-resilience/index.d.ts +3 -3
  410. package/dist/services/provider-resilience/index.d.ts.map +1 -1
  411. package/dist/services/provider-resilience/index.js +3 -1
  412. package/dist/services/provider-resilience/index.js.map +1 -1
  413. package/dist/services/provider-resilience/request-gate.d.ts +6 -0
  414. package/dist/services/provider-resilience/request-gate.d.ts.map +1 -1
  415. package/dist/services/provider-resilience/request-gate.js +24 -9
  416. package/dist/services/provider-resilience/request-gate.js.map +1 -1
  417. package/dist/services/provider-resilience/types.d.ts +10 -1
  418. package/dist/services/provider-resilience/types.d.ts.map +1 -1
  419. package/dist/services/provider-resilience/types.js.map +1 -1
  420. package/dist/services/redaction.d.ts.map +1 -1
  421. package/dist/services/redaction.js +29 -1
  422. package/dist/services/redaction.js.map +1 -1
  423. package/dist/services/session-index.d.ts.map +1 -1
  424. package/dist/services/session-index.js +75 -44
  425. package/dist/services/session-index.js.map +1 -1
  426. package/dist/services/session-memory/sessionMemory.d.ts.map +1 -1
  427. package/dist/services/session-memory/sessionMemory.js +6 -3
  428. package/dist/services/session-memory/sessionMemory.js.map +1 -1
  429. package/dist/services/session-storage.d.ts +12 -0
  430. package/dist/services/session-storage.d.ts.map +1 -1
  431. package/dist/services/session-storage.js +301 -230
  432. package/dist/services/session-storage.js.map +1 -1
  433. package/dist/services/storage-maintenance.d.ts.map +1 -1
  434. package/dist/services/storage-maintenance.js +25 -7
  435. package/dist/services/storage-maintenance.js.map +1 -1
  436. package/dist/services/task-manager.d.ts +6 -1
  437. package/dist/services/task-manager.d.ts.map +1 -1
  438. package/dist/services/task-manager.js +18 -4
  439. package/dist/services/task-manager.js.map +1 -1
  440. package/dist/services/tool-allowlist.d.ts +20 -10
  441. package/dist/services/tool-allowlist.d.ts.map +1 -1
  442. package/dist/services/tool-allowlist.js +64 -15
  443. package/dist/services/tool-allowlist.js.map +1 -1
  444. package/dist/services/usage-state.d.ts +10 -0
  445. package/dist/services/usage-state.d.ts.map +1 -1
  446. package/dist/services/usage-state.js +116 -45
  447. package/dist/services/usage-state.js.map +1 -1
  448. package/dist/services/verification-profile.d.ts.map +1 -1
  449. package/dist/services/verification-profile.js +23 -3
  450. package/dist/services/verification-profile.js.map +1 -1
  451. package/dist/services/workspace-diff.d.ts +14 -0
  452. package/dist/services/workspace-diff.d.ts.map +1 -1
  453. package/dist/services/workspace-diff.js +60 -11
  454. package/dist/services/workspace-diff.js.map +1 -1
  455. package/dist/services/yaml-config.d.ts.map +1 -1
  456. package/dist/services/yaml-config.js +2 -1
  457. package/dist/services/yaml-config.js.map +1 -1
  458. package/dist/skills/loader.d.ts.map +1 -1
  459. package/dist/skills/loader.js +23 -9
  460. package/dist/skills/loader.js.map +1 -1
  461. package/dist/skills/runtime.d.ts +3 -3
  462. package/dist/skills/runtime.d.ts.map +1 -1
  463. package/dist/skills/runtime.js +37 -4
  464. package/dist/skills/runtime.js.map +1 -1
  465. package/dist/skills/types.d.ts +1 -1
  466. package/dist/skills/types.d.ts.map +1 -1
  467. package/dist/terminal-ui/launch.d.ts +26 -8
  468. package/dist/terminal-ui/launch.d.ts.map +1 -1
  469. package/dist/terminal-ui/launch.js +82 -39
  470. package/dist/terminal-ui/launch.js.map +1 -1
  471. package/dist/tools/bash_security.d.ts +17 -0
  472. package/dist/tools/bash_security.d.ts.map +1 -1
  473. package/dist/tools/bash_security.js +233 -27
  474. package/dist/tools/bash_security.js.map +1 -1
  475. package/dist/tools/git.d.ts +8 -8
  476. package/dist/tools/git.d.ts.map +1 -1
  477. package/dist/tools/git.js +248 -55
  478. package/dist/tools/git.js.map +1 -1
  479. package/dist/tools/index.d.ts +13 -3
  480. package/dist/tools/index.d.ts.map +1 -1
  481. package/dist/tools/index.js +262 -30
  482. package/dist/tools/index.js.map +1 -1
  483. package/dist/tools/lsp.d.ts +74 -6
  484. package/dist/tools/lsp.d.ts.map +1 -1
  485. package/dist/tools/lsp.js +24 -5
  486. package/dist/tools/lsp.js.map +1 -1
  487. package/dist/tools/mcp.d.ts +11 -4
  488. package/dist/tools/mcp.d.ts.map +1 -1
  489. package/dist/tools/mcp.js +99 -3
  490. package/dist/tools/mcp.js.map +1 -1
  491. package/dist/tools/plan.d.ts +4 -4
  492. package/dist/tools/sandbox.d.ts +5 -1
  493. package/dist/tools/sandbox.d.ts.map +1 -1
  494. package/dist/tools/sandbox.js +29 -13
  495. package/dist/tools/sandbox.js.map +1 -1
  496. package/dist/tools/todo.d.ts +3 -3
  497. package/dist/tools/web.d.ts +15 -4
  498. package/dist/tools/web.d.ts.map +1 -1
  499. package/dist/tools/web.js +240 -26
  500. package/dist/tools/web.js.map +1 -1
  501. package/dist/tui-ui/launch.d.ts +3 -3
  502. package/dist/tui-ui/launch.d.ts.map +1 -1
  503. package/dist/tui-ui/launch.js +3 -3
  504. package/dist/tui-ui/launch.js.map +1 -1
  505. package/dist/tui-ui/layout.d.ts.map +1 -1
  506. package/dist/tui-ui/layout.js +19 -5
  507. package/dist/tui-ui/layout.js.map +1 -1
  508. package/dist/tui-ui/pickers.d.ts.map +1 -1
  509. package/dist/tui-ui/pickers.js +1 -0
  510. package/dist/tui-ui/pickers.js.map +1 -1
  511. package/dist/tui-ui/runner.d.ts +2 -1
  512. package/dist/tui-ui/runner.d.ts.map +1 -1
  513. package/dist/tui-ui/runner.js +18 -29
  514. package/dist/tui-ui/runner.js.map +1 -1
  515. package/dist/tui-ui/state.d.ts +13 -1
  516. package/dist/tui-ui/state.d.ts.map +1 -1
  517. package/dist/tui-ui/state.js +28 -1
  518. package/dist/tui-ui/state.js.map +1 -1
  519. package/dist/ui/markdown.js.map +1 -1
  520. package/dist/utils/debug-log.d.ts +3 -3
  521. package/dist/utils/debug-log.d.ts.map +1 -1
  522. package/dist/utils/debug-log.js +7 -4
  523. package/dist/utils/debug-log.js.map +1 -1
  524. package/dist/utils/json.d.ts +6 -0
  525. package/dist/utils/json.d.ts.map +1 -0
  526. package/dist/utils/json.js +66 -0
  527. package/dist/utils/json.js.map +1 -0
  528. package/dist/utils/mask.d.ts +8 -1
  529. package/dist/utils/mask.d.ts.map +1 -1
  530. package/dist/utils/mask.js +10 -12
  531. package/dist/utils/mask.js.map +1 -1
  532. package/dist/utils/observability.d.ts +22 -0
  533. package/dist/utils/observability.d.ts.map +1 -0
  534. package/dist/utils/observability.js +80 -0
  535. package/dist/utils/observability.js.map +1 -0
  536. package/dist/utils/token-estimate.d.ts +8 -0
  537. package/dist/utils/token-estimate.d.ts.map +1 -1
  538. package/dist/utils/token-estimate.js +30 -17
  539. package/dist/utils/token-estimate.js.map +1 -1
  540. package/package.json +9 -8
@@ -0,0 +1,1043 @@
1
+ "use strict";
2
+ /** Handler implementations for the diagnostic-command-handlers boundary. */
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.handleDoctor = handleDoctor;
8
+ exports.handleStorage = handleStorage;
9
+ exports.handleUsage = handleUsage;
10
+ exports.handleLoopStats = handleLoopStats;
11
+ exports.handleTrace = handleTrace;
12
+ exports.handleLastTool = handleLastTool;
13
+ exports.handleArtifacts = handleArtifacts;
14
+ exports.handleCheckpoint = handleCheckpoint;
15
+ exports.handleCost = handleCost;
16
+ exports.showAgents = showAgents;
17
+ const chalk_1 = __importDefault(require("chalk"));
18
+ const format_1 = require("../services/format");
19
+ const session_storage_1 = require("../services/session-storage");
20
+ const doctor_1 = require("../services/doctor");
21
+ const tool_artifacts_1 = require("../core/tool-artifacts");
22
+ const checkpoint_1 = require("../core/checkpoint");
23
+ const storage_maintenance_1 = require("../services/storage-maintenance");
24
+ const usage_state_1 = require("../services/usage-state");
25
+ // ============================================================================
26
+ // 颜色常量
27
+ // ============================================================================
28
+ const BRAND = chalk_1.default.hex('#FF6B35');
29
+ const ACCENT = chalk_1.default.hex('#00D4AA');
30
+ const DIM = chalk_1.default.dim;
31
+ const ERROR = chalk_1.default.red;
32
+ const WARN = chalk_1.default.yellow;
33
+ const SUCCESS = chalk_1.default.green;
34
+ const HEADER = chalk_1.default.cyan.bold;
35
+ function formatDurationMs(ms) {
36
+ if (ms >= 1000)
37
+ return `${(ms / 1000).toFixed(1)}s`;
38
+ return `${Math.round(ms)}ms`;
39
+ }
40
+ function formatLoopBudgetSource(stats) {
41
+ const source = stats.loopBudgetSource ?? 'unknown';
42
+ if (source === 'config' && stats.loopBudgetBaseProfile) {
43
+ return `config over ${stats.loopBudgetBaseProfile}`;
44
+ }
45
+ return source;
46
+ }
47
+ function formatLoopStatsLines(stats, detail = false) {
48
+ const lines = [
49
+ `Finish ${stats.finishReason}`,
50
+ `Requests ${stats.llmRequests} LLM / ${stats.turnsStarted} turns`,
51
+ `Tools ${stats.toolCalls} total (${stats.readOnlyToolCalls} read-only, ${stats.unsafeToolCalls} unsafe)`,
52
+ `Tool bytes ${(0, format_1.formatBytes)(stats.modelVisibleToolBytes)} model-visible / ${(0, format_1.formatBytes)(stats.toolResultBytes)} total`,
53
+ ];
54
+ if (stats.summarizedBytes > 0) {
55
+ lines.push(`Saved ${(0, format_1.formatBytes)(stats.summarizedBytes)} from model context`);
56
+ }
57
+ if (stats.compactTrigger) {
58
+ lines.push(`Compact ${stats.compactTrigger}`);
59
+ }
60
+ if (stats.localFastPathUsed) {
61
+ lines.push('Fast path yes');
62
+ }
63
+ if (stats.budgetExceededReason) {
64
+ lines.push(`Budget ${stats.budgetExceededReason}`);
65
+ }
66
+ if (stats.continuationActions && stats.continuationActions.length > 0) {
67
+ lines.push(`Next ${stats.continuationActions.join(', ')}`);
68
+ }
69
+ if ((stats.providerRetryCount ?? 0) > 0) {
70
+ const retryParts = [
71
+ `${stats.providerRetryCount} retries`,
72
+ `delay ${formatDurationMs(stats.providerRetryDelayMs ?? 0)}`,
73
+ stats.providerLastRetryErrorType
74
+ ? `last ${stats.providerLastRetryErrorType}${stats.providerLastRetryStatus ? `/${stats.providerLastRetryStatus}` : ''}`
75
+ : undefined,
76
+ ].filter(Boolean);
77
+ lines.push(`Provider ${retryParts.join(', ')}`);
78
+ }
79
+ if ((stats.providerFallbackCount ?? 0) > 0 || stats.providerUsingFallback) {
80
+ const fallbackPath = stats.providerFallbackFromModel && stats.providerFallbackToModel
81
+ ? `${stats.providerFallbackFromModel} -> ${stats.providerFallbackToModel}`
82
+ : stats.providerFinalModel
83
+ ? `final ${stats.providerFinalModel}`
84
+ : 'active';
85
+ lines.push(`Fallback ${fallbackPath}`);
86
+ }
87
+ if (typeof stats.verificationClaimAllowed === 'boolean') {
88
+ const verificationParts = [
89
+ stats.verificationProfile ?? 'unknown',
90
+ `required=${stats.verificationRequired ? 'yes' : 'no'}`,
91
+ `passed=${stats.verificationPassedCommands?.length ?? 0}`,
92
+ `failed=${stats.verificationFailedCommands?.length ?? 0}`,
93
+ `missing=${stats.verificationMissingCommands?.length ?? 0}`,
94
+ `claim=${stats.verificationClaimAllowed ? 'yes' : 'no'}`,
95
+ ];
96
+ lines.push(`Verify ${verificationParts.join(' ')}`);
97
+ }
98
+ if (typeof stats.loopBudgetMaxLlmRequests === 'number' ||
99
+ typeof stats.loopBudgetMaxToolCalls === 'number' ||
100
+ typeof stats.loopBudgetMaxModelVisibleBytes === 'number') {
101
+ const caps = [
102
+ typeof stats.loopBudgetMaxLlmRequests === 'number'
103
+ ? `${stats.llmRequests}/${stats.loopBudgetMaxLlmRequests} LLM`
104
+ : undefined,
105
+ typeof stats.loopBudgetMaxToolCalls === 'number'
106
+ ? `${stats.toolCalls}/${stats.loopBudgetMaxToolCalls} tools`
107
+ : undefined,
108
+ typeof stats.loopBudgetMaxModelVisibleBytes === 'number'
109
+ ? `${(0, format_1.formatBytes)(stats.modelVisibleToolBytes)}/${(0, format_1.formatBytes)(stats.loopBudgetMaxModelVisibleBytes)} visible`
110
+ : undefined,
111
+ typeof stats.loopBudgetMaxReadOnlyFragmentation === 'number'
112
+ ? `fragment ${stats.singleReadOnlyStreak}/${stats.loopBudgetMaxReadOnlyFragmentation}`
113
+ : undefined,
114
+ ].filter(Boolean);
115
+ lines.push(`Budget cap ${caps.join(', ')} (${formatLoopBudgetSource(stats)})`);
116
+ }
117
+ if (stats.singleReadOnlyStreak > 0 || stats.batchReadSuggestionCount > 0) {
118
+ lines.push(`Read-only streak ${stats.singleReadOnlyStreak}, batch_read hints ${stats.batchReadSuggestionCount}`);
119
+ }
120
+ if (detail) {
121
+ lines.push(`Unsafe ${stats.unsafeToolCalls}`);
122
+ if (stats.providerRetryErrorTypes && stats.providerRetryErrorTypes.length > 0) {
123
+ lines.push(`Retry type ${stats.providerRetryErrorTypes.join(', ')}`);
124
+ }
125
+ if (stats.verificationFailedCommands && stats.verificationFailedCommands.length > 0) {
126
+ lines.push(`Failed ${stats.verificationFailedCommands.join(' && ')}`);
127
+ }
128
+ if (stats.verificationMissingCommands && stats.verificationMissingCommands.length > 0) {
129
+ lines.push(`Missing ${stats.verificationMissingCommands.join(' && ')}`);
130
+ }
131
+ if (stats.verificationSkippedReason) {
132
+ lines.push(`Verify why ${stats.verificationSkippedReason}`);
133
+ }
134
+ if (stats.continuationHint) {
135
+ lines.push(`Next why ${stats.continuationHint}`);
136
+ }
137
+ lines.push(`Budget hit ${stats.finishReason === 'budget_exceeded' ? 'yes' : 'no'}`);
138
+ }
139
+ return lines;
140
+ }
141
+ function handleLoopStats(ctx) {
142
+ const stats = ctx.store.getSnapshot().lastLoopStats;
143
+ if (!stats) {
144
+ console.log('No agent-loop stats recorded yet.');
145
+ return { success: true };
146
+ }
147
+ console.log(HEADER('Agent Loop Stats'));
148
+ console.log();
149
+ for (const line of formatLoopStatsLines(stats, true)) {
150
+ console.log(` ${line}`);
151
+ }
152
+ console.log();
153
+ console.log(DIM('Use this to spot excessive LLM requests, fragmented read-only tool calls, and local fast-path hits.'));
154
+ return { success: true };
155
+ }
156
+ function formatTraceEventLine(event) {
157
+ const time = new Date(event.timestamp).toLocaleTimeString();
158
+ const prefix = `${DIM(time)} ${ACCENT(event.type)}`;
159
+ switch (event.type) {
160
+ case 'turn_start':
161
+ return `${prefix} input=${(0, format_1.formatBytes)(event.inputBytes ?? 0)}${event.localFastPathUsed ? ' fast-path' : ''}${event.note ? ` ${DIM(event.note)}` : ''}`;
162
+ case 'request_start':
163
+ return `${prefix} model=${event.model ?? 'unknown'} iteration=${event.turn ?? '?'}`;
164
+ case 'provider_retry': {
165
+ const parts = [
166
+ `count=${event.providerRetryCount ?? 0}`,
167
+ `delay=${formatDurationMs(event.providerRetryDelayMs ?? 0)}`,
168
+ event.providerLastRetryErrorType
169
+ ? `last=${event.providerLastRetryErrorType}${event.providerLastRetryStatus ? `/${event.providerLastRetryStatus}` : ''}`
170
+ : '',
171
+ event.providerRetryErrorTypes?.length
172
+ ? `types=${event.providerRetryErrorTypes.join(',')}`
173
+ : '',
174
+ event.providerFinalModel ? `final=${event.providerFinalModel}` : '',
175
+ ].filter(Boolean);
176
+ return `${prefix} ${parts.join(' ')}`;
177
+ }
178
+ case 'provider_fallback': {
179
+ const path = event.providerFallbackFromModel && event.providerFallbackToModel
180
+ ? `${event.providerFallbackFromModel}->${event.providerFallbackToModel}`
181
+ : (event.providerFinalModel ?? 'active');
182
+ const parts = [
183
+ `count=${event.providerFallbackCount ?? 0}`,
184
+ `path=${path}`,
185
+ `using=${event.providerUsingFallback ? 'yes' : 'no'}`,
186
+ ];
187
+ return `${prefix} ${parts.join(' ')}`;
188
+ }
189
+ case 'prompt_assembly': {
190
+ const parts = [
191
+ `model=${event.promptModelId ?? 'unknown'}`,
192
+ `tokens=${event.promptEstimatedTokens ?? 0}/${event.promptBudgetTokens ?? 0}`,
193
+ `core=${event.promptCoreTokens ?? 0}`,
194
+ `evidenceBudget=${event.promptEvidenceBudgetTokens ?? 0}`,
195
+ `recentBudget=${event.promptRecentTurnBudgetTokens ?? 0}`,
196
+ `included=${event.promptIncludedEvidenceCount ?? 0}`,
197
+ `omitted=${event.promptOmittedEvidenceCount ?? 0}`,
198
+ ];
199
+ const sections = event.promptSections?.length
200
+ ? ` sections=${event.promptSections.join(',')}`
201
+ : '';
202
+ const evidence = event.promptIncludedEvidence?.length
203
+ ? ` evidence=${event.promptIncludedEvidence.slice(0, 6).join(', ')}${event.promptIncludedEvidence.length > 6 ? ', ...' : ''}`
204
+ : '';
205
+ return `${prefix} ${parts.join(' ')}${sections ? DIM(sections) : ''}${evidence ? ` ${DIM(evidence)}` : ''}`;
206
+ }
207
+ case 'assistant_tool_calls':
208
+ return `${prefix} calls=${event.toolCallCount ?? 0} assistant=${(0, format_1.formatBytes)(event.contentBytes ?? 0)}`;
209
+ case 'checkpoint': {
210
+ const files = event.checkpointFiles?.length
211
+ ? ` files=${event.checkpointFiles.slice(0, 6).join(', ')}${event.checkpointFiles.length > 6 ? ', ...' : ''}`
212
+ : '';
213
+ const targets = event.workspaceFiles?.length && !files
214
+ ? ` targets=${event.workspaceFiles.slice(0, 6).join(', ')}${event.workspaceFiles.length > 6 ? ', ...' : ''}`
215
+ : '';
216
+ return `${prefix} id=${event.checkpointId ?? 'unknown'} saved=${event.checkpointFileCount ?? 0}${files}${targets}${event.note ? ` ${DIM(event.note)}` : ''}`;
217
+ }
218
+ case 'tool_call':
219
+ return `${prefix} ${event.name ?? 'tool'}${event.argsSummary ? ` ${DIM(event.argsSummary)}` : ''}${event.argsArtifactId ? ` ${DIM(`args=/artifacts show ${event.argsArtifactId} --full${event.argsBytes ? ` (${(0, format_1.formatBytes)(event.argsBytes)})` : ''}`)}` : ''}${event.callId ? ` ${DIM(event.callId)}` : ''}`;
220
+ case 'permission_decision': {
221
+ const status = event.permissionApproved ? SUCCESS('approved') : ERROR('denied');
222
+ const parts = [
223
+ `source=${event.permissionSource ?? 'unknown'}`,
224
+ `behavior=${event.permissionBehavior ?? 'unknown'}`,
225
+ ];
226
+ if (typeof event.permissionDuration === 'number') {
227
+ parts.push(`${event.permissionDuration}ms`);
228
+ }
229
+ return `${prefix} ${status} ${event.name ?? 'tool'} ${DIM(parts.join(' '))}${event.permissionReason ? ` ${DIM(event.permissionReason)}` : ''}`;
230
+ }
231
+ case 'tool_result': {
232
+ const status = event.success === false ? ERROR('error') : SUCCESS('ok');
233
+ const bytes = [
234
+ `output=${(0, format_1.formatBytes)(event.outputBytes ?? 0)}`,
235
+ `model=${(0, format_1.formatBytes)(event.modelVisibleBytes ?? 0)}`,
236
+ ];
237
+ if (event.artifactId)
238
+ bytes.push(`artifact=${event.artifactId}`);
239
+ return `${prefix} ${status} ${event.name ?? 'tool'} ${DIM(`${event.duration ?? 0}ms`)} ${DIM(bytes.join(' '))}${event.error ? ` ${ERROR(event.error)}` : ''}`;
240
+ }
241
+ case 'message':
242
+ return `${prefix} assistant=${(0, format_1.formatBytes)(event.contentBytes ?? 0)}`;
243
+ case 'strategy_exhausted':
244
+ return `${prefix}${event.note ? ` ${WARN(event.note)}` : ''}`;
245
+ case 'complete': {
246
+ const stats = [
247
+ `finish=${event.finishReason ?? 'unknown'}`,
248
+ `llm=${typeof event.llmRequests === 'number' ? event.llmRequests : 'unknown'}`,
249
+ `tools=${typeof event.toolCalls === 'number' ? event.toolCalls : 'unknown'}`,
250
+ ];
251
+ if (event.loopBudgetSource ||
252
+ typeof event.loopBudgetMaxLlmRequests === 'number' ||
253
+ typeof event.loopBudgetMaxToolCalls === 'number' ||
254
+ typeof event.loopBudgetMaxModelVisibleBytes === 'number') {
255
+ const source = event.loopBudgetSource === 'config' && event.loopBudgetBaseProfile
256
+ ? `config/${event.loopBudgetBaseProfile}`
257
+ : (event.loopBudgetSource ?? 'unknown');
258
+ const caps = [
259
+ typeof event.loopBudgetMaxLlmRequests === 'number'
260
+ ? `${typeof event.llmRequests === 'number' ? event.llmRequests : '?'}/${event.loopBudgetMaxLlmRequests}llm`
261
+ : undefined,
262
+ typeof event.loopBudgetMaxToolCalls === 'number'
263
+ ? `${typeof event.toolCalls === 'number' ? event.toolCalls : '?'}/${event.loopBudgetMaxToolCalls}tools`
264
+ : undefined,
265
+ typeof event.loopBudgetMaxModelVisibleBytes === 'number'
266
+ ? `${(0, format_1.formatBytes)(event.loopBudgetMaxModelVisibleBytes)}visible`
267
+ : undefined,
268
+ typeof event.loopBudgetMaxReadOnlyFragmentation === 'number'
269
+ ? `frag=${event.loopBudgetMaxReadOnlyFragmentation}`
270
+ : undefined,
271
+ event.loopBudgetConfigOverride ? 'override=yes' : undefined,
272
+ ].filter(Boolean);
273
+ stats.push(`budgetProfile=${source}${caps.length ? `(${caps.join(',')})` : ''}`);
274
+ }
275
+ if (event.budgetExceededReason)
276
+ stats.push(`budget=${event.budgetExceededReason}`);
277
+ if (event.continuationActions?.length)
278
+ stats.push(`next=${event.continuationActions.join(',')}`);
279
+ if (event.continuationHint)
280
+ stats.push(`hint=${event.continuationHint}`);
281
+ if (event.localFastPathUsed)
282
+ stats.push('fast-path=yes');
283
+ return `${prefix} ${stats.join(' ')}`;
284
+ }
285
+ case 'local_fast_path':
286
+ return `${prefix} ${event.name ?? 'tool'}${event.argsSummary ? ` ${DIM(event.argsSummary)}` : ''}${event.argsArtifactId ? ` ${DIM(`args=/artifacts show ${event.argsArtifactId} --full${event.argsBytes ? ` (${(0, format_1.formatBytes)(event.argsBytes)})` : ''}`)}` : ''}${event.note ? ` ${DIM(event.note)}` : ''}`;
287
+ case 'workspace_snapshot': {
288
+ const state = event.workspaceGitAvailable === false
289
+ ? WARN('not-git')
290
+ : event.workspaceDirty
291
+ ? WARN('dirty')
292
+ : SUCCESS('clean');
293
+ const files = event.workspaceFiles?.length
294
+ ? ` files=${event.workspaceFiles.slice(0, 6).join(', ')}${event.workspaceFiles.length > 6 ? ', ...' : ''}`
295
+ : '';
296
+ return `${prefix} ${event.workspacePhase ?? 'unknown'} ${state} count=${event.workspaceFileCount ?? 0}${event.workspaceBranch ? ` branch=${event.workspaceBranch}` : ''}${files}${event.error ? ` ${ERROR(event.error)}` : ''}`;
297
+ }
298
+ case 'workspace_delta': {
299
+ const added = event.workspaceNewByTurn ?? [];
300
+ const changed = event.workspaceChangedByTurn ?? [];
301
+ const modifiedPreExisting = event.workspaceModifiedPreExistingByTurn ?? [];
302
+ const resolved = event.workspaceResolvedByTurn ?? [];
303
+ const parts = [
304
+ `after=${event.workspaceFileCount ?? 0}`,
305
+ `new=${added.length}`,
306
+ `changed=${changed.length}`,
307
+ `pre-existing-modified=${modifiedPreExisting.length}`,
308
+ `resolved=${resolved.length}`,
309
+ ];
310
+ const details = [
311
+ added.length
312
+ ? `new: ${added.slice(0, 6).join(', ')}${added.length > 6 ? ', ...' : ''}`
313
+ : '',
314
+ changed.length
315
+ ? `changed: ${changed.slice(0, 6).join(', ')}${changed.length > 6 ? ', ...' : ''}`
316
+ : '',
317
+ modifiedPreExisting.length
318
+ ? `pre-existing modified: ${modifiedPreExisting.slice(0, 6).join(', ')}${modifiedPreExisting.length > 6 ? ', ...' : ''}`
319
+ : '',
320
+ resolved.length
321
+ ? `resolved: ${resolved.slice(0, 6).join(', ')}${resolved.length > 6 ? ', ...' : ''}`
322
+ : '',
323
+ ]
324
+ .filter(Boolean)
325
+ .join(' | ');
326
+ return `${prefix} ${parts.join(' ')}${details ? ` ${DIM(details)}` : ''}${event.note ? ` ${DIM(event.note)}` : ''}`;
327
+ }
328
+ case 'verification_profile': {
329
+ const commands = event.verificationCommands ?? [];
330
+ const files = event.verificationChangedFiles ?? [];
331
+ const details = [
332
+ `profile=${event.verificationProfile ?? 'unknown'}`,
333
+ `required=${event.verificationRequired === false ? 'no' : 'yes'}`,
334
+ `commands=${commands.length}`,
335
+ `files=${files.length}`,
336
+ ];
337
+ if (event.verificationRisky) {
338
+ details.push(`risk=${WARN('high')}(${files.length} files)`);
339
+ }
340
+ const commandPreview = commands.length
341
+ ? ` cmds: ${commands.slice(0, 4).join(' && ')}${commands.length > 4 ? ' && ...' : ''}`
342
+ : '';
343
+ return `${prefix} ${details.join(' ')}${commandPreview ? ` ${DIM(commandPreview)}` : ''}${event.note ? ` ${DIM(event.note)}` : ''}`;
344
+ }
345
+ case 'verification_result': {
346
+ const status = event.verificationPassed === true ? SUCCESS('passed') : ERROR('failed');
347
+ const command = event.verificationCommand ?? 'unknown';
348
+ return `${prefix} ${status} ${command}${typeof event.outputBytes === 'number' ? ` ${DIM((0, format_1.formatBytes)(event.outputBytes))}` : ''}${event.error ? ` ${ERROR(event.error)}` : ''}`;
349
+ }
350
+ case 'verification_summary': {
351
+ const passed = event.verificationPassedCommands?.length ?? 0;
352
+ const failed = event.verificationFailedCommands?.length ?? 0;
353
+ const missing = event.verificationMissingCommands?.length ?? 0;
354
+ const parts = [
355
+ `profile=${event.verificationProfile ?? 'unknown'}`,
356
+ `required=${event.verificationRequired === false ? 'no' : 'yes'}`,
357
+ `passed=${passed}`,
358
+ `failed=${failed}`,
359
+ `missing=${missing}`,
360
+ `claimAllowed=${event.verificationClaimAllowed ? 'yes' : 'no'}`,
361
+ ];
362
+ const missingPreview = missing > 0
363
+ ? ` missing: ${(event.verificationMissingCommands ?? []).slice(0, 4).join(' && ')}${missing > 4 ? ' && ...' : ''}`
364
+ : '';
365
+ return `${prefix} ${parts.join(' ')}${missingPreview ? ` ${DIM(missingPreview)}` : ''}${event.note ? ` ${DIM(event.note)}` : ''}`;
366
+ }
367
+ case 'aborted':
368
+ return `${prefix}${event.note ? ` ${WARN(event.note)}` : ''}`;
369
+ case 'error':
370
+ return `${prefix} ${ERROR(event.error ?? 'unknown error')}`;
371
+ default:
372
+ return prefix;
373
+ }
374
+ }
375
+ function handleTrace(ctx, args = '') {
376
+ const session = ctx.getSession?.() ?? (ctx.sessionId ? (0, session_storage_1.loadSessionMeta)(ctx.sessionId) : null);
377
+ if (!session) {
378
+ console.log(ERROR('No active session.'));
379
+ console.log(DIM('Use /resume <session-id> first, or start a chat turn to create a session.'));
380
+ return { success: false };
381
+ }
382
+ const events = (0, session_storage_1.readSessionTraceEvents)(session.id);
383
+ if (events.length === 0) {
384
+ console.log(DIM(`No trace events recorded for session ${session.id.slice(0, 8)} yet.`));
385
+ return { success: true };
386
+ }
387
+ const ref = args.trim();
388
+ const requestedTurnId = ref && ref !== 'latest' ? ref : events[events.length - 1].turnId;
389
+ const turnEvents = events.filter(event => event.turnId === requestedTurnId);
390
+ if (turnEvents.length === 0) {
391
+ const recentTurnIds = [...new Set(events.map(event => event.turnId))].slice(-8).reverse();
392
+ console.log(ERROR(`Trace turn not found: ${requestedTurnId}`));
393
+ console.log(DIM(`Recent turns: ${recentTurnIds.join(', ')}`));
394
+ return { success: false };
395
+ }
396
+ console.log(HEADER(`Trace ${requestedTurnId}`));
397
+ console.log(DIM(`Session ${session.id} Events ${turnEvents.length}`));
398
+ console.log(DIM('─'.repeat(40)));
399
+ for (const event of turnEvents) {
400
+ console.log(` ${formatTraceEventLine(event)}`);
401
+ }
402
+ console.log();
403
+ console.log(DIM('Trace stores metadata only; full transcript and tool output stay in session/artifacts.'));
404
+ return { success: true };
405
+ }
406
+ function latestToolTrace(events) {
407
+ for (let index = events.length - 1; index >= 0; index--) {
408
+ const event = events[index];
409
+ if (event.type !== 'tool_result' && event.type !== 'tool_call')
410
+ continue;
411
+ const callId = event.callId;
412
+ const result = event.type === 'tool_result' ? event : undefined;
413
+ const call = event.type === 'tool_call'
414
+ ? event
415
+ : callId
416
+ ? events
417
+ .slice(0, index)
418
+ .reverse()
419
+ .find(candidate => candidate.type === 'tool_call' && candidate.callId === callId)
420
+ : undefined;
421
+ return { call, result };
422
+ }
423
+ return null;
424
+ }
425
+ /** Find tool trace by 1-based sequence number across all tool events. */
426
+ function toolTraceBySeq(events, seq) {
427
+ let counter = 0;
428
+ const toolEvents = new Map();
429
+ for (const event of events) {
430
+ if (event.type !== 'tool_call' && event.type !== 'tool_result')
431
+ continue;
432
+ if (!event.callId)
433
+ continue;
434
+ const entry = toolEvents.get(event.callId) ?? {};
435
+ if (event.type === 'tool_call') {
436
+ counter++;
437
+ entry.call = event;
438
+ }
439
+ else {
440
+ if (!entry.call)
441
+ counter++;
442
+ entry.result = event;
443
+ }
444
+ toolEvents.set(event.callId, entry);
445
+ if (counter === seq) {
446
+ return toolEvents.get(event.callId) ?? null;
447
+ }
448
+ }
449
+ return null;
450
+ }
451
+ /** Find tool trace by callId prefix. */
452
+ function toolTraceByCallId(events, callIdPrefix) {
453
+ let call;
454
+ let result;
455
+ for (const event of events) {
456
+ if (event.type !== 'tool_call' && event.type !== 'tool_result')
457
+ continue;
458
+ if (!event.callId?.startsWith(callIdPrefix))
459
+ continue;
460
+ if (event.type === 'tool_call')
461
+ call = event;
462
+ else
463
+ result = event;
464
+ }
465
+ if (!call && !result)
466
+ return null;
467
+ return { call, result };
468
+ }
469
+ /** Collect all tool trace pairs ordered by appearance (1-based sequence). */
470
+ function collectToolTracePairs(events) {
471
+ const pairs = [];
472
+ const seen = new Map();
473
+ let counter = 0;
474
+ for (const event of events) {
475
+ if (event.type !== 'tool_call' && event.type !== 'tool_result')
476
+ continue;
477
+ if (!event.callId)
478
+ continue;
479
+ let entry = seen.get(event.callId);
480
+ if (!entry) {
481
+ counter++;
482
+ entry = { seq: counter };
483
+ seen.set(event.callId, entry);
484
+ pairs.push(entry);
485
+ }
486
+ if (event.type === 'tool_call')
487
+ entry.call = event;
488
+ else
489
+ entry.result = event;
490
+ }
491
+ return pairs;
492
+ }
493
+ function parseLastToolArgs(args = '') {
494
+ const parts = args.trim().split(/\s+/).filter(Boolean);
495
+ const ref = parts.length > 0 && !parts[0].startsWith('--') ? parts[0] : undefined;
496
+ return {
497
+ full: parts.includes('--full'),
498
+ preview: !parts.includes('--no-preview'),
499
+ ref,
500
+ };
501
+ }
502
+ function printLastToolArtifactPreview(projectPath, label, artifactId, full) {
503
+ if (!artifactId)
504
+ return;
505
+ const artifact = (0, tool_artifacts_1.findArtifact)(projectPath, artifactId);
506
+ if (!artifact) {
507
+ console.log(` ${label} preview ${DIM(`artifact not found or ambiguous: ${artifactId}`)}`);
508
+ return;
509
+ }
510
+ const content = (0, tool_artifacts_1.retrieveArtifact)(artifact.path);
511
+ if (content == null) {
512
+ console.log(` ${label} preview ${DIM(`artifact cannot be read: ${artifact.id}`)}`);
513
+ return;
514
+ }
515
+ const redacted = (0, session_storage_1.redactTraceText)(content);
516
+ const maxPreviewBytes = 4 * 1024;
517
+ const shouldTruncate = !full && Buffer.byteLength(redacted, 'utf8') > maxPreviewBytes;
518
+ const preview = shouldTruncate
519
+ ? Buffer.from(redacted, 'utf8').subarray(0, maxPreviewBytes).toString('utf8')
520
+ : redacted;
521
+ console.log(` ${label} preview`);
522
+ console.log(` ${DIM('─'.repeat(40))}`);
523
+ for (const line of preview.split('\n')) {
524
+ console.log(` ${line}`);
525
+ }
526
+ if (shouldTruncate) {
527
+ console.log(` ${DIM(`... preview truncated at ${(0, format_1.formatBytes)(maxPreviewBytes)}. Use /last-tool --full or /artifacts show ${artifact.id} --full.`)}`);
528
+ }
529
+ }
530
+ function lastToolInputLabel(toolName) {
531
+ return toolName === 'exec_command' ? 'Command' : 'Args';
532
+ }
533
+ function lastToolField(label) {
534
+ return label.padEnd(13, ' ');
535
+ }
536
+ function handleLastTool(ctx, args = '') {
537
+ const options = parseLastToolArgs(args);
538
+ const session = ctx.getSession?.() ?? (ctx.sessionId ? (0, session_storage_1.loadSessionMeta)(ctx.sessionId) : null);
539
+ if (!session) {
540
+ console.log(ERROR('No active session.'));
541
+ console.log(DIM('Use /resume <session-id> first, or start a chat turn to create a session.'));
542
+ return { success: false };
543
+ }
544
+ const events = (0, session_storage_1.readSessionTraceEvents)(session.id);
545
+ // Resolve reference: latest (default), #N, or callId prefix
546
+ let trace = null;
547
+ let listMode = false;
548
+ if (!options.ref || options.ref === 'latest') {
549
+ trace = latestToolTrace(events);
550
+ }
551
+ else if (/^#?\d+$/.test(options.ref)) {
552
+ const seq = parseInt(options.ref.replace('#', ''), 10);
553
+ trace = toolTraceBySeq(events, seq);
554
+ if (!trace) {
555
+ console.log(ERROR(`Tool #${seq} not found in session trace.`));
556
+ // Fall back to listing available tools
557
+ listMode = true;
558
+ }
559
+ }
560
+ else {
561
+ trace = toolTraceByCallId(events, options.ref);
562
+ if (!trace) {
563
+ console.log(ERROR(`Tool with callId prefix "${options.ref}" not found in session trace.`));
564
+ listMode = true;
565
+ }
566
+ }
567
+ if (listMode || !trace) {
568
+ const pairs = collectToolTracePairs(events);
569
+ if (pairs.length === 0) {
570
+ console.log(DIM(`No tool trace events recorded for session ${session.id.slice(0, 8)} yet.`));
571
+ return { success: true };
572
+ }
573
+ console.log(HEADER(`Tools (${pairs.length})`));
574
+ console.log(DIM('─'.repeat(60)));
575
+ for (const pair of pairs.slice(-30)) {
576
+ const source = pair.result ?? pair.call;
577
+ const name = source?.name ?? 'tool';
578
+ const status = pair.result ? (pair.result.success === false ? '✗' : '✓') : '…';
579
+ const duration = typeof pair.result?.duration === 'number'
580
+ ? ` (${formatDurationMs(pair.result.duration)})`
581
+ : '';
582
+ const argsShort = (pair.call?.argsSummary ?? '').slice(0, 40);
583
+ console.log(` #${pair.seq} ${status} ${ACCENT(name)}${duration} ${DIM(argsShort)}`);
584
+ }
585
+ console.log();
586
+ console.log(DIM('Use /last-tool #N or /last-tool <callId> for details.'));
587
+ return { success: true };
588
+ }
589
+ const call = trace.call;
590
+ const result = trace.result;
591
+ const source = result ?? call;
592
+ const argsSource = call ?? result;
593
+ const name = source?.name ?? 'tool';
594
+ const inputLabel = lastToolInputLabel(name);
595
+ const callId = source?.callId ?? call?.callId;
596
+ const status = result
597
+ ? result.success === false
598
+ ? ERROR('error')
599
+ : SUCCESS('ok')
600
+ : WARN('running');
601
+ // Resolve sequence number from the trace events
602
+ let seqLabel = '';
603
+ if (options.ref && /^#?\d+$/.test(options.ref)) {
604
+ seqLabel = `#${parseInt(options.ref.replace('#', ''), 10)} `;
605
+ }
606
+ else if (result || call) {
607
+ const allPairs = collectToolTracePairs(events);
608
+ const matchingPair = allPairs.find(p => p.call?.callId === callId || p.result?.callId === callId);
609
+ if (matchingPair)
610
+ seqLabel = `#${matchingPair.seq} `;
611
+ }
612
+ console.log(HEADER(`Last Tool ${seqLabel}`.trimEnd()));
613
+ console.log(DIM('─'.repeat(40)));
614
+ console.log(` Tool ${ACCENT(name)}`);
615
+ console.log(` Turn ${DIM(source?.turnId ?? 'unknown')}`);
616
+ if (callId)
617
+ console.log(` Call ${DIM(callId)}`);
618
+ console.log(` Status ${status}`);
619
+ if (typeof result?.duration === 'number') {
620
+ console.log(` Time ${DIM(formatDurationMs(result.duration))}`);
621
+ }
622
+ if (argsSource?.argsSummary) {
623
+ console.log(` ${lastToolField(inputLabel)}${DIM((0, session_storage_1.redactTraceText)(argsSource.argsSummary))}`);
624
+ }
625
+ if (argsSource?.argsArtifactId) {
626
+ const size = typeof argsSource.argsBytes === 'number' ? ` (${(0, format_1.formatBytes)(argsSource.argsBytes)})` : '';
627
+ console.log(` ${lastToolField(`${inputLabel} full`)}${DIM(`/artifacts show ${argsSource.argsArtifactId} --full${size}`)}`);
628
+ }
629
+ if (typeof result?.outputBytes === 'number') {
630
+ const modelVisible = typeof result.modelVisibleBytes === 'number'
631
+ ? `, model-visible ${(0, format_1.formatBytes)(result.modelVisibleBytes)}`
632
+ : '';
633
+ console.log(` Output ${DIM(`${(0, format_1.formatBytes)(result.outputBytes)}${modelVisible}`)}`);
634
+ }
635
+ if (result?.artifactId) {
636
+ console.log(` Output full ${DIM(`/artifacts show ${result.artifactId} --full`)}`);
637
+ }
638
+ if (result?.error) {
639
+ console.log(` Error ${ERROR((0, session_storage_1.redactTraceText)(result.error))}`);
640
+ }
641
+ if (options.preview) {
642
+ const projectPath = session.projectPath || ctx.cwd;
643
+ printLastToolArtifactPreview(projectPath, inputLabel, argsSource?.argsArtifactId, options.full);
644
+ printLastToolArtifactPreview(projectPath, 'Output', result?.artifactId, options.full);
645
+ }
646
+ console.log();
647
+ console.log(DIM('Use /last-tool --full for redacted full previews, --no-preview for metadata only, or /trace latest for the ordered turn timeline.'));
648
+ return { success: true };
649
+ }
650
+ function formatDateTime(timestamp) {
651
+ return new Date(timestamp).toLocaleString();
652
+ }
653
+ function parseArtifactArgs(args) {
654
+ const parts = args.trim().split(/\s+/).filter(Boolean);
655
+ let full = false;
656
+ let limit = 20;
657
+ const positional = [];
658
+ for (let i = 0; i < parts.length; i++) {
659
+ const part = parts[i];
660
+ if (part === '--full') {
661
+ full = true;
662
+ continue;
663
+ }
664
+ if ((part === '--limit' || part === '-n') && parts[i + 1]) {
665
+ const parsed = Number(parts[i + 1]);
666
+ if (Number.isInteger(parsed) && parsed > 0) {
667
+ limit = Math.min(parsed, 200);
668
+ }
669
+ i++;
670
+ continue;
671
+ }
672
+ positional.push(part);
673
+ }
674
+ if (positional[0] === 'show' || positional[0] === 'cat') {
675
+ return { action: 'show', ref: positional[1], full, limit };
676
+ }
677
+ if (positional[0]) {
678
+ return { action: 'show', ref: positional[0], full, limit };
679
+ }
680
+ return { action: 'list', full, limit };
681
+ }
682
+ function printArtifactPreview(content, full) {
683
+ const maxPreviewBytes = 16 * 1024;
684
+ if (full || Buffer.byteLength(content, 'utf8') <= maxPreviewBytes) {
685
+ console.log(content);
686
+ return;
687
+ }
688
+ const preview = Buffer.from(content, 'utf8').subarray(0, maxPreviewBytes).toString('utf8');
689
+ console.log(preview);
690
+ console.log();
691
+ console.log(DIM(`... preview truncated at ${(0, format_1.formatBytes)(maxPreviewBytes)}. Use /artifacts show <id> --full for full output.`));
692
+ }
693
+ function formatArtifactPathForDisplay(artifactPath) {
694
+ return (0, session_storage_1.redactTraceText)(artifactPath);
695
+ }
696
+ function handleArtifacts(ctx, args = '') {
697
+ const parsed = parseArtifactArgs(args);
698
+ if (parsed.action === 'list') {
699
+ const artifacts = (0, tool_artifacts_1.listArtifacts)(ctx.cwd, parsed.limit);
700
+ console.log(HEADER('Artifacts'));
701
+ console.log(DIM('─'.repeat(40)));
702
+ if (artifacts.length === 0) {
703
+ console.log(DIM('No artifacts found for this project.'));
704
+ return { success: true };
705
+ }
706
+ for (const artifact of artifacts) {
707
+ console.log(`${ACCENT(artifact.id)} ${DIM(artifact.toolName)} ${(0, format_1.formatBytes)(artifact.outputBytes)}`);
708
+ console.log(` ${DIM(formatDateTime(artifact.modifiedAt))}`);
709
+ console.log(` ${DIM(formatArtifactPathForDisplay(artifact.path))}`);
710
+ }
711
+ console.log();
712
+ console.log(DIM('Use /artifacts show <id|prefix> to preview, or add --full for full output.'));
713
+ return { success: true };
714
+ }
715
+ if (!parsed.ref) {
716
+ console.log(ERROR('Usage: /artifacts show <id|prefix> [--full]'));
717
+ return { success: false };
718
+ }
719
+ const artifact = (0, tool_artifacts_1.findArtifact)(ctx.cwd, parsed.ref);
720
+ if (!artifact) {
721
+ console.log(ERROR(`Artifact not found or ambiguous: ${parsed.ref}`));
722
+ console.log(DIM('Run /artifacts to list available artifact ids.'));
723
+ return { success: false };
724
+ }
725
+ const content = (0, tool_artifacts_1.retrieveArtifact)(artifact.path);
726
+ if (content == null) {
727
+ console.log(ERROR(`Artifact exists but cannot be read: ${artifact.id}`));
728
+ console.log(DIM(formatArtifactPathForDisplay(artifact.path)));
729
+ return { success: false };
730
+ }
731
+ console.log(HEADER(`Artifact ${artifact.id}`));
732
+ console.log(DIM(`Tool ${artifact.toolName} Size ${(0, format_1.formatBytes)(artifact.outputBytes)} Modified ${formatDateTime(artifact.modifiedAt)}`));
733
+ console.log(DIM(formatArtifactPathForDisplay(artifact.path)));
734
+ console.log(DIM('─'.repeat(40)));
735
+ printArtifactPreview(content, parsed.full);
736
+ return { success: true };
737
+ }
738
+ function findCheckpointByRef(ctx, ref) {
739
+ const checkpoints = (0, checkpoint_1.listCheckpoints)(ctx.cwd);
740
+ const exact = checkpoints.find(checkpoint => checkpoint.turnId === ref);
741
+ if (exact)
742
+ return { checkpoint: exact, ambiguous: false };
743
+ const matches = checkpoints.filter(checkpoint => checkpoint.turnId.startsWith(ref));
744
+ return {
745
+ checkpoint: matches.length === 1 ? matches[0] : undefined,
746
+ ambiguous: matches.length > 1,
747
+ };
748
+ }
749
+ function handleCheckpoint(ctx, args = '') {
750
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
751
+ const action = tokens[0] ?? 'list';
752
+ if (action === 'list') {
753
+ const checkpoints = (0, checkpoint_1.listCheckpoints)(ctx.cwd);
754
+ console.log(HEADER('Checkpoints'));
755
+ console.log(DIM('─'.repeat(40)));
756
+ if (checkpoints.length === 0) {
757
+ console.log(DIM('No checkpoints found for this project.'));
758
+ return { success: true };
759
+ }
760
+ for (const checkpoint of checkpoints.slice(0, 20)) {
761
+ console.log(`${ACCENT(checkpoint.turnId)} ${DIM(formatDateTime(checkpoint.createdAt))}`);
762
+ const files = checkpoint.files
763
+ .map(file => file.path)
764
+ .slice(0, 8)
765
+ .join(', ');
766
+ console.log(` ${DIM(`${checkpoint.files.length} file(s)${files ? `: ${files}` : ''}`)}`);
767
+ }
768
+ console.log();
769
+ console.log(DIM('Use /rewind restore <turn-id|prefix> to preview, then add --yes to restore.'));
770
+ return { success: true };
771
+ }
772
+ if (action !== 'restore') {
773
+ console.log(ERROR('Usage: /rewind [list|restore <turn-id|prefix> [--yes]]'));
774
+ return { success: false };
775
+ }
776
+ const ref = tokens.find(token => token !== 'restore' && token !== '--yes');
777
+ const confirmed = tokens.includes('--yes');
778
+ if (!ref) {
779
+ console.log(ERROR('Usage: /rewind restore <turn-id|prefix> [--yes]'));
780
+ return { success: false };
781
+ }
782
+ const { checkpoint, ambiguous } = findCheckpointByRef(ctx, ref);
783
+ if (!checkpoint) {
784
+ console.log(ERROR(ambiguous ? `Checkpoint prefix is ambiguous: ${ref}` : `Checkpoint not found: ${ref}`));
785
+ console.log(DIM('Run /rewind to list available checkpoint ids.'));
786
+ return { success: false };
787
+ }
788
+ if (!confirmed) {
789
+ console.log(HEADER(`Checkpoint ${checkpoint.turnId}`));
790
+ console.log(DIM(`${formatDateTime(checkpoint.createdAt)} ${checkpoint.files.length} file(s)`));
791
+ for (const file of checkpoint.files.slice(0, 20)) {
792
+ console.log(` ${file.path} ${DIM((0, format_1.formatBytes)(file.sizeBytes))}`);
793
+ }
794
+ console.log();
795
+ console.log(WARN(`This will overwrite current files from checkpoint ${checkpoint.turnId}.`));
796
+ console.log(DIM(`Run /rewind restore ${checkpoint.turnId} --yes to restore.`));
797
+ return { success: true };
798
+ }
799
+ const result = (0, checkpoint_1.restoreCheckpoint)(ctx.cwd, checkpoint.turnId);
800
+ if (result.error) {
801
+ console.log(ERROR(result.error));
802
+ return { success: false, error: result.error };
803
+ }
804
+ console.log(SUCCESS(`Restored ${result.restored.length} file(s) from checkpoint ${checkpoint.turnId}.`));
805
+ for (const file of result.restored.slice(0, 20)) {
806
+ console.log(` ${file}`);
807
+ }
808
+ return { success: true, output: result.restored.join('\n') };
809
+ }
810
+ function showAgents(ctx) {
811
+ console.log();
812
+ console.log(HEADER('Registered Agents'));
813
+ console.log(DIM('─'.repeat(40)));
814
+ for (const agent of ctx.runtime.agents) {
815
+ const status = agent.getStatus();
816
+ const statusColor = status.status === 'idle' ? SUCCESS : WARN;
817
+ console.log();
818
+ console.log(` ${ACCENT(status.name)} ${DIM(`(${status.id})`)}`);
819
+ console.log(` Status: ${statusColor(status.status)}`);
820
+ console.log(` Capabilities: ${status.capabilities.join(', ')}`);
821
+ }
822
+ console.log();
823
+ return { success: true };
824
+ }
825
+ function handleCost(ctx) {
826
+ console.log();
827
+ console.log(HEADER('Lifetime Cost'));
828
+ console.log(DIM('─'.repeat(40)));
829
+ const costTracker = ctx.store.getSnapshot().costTracker;
830
+ const state = (0, usage_state_1.loadUsageState)();
831
+ const ledger = (0, usage_state_1.summarizeUsageLedger)();
832
+ if (state.totalTokens === 0 && state.totalCost === 0) {
833
+ console.log(DIM(' No usage recorded yet.'));
834
+ console.log(DIM(' Use /run or /chat to interact with LLM.'));
835
+ console.log();
836
+ return { success: true };
837
+ }
838
+ // Summary
839
+ console.log();
840
+ console.log(` ${ACCENT('Total Tokens')} ${state.totalTokens.toLocaleString()}`);
841
+ console.log(` ${ACCENT('Tracked Cost')} ${costTracker.formatCost(state.totalCost)}`);
842
+ console.log(` ${ACCENT('Provider Cost')} ${costTracker.formatCost(state.providerCost)}`);
843
+ console.log(` ${ACCENT('Estimated Cost')} ${costTracker.formatCost(state.estimatedCost)}`);
844
+ console.log(` ${ACCENT('Requests')} ${state.usageRecords.toLocaleString()}`);
845
+ console.log(` ${ACCENT('Sessions')} ${state.totalSessions.toLocaleString()}`);
846
+ // By Model
847
+ if (Object.keys(ledger.byModel).length > 0) {
848
+ console.log();
849
+ console.log(HEADER(' By Model:'));
850
+ for (const [model, data] of Object.entries(ledger.byModel)) {
851
+ console.log(` ${BRAND(model.padEnd(20))} ${data.tokens} tokens, ${costTracker.formatCost(data.cost)}`);
852
+ }
853
+ }
854
+ console.log();
855
+ console.log(HEADER(' Cost Sources:'));
856
+ for (const source of ['provider', 'configured', 'builtin', 'fallback']) {
857
+ const data = ledger.bySource[source];
858
+ if (data.count === 0)
859
+ continue;
860
+ console.log(` ${source.padEnd(12)} ${data.count} requests, ${costTracker.formatCost(data.cost)}`);
861
+ }
862
+ if (state.baselineCost > 0 || state.baselineTokens > 0) {
863
+ console.log(DIM(` legacy ${state.baselineTokens.toLocaleString()} tokens, ${costTracker.formatCost(state.baselineCost)}`));
864
+ }
865
+ if (ledger.bySource.fallback.count > 0) {
866
+ console.log();
867
+ console.log(WARN(' Unknown-model fallback pricing is an estimate.'));
868
+ console.log(DIM(' Configure cost.modelPricing in ~/.orion-code/orion.json for accuracy.'));
869
+ }
870
+ if (ledger.droppedCorruptLines > 0) {
871
+ console.log();
872
+ console.log(WARN(` Ignored ${ledger.droppedCorruptLines} corrupt usage ledger line(s); run /storage doctor.`));
873
+ }
874
+ // Budget
875
+ const budget = costTracker.getBudget();
876
+ if (budget !== null) {
877
+ const check = costTracker.checkBudget();
878
+ console.log();
879
+ console.log(HEADER(' Budget:'));
880
+ console.log(` ${ACCENT('Limit')} ${costTracker.formatCost(budget)}`);
881
+ console.log(` ${ACCENT('Used this run')} ${costTracker.formatCost(check.used)}`);
882
+ console.log(` ${check.ok ? SUCCESS('✓ Within budget') : WARN('⚠ Budget exceeded')}`);
883
+ }
884
+ console.log();
885
+ return { success: true };
886
+ }
887
+ function handleDoctor(ctx) {
888
+ const report = (0, doctor_1.collectDoctorReport)(ctx);
889
+ console.log();
890
+ console.log((0, doctor_1.formatDoctorReport)(report));
891
+ console.log();
892
+ return { success: !(0, doctor_1.hasDoctorFailures)(report) };
893
+ }
894
+ function handleStorage(_ctx, args) {
895
+ const usage = '/storage [doctor|status|repair [--dry-run|--yes] [--plan=<token>]|cleanup [--dry-run|--yes] [--plan=<token>]]';
896
+ const trimmed = args.trim();
897
+ const tokens = trimmed ? trimmed.split(/\s+/u) : [];
898
+ const action = tokens[0] ?? 'doctor';
899
+ const flags = tokens.slice(1);
900
+ const acceptsMutationFlags = action === 'cleanup' || action === 'repair';
901
+ const planFlags = flags.filter(flag => flag.startsWith('--plan='));
902
+ const invalidTokens = flags.filter(flag => !acceptsMutationFlags ||
903
+ (flag !== '--dry-run' && flag !== '--yes' && !flag.startsWith('--plan=')) ||
904
+ (flag.startsWith('--plan=') && flag.length === '--plan='.length));
905
+ if (planFlags.length > 1)
906
+ invalidTokens.push(...planFlags.slice(1));
907
+ if (invalidTokens.length > 0) {
908
+ return {
909
+ success: false,
910
+ error: `Unknown /storage option: ${invalidTokens.join(', ')}. Usage: ${usage}`,
911
+ };
912
+ }
913
+ const confirmed = flags.includes('--yes');
914
+ const explicitDryRun = flags.includes('--dry-run');
915
+ const planToken = planFlags[0]?.slice('--plan='.length);
916
+ const decodedPlan = planToken ? (0, storage_maintenance_1.deserializeStorageMaintenancePlan)(planToken) : undefined;
917
+ if (planToken && !decodedPlan) {
918
+ return { success: false, error: `Invalid or corrupted storage plan token. Usage: ${usage}` };
919
+ }
920
+ if (action === 'cleanup') {
921
+ if (decodedPlan && decodedPlan.kind !== 'cleanup') {
922
+ return { success: false, error: 'The supplied storage plan is not a cleanup plan.' };
923
+ }
924
+ const dryRun = explicitDryRun || !confirmed;
925
+ if (!dryRun && !decodedPlan) {
926
+ return {
927
+ success: false,
928
+ error: 'Cleanup requires the exact preview plan. Run /storage cleanup first.',
929
+ };
930
+ }
931
+ const consumedPlan = !dryRun && planToken ? (0, storage_maintenance_1.consumeStorageMaintenancePlan)(planToken) : undefined;
932
+ if (!dryRun && (!consumedPlan || consumedPlan.kind !== 'cleanup')) {
933
+ return {
934
+ success: false,
935
+ error: 'The storage cleanup plan expired, was already used, or is not valid in this process.',
936
+ };
937
+ }
938
+ const plan = dryRun
939
+ ? decodedPlan?.kind === 'cleanup'
940
+ ? decodedPlan.plan
941
+ : (0, storage_maintenance_1.collectStorageCleanupPlan)()
942
+ : consumedPlan
943
+ .plan;
944
+ const result = (0, storage_maintenance_1.cleanupStorage)({ dryRun }, plan);
945
+ console.log();
946
+ console.log((0, storage_maintenance_1.formatStorageCleanupResult)(result));
947
+ if (dryRun) {
948
+ const portablePlan = planToken ?? (0, storage_maintenance_1.serializeStorageMaintenancePlan)({ kind: 'cleanup', plan });
949
+ console.log(DIM(`Preview only. Run /storage cleanup --plan=${portablePlan} --yes to apply this plan.`));
950
+ }
951
+ console.log();
952
+ return { success: true };
953
+ }
954
+ if (action === 'repair') {
955
+ if (decodedPlan && decodedPlan.kind !== 'repair') {
956
+ return { success: false, error: 'The supplied storage plan is not a repair plan.' };
957
+ }
958
+ const plan = decodedPlan?.kind === 'repair' ? decodedPlan.plan : (0, storage_maintenance_1.collectProjectMetadataRepairPlan)();
959
+ if (explicitDryRun || !confirmed) {
960
+ console.log();
961
+ console.log(HEADER('Orion Code Storage Repair Preview'));
962
+ console.log(DIM('─'.repeat(40)));
963
+ console.log(` Repairable metadata entries ${ACCENT(String(plan.actions.length))}`);
964
+ for (const action of plan.actions.slice(0, 12)) {
965
+ console.log(` ${DIM('•')} ${DIM(action.metadataPath)}`);
966
+ }
967
+ const portablePlan = planToken ?? (0, storage_maintenance_1.serializeStorageMaintenancePlan)({ kind: 'repair', plan });
968
+ console.log(DIM(` Preview only. Writable repair is disabled; /storage repair --plan=${portablePlan} --yes will fail closed.`));
969
+ console.log();
970
+ return { success: true };
971
+ }
972
+ if (!decodedPlan) {
973
+ return {
974
+ success: false,
975
+ error: 'Repair requires the exact preview plan. Run /storage repair first.',
976
+ };
977
+ }
978
+ const consumedPlan = planToken ? (0, storage_maintenance_1.consumeStorageMaintenancePlan)(planToken) : undefined;
979
+ if (!consumedPlan || consumedPlan.kind !== 'repair') {
980
+ return {
981
+ success: false,
982
+ error: 'The storage repair plan expired, was already used, or is not valid in this process.',
983
+ };
984
+ }
985
+ const result = (0, storage_maintenance_1.repairProjectMetadata)(consumedPlan.plan);
986
+ return { success: false, error: result.blockedReason };
987
+ }
988
+ if (action !== 'doctor' && action !== 'status') {
989
+ return {
990
+ success: false,
991
+ error: `Usage: ${usage}`,
992
+ };
993
+ }
994
+ const report = (0, storage_maintenance_1.collectStorageReport)();
995
+ console.log();
996
+ console.log((0, storage_maintenance_1.formatStorageReport)(report));
997
+ console.log();
998
+ return { success: true };
999
+ }
1000
+ function handleUsage(ctx) {
1001
+ console.log();
1002
+ console.log(HEADER('Usage Statistics'));
1003
+ console.log(DIM('─'.repeat(40)));
1004
+ const snapshot = ctx.store.getSnapshot();
1005
+ const usage = snapshot.tokenUsage;
1006
+ const history = snapshot.conversationHistory;
1007
+ console.log();
1008
+ // Token usage
1009
+ console.log(HEADER(' Tokens:'));
1010
+ if (usage) {
1011
+ console.log(` Input ${ACCENT(usage.promptTokens.toLocaleString())}`);
1012
+ console.log(` Output ${ACCENT(usage.completionTokens.toLocaleString())}`);
1013
+ const total = usage.promptTokens + usage.completionTokens;
1014
+ console.log(` Total ${DIM(total.toLocaleString())}`);
1015
+ const ratio = usage.completionTokens / usage.promptTokens;
1016
+ console.log(` Ratio ${DIM(ratio.toFixed(2))} (output/input)`);
1017
+ }
1018
+ else {
1019
+ console.log(DIM(' No token usage recorded'));
1020
+ }
1021
+ console.log();
1022
+ // Conversation stats
1023
+ console.log(HEADER(' Conversation:'));
1024
+ console.log(` Messages ${DIM(history.length.toString())}`);
1025
+ console.log(` Turns ${DIM(Math.floor(history.length / 2).toString())}`);
1026
+ // Count by role
1027
+ const byRole = { user: 0, assistant: 0, system: 0, tool: 0 };
1028
+ for (const msg of history) {
1029
+ byRole[msg.role] = (byRole[msg.role] || 0) + 1;
1030
+ }
1031
+ console.log(` User msgs ${DIM(byRole.user.toString())}`);
1032
+ console.log(` Assistant ${DIM(byRole.assistant.toString())}`);
1033
+ console.log();
1034
+ // Model info
1035
+ console.log(HEADER(' Model:'));
1036
+ console.log(` Current ${BRAND(snapshot.currentModel)}`);
1037
+ if (ctx.llm) {
1038
+ console.log(` Active ${ACCENT(ctx.llm.getModel())}`);
1039
+ }
1040
+ console.log();
1041
+ return { success: true };
1042
+ }
1043
+ //# sourceMappingURL=diagnostic-command-handlers.js.map