praxis-agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (395) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +534 -0
  3. package/dist/application/background-agent-manager.d.ts +66 -0
  4. package/dist/application/background-agent-manager.d.ts.map +1 -0
  5. package/dist/application/background-agent-manager.js +362 -0
  6. package/dist/application/background-agent-manager.js.map +1 -0
  7. package/dist/application/background-bash-manager.d.ts +54 -0
  8. package/dist/application/background-bash-manager.d.ts.map +1 -0
  9. package/dist/application/background-bash-manager.js +354 -0
  10. package/dist/application/background-bash-manager.js.map +1 -0
  11. package/dist/application/background-task-id.d.ts +5 -0
  12. package/dist/application/background-task-id.d.ts.map +1 -0
  13. package/dist/application/background-task-id.js +25 -0
  14. package/dist/application/background-task-id.js.map +1 -0
  15. package/dist/application/claude-project-purge.d.ts +50 -0
  16. package/dist/application/claude-project-purge.d.ts.map +1 -0
  17. package/dist/application/claude-project-purge.js +459 -0
  18. package/dist/application/claude-project-purge.js.map +1 -0
  19. package/dist/application/managed-worktree.d.ts +15 -0
  20. package/dist/application/managed-worktree.d.ts.map +1 -0
  21. package/dist/application/managed-worktree.js +127 -0
  22. package/dist/application/managed-worktree.js.map +1 -0
  23. package/dist/application/model-compactor.d.ts +8 -0
  24. package/dist/application/model-compactor.d.ts.map +1 -0
  25. package/dist/application/model-compactor.js +70 -0
  26. package/dist/application/model-compactor.js.map +1 -0
  27. package/dist/application/scheduled-prompt-manager.d.ts +69 -0
  28. package/dist/application/scheduled-prompt-manager.d.ts.map +1 -0
  29. package/dist/application/scheduled-prompt-manager.js +387 -0
  30. package/dist/application/scheduled-prompt-manager.js.map +1 -0
  31. package/dist/application/session-service.d.ts +142 -0
  32. package/dist/application/session-service.d.ts.map +1 -0
  33. package/dist/application/session-service.js +1690 -0
  34. package/dist/application/session-service.js.map +1 -0
  35. package/dist/application/session-worktree.d.ts +55 -0
  36. package/dist/application/session-worktree.d.ts.map +1 -0
  37. package/dist/application/session-worktree.js +311 -0
  38. package/dist/application/session-worktree.js.map +1 -0
  39. package/dist/application/subagent-service.d.ts +98 -0
  40. package/dist/application/subagent-service.d.ts.map +1 -0
  41. package/dist/application/subagent-service.js +1305 -0
  42. package/dist/application/subagent-service.js.map +1 -0
  43. package/dist/application/tool-use-summary.d.ts +8 -0
  44. package/dist/application/tool-use-summary.d.ts.map +1 -0
  45. package/dist/application/tool-use-summary.js +53 -0
  46. package/dist/application/tool-use-summary.js.map +1 -0
  47. package/dist/application/top-level-agent-manager.d.ts +58 -0
  48. package/dist/application/top-level-agent-manager.d.ts.map +1 -0
  49. package/dist/application/top-level-agent-manager.js +907 -0
  50. package/dist/application/top-level-agent-manager.js.map +1 -0
  51. package/dist/application/workflow-manager.d.ts +61 -0
  52. package/dist/application/workflow-manager.d.ts.map +1 -0
  53. package/dist/application/workflow-manager.js +582 -0
  54. package/dist/application/workflow-manager.js.map +1 -0
  55. package/dist/application/workflow-meta.d.ts +18 -0
  56. package/dist/application/workflow-meta.d.ts.map +1 -0
  57. package/dist/application/workflow-meta.js +146 -0
  58. package/dist/application/workflow-meta.js.map +1 -0
  59. package/dist/application/workflow-runtime.d.ts +29 -0
  60. package/dist/application/workflow-runtime.d.ts.map +1 -0
  61. package/dist/application/workflow-runtime.js +176 -0
  62. package/dist/application/workflow-runtime.js.map +1 -0
  63. package/dist/application/workflow-worktree.d.ts +9 -0
  64. package/dist/application/workflow-worktree.d.ts.map +1 -0
  65. package/dist/application/workflow-worktree.js +11 -0
  66. package/dist/application/workflow-worktree.js.map +1 -0
  67. package/dist/cli/agents-dashboard.d.ts +37 -0
  68. package/dist/cli/agents-dashboard.d.ts.map +1 -0
  69. package/dist/cli/agents-dashboard.js +408 -0
  70. package/dist/cli/agents-dashboard.js.map +1 -0
  71. package/dist/cli/controls.d.ts +15 -0
  72. package/dist/cli/controls.d.ts.map +1 -0
  73. package/dist/cli/controls.js +219 -0
  74. package/dist/cli/controls.js.map +1 -0
  75. package/dist/cli/debug.d.ts +13 -0
  76. package/dist/cli/debug.d.ts.map +1 -0
  77. package/dist/cli/debug.js +37 -0
  78. package/dist/cli/debug.js.map +1 -0
  79. package/dist/cli/interactive.d.ts +63 -0
  80. package/dist/cli/interactive.d.ts.map +1 -0
  81. package/dist/cli/interactive.js +600 -0
  82. package/dist/cli/interactive.js.map +1 -0
  83. package/dist/cli/protocol.d.ts +251 -0
  84. package/dist/cli/protocol.d.ts.map +1 -0
  85. package/dist/cli/protocol.js +2146 -0
  86. package/dist/cli/protocol.js.map +1 -0
  87. package/dist/cli.d.ts +116 -0
  88. package/dist/cli.d.ts.map +1 -0
  89. package/dist/cli.js +3901 -0
  90. package/dist/cli.js.map +1 -0
  91. package/dist/compatibility/claude/compaction.d.ts +19 -0
  92. package/dist/compatibility/claude/compaction.d.ts.map +1 -0
  93. package/dist/compatibility/claude/compaction.js +82 -0
  94. package/dist/compatibility/claude/compaction.js.map +1 -0
  95. package/dist/compatibility/claude/context.d.ts +24 -0
  96. package/dist/compatibility/claude/context.d.ts.map +1 -0
  97. package/dist/compatibility/claude/context.js +92 -0
  98. package/dist/compatibility/claude/context.js.map +1 -0
  99. package/dist/compatibility/claude/dynamic-context.d.ts +20 -0
  100. package/dist/compatibility/claude/dynamic-context.d.ts.map +1 -0
  101. package/dist/compatibility/claude/dynamic-context.js +168 -0
  102. package/dist/compatibility/claude/dynamic-context.js.map +1 -0
  103. package/dist/compatibility/claude/file-history.d.ts +14 -0
  104. package/dist/compatibility/claude/file-history.d.ts.map +1 -0
  105. package/dist/compatibility/claude/file-history.js +340 -0
  106. package/dist/compatibility/claude/file-history.js.map +1 -0
  107. package/dist/compatibility/claude/file-resources.d.ts +28 -0
  108. package/dist/compatibility/claude/file-resources.d.ts.map +1 -0
  109. package/dist/compatibility/claude/file-resources.js +168 -0
  110. package/dist/compatibility/claude/file-resources.js.map +1 -0
  111. package/dist/compatibility/claude/fork.d.ts +9 -0
  112. package/dist/compatibility/claude/fork.d.ts.map +1 -0
  113. package/dist/compatibility/claude/fork.js +225 -0
  114. package/dist/compatibility/claude/fork.js.map +1 -0
  115. package/dist/compatibility/claude/history.d.ts +4 -0
  116. package/dist/compatibility/claude/history.d.ts.map +1 -0
  117. package/dist/compatibility/claude/history.js +86 -0
  118. package/dist/compatibility/claude/history.js.map +1 -0
  119. package/dist/compatibility/claude/ownership.d.ts +87 -0
  120. package/dist/compatibility/claude/ownership.d.ts.map +1 -0
  121. package/dist/compatibility/claude/ownership.js +100 -0
  122. package/dist/compatibility/claude/ownership.js.map +1 -0
  123. package/dist/compatibility/claude/paths.d.ts +17 -0
  124. package/dist/compatibility/claude/paths.d.ts.map +1 -0
  125. package/dist/compatibility/claude/paths.js +54 -0
  126. package/dist/compatibility/claude/paths.js.map +1 -0
  127. package/dist/compatibility/claude/pr-links.d.ts +25 -0
  128. package/dist/compatibility/claude/pr-links.d.ts.map +1 -0
  129. package/dist/compatibility/claude/pr-links.js +80 -0
  130. package/dist/compatibility/claude/pr-links.js.map +1 -0
  131. package/dist/compatibility/claude/projection.d.ts +11 -0
  132. package/dist/compatibility/claude/projection.d.ts.map +1 -0
  133. package/dist/compatibility/claude/projection.js +325 -0
  134. package/dist/compatibility/claude/projection.js.map +1 -0
  135. package/dist/compatibility/claude/schema.d.ts +18 -0
  136. package/dist/compatibility/claude/schema.d.ts.map +1 -0
  137. package/dist/compatibility/claude/schema.js +983 -0
  138. package/dist/compatibility/claude/schema.js.map +1 -0
  139. package/dist/compatibility/claude/shared-resources.d.ts +51 -0
  140. package/dist/compatibility/claude/shared-resources.d.ts.map +1 -0
  141. package/dist/compatibility/claude/shared-resources.js +382 -0
  142. package/dist/compatibility/claude/shared-resources.js.map +1 -0
  143. package/dist/compatibility/claude/sidechain.d.ts +50 -0
  144. package/dist/compatibility/claude/sidechain.d.ts.map +1 -0
  145. package/dist/compatibility/claude/sidechain.js +90 -0
  146. package/dist/compatibility/claude/sidechain.js.map +1 -0
  147. package/dist/compatibility/claude/tool-links.d.ts +13 -0
  148. package/dist/compatibility/claude/tool-links.d.ts.map +1 -0
  149. package/dist/compatibility/claude/tool-links.js +61 -0
  150. package/dist/compatibility/claude/tool-links.js.map +1 -0
  151. package/dist/compatibility/claude/translation.d.ts +71 -0
  152. package/dist/compatibility/claude/translation.d.ts.map +1 -0
  153. package/dist/compatibility/claude/translation.js +443 -0
  154. package/dist/compatibility/claude/translation.js.map +1 -0
  155. package/dist/compatibility/claude/workflow-replay.d.ts +10 -0
  156. package/dist/compatibility/claude/workflow-replay.d.ts.map +1 -0
  157. package/dist/compatibility/claude/workflow-replay.js +66 -0
  158. package/dist/compatibility/claude/workflow-replay.js.map +1 -0
  159. package/dist/compatibility/claude/workflow.d.ts +33 -0
  160. package/dist/compatibility/claude/workflow.d.ts.map +1 -0
  161. package/dist/compatibility/claude/workflow.js +76 -0
  162. package/dist/compatibility/claude/workflow.js.map +1 -0
  163. package/dist/core/compaction.d.ts +16 -0
  164. package/dist/core/compaction.d.ts.map +1 -0
  165. package/dist/core/compaction.js +2 -0
  166. package/dist/core/compaction.js.map +1 -0
  167. package/dist/core/context-budget.d.ts +28 -0
  168. package/dist/core/context-budget.d.ts.map +1 -0
  169. package/dist/core/context-budget.js +108 -0
  170. package/dist/core/context-budget.js.map +1 -0
  171. package/dist/core/context.d.ts +16 -0
  172. package/dist/core/context.d.ts.map +1 -0
  173. package/dist/core/context.js +13 -0
  174. package/dist/core/context.js.map +1 -0
  175. package/dist/core/runtime.d.ts +394 -0
  176. package/dist/core/runtime.d.ts.map +1 -0
  177. package/dist/core/runtime.js +507 -0
  178. package/dist/core/runtime.js.map +1 -0
  179. package/dist/core/usage.d.ts +26 -0
  180. package/dist/core/usage.d.ts.map +1 -0
  181. package/dist/core/usage.js +133 -0
  182. package/dist/core/usage.js.map +1 -0
  183. package/dist/extensions/claude-extension-tools.d.ts +16 -0
  184. package/dist/extensions/claude-extension-tools.d.ts.map +1 -0
  185. package/dist/extensions/claude-extension-tools.js +78 -0
  186. package/dist/extensions/claude-extension-tools.js.map +1 -0
  187. package/dist/extensions/claude-extensions.d.ts +41 -0
  188. package/dist/extensions/claude-extensions.d.ts.map +1 -0
  189. package/dist/extensions/claude-extensions.js +270 -0
  190. package/dist/extensions/claude-extensions.js.map +1 -0
  191. package/dist/hooks/claude-hook-tools.d.ts +26 -0
  192. package/dist/hooks/claude-hook-tools.d.ts.map +1 -0
  193. package/dist/hooks/claude-hook-tools.js +129 -0
  194. package/dist/hooks/claude-hook-tools.js.map +1 -0
  195. package/dist/hooks/claude-hooks.d.ts +87 -0
  196. package/dist/hooks/claude-hooks.d.ts.map +1 -0
  197. package/dist/hooks/claude-hooks.js +411 -0
  198. package/dist/hooks/claude-hooks.js.map +1 -0
  199. package/dist/maintenance/doctor.d.ts +33 -0
  200. package/dist/maintenance/doctor.d.ts.map +1 -0
  201. package/dist/maintenance/doctor.js +391 -0
  202. package/dist/maintenance/doctor.js.map +1 -0
  203. package/dist/maintenance/self-update.d.ts +31 -0
  204. package/dist/maintenance/self-update.d.ts.map +1 -0
  205. package/dist/maintenance/self-update.js +81 -0
  206. package/dist/maintenance/self-update.js.map +1 -0
  207. package/dist/mcp/claude-mcp-management.d.ts +28 -0
  208. package/dist/mcp/claude-mcp-management.d.ts.map +1 -0
  209. package/dist/mcp/claude-mcp-management.js +169 -0
  210. package/dist/mcp/claude-mcp-management.js.map +1 -0
  211. package/dist/mcp/claude-mcp-oauth.d.ts +113 -0
  212. package/dist/mcp/claude-mcp-oauth.d.ts.map +1 -0
  213. package/dist/mcp/claude-mcp-oauth.js +1053 -0
  214. package/dist/mcp/claude-mcp-oauth.js.map +1 -0
  215. package/dist/mcp/claude-mcp-tools.d.ts +98 -0
  216. package/dist/mcp/claude-mcp-tools.d.ts.map +1 -0
  217. package/dist/mcp/claude-mcp-tools.js +1246 -0
  218. package/dist/mcp/claude-mcp-tools.js.map +1 -0
  219. package/dist/mcp/praxis-mcp-server.d.ts +35 -0
  220. package/dist/mcp/praxis-mcp-server.d.ts.map +1 -0
  221. package/dist/mcp/praxis-mcp-server.js +520 -0
  222. package/dist/mcp/praxis-mcp-server.js.map +1 -0
  223. package/dist/permissions/claude-auto-classifier.d.ts +20 -0
  224. package/dist/permissions/claude-auto-classifier.d.ts.map +1 -0
  225. package/dist/permissions/claude-auto-classifier.js +140 -0
  226. package/dist/permissions/claude-auto-classifier.js.map +1 -0
  227. package/dist/permissions/claude-permission-resolver.d.ts +30 -0
  228. package/dist/permissions/claude-permission-resolver.d.ts.map +1 -0
  229. package/dist/permissions/claude-permission-resolver.js +334 -0
  230. package/dist/permissions/claude-permission-resolver.js.map +1 -0
  231. package/dist/persistence/claude-job-store.d.ts +68 -0
  232. package/dist/persistence/claude-job-store.d.ts.map +1 -0
  233. package/dist/persistence/claude-job-store.js +311 -0
  234. package/dist/persistence/claude-job-store.js.map +1 -0
  235. package/dist/persistence/claude-scheduled-task-store.d.ts +29 -0
  236. package/dist/persistence/claude-scheduled-task-store.d.ts.map +1 -0
  237. package/dist/persistence/claude-scheduled-task-store.js +163 -0
  238. package/dist/persistence/claude-scheduled-task-store.js.map +1 -0
  239. package/dist/persistence/claude-sidechain-store.d.ts +18 -0
  240. package/dist/persistence/claude-sidechain-store.d.ts.map +1 -0
  241. package/dist/persistence/claude-sidechain-store.js +107 -0
  242. package/dist/persistence/claude-sidechain-store.js.map +1 -0
  243. package/dist/persistence/claude-task-store.d.ts +72 -0
  244. package/dist/persistence/claude-task-store.d.ts.map +1 -0
  245. package/dist/persistence/claude-task-store.js +440 -0
  246. package/dist/persistence/claude-task-store.js.map +1 -0
  247. package/dist/persistence/claude-transcript-store.d.ts +85 -0
  248. package/dist/persistence/claude-transcript-store.d.ts.map +1 -0
  249. package/dist/persistence/claude-transcript-store.js +385 -0
  250. package/dist/persistence/claude-transcript-store.js.map +1 -0
  251. package/dist/persistence/claude-workflow-store.d.ts +41 -0
  252. package/dist/persistence/claude-workflow-store.d.ts.map +1 -0
  253. package/dist/persistence/claude-workflow-store.js +263 -0
  254. package/dist/persistence/claude-workflow-store.js.map +1 -0
  255. package/dist/persistence/in-memory-sidechain-store.d.ts +12 -0
  256. package/dist/persistence/in-memory-sidechain-store.d.ts.map +1 -0
  257. package/dist/persistence/in-memory-sidechain-store.js +30 -0
  258. package/dist/persistence/in-memory-sidechain-store.js.map +1 -0
  259. package/dist/persistence/in-memory-transcript-store.d.ts +15 -0
  260. package/dist/persistence/in-memory-transcript-store.d.ts.map +1 -0
  261. package/dist/persistence/in-memory-transcript-store.js +95 -0
  262. package/dist/persistence/in-memory-transcript-store.js.map +1 -0
  263. package/dist/platform/atomic-write.d.ts +5 -0
  264. package/dist/platform/atomic-write.d.ts.map +1 -0
  265. package/dist/platform/atomic-write.js +25 -0
  266. package/dist/platform/atomic-write.js.map +1 -0
  267. package/dist/platform/bounded-process-runner.d.ts +28 -0
  268. package/dist/platform/bounded-process-runner.d.ts.map +1 -0
  269. package/dist/platform/bounded-process-runner.js +209 -0
  270. package/dist/platform/bounded-process-runner.js.map +1 -0
  271. package/dist/platform/claude-version.d.ts +5 -0
  272. package/dist/platform/claude-version.d.ts.map +1 -0
  273. package/dist/platform/claude-version.js +17 -0
  274. package/dist/platform/claude-version.js.map +1 -0
  275. package/dist/platform/command-shell.d.ts +3 -0
  276. package/dist/platform/command-shell.d.ts.map +1 -0
  277. package/dist/platform/command-shell.js +15 -0
  278. package/dist/platform/command-shell.js.map +1 -0
  279. package/dist/platform/exclusive-file-lease.d.ts +15 -0
  280. package/dist/platform/exclusive-file-lease.d.ts.map +1 -0
  281. package/dist/platform/exclusive-file-lease.js +265 -0
  282. package/dist/platform/exclusive-file-lease.js.map +1 -0
  283. package/dist/platform/sensitive-data.d.ts +8 -0
  284. package/dist/platform/sensitive-data.d.ts.map +1 -0
  285. package/dist/platform/sensitive-data.js +138 -0
  286. package/dist/platform/sensitive-data.js.map +1 -0
  287. package/dist/platform/tmux-worktree.d.ts +30 -0
  288. package/dist/platform/tmux-worktree.d.ts.map +1 -0
  289. package/dist/platform/tmux-worktree.js +138 -0
  290. package/dist/platform/tmux-worktree.js.map +1 -0
  291. package/dist/plugins/claude-plugin-eval-discovery.d.ts +20 -0
  292. package/dist/plugins/claude-plugin-eval-discovery.d.ts.map +1 -0
  293. package/dist/plugins/claude-plugin-eval-discovery.js +128 -0
  294. package/dist/plugins/claude-plugin-eval-discovery.js.map +1 -0
  295. package/dist/plugins/claude-plugin-eval-graders.d.ts +49 -0
  296. package/dist/plugins/claude-plugin-eval-graders.d.ts.map +1 -0
  297. package/dist/plugins/claude-plugin-eval-graders.js +137 -0
  298. package/dist/plugins/claude-plugin-eval-graders.js.map +1 -0
  299. package/dist/plugins/claude-plugin-eval-runner.d.ts +50 -0
  300. package/dist/plugins/claude-plugin-eval-runner.d.ts.map +1 -0
  301. package/dist/plugins/claude-plugin-eval-runner.js +189 -0
  302. package/dist/plugins/claude-plugin-eval-runner.js.map +1 -0
  303. package/dist/plugins/claude-plugin-eval-schema.d.ts +80 -0
  304. package/dist/plugins/claude-plugin-eval-schema.d.ts.map +1 -0
  305. package/dist/plugins/claude-plugin-eval-schema.js +436 -0
  306. package/dist/plugins/claude-plugin-eval-schema.js.map +1 -0
  307. package/dist/plugins/claude-plugin-eval.d.ts +66 -0
  308. package/dist/plugins/claude-plugin-eval.d.ts.map +1 -0
  309. package/dist/plugins/claude-plugin-eval.js +438 -0
  310. package/dist/plugins/claude-plugin-eval.js.map +1 -0
  311. package/dist/plugins/claude-plugin-maintenance.d.ts +39 -0
  312. package/dist/plugins/claude-plugin-maintenance.d.ts.map +1 -0
  313. package/dist/plugins/claude-plugin-maintenance.js +336 -0
  314. package/dist/plugins/claude-plugin-maintenance.js.map +1 -0
  315. package/dist/plugins/claude-plugin-marketplace.d.ts +97 -0
  316. package/dist/plugins/claude-plugin-marketplace.d.ts.map +1 -0
  317. package/dist/plugins/claude-plugin-marketplace.js +1433 -0
  318. package/dist/plugins/claude-plugin-marketplace.js.map +1 -0
  319. package/dist/plugins/claude-plugin-mcpb.d.ts +71 -0
  320. package/dist/plugins/claude-plugin-mcpb.d.ts.map +1 -0
  321. package/dist/plugins/claude-plugin-mcpb.js +885 -0
  322. package/dist/plugins/claude-plugin-mcpb.js.map +1 -0
  323. package/dist/plugins/claude-plugin-runtime.d.ts +120 -0
  324. package/dist/plugins/claude-plugin-runtime.d.ts.map +1 -0
  325. package/dist/plugins/claude-plugin-runtime.js +1263 -0
  326. package/dist/plugins/claude-plugin-runtime.js.map +1 -0
  327. package/dist/providers/anthropic-compatible.d.ts +35 -0
  328. package/dist/providers/anthropic-compatible.d.ts.map +1 -0
  329. package/dist/providers/anthropic-compatible.js +733 -0
  330. package/dist/providers/anthropic-compatible.js.map +1 -0
  331. package/dist/providers/environment.d.ts +14 -0
  332. package/dist/providers/environment.d.ts.map +1 -0
  333. package/dist/providers/environment.js +67 -0
  334. package/dist/providers/environment.js.map +1 -0
  335. package/dist/providers/fallback-provider.d.ts +17 -0
  336. package/dist/providers/fallback-provider.d.ts.map +1 -0
  337. package/dist/providers/fallback-provider.js +70 -0
  338. package/dist/providers/fallback-provider.js.map +1 -0
  339. package/dist/providers/openai-compatible.d.ts +30 -0
  340. package/dist/providers/openai-compatible.d.ts.map +1 -0
  341. package/dist/providers/openai-compatible.js +409 -0
  342. package/dist/providers/openai-compatible.js.map +1 -0
  343. package/dist/tools/claude-interactive-tools.d.ts +58 -0
  344. package/dist/tools/claude-interactive-tools.d.ts.map +1 -0
  345. package/dist/tools/claude-interactive-tools.js +390 -0
  346. package/dist/tools/claude-interactive-tools.js.map +1 -0
  347. package/dist/tools/claude-lsp-formatters.d.ts +2 -0
  348. package/dist/tools/claude-lsp-formatters.d.ts.map +1 -0
  349. package/dist/tools/claude-lsp-formatters.js +291 -0
  350. package/dist/tools/claude-lsp-formatters.js.map +1 -0
  351. package/dist/tools/claude-lsp-tool.d.ts +22 -0
  352. package/dist/tools/claude-lsp-tool.d.ts.map +1 -0
  353. package/dist/tools/claude-lsp-tool.js +744 -0
  354. package/dist/tools/claude-lsp-tool.js.map +1 -0
  355. package/dist/tools/claude-scheduled-tools.d.ts +20 -0
  356. package/dist/tools/claude-scheduled-tools.d.ts.map +1 -0
  357. package/dist/tools/claude-scheduled-tools.js +344 -0
  358. package/dist/tools/claude-scheduled-tools.js.map +1 -0
  359. package/dist/tools/claude-task-tools.d.ts +30 -0
  360. package/dist/tools/claude-task-tools.d.ts.map +1 -0
  361. package/dist/tools/claude-task-tools.js +503 -0
  362. package/dist/tools/claude-task-tools.js.map +1 -0
  363. package/dist/tools/claude-user-message.d.ts +16 -0
  364. package/dist/tools/claude-user-message.d.ts.map +1 -0
  365. package/dist/tools/claude-user-message.js +98 -0
  366. package/dist/tools/claude-user-message.js.map +1 -0
  367. package/dist/tools/claude-workflow-tools.d.ts +27 -0
  368. package/dist/tools/claude-workflow-tools.d.ts.map +1 -0
  369. package/dist/tools/claude-workflow-tools.js +257 -0
  370. package/dist/tools/claude-workflow-tools.js.map +1 -0
  371. package/dist/tools/claude-worktree-tools.d.ts +17 -0
  372. package/dist/tools/claude-worktree-tools.d.ts.map +1 -0
  373. package/dist/tools/claude-worktree-tools.js +135 -0
  374. package/dist/tools/claude-worktree-tools.js.map +1 -0
  375. package/dist/tools/filtered-tool-registry.d.ts +16 -0
  376. package/dist/tools/filtered-tool-registry.d.ts.map +1 -0
  377. package/dist/tools/filtered-tool-registry.js +51 -0
  378. package/dist/tools/filtered-tool-registry.js.map +1 -0
  379. package/dist/tools/glob.d.ts +9 -0
  380. package/dist/tools/glob.d.ts.map +1 -0
  381. package/dist/tools/glob.js +88 -0
  382. package/dist/tools/glob.js.map +1 -0
  383. package/dist/tools/local-tools.d.ts +47 -0
  384. package/dist/tools/local-tools.d.ts.map +1 -0
  385. package/dist/tools/local-tools.js +1082 -0
  386. package/dist/tools/local-tools.js.map +1 -0
  387. package/dist/tools/notebook.d.ts +22 -0
  388. package/dist/tools/notebook.d.ts.map +1 -0
  389. package/dist/tools/notebook.js +154 -0
  390. package/dist/tools/notebook.js.map +1 -0
  391. package/dist/tools/web.d.ts +48 -0
  392. package/dist/tools/web.d.ts.map +1 -0
  393. package/dist/tools/web.js +726 -0
  394. package/dist/tools/web.js.map +1 -0
  395. package/package.json +145 -0
@@ -0,0 +1,2146 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export function createSuccessResult(result, info, startedAt, modelTurns) {
3
+ const duration = Date.now() - startedAt;
4
+ const modelUsage = result.modelUsage ?? { [info.model]: result.usage };
5
+ const usage = {
6
+ input_tokens: result.usage.inputTokens,
7
+ output_tokens: result.usage.outputTokens,
8
+ ...(result.usage.cacheReadInputTokens === undefined
9
+ ? {}
10
+ : { cache_read_input_tokens: result.usage.cacheReadInputTokens }),
11
+ ...(result.usage.cacheCreationInputTokens === undefined
12
+ ? {}
13
+ : {
14
+ cache_creation_input_tokens: result.usage.cacheCreationInputTokens,
15
+ }),
16
+ };
17
+ return {
18
+ type: 'result',
19
+ subtype: 'success',
20
+ is_error: false,
21
+ duration_ms: duration,
22
+ duration_api_ms: result.durationApiMs === undefined
23
+ ? null
24
+ : Math.round(result.durationApiMs),
25
+ num_turns: modelTurns,
26
+ result: result.text,
27
+ stop_reason: null,
28
+ session_id: result.sessionId,
29
+ total_cost_usd: result.costUsd ?? null,
30
+ usage,
31
+ modelUsage: Object.fromEntries(Object.entries(modelUsage).map(([model, modelUsage]) => [
32
+ model,
33
+ {
34
+ inputTokens: modelUsage.inputTokens,
35
+ outputTokens: modelUsage.outputTokens,
36
+ cacheReadInputTokens: modelUsage.cacheReadInputTokens ?? 0,
37
+ cacheCreationInputTokens: modelUsage.cacheCreationInputTokens ?? 0,
38
+ costUSD: model === info.model ? (result.costUsd ?? null) : null,
39
+ },
40
+ ])),
41
+ permission_denials: [],
42
+ ...(result.structuredOutput === undefined
43
+ ? {}
44
+ : { structured_output: result.structuredOutput }),
45
+ fast_mode_state: 'off',
46
+ uuid: randomUUID(),
47
+ };
48
+ }
49
+ function errorResultSubtype(message) {
50
+ if (/maximum budget|budget .* exceeded/iu.test(message))
51
+ return 'error_max_budget_usd';
52
+ if (/maximum model turns|model turn limit/iu.test(message))
53
+ return 'error_max_turns';
54
+ if (/StructuredOutput/iu.test(message))
55
+ return 'error_max_structured_output_retries';
56
+ return 'error_during_execution';
57
+ }
58
+ export function createErrorResult(message, sessionId, startedAt, modelTurns) {
59
+ const duration = Date.now() - startedAt;
60
+ return {
61
+ type: 'result',
62
+ subtype: errorResultSubtype(message),
63
+ is_error: true,
64
+ duration_ms: duration,
65
+ duration_api_ms: null,
66
+ num_turns: modelTurns,
67
+ stop_reason: null,
68
+ session_id: sessionId,
69
+ total_cost_usd: null,
70
+ usage: {
71
+ input_tokens: 0,
72
+ output_tokens: 0,
73
+ cache_creation_input_tokens: 0,
74
+ cache_read_input_tokens: 0,
75
+ },
76
+ modelUsage: {},
77
+ permission_denials: [],
78
+ errors: [message],
79
+ fast_mode_state: 'off',
80
+ uuid: randomUUID(),
81
+ };
82
+ }
83
+ const INPUT_FORMATS = ['text', 'stream-json'];
84
+ const OUTPUT_FORMATS = ['text', 'json', 'stream-json'];
85
+ const PERMISSION_MODES = [
86
+ 'acceptEdits',
87
+ 'auto',
88
+ 'bypassPermissions',
89
+ 'manual',
90
+ 'dontAsk',
91
+ 'plan',
92
+ 'default',
93
+ ];
94
+ const SETTING_SOURCES = ['user', 'project', 'local'];
95
+ const MCP_SCOPES = ['local', 'project', 'user'];
96
+ const MCP_TRANSPORTS = ['stdio', 'sse', 'http'];
97
+ const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
98
+ const THINKING_MODES = ['enabled', 'adaptive', 'disabled'];
99
+ const MAX_INPUT_LINE_BYTES = 1024 * 1024;
100
+ const IMAGE_MEDIA_TYPES = new Set([
101
+ 'image/png',
102
+ 'image/jpeg',
103
+ 'image/gif',
104
+ 'image/webp',
105
+ ]);
106
+ const DOCUMENT_MEDIA_TYPES = new Set([
107
+ 'application/pdf',
108
+ 'text/plain',
109
+ 'text/markdown',
110
+ 'application/json',
111
+ ]);
112
+ function isBase64Data(value) {
113
+ return (value.length > 0 &&
114
+ value.length % 4 === 0 &&
115
+ /^[A-Za-z0-9+/]*={0,2}$/.test(value) &&
116
+ Buffer.from(value, 'base64').toString('base64') === value);
117
+ }
118
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
119
+ const PLUGIN_INIT_COMPONENTS = new Set([
120
+ 'skills',
121
+ 'agents',
122
+ 'hooks',
123
+ 'mcp',
124
+ 'lsp',
125
+ 'output-style',
126
+ 'channel',
127
+ ]);
128
+ function requiredValue(argv, index, label) {
129
+ const value = argv[index + 1];
130
+ if (!value || value.startsWith('-'))
131
+ throw new Error(`${label} is required`);
132
+ return value;
133
+ }
134
+ function choice(value, label, choices) {
135
+ if (!choices.includes(value)) {
136
+ throw new Error(`${label} must be one of ${choices.join(', ')}`);
137
+ }
138
+ return value;
139
+ }
140
+ function positiveDecimal(value, label) {
141
+ const parsed = Number(value);
142
+ if (!Number.isFinite(parsed) || parsed <= 0) {
143
+ throw new Error(`${label} must be a positive number`);
144
+ }
145
+ return parsed;
146
+ }
147
+ function optionValue(argv, index, option) {
148
+ const current = argv[index];
149
+ if (current === option) {
150
+ return { value: requiredValue(argv, index, option), consumed: 1 };
151
+ }
152
+ const prefix = `${option}=`;
153
+ if (current?.startsWith(prefix)) {
154
+ const value = current.slice(prefix.length);
155
+ if (!value)
156
+ throw new Error(`${option} is required`);
157
+ return { value, consumed: 0 };
158
+ }
159
+ return null;
160
+ }
161
+ function optionalValue(argv, index, option) {
162
+ const current = argv[index];
163
+ if (current === option) {
164
+ const candidate = argv[index + 1];
165
+ if (candidate !== undefined &&
166
+ candidate !== '--' &&
167
+ !candidate.startsWith('-')) {
168
+ return { value: candidate, consumed: 1 };
169
+ }
170
+ return { value: true, consumed: 0 };
171
+ }
172
+ const prefix = `${option}=`;
173
+ if (current?.startsWith(prefix)) {
174
+ return { value: current.slice(prefix.length), consumed: 0 };
175
+ }
176
+ return null;
177
+ }
178
+ function listOptionValue(argv, index, options) {
179
+ const current = argv[index];
180
+ const option = options.find((candidate) => current === candidate);
181
+ if (option) {
182
+ const values = [];
183
+ let consumed = 0;
184
+ while (index + consumed + 1 < argv.length) {
185
+ const candidate = argv[index + consumed + 1];
186
+ if (candidate === undefined || candidate === '--')
187
+ break;
188
+ if (candidate.startsWith('-') && candidate !== '-')
189
+ break;
190
+ values.push(candidate);
191
+ consumed += 1;
192
+ }
193
+ if (values.length === 0)
194
+ throw new Error(`${option} is required`);
195
+ return { values, consumed };
196
+ }
197
+ for (const candidate of options) {
198
+ const prefix = `${candidate}=`;
199
+ if (current?.startsWith(prefix)) {
200
+ return { values: [current.slice(prefix.length)], consumed: 0 };
201
+ }
202
+ }
203
+ return null;
204
+ }
205
+ function pluginWithOptionValue(argv, index) {
206
+ const current = argv[index];
207
+ if (current?.startsWith('--with=')) {
208
+ const value = current.slice('--with='.length);
209
+ if (!value)
210
+ throw new Error('--with is required');
211
+ return { values: value.split(','), consumed: 0 };
212
+ }
213
+ if (current !== '--with')
214
+ return null;
215
+ const values = [];
216
+ let consumed = 0;
217
+ while (index + consumed + 1 < argv.length) {
218
+ const candidate = argv[index + consumed + 1];
219
+ if (candidate === undefined ||
220
+ candidate === '--' ||
221
+ candidate.startsWith('-')) {
222
+ break;
223
+ }
224
+ const components = candidate.split(',').map((value) => value.trim());
225
+ if (components.length === 0 ||
226
+ components.some((component) => !PLUGIN_INIT_COMPONENTS.has(component))) {
227
+ break;
228
+ }
229
+ values.push(...components);
230
+ consumed += 1;
231
+ }
232
+ if (values.length === 0) {
233
+ throw new Error(`--with requires one or more components: ${[...PLUGIN_INIT_COMPONENTS].join(', ')}`);
234
+ }
235
+ return { values, consumed };
236
+ }
237
+ function splitList(values) {
238
+ return values.flatMap((value) => value
239
+ .split(',')
240
+ .map((item) => item.trim())
241
+ .filter((item) => item.length > 0));
242
+ }
243
+ function positiveInteger(value, label) {
244
+ if (!/^\d+$/.test(value))
245
+ throw new Error(`${label} must be a positive integer`);
246
+ const parsed = Number(value);
247
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
248
+ throw new Error(`${label} must be a positive integer`);
249
+ }
250
+ return parsed;
251
+ }
252
+ function parseMcpTransport(value) {
253
+ if (value === 'streamable-http')
254
+ return 'http';
255
+ if (MCP_TRANSPORTS.includes(value)) {
256
+ return value;
257
+ }
258
+ throw new Error(`Invalid transport type: ${value}. Must be one of: stdio, sse, http (or streamable-http)`);
259
+ }
260
+ export function parseCliInvocation(argv) {
261
+ const args = [];
262
+ let agent;
263
+ let background = false;
264
+ let print = false;
265
+ let agentsAll = false;
266
+ let agentsCwd;
267
+ let inputFormat = 'text';
268
+ let outputFormat = 'text';
269
+ let includePartialMessages = false;
270
+ let includeHookEvents = false;
271
+ let replayUserMessages = false;
272
+ let retryInterruptedTools = false;
273
+ let sessionId;
274
+ let resumeSelector;
275
+ let resumeSessionAt;
276
+ let fromPr;
277
+ let verbose = false;
278
+ let legacyJson = false;
279
+ let pluginAvailable = false;
280
+ let pluginKeepData = false;
281
+ let pluginPrune = false;
282
+ let pluginYes = false;
283
+ let pluginStrict = false;
284
+ const pluginConfig = [];
285
+ let pluginAuthor;
286
+ let pluginAuthorEmail;
287
+ let pluginDescription;
288
+ let pluginForce = false;
289
+ const pluginWith = [];
290
+ let pluginDryRun = false;
291
+ let pluginMessage;
292
+ let pluginPush = false;
293
+ let pluginRemote;
294
+ const pluginSparsePaths = [];
295
+ let autoModeLabel;
296
+ let optionsEnded = false;
297
+ let settings;
298
+ let maxTurns;
299
+ const betas = [];
300
+ let debug;
301
+ let debugFile;
302
+ let brief = false;
303
+ let axScreenReader = false;
304
+ const fileResources = [];
305
+ let agentDefinitions;
306
+ const mcpConfigs = [];
307
+ let strictMcpConfig = false;
308
+ let disableSlashCommands = false;
309
+ let settingSources;
310
+ let safeMode = false;
311
+ let bare = false;
312
+ let systemPrompt;
313
+ let systemPromptFile;
314
+ let appendSystemPrompt;
315
+ let appendSystemPromptFile;
316
+ let excludeDynamicSystemPromptSections = false;
317
+ const addDirectories = [];
318
+ const pluginDirectories = [];
319
+ const pluginUrls = [];
320
+ let tools;
321
+ const allowedTools = [];
322
+ const disallowedTools = [];
323
+ let permissionMode = 'default';
324
+ let permissionPromptTool;
325
+ let init = false;
326
+ let initOnly = false;
327
+ let maintenance = false;
328
+ let dangerouslySkipPermissions = false;
329
+ let allowDangerouslySkipPermissions = false;
330
+ let continueSession = false;
331
+ let forkSession = false;
332
+ let rewindFiles;
333
+ let name;
334
+ let sessionPersistence = true;
335
+ let worktreeName;
336
+ let worktreeRequested = false;
337
+ let tmux;
338
+ let model;
339
+ let effort;
340
+ let thinking;
341
+ let maxThinkingTokens;
342
+ let fallbackModels;
343
+ let jsonSchema;
344
+ let maxBudgetUsd;
345
+ let prefill;
346
+ let promptSuggestions = false;
347
+ let mcpScope;
348
+ let mcpTransport;
349
+ const mcpEnv = [];
350
+ const mcpHeaders = [];
351
+ let mcpCallbackPort;
352
+ let mcpClientId;
353
+ let mcpClientSecret = false;
354
+ let mcpNoBrowser = false;
355
+ let mcpDebug = false;
356
+ for (let index = 0; index < argv.length; index += 1) {
357
+ const value = argv[index];
358
+ if (value === undefined)
359
+ continue;
360
+ if (!optionsEnded && value === '--') {
361
+ optionsEnded = true;
362
+ continue;
363
+ }
364
+ if (optionsEnded || !value.startsWith('-') || value === '-') {
365
+ args.push(value);
366
+ continue;
367
+ }
368
+ const input = optionValue(argv, index, '--input-format');
369
+ if (input) {
370
+ inputFormat = choice(input.value, '--input-format', INPUT_FORMATS);
371
+ index += input.consumed;
372
+ continue;
373
+ }
374
+ const output = optionValue(argv, index, '--output-format');
375
+ if (output) {
376
+ outputFormat = choice(output.value, '--output-format', OUTPUT_FORMATS);
377
+ index += output.consumed;
378
+ continue;
379
+ }
380
+ const selectedAgent = optionValue(argv, index, '--agent');
381
+ if (selectedAgent) {
382
+ if (agent !== undefined)
383
+ throw new Error('--agent may only be specified once');
384
+ agent = selectedAgent.value;
385
+ index += selectedAgent.consumed;
386
+ continue;
387
+ }
388
+ const selectedModel = optionValue(argv, index, '--model');
389
+ if (selectedModel) {
390
+ if (model !== undefined)
391
+ throw new Error('--model may only be specified once');
392
+ model = selectedModel.value;
393
+ index += selectedModel.consumed;
394
+ continue;
395
+ }
396
+ const selectedEffort = optionValue(argv, index, '--effort');
397
+ if (selectedEffort) {
398
+ if (effort !== undefined)
399
+ throw new Error('--effort may only be specified once');
400
+ effort = choice(selectedEffort.value, '--effort', EFFORT_LEVELS);
401
+ index += selectedEffort.consumed;
402
+ continue;
403
+ }
404
+ const selectedThinking = optionValue(argv, index, '--thinking');
405
+ if (selectedThinking) {
406
+ if (thinking !== undefined)
407
+ throw new Error('--thinking may only be specified once');
408
+ thinking = choice(selectedThinking.value, '--thinking', THINKING_MODES);
409
+ index += selectedThinking.consumed;
410
+ continue;
411
+ }
412
+ const selectedThinkingTokens = optionValue(argv, index, '--max-thinking-tokens');
413
+ if (selectedThinkingTokens) {
414
+ if (maxThinkingTokens !== undefined) {
415
+ throw new Error('--max-thinking-tokens may only be specified once');
416
+ }
417
+ maxThinkingTokens = positiveInteger(selectedThinkingTokens.value, '--max-thinking-tokens');
418
+ index += selectedThinkingTokens.consumed;
419
+ continue;
420
+ }
421
+ const selectedFallback = optionValue(argv, index, '--fallback-model');
422
+ if (selectedFallback) {
423
+ if (fallbackModels !== undefined)
424
+ throw new Error('--fallback-model may only be specified once');
425
+ fallbackModels = splitList([selectedFallback.value]);
426
+ if (fallbackModels.length === 0)
427
+ throw new Error('--fallback-model requires at least one model');
428
+ index += selectedFallback.consumed;
429
+ continue;
430
+ }
431
+ const selectedSchema = optionValue(argv, index, '--json-schema');
432
+ if (selectedSchema) {
433
+ if (jsonSchema !== undefined)
434
+ throw new Error('--json-schema may only be specified once');
435
+ let parsed;
436
+ try {
437
+ parsed = JSON.parse(selectedSchema.value);
438
+ }
439
+ catch (error) {
440
+ throw new Error('--json-schema must be valid JSON', { cause: error });
441
+ }
442
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
443
+ throw new Error('--json-schema must be a JSON object');
444
+ }
445
+ jsonSchema = parsed;
446
+ index += selectedSchema.consumed;
447
+ continue;
448
+ }
449
+ const selectedBudget = optionValue(argv, index, '--max-budget-usd');
450
+ if (selectedBudget) {
451
+ if (maxBudgetUsd !== undefined)
452
+ throw new Error('--max-budget-usd may only be specified once');
453
+ maxBudgetUsd = positiveDecimal(selectedBudget.value, '--max-budget-usd');
454
+ index += selectedBudget.consumed;
455
+ continue;
456
+ }
457
+ if (value === '--prefill') {
458
+ const candidate = argv[index + 1];
459
+ if (candidate === undefined || candidate.startsWith('-')) {
460
+ throw new Error('--prefill is required');
461
+ }
462
+ prefill = candidate;
463
+ index += 1;
464
+ continue;
465
+ }
466
+ if (value.startsWith('--prefill=')) {
467
+ prefill = value.slice('--prefill='.length);
468
+ continue;
469
+ }
470
+ const selectedMcpScope = value === '-s'
471
+ ? { value: requiredValue(argv, index, '--scope'), consumed: 1 }
472
+ : value.startsWith('-s=')
473
+ ? { value: value.slice(3), consumed: 0 }
474
+ : optionValue(argv, index, '--scope');
475
+ if (selectedMcpScope) {
476
+ if (mcpScope !== undefined)
477
+ throw new Error('--scope may only be specified once');
478
+ mcpScope = choice(selectedMcpScope.value, '--scope', MCP_SCOPES);
479
+ index += selectedMcpScope.consumed;
480
+ continue;
481
+ }
482
+ const selectedMcpTransport = value === '-t'
483
+ ? { value: requiredValue(argv, index, '--transport'), consumed: 1 }
484
+ : optionValue(argv, index, '--transport');
485
+ if (selectedMcpTransport) {
486
+ if (mcpTransport !== undefined) {
487
+ throw new Error('--transport may only be specified once');
488
+ }
489
+ mcpTransport = parseMcpTransport(selectedMcpTransport.value);
490
+ index += selectedMcpTransport.consumed;
491
+ continue;
492
+ }
493
+ const selectedMcpEnv = listOptionValue(argv, index, ['-e', '--env']);
494
+ if (selectedMcpEnv) {
495
+ mcpEnv.push(...selectedMcpEnv.values);
496
+ index += selectedMcpEnv.consumed;
497
+ continue;
498
+ }
499
+ const selectedMcpHeaders = listOptionValue(argv, index, ['-H', '--header']);
500
+ if (selectedMcpHeaders) {
501
+ mcpHeaders.push(...selectedMcpHeaders.values);
502
+ index += selectedMcpHeaders.consumed;
503
+ continue;
504
+ }
505
+ const selectedMcpCallbackPort = value === '--callback-port' && /^-\d+$/u.test(argv[index + 1] ?? '')
506
+ ? { value: argv[index + 1], consumed: 1 }
507
+ : optionValue(argv, index, '--callback-port');
508
+ if (selectedMcpCallbackPort) {
509
+ if (mcpCallbackPort !== undefined) {
510
+ throw new Error('--callback-port may only be specified once');
511
+ }
512
+ mcpCallbackPort = selectedMcpCallbackPort.value;
513
+ index += selectedMcpCallbackPort.consumed;
514
+ continue;
515
+ }
516
+ const selectedMcpClientId = optionValue(argv, index, '--client-id');
517
+ if (selectedMcpClientId) {
518
+ if (mcpClientId !== undefined) {
519
+ throw new Error('--client-id may only be specified once');
520
+ }
521
+ mcpClientId = selectedMcpClientId.value;
522
+ index += selectedMcpClientId.consumed;
523
+ continue;
524
+ }
525
+ if (value === '--client-secret') {
526
+ mcpClientSecret = true;
527
+ continue;
528
+ }
529
+ const selectedCwd = optionValue(argv, index, '--cwd');
530
+ if (selectedCwd) {
531
+ if (agentsCwd !== undefined)
532
+ throw new Error('--cwd may only be specified once');
533
+ agentsCwd = selectedCwd.value;
534
+ index += selectedCwd.consumed;
535
+ continue;
536
+ }
537
+ const selectedSession = optionValue(argv, index, '--session-id');
538
+ if (selectedSession) {
539
+ if (sessionId !== undefined) {
540
+ throw new Error('--session-id may only be specified once');
541
+ }
542
+ sessionId = selectedSession.value;
543
+ index += selectedSession.consumed;
544
+ continue;
545
+ }
546
+ const selectedResumeAt = optionValue(argv, index, '--resume-session-at');
547
+ if (selectedResumeAt) {
548
+ if (resumeSessionAt !== undefined) {
549
+ throw new Error('--resume-session-at may only be specified once');
550
+ }
551
+ resumeSessionAt = selectedResumeAt.value;
552
+ index += selectedResumeAt.consumed;
553
+ continue;
554
+ }
555
+ const selectedSettings = optionValue(argv, index, '--settings');
556
+ if (selectedSettings) {
557
+ if (settings !== undefined)
558
+ throw new Error('--settings may only be specified once');
559
+ settings = selectedSettings.value;
560
+ index += selectedSettings.consumed;
561
+ continue;
562
+ }
563
+ const selectedPluginConfig = optionValue(argv, index, '--config');
564
+ if (selectedPluginConfig) {
565
+ pluginConfig.push(selectedPluginConfig.value);
566
+ index += selectedPluginConfig.consumed;
567
+ continue;
568
+ }
569
+ const selectedPluginAuthor = optionValue(argv, index, '--author');
570
+ if (selectedPluginAuthor) {
571
+ if (pluginAuthor !== undefined)
572
+ throw new Error('--author may only be specified once');
573
+ pluginAuthor = selectedPluginAuthor.value;
574
+ index += selectedPluginAuthor.consumed;
575
+ continue;
576
+ }
577
+ const selectedPluginAuthorEmail = optionValue(argv, index, '--author-email');
578
+ if (selectedPluginAuthorEmail) {
579
+ if (pluginAuthorEmail !== undefined)
580
+ throw new Error('--author-email may only be specified once');
581
+ pluginAuthorEmail = selectedPluginAuthorEmail.value;
582
+ index += selectedPluginAuthorEmail.consumed;
583
+ continue;
584
+ }
585
+ const selectedPluginDescription = optionValue(argv, index, '--description');
586
+ if (selectedPluginDescription) {
587
+ if (pluginDescription !== undefined)
588
+ throw new Error('--description may only be specified once');
589
+ pluginDescription = selectedPluginDescription.value;
590
+ index += selectedPluginDescription.consumed;
591
+ continue;
592
+ }
593
+ const selectedPluginWith = pluginWithOptionValue(argv, index);
594
+ if (selectedPluginWith) {
595
+ pluginWith.push(...selectedPluginWith.values);
596
+ index += selectedPluginWith.consumed;
597
+ continue;
598
+ }
599
+ const selectedPluginMessage = value === '-m'
600
+ ? { value: requiredValue(argv, index, '--message'), consumed: 1 }
601
+ : value.startsWith('-m=')
602
+ ? { value: value.slice(3), consumed: 0 }
603
+ : optionValue(argv, index, '--message');
604
+ if (selectedPluginMessage) {
605
+ if (pluginMessage !== undefined)
606
+ throw new Error('--message may only be specified once');
607
+ pluginMessage = selectedPluginMessage.value;
608
+ index += selectedPluginMessage.consumed;
609
+ continue;
610
+ }
611
+ const selectedPluginRemote = optionValue(argv, index, '--remote');
612
+ if (selectedPluginRemote) {
613
+ if (pluginRemote !== undefined)
614
+ throw new Error('--remote may only be specified once');
615
+ pluginRemote = selectedPluginRemote.value;
616
+ index += selectedPluginRemote.consumed;
617
+ continue;
618
+ }
619
+ const selectedPluginSparse = listOptionValue(argv, index, ['--sparse']);
620
+ if (selectedPluginSparse) {
621
+ if (pluginSparsePaths.length > 0)
622
+ throw new Error('--sparse may only be specified once');
623
+ pluginSparsePaths.push(...selectedPluginSparse.values);
624
+ index += selectedPluginSparse.consumed;
625
+ continue;
626
+ }
627
+ const selectedAutoModeLabel = optionValue(argv, index, '--label');
628
+ if (selectedAutoModeLabel) {
629
+ if (autoModeLabel !== undefined)
630
+ throw new Error('--label may only be specified once');
631
+ autoModeLabel = selectedAutoModeLabel.value;
632
+ index += selectedAutoModeLabel.consumed;
633
+ continue;
634
+ }
635
+ const selectedMaxTurns = optionValue(argv, index, '--max-turns');
636
+ if (selectedMaxTurns) {
637
+ if (maxTurns !== undefined)
638
+ throw new Error('--max-turns may only be specified once');
639
+ maxTurns = positiveInteger(selectedMaxTurns.value, '--max-turns');
640
+ index += selectedMaxTurns.consumed;
641
+ continue;
642
+ }
643
+ const selectedBetas = listOptionValue(argv, index, ['--betas']);
644
+ if (selectedBetas) {
645
+ betas.push(...splitList(selectedBetas.values));
646
+ index += selectedBetas.consumed;
647
+ continue;
648
+ }
649
+ const mcpServe = args[0] === 'mcp' && args[1] === 'serve';
650
+ if (mcpServe && (value === '-d' || value === '--debug')) {
651
+ debug = true;
652
+ mcpDebug = true;
653
+ continue;
654
+ }
655
+ if (args[0] === 'mcp' &&
656
+ (value.startsWith('-d') || value.startsWith('--debug'))) {
657
+ throw new Error(`Unknown option: ${value}`);
658
+ }
659
+ const selectedDebug = optionalValue(argv, index, '--debug');
660
+ if (selectedDebug) {
661
+ debug = selectedDebug.value || true;
662
+ index += selectedDebug.consumed;
663
+ continue;
664
+ }
665
+ if (value === '-d' || value.startsWith('-d')) {
666
+ if (value.length > 2) {
667
+ debug = value.slice(2);
668
+ }
669
+ else {
670
+ const candidate = argv[index + 1];
671
+ if (candidate !== undefined &&
672
+ candidate !== '--' &&
673
+ !candidate.startsWith('-')) {
674
+ debug = candidate;
675
+ index += 1;
676
+ }
677
+ else {
678
+ debug = true;
679
+ }
680
+ }
681
+ continue;
682
+ }
683
+ const selectedDebugFile = optionValue(argv, index, '--debug-file');
684
+ if (selectedDebugFile) {
685
+ if (debugFile !== undefined)
686
+ throw new Error('--debug-file may only be specified once');
687
+ debugFile = selectedDebugFile.value;
688
+ index += selectedDebugFile.consumed;
689
+ continue;
690
+ }
691
+ if (value === '--mcp-debug') {
692
+ mcpDebug = true;
693
+ continue;
694
+ }
695
+ if (value === '--brief') {
696
+ brief = true;
697
+ continue;
698
+ }
699
+ if (value === '--ax-screen-reader') {
700
+ axScreenReader = true;
701
+ continue;
702
+ }
703
+ const selectedFileResources = listOptionValue(argv, index, ['--file']);
704
+ if (selectedFileResources) {
705
+ fileResources.push(...selectedFileResources.values);
706
+ index += selectedFileResources.consumed;
707
+ continue;
708
+ }
709
+ const selectedAgents = optionValue(argv, index, '--agents');
710
+ if (selectedAgents) {
711
+ if (agentDefinitions !== undefined)
712
+ throw new Error('--agents may only be specified once');
713
+ agentDefinitions = selectedAgents.value;
714
+ index += selectedAgents.consumed;
715
+ continue;
716
+ }
717
+ const selectedMcpConfigs = listOptionValue(argv, index, ['--mcp-config']);
718
+ if (selectedMcpConfigs) {
719
+ mcpConfigs.push(...selectedMcpConfigs.values);
720
+ index += selectedMcpConfigs.consumed;
721
+ continue;
722
+ }
723
+ const selectedSources = value === '--setting-sources='
724
+ ? { value: '', consumed: 0 }
725
+ : optionValue(argv, index, '--setting-sources');
726
+ if (selectedSources) {
727
+ if (settingSources !== undefined)
728
+ throw new Error('--setting-sources may only be specified once');
729
+ const sources = splitList([selectedSources.value]);
730
+ for (const source of sources) {
731
+ if (!SETTING_SOURCES.includes(source)) {
732
+ throw new Error(`Invalid setting source: ${source}`);
733
+ }
734
+ }
735
+ settingSources = sources;
736
+ index += selectedSources.consumed;
737
+ continue;
738
+ }
739
+ const selectedSystemPrompt = optionValue(argv, index, '--system-prompt');
740
+ if (selectedSystemPrompt) {
741
+ if (systemPrompt !== undefined)
742
+ throw new Error('--system-prompt may only be specified once');
743
+ systemPrompt = selectedSystemPrompt.value;
744
+ index += selectedSystemPrompt.consumed;
745
+ continue;
746
+ }
747
+ if (value === '--exclude-dynamic-system-prompt-sections') {
748
+ excludeDynamicSystemPromptSections = true;
749
+ continue;
750
+ }
751
+ const selectedSystemPromptFile = optionValue(argv, index, '--system-prompt-file');
752
+ if (selectedSystemPromptFile) {
753
+ if (systemPromptFile !== undefined)
754
+ throw new Error('--system-prompt-file may only be specified once');
755
+ systemPromptFile = selectedSystemPromptFile.value;
756
+ index += selectedSystemPromptFile.consumed;
757
+ continue;
758
+ }
759
+ const selectedAppendPrompt = optionValue(argv, index, '--append-system-prompt');
760
+ if (selectedAppendPrompt) {
761
+ if (appendSystemPrompt !== undefined)
762
+ throw new Error('--append-system-prompt may only be specified once');
763
+ appendSystemPrompt = selectedAppendPrompt.value;
764
+ index += selectedAppendPrompt.consumed;
765
+ continue;
766
+ }
767
+ const selectedAppendPromptFile = optionValue(argv, index, '--append-system-prompt-file');
768
+ if (selectedAppendPromptFile) {
769
+ if (appendSystemPromptFile !== undefined) {
770
+ throw new Error('--append-system-prompt-file may only be specified once');
771
+ }
772
+ appendSystemPromptFile = selectedAppendPromptFile.value;
773
+ index += selectedAppendPromptFile.consumed;
774
+ continue;
775
+ }
776
+ const selectedDirectories = listOptionValue(argv, index, ['--add-dir']);
777
+ if (selectedDirectories) {
778
+ addDirectories.push(...splitList(selectedDirectories.values));
779
+ index += selectedDirectories.consumed;
780
+ continue;
781
+ }
782
+ const selectedPluginDirectory = optionValue(argv, index, '--plugin-dir');
783
+ if (selectedPluginDirectory) {
784
+ pluginDirectories.push(selectedPluginDirectory.value);
785
+ index += selectedPluginDirectory.consumed;
786
+ continue;
787
+ }
788
+ const selectedPluginUrl = optionValue(argv, index, '--plugin-url');
789
+ if (selectedPluginUrl) {
790
+ pluginUrls.push(selectedPluginUrl.value);
791
+ index += selectedPluginUrl.consumed;
792
+ continue;
793
+ }
794
+ const selectedTools = listOptionValue(argv, index, ['--tools']);
795
+ if (selectedTools) {
796
+ if (tools !== undefined)
797
+ throw new Error('--tools may only be specified once');
798
+ tools = splitList(selectedTools.values);
799
+ index += selectedTools.consumed;
800
+ continue;
801
+ }
802
+ const selectedAllowedTools = listOptionValue(argv, index, [
803
+ '--allowedTools',
804
+ '--allowed-tools',
805
+ ]);
806
+ if (selectedAllowedTools) {
807
+ allowedTools.push(...splitList(selectedAllowedTools.values));
808
+ index += selectedAllowedTools.consumed;
809
+ continue;
810
+ }
811
+ const selectedDisallowedTools = listOptionValue(argv, index, [
812
+ '--disallowedTools',
813
+ '--disallowed-tools',
814
+ ]);
815
+ if (selectedDisallowedTools) {
816
+ disallowedTools.push(...splitList(selectedDisallowedTools.values));
817
+ index += selectedDisallowedTools.consumed;
818
+ continue;
819
+ }
820
+ const selectedPermissionMode = optionValue(argv, index, '--permission-mode');
821
+ if (selectedPermissionMode) {
822
+ permissionMode = choice(selectedPermissionMode.value, '--permission-mode', PERMISSION_MODES);
823
+ index += selectedPermissionMode.consumed;
824
+ continue;
825
+ }
826
+ if ((value === '--permission-prompt-tool' &&
827
+ (argv[index + 1] === undefined || argv[index + 1]?.startsWith('-'))) ||
828
+ value === '--permission-prompt-tool=') {
829
+ throw new Error("option '--permission-prompt-tool <tool>' argument missing");
830
+ }
831
+ const selectedPermissionPromptTool = optionValue(argv, index, '--permission-prompt-tool');
832
+ if (selectedPermissionPromptTool) {
833
+ permissionPromptTool = selectedPermissionPromptTool.value;
834
+ index += selectedPermissionPromptTool.consumed;
835
+ continue;
836
+ }
837
+ const selectedName = optionValue(argv, index, '--name');
838
+ if (selectedName || value === '-n') {
839
+ if (name !== undefined)
840
+ throw new Error('--name may only be specified once');
841
+ name = selectedName?.value ?? requiredValue(argv, index, '--name');
842
+ index += selectedName?.consumed ?? 1;
843
+ continue;
844
+ }
845
+ if (value === '--worktree' || value === '-w') {
846
+ worktreeRequested = true;
847
+ const candidate = argv[index + 1];
848
+ if (candidate !== undefined &&
849
+ candidate !== '--' &&
850
+ !candidate.startsWith('-')) {
851
+ worktreeName = candidate;
852
+ index += 1;
853
+ }
854
+ continue;
855
+ }
856
+ if (value.startsWith('--worktree=')) {
857
+ worktreeRequested = true;
858
+ worktreeName = value.slice('--worktree='.length);
859
+ if (!worktreeName)
860
+ throw new Error('--worktree name must not be empty');
861
+ continue;
862
+ }
863
+ if (value === '--tmux' || value === '--tmux=classic') {
864
+ if (tmux !== undefined)
865
+ throw new Error('--tmux may only be specified once');
866
+ tmux = value === '--tmux' ? 'native' : 'classic';
867
+ continue;
868
+ }
869
+ if (value.startsWith('--tmux='))
870
+ throw new Error('--tmux must be classic');
871
+ if (value === '-r' || value === '--resume') {
872
+ if (resumeSelector !== undefined)
873
+ throw new Error('--resume may only be specified once');
874
+ const candidate = argv[index + 1];
875
+ if (candidate !== undefined &&
876
+ candidate !== '--' &&
877
+ !candidate.startsWith('-')) {
878
+ resumeSelector = candidate;
879
+ index += 1;
880
+ }
881
+ else {
882
+ resumeSelector = true;
883
+ }
884
+ continue;
885
+ }
886
+ if (value.startsWith('--resume=')) {
887
+ if (resumeSelector !== undefined)
888
+ throw new Error('--resume may only be specified once');
889
+ resumeSelector = value.slice('--resume='.length) || true;
890
+ continue;
891
+ }
892
+ if (value.startsWith('-r') && value.length > 2) {
893
+ if (resumeSelector !== undefined)
894
+ throw new Error('--resume may only be specified once');
895
+ resumeSelector = value.slice(2);
896
+ continue;
897
+ }
898
+ const selectedRewindFiles = optionValue(argv, index, '--rewind-files');
899
+ if (selectedRewindFiles) {
900
+ if (rewindFiles !== undefined)
901
+ throw new Error('--rewind-files may only be specified once');
902
+ rewindFiles = selectedRewindFiles.value;
903
+ index += selectedRewindFiles.consumed;
904
+ continue;
905
+ }
906
+ if (value === '--from-pr') {
907
+ if (fromPr !== undefined)
908
+ throw new Error('--from-pr may only be specified once');
909
+ const candidate = argv[index + 1];
910
+ if (candidate !== undefined &&
911
+ candidate !== '--' &&
912
+ !candidate.startsWith('-')) {
913
+ fromPr = candidate;
914
+ index += 1;
915
+ }
916
+ else {
917
+ fromPr = true;
918
+ }
919
+ continue;
920
+ }
921
+ if (value.startsWith('--from-pr=')) {
922
+ if (fromPr !== undefined)
923
+ throw new Error('--from-pr may only be specified once');
924
+ const candidate = value.slice('--from-pr='.length);
925
+ if (!candidate)
926
+ throw new Error('--from-pr value must not be empty');
927
+ fromPr = candidate;
928
+ continue;
929
+ }
930
+ if (value === '-p' || value === '--print') {
931
+ print = true;
932
+ continue;
933
+ }
934
+ if (value === '--bg' || value === '--background') {
935
+ background = true;
936
+ continue;
937
+ }
938
+ if (value === '--all' || value === '-a') {
939
+ agentsAll = true;
940
+ continue;
941
+ }
942
+ if (value === '--available') {
943
+ pluginAvailable = true;
944
+ continue;
945
+ }
946
+ if (value === '--keep-data') {
947
+ pluginKeepData = true;
948
+ continue;
949
+ }
950
+ if (value === '--prune') {
951
+ pluginPrune = true;
952
+ continue;
953
+ }
954
+ if (value === '-y' || value === '--yes') {
955
+ pluginYes = true;
956
+ continue;
957
+ }
958
+ if (value === '--strict') {
959
+ pluginStrict = true;
960
+ continue;
961
+ }
962
+ if (value === '-f' || value === '--force') {
963
+ pluginForce = true;
964
+ continue;
965
+ }
966
+ if (value === '--dry-run') {
967
+ pluginDryRun = true;
968
+ continue;
969
+ }
970
+ if (value === '--push') {
971
+ pluginPush = true;
972
+ continue;
973
+ }
974
+ if (value === '-c' || value === '--continue') {
975
+ continueSession = true;
976
+ continue;
977
+ }
978
+ if (value === '--fork-session') {
979
+ forkSession = true;
980
+ continue;
981
+ }
982
+ if (value === '--no-session-persistence') {
983
+ sessionPersistence = false;
984
+ continue;
985
+ }
986
+ if (value === '--safe-mode') {
987
+ safeMode = true;
988
+ continue;
989
+ }
990
+ if (value === '--bare') {
991
+ bare = true;
992
+ continue;
993
+ }
994
+ if (value === '--init') {
995
+ init = true;
996
+ continue;
997
+ }
998
+ if (value === '--init-only') {
999
+ initOnly = true;
1000
+ continue;
1001
+ }
1002
+ if (value === '--maintenance') {
1003
+ maintenance = true;
1004
+ continue;
1005
+ }
1006
+ if (value === '--strict-mcp-config') {
1007
+ strictMcpConfig = true;
1008
+ continue;
1009
+ }
1010
+ if (value === '--disable-slash-commands') {
1011
+ disableSlashCommands = true;
1012
+ continue;
1013
+ }
1014
+ if (value === '--dangerously-skip-permissions') {
1015
+ dangerouslySkipPermissions = true;
1016
+ continue;
1017
+ }
1018
+ if (value === '--allow-dangerously-skip-permissions') {
1019
+ allowDangerouslySkipPermissions = true;
1020
+ continue;
1021
+ }
1022
+ if (value === '--verbose') {
1023
+ verbose = true;
1024
+ continue;
1025
+ }
1026
+ if (value === '--no-browser') {
1027
+ mcpNoBrowser = true;
1028
+ continue;
1029
+ }
1030
+ if (value === '--json') {
1031
+ legacyJson = true;
1032
+ continue;
1033
+ }
1034
+ if (value === '--include-partial-messages') {
1035
+ includePartialMessages = true;
1036
+ continue;
1037
+ }
1038
+ if (value === '--include-hook-events') {
1039
+ includeHookEvents = true;
1040
+ continue;
1041
+ }
1042
+ if (value === '--replay-user-messages') {
1043
+ replayUserMessages = true;
1044
+ continue;
1045
+ }
1046
+ if (value === '--retry-interrupted-tools') {
1047
+ retryInterruptedTools = true;
1048
+ continue;
1049
+ }
1050
+ if (args[0] === 'mcp' && value.startsWith('--prompt-suggestions')) {
1051
+ throw new Error(`Unknown option: ${value}`);
1052
+ }
1053
+ const selectedPromptSuggestions = optionalValue(argv, index, '--prompt-suggestions');
1054
+ if (selectedPromptSuggestions) {
1055
+ if (selectedPromptSuggestions.value === true) {
1056
+ promptSuggestions = true;
1057
+ continue;
1058
+ }
1059
+ const raw = selectedPromptSuggestions.value.trim().toLowerCase();
1060
+ if (!['true', 'false', '1', '0', 'yes', 'no', 'on', 'off'].includes(raw)) {
1061
+ throw new Error(`option '--prompt-suggestions [value]' argument '${selectedPromptSuggestions.value}' is invalid. Allowed choices are true, false, 1, 0, yes, no, on, off.`);
1062
+ }
1063
+ promptSuggestions = ['true', '1', 'yes', 'on'].includes(raw);
1064
+ index += selectedPromptSuggestions.consumed;
1065
+ continue;
1066
+ }
1067
+ throw new Error(`Unknown option: ${value}`);
1068
+ }
1069
+ if (legacyJson) {
1070
+ if (outputFormat !== 'text') {
1071
+ throw new Error('--json cannot be combined with --output-format');
1072
+ }
1073
+ outputFormat = 'stream-json';
1074
+ }
1075
+ if (thinking === 'disabled' && maxThinkingTokens !== undefined) {
1076
+ throw new Error('--max-thinking-tokens cannot be combined with --thinking=disabled');
1077
+ }
1078
+ if (debug !== undefined && args[0] === 'mcp' && args[1] === 'serve') {
1079
+ mcpDebug = true;
1080
+ }
1081
+ if (background && print) {
1082
+ throw new Error("--bg and --print conflict: --print never starts the interactive session that `claude agents` attaches to, so the job would be unattachable. The prompt is the positional — drop --print: `claude --bg '<task>'`.");
1083
+ }
1084
+ if (inputFormat === 'stream-json' && outputFormat !== 'stream-json') {
1085
+ throw new Error('--input-format=stream-json requires --output-format=stream-json');
1086
+ }
1087
+ if (inputFormat === 'stream-json' && legacyJson) {
1088
+ throw new Error('--input-format=stream-json cannot be combined with --json');
1089
+ }
1090
+ if (outputFormat === 'stream-json' && !verbose && !legacyJson) {
1091
+ throw new Error('--output-format=stream-json requires --verbose');
1092
+ }
1093
+ if (includePartialMessages && outputFormat !== 'stream-json') {
1094
+ throw new Error('--include-partial-messages requires --output-format=stream-json');
1095
+ }
1096
+ if (includePartialMessages && legacyJson) {
1097
+ throw new Error('--include-partial-messages cannot be combined with --json');
1098
+ }
1099
+ if (includeHookEvents && outputFormat !== 'stream-json') {
1100
+ throw new Error('--include-hook-events requires --output-format=stream-json');
1101
+ }
1102
+ if (includeHookEvents && legacyJson) {
1103
+ throw new Error('--include-hook-events cannot be combined with --json');
1104
+ }
1105
+ const managementCommand = [
1106
+ 'fork',
1107
+ 'sessions',
1108
+ 'inspect',
1109
+ 'export',
1110
+ 'agents',
1111
+ 'attach',
1112
+ 'logs',
1113
+ 'stop',
1114
+ 'mcp',
1115
+ 'auto-mode',
1116
+ 'plugin',
1117
+ 'doctor',
1118
+ ].includes(args[0] ?? '');
1119
+ if (promptSuggestions &&
1120
+ !managementCommand &&
1121
+ (!print || outputFormat !== 'stream-json')) {
1122
+ throw new Error('--prompt-suggestions requires --print and --output-format=stream-json');
1123
+ }
1124
+ if (maxTurns !== undefined && !print) {
1125
+ throw new Error('--max-turns requires --print');
1126
+ }
1127
+ if (replayUserMessages &&
1128
+ (inputFormat !== 'stream-json' || outputFormat !== 'stream-json')) {
1129
+ throw new Error('--replay-user-messages requires stream-json input and output');
1130
+ }
1131
+ if (systemPrompt !== undefined && systemPromptFile !== undefined) {
1132
+ throw new Error('Cannot use both --system-prompt and --system-prompt-file');
1133
+ }
1134
+ if (appendSystemPrompt !== undefined &&
1135
+ appendSystemPromptFile !== undefined) {
1136
+ throw new Error('Cannot use both --append-system-prompt and --append-system-prompt-file');
1137
+ }
1138
+ if (tmux !== undefined && !worktreeRequested) {
1139
+ throw new Error('--tmux requires --worktree');
1140
+ }
1141
+ if (resumeSessionAt !== undefined && typeof resumeSelector !== 'string') {
1142
+ throw new Error('--resume-session-at requires an explicit --resume selector');
1143
+ }
1144
+ if (resumeSelector !== undefined) {
1145
+ if (args[0] === 'resume')
1146
+ throw new Error('resume command cannot be combined with --resume');
1147
+ args.unshift('resume', ...(typeof resumeSelector === 'string' ? [resumeSelector] : []));
1148
+ }
1149
+ if (fromPr !== undefined &&
1150
+ (args[0] === 'resume' || resumeSelector !== undefined || continueSession)) {
1151
+ throw new Error('--from-pr cannot be combined with --resume or --continue');
1152
+ }
1153
+ if (sessionId !== undefined && !UUID_PATTERN.test(sessionId)) {
1154
+ throw new Error('--session-id must be a valid UUID');
1155
+ }
1156
+ const resumesSession = args[0] === 'resume' || continueSession || fromPr !== undefined;
1157
+ if (resumeSelector !== undefined && continueSession) {
1158
+ throw new Error('--resume cannot be combined with --continue');
1159
+ }
1160
+ if (rewindFiles !== undefined &&
1161
+ (args[0] !== 'resume' || args[1] === undefined)) {
1162
+ throw new Error('--rewind-files requires --resume with an explicit selector');
1163
+ }
1164
+ if (sessionId !== undefined && resumesSession && !forkSession) {
1165
+ throw new Error('--session-id can only be used with --continue, --resume, or --from-pr if --fork-session is also specified');
1166
+ }
1167
+ if (sessionId !== undefined &&
1168
+ [
1169
+ 'fork',
1170
+ 'sessions',
1171
+ 'inspect',
1172
+ 'export',
1173
+ 'agents',
1174
+ 'attach',
1175
+ 'logs',
1176
+ 'stop',
1177
+ ].includes(args[0] ?? '')) {
1178
+ throw new Error('--session-id is only valid when starting a session');
1179
+ }
1180
+ const pluginDisableAll = agentsAll &&
1181
+ ['plugin', 'plugins'].includes(args[0] ?? '') &&
1182
+ args[1] === 'disable';
1183
+ if ((pluginAvailable ||
1184
+ pluginKeepData ||
1185
+ pluginPrune ||
1186
+ pluginYes ||
1187
+ pluginStrict ||
1188
+ pluginConfig.length > 0 ||
1189
+ pluginAuthor !== undefined ||
1190
+ pluginAuthorEmail !== undefined ||
1191
+ pluginDescription !== undefined ||
1192
+ pluginForce ||
1193
+ pluginWith.length > 0 ||
1194
+ pluginDryRun ||
1195
+ pluginMessage !== undefined ||
1196
+ pluginPush ||
1197
+ pluginRemote !== undefined ||
1198
+ pluginSparsePaths.length > 0) &&
1199
+ !['plugin', 'plugins'].includes(args[0] ?? '')) {
1200
+ throw new Error('Plugin options are only valid with plugin commands');
1201
+ }
1202
+ return {
1203
+ command: args[0],
1204
+ args,
1205
+ agent,
1206
+ background,
1207
+ print,
1208
+ agentsAll: pluginDisableAll ? false : agentsAll,
1209
+ agentsCwd,
1210
+ inputFormat,
1211
+ outputFormat,
1212
+ includePartialMessages,
1213
+ includeHookEvents,
1214
+ replayUserMessages,
1215
+ retryInterruptedTools,
1216
+ sessionId,
1217
+ resumeSelector,
1218
+ fromPr,
1219
+ verbose,
1220
+ legacyJson,
1221
+ pluginAvailable,
1222
+ pluginAll: pluginDisableAll,
1223
+ pluginKeepData,
1224
+ pluginPrune,
1225
+ pluginYes,
1226
+ pluginStrict,
1227
+ pluginConfig,
1228
+ ...(pluginAuthor === undefined ? {} : { pluginAuthor }),
1229
+ ...(pluginAuthorEmail === undefined ? {} : { pluginAuthorEmail }),
1230
+ ...(pluginDescription === undefined ? {} : { pluginDescription }),
1231
+ pluginForce,
1232
+ pluginWith,
1233
+ pluginDryRun,
1234
+ ...(pluginMessage === undefined ? {} : { pluginMessage }),
1235
+ pluginPush,
1236
+ ...(pluginRemote === undefined ? {} : { pluginRemote }),
1237
+ pluginSparsePaths,
1238
+ ...(autoModeLabel === undefined ? {} : { autoModeLabel }),
1239
+ settings,
1240
+ ...(agentDefinitions === undefined ? {} : { agentDefinitions }),
1241
+ mcpConfigs,
1242
+ strictMcpConfig,
1243
+ disableSlashCommands,
1244
+ settingSources,
1245
+ safeMode,
1246
+ bare,
1247
+ systemPrompt,
1248
+ systemPromptFile,
1249
+ appendSystemPrompt,
1250
+ appendSystemPromptFile,
1251
+ excludeDynamicSystemPromptSections,
1252
+ addDirectories,
1253
+ pluginDirectories,
1254
+ pluginUrls,
1255
+ ...(maxTurns === undefined ? {} : { maxTurns }),
1256
+ betas,
1257
+ ...(debug === undefined ? {} : { debug }),
1258
+ ...(debugFile === undefined ? {} : { debugFile }),
1259
+ ...(brief ? { brief: true } : {}),
1260
+ ...(axScreenReader ? { axScreenReader: true } : {}),
1261
+ fileResources,
1262
+ tools,
1263
+ allowedTools,
1264
+ disallowedTools,
1265
+ permissionMode,
1266
+ ...(permissionPromptTool === undefined ? {} : { permissionPromptTool }),
1267
+ init,
1268
+ initOnly,
1269
+ maintenance,
1270
+ dangerouslySkipPermissions,
1271
+ allowDangerouslySkipPermissions,
1272
+ continueSession,
1273
+ forkSession,
1274
+ resumeSessionAt,
1275
+ ...(rewindFiles === undefined ? {} : { rewindFiles }),
1276
+ name,
1277
+ sessionPersistence,
1278
+ ...(worktreeName === undefined ? {} : { worktreeName }),
1279
+ ...(worktreeRequested ? { worktreeRequested: true } : {}),
1280
+ ...(tmux === undefined ? {} : { tmux }),
1281
+ ...(model === undefined ? {} : { model }),
1282
+ ...(effort === undefined ? {} : { effort }),
1283
+ ...(thinking === undefined ? {} : { thinking }),
1284
+ ...(maxThinkingTokens === undefined ? {} : { maxThinkingTokens }),
1285
+ ...(fallbackModels === undefined ? {} : { fallbackModels }),
1286
+ ...(jsonSchema === undefined ? {} : { jsonSchema }),
1287
+ ...(maxBudgetUsd === undefined ? {} : { maxBudgetUsd }),
1288
+ prefill,
1289
+ promptSuggestions,
1290
+ ...(mcpScope === undefined ? {} : { mcpScope }),
1291
+ ...(mcpTransport === undefined ? {} : { mcpTransport }),
1292
+ mcpEnv,
1293
+ mcpHeaders,
1294
+ ...(mcpCallbackPort === undefined ? {} : { mcpCallbackPort }),
1295
+ ...(mcpClientId === undefined ? {} : { mcpClientId }),
1296
+ mcpClientSecret,
1297
+ mcpNoBrowser,
1298
+ mcpDebug,
1299
+ };
1300
+ }
1301
+ function parseUserMessage(value, lineNumber) {
1302
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1303
+ throw new Error(`stream-json input line ${lineNumber} must be an object`);
1304
+ }
1305
+ const record = value;
1306
+ if (record.type !== 'user') {
1307
+ throw new Error(`stream-json input line ${lineNumber} must have type user`);
1308
+ }
1309
+ if (!record.message ||
1310
+ typeof record.message !== 'object' ||
1311
+ Array.isArray(record.message)) {
1312
+ throw new Error(`stream-json input line ${lineNumber} requires a message object`);
1313
+ }
1314
+ const message = record.message;
1315
+ if (message.role !== 'user') {
1316
+ throw new Error(`stream-json input line ${lineNumber} message role must be user`);
1317
+ }
1318
+ const content = message.content;
1319
+ if (typeof content === 'string') {
1320
+ if (content.trim().length === 0) {
1321
+ throw new Error(`stream-json input line ${lineNumber} has empty user content`);
1322
+ }
1323
+ return { message: { role: 'user', content }, prompt: content };
1324
+ }
1325
+ if (!Array.isArray(content) || content.length === 0) {
1326
+ throw new Error(`stream-json input line ${lineNumber} requires text content`);
1327
+ }
1328
+ const images = [];
1329
+ const documents = [];
1330
+ const blocks = content.map((block) => {
1331
+ if (!block ||
1332
+ typeof block !== 'object' ||
1333
+ Array.isArray(block) ||
1334
+ typeof block.type !== 'string') {
1335
+ throw new Error(`stream-json input line ${lineNumber} contains unsupported content`);
1336
+ }
1337
+ const record = block;
1338
+ if (record.type === 'text' && typeof record.text === 'string') {
1339
+ return { type: 'text', text: record.text };
1340
+ }
1341
+ const source = record.source;
1342
+ if (record.type === 'image' &&
1343
+ source &&
1344
+ typeof source === 'object' &&
1345
+ !Array.isArray(source) &&
1346
+ source.type === 'base64' &&
1347
+ typeof source.media_type === 'string' &&
1348
+ IMAGE_MEDIA_TYPES.has(source.media_type) &&
1349
+ typeof source.data === 'string' &&
1350
+ isBase64Data(source.data)) {
1351
+ const image = {
1352
+ type: 'image',
1353
+ mediaType: source
1354
+ .media_type,
1355
+ data: source.data,
1356
+ };
1357
+ images.push(image);
1358
+ return {
1359
+ type: 'image',
1360
+ source: {
1361
+ type: 'base64',
1362
+ media_type: image.mediaType,
1363
+ data: image.data,
1364
+ },
1365
+ };
1366
+ }
1367
+ if (record.type === 'document' &&
1368
+ source &&
1369
+ typeof source === 'object' &&
1370
+ !Array.isArray(source) &&
1371
+ source.type === 'base64' &&
1372
+ typeof source.media_type === 'string' &&
1373
+ DOCUMENT_MEDIA_TYPES.has(source
1374
+ .media_type) &&
1375
+ typeof source.data === 'string' &&
1376
+ isBase64Data(source.data)) {
1377
+ const document = {
1378
+ type: 'document',
1379
+ mediaType: source
1380
+ .media_type,
1381
+ data: source.data,
1382
+ };
1383
+ documents.push(document);
1384
+ return {
1385
+ type: 'document',
1386
+ source: {
1387
+ type: 'base64',
1388
+ media_type: document.mediaType,
1389
+ data: document.data,
1390
+ },
1391
+ };
1392
+ }
1393
+ throw new Error(`stream-json input line ${lineNumber} contains unsupported content`);
1394
+ });
1395
+ const prompt = blocks
1396
+ .filter((block) => block.type === 'text')
1397
+ .map((block) => block.text)
1398
+ .join('');
1399
+ if (prompt.trim().length === 0 &&
1400
+ images.length === 0 &&
1401
+ documents.length === 0) {
1402
+ throw new Error(`stream-json input line ${lineNumber} has empty user content`);
1403
+ }
1404
+ return {
1405
+ message: { role: 'user', content: blocks },
1406
+ prompt,
1407
+ ...(images.length > 0 ? { images } : {}),
1408
+ ...(documents.length > 0 ? { documents } : {}),
1409
+ };
1410
+ }
1411
+ function parseStreamJsonMessage(value, lineNumber) {
1412
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1413
+ throw new Error(`stream-json input line ${lineNumber} must be an object`);
1414
+ }
1415
+ const record = value;
1416
+ if (record.type === 'user')
1417
+ return parseUserMessage(value, lineNumber);
1418
+ if (record.type === 'control_cancel_request') {
1419
+ if (typeof record.request_id !== 'string' ||
1420
+ record.request_id.length === 0) {
1421
+ throw new Error(`stream-json input line ${lineNumber} has invalid request_id`);
1422
+ }
1423
+ return { type: 'control_cancel_request', request_id: record.request_id };
1424
+ }
1425
+ if (record.type === 'control_request') {
1426
+ const request = record.request;
1427
+ if (typeof record.request_id !== 'string' ||
1428
+ record.request_id.length === 0 ||
1429
+ !request ||
1430
+ typeof request !== 'object' ||
1431
+ Array.isArray(request) ||
1432
+ request.subtype !== 'interrupt') {
1433
+ throw new Error(`stream-json input line ${lineNumber} has invalid interrupt request`);
1434
+ }
1435
+ return {
1436
+ type: 'control_request',
1437
+ request_id: record.request_id,
1438
+ request: { subtype: 'interrupt' },
1439
+ };
1440
+ }
1441
+ if (record.type === 'control_response') {
1442
+ const response = record.response;
1443
+ if (!response || typeof response !== 'object' || Array.isArray(response)) {
1444
+ throw new Error(`stream-json input line ${lineNumber} has invalid control response`);
1445
+ }
1446
+ const responseRecord = response;
1447
+ if (typeof responseRecord.request_id !== 'string' ||
1448
+ responseRecord.request_id.length === 0) {
1449
+ throw new Error(`stream-json input line ${lineNumber} has invalid request_id`);
1450
+ }
1451
+ if (responseRecord.subtype === 'success') {
1452
+ if (responseRecord.response !== undefined &&
1453
+ (!responseRecord.response ||
1454
+ typeof responseRecord.response !== 'object' ||
1455
+ Array.isArray(responseRecord.response))) {
1456
+ throw new Error(`stream-json input line ${lineNumber} has invalid success response`);
1457
+ }
1458
+ return {
1459
+ type: 'control_response',
1460
+ response: {
1461
+ subtype: 'success',
1462
+ request_id: responseRecord.request_id,
1463
+ ...(responseRecord.response === undefined
1464
+ ? {}
1465
+ : { response: responseRecord.response }),
1466
+ },
1467
+ };
1468
+ }
1469
+ if (responseRecord.subtype === 'error' &&
1470
+ typeof responseRecord.error === 'string') {
1471
+ return {
1472
+ type: 'control_response',
1473
+ response: {
1474
+ subtype: 'error',
1475
+ request_id: responseRecord.request_id,
1476
+ error: responseRecord.error,
1477
+ },
1478
+ };
1479
+ }
1480
+ throw new Error(`stream-json input line ${lineNumber} has invalid control response`);
1481
+ }
1482
+ throw new Error(`stream-json input line ${lineNumber} must have type user or a supported control type`);
1483
+ }
1484
+ export async function* readStreamJsonMessages(input) {
1485
+ const decoder = new TextDecoder('utf-8', { fatal: true });
1486
+ let buffer = '';
1487
+ let lineNumber = 0;
1488
+ const parseLine = (line) => {
1489
+ lineNumber += 1;
1490
+ if (line.trim().length === 0)
1491
+ return null;
1492
+ if (Buffer.byteLength(line) > MAX_INPUT_LINE_BYTES) {
1493
+ throw new Error(`stream-json input line ${lineNumber} exceeds ${MAX_INPUT_LINE_BYTES} bytes`);
1494
+ }
1495
+ let value;
1496
+ try {
1497
+ value = JSON.parse(line);
1498
+ }
1499
+ catch {
1500
+ throw new Error(`Invalid stream-json input at line ${lineNumber}`);
1501
+ }
1502
+ return parseStreamJsonMessage(value, lineNumber);
1503
+ };
1504
+ try {
1505
+ for await (const chunk of input) {
1506
+ buffer +=
1507
+ typeof chunk === 'string'
1508
+ ? chunk
1509
+ : decoder.decode(chunk, { stream: true });
1510
+ if (Buffer.byteLength(buffer) > MAX_INPUT_LINE_BYTES &&
1511
+ !buffer.includes('\n')) {
1512
+ throw new Error(`stream-json input line ${lineNumber + 1} exceeds ${MAX_INPUT_LINE_BYTES} bytes`);
1513
+ }
1514
+ for (;;) {
1515
+ const newline = buffer.indexOf('\n');
1516
+ if (newline < 0)
1517
+ break;
1518
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
1519
+ buffer = buffer.slice(newline + 1);
1520
+ const message = parseLine(line);
1521
+ if (message)
1522
+ yield message;
1523
+ }
1524
+ }
1525
+ buffer += decoder.decode();
1526
+ }
1527
+ catch (error) {
1528
+ if (error instanceof TypeError)
1529
+ throw new Error('stream-json input is not valid UTF-8');
1530
+ throw error;
1531
+ }
1532
+ if (buffer.length > 0) {
1533
+ const message = parseLine(buffer.replace(/\r$/, ''));
1534
+ if (message)
1535
+ yield message;
1536
+ }
1537
+ }
1538
+ export async function* readStreamUserMessages(input) {
1539
+ for await (const message of readStreamJsonMessages(input)) {
1540
+ if (!('type' in message))
1541
+ yield message;
1542
+ }
1543
+ }
1544
+ const emptyUsage = () => ({ inputTokens: 0, outputTokens: 0 });
1545
+ export class StreamJsonOutput {
1546
+ write;
1547
+ info;
1548
+ sessionId;
1549
+ includePartialMessages;
1550
+ includeHookEvents;
1551
+ turnId = randomUUID();
1552
+ turnText = '';
1553
+ turnThinking = [];
1554
+ turnCalls = [];
1555
+ turnUsage = emptyUsage();
1556
+ turnActive = false;
1557
+ assistantFlushed = true;
1558
+ contentStarted = false;
1559
+ textContentIndex;
1560
+ activeThinkingIndex;
1561
+ nextContentIndex = 0;
1562
+ modelTurns = 0;
1563
+ compacting = false;
1564
+ sessionState;
1565
+ constructor(write, info, sessionId, includePartialMessages, includeHookEvents = false) {
1566
+ this.write = write;
1567
+ this.info = info;
1568
+ this.sessionId = sessionId;
1569
+ this.includePartialMessages = includePartialMessages;
1570
+ this.includeHookEvents = includeHookEvents;
1571
+ }
1572
+ init() {
1573
+ this.write({
1574
+ type: 'system',
1575
+ subtype: 'init',
1576
+ cwd: this.info.cwd,
1577
+ session_id: this.sessionId,
1578
+ tools: this.info.tools,
1579
+ mcp_servers: this.info.mcpServers,
1580
+ model: this.info.model,
1581
+ permissionMode: this.info.permissionMode,
1582
+ slash_commands: this.info.slashCommands,
1583
+ apiKeySource: 'PRAXIS_API_KEY',
1584
+ praxis_version: '0.1.0',
1585
+ claude_code_version: this.info.claudeCodeVersion,
1586
+ agents: this.info.agents,
1587
+ skills: this.info.skills,
1588
+ output_style: 'default',
1589
+ plugins: this.info.plugins ?? [],
1590
+ fast_mode_state: 'off',
1591
+ uuid: randomUUID(),
1592
+ });
1593
+ }
1594
+ replayUser(message) {
1595
+ this.write({ type: 'user', message, session_id: this.sessionId });
1596
+ }
1597
+ controlRequest(request) {
1598
+ this.write({ type: 'control_request', ...request });
1599
+ }
1600
+ sink = (event) => this.onEvent(event);
1601
+ result(result, startedAt) {
1602
+ this.finishTurn();
1603
+ this.write(createSuccessResult(result, this.info, startedAt, this.modelTurns));
1604
+ this.modelTurns = 0;
1605
+ }
1606
+ promptSuggestion(suggestion) {
1607
+ this.write({
1608
+ type: 'prompt_suggestion',
1609
+ suggestion,
1610
+ uuid: randomUUID(),
1611
+ session_id: this.sessionId,
1612
+ });
1613
+ }
1614
+ error(message, startedAt) {
1615
+ this.finishTurn();
1616
+ this.write(createErrorResult(message, this.sessionId, startedAt, this.modelTurns));
1617
+ this.modelTurns = 0;
1618
+ }
1619
+ onEvent(event) {
1620
+ if (event.type === 'state') {
1621
+ if (this.compacting && event.state !== 'compacting') {
1622
+ this.compacting = false;
1623
+ this.write({
1624
+ type: 'system',
1625
+ subtype: 'status',
1626
+ status: null,
1627
+ permissionMode: this.info.permissionMode,
1628
+ uuid: randomUUID(),
1629
+ session_id: this.sessionId,
1630
+ });
1631
+ }
1632
+ if (event.state === 'awaiting-model') {
1633
+ this.startTurn();
1634
+ this.writeSessionState('running');
1635
+ }
1636
+ if (event.state === 'compacting') {
1637
+ this.compacting = true;
1638
+ this.write({
1639
+ type: 'system',
1640
+ subtype: 'status',
1641
+ status: 'compacting',
1642
+ permissionMode: this.info.permissionMode,
1643
+ uuid: randomUUID(),
1644
+ session_id: this.sessionId,
1645
+ });
1646
+ }
1647
+ else if (event.state === 'awaiting-permission' ||
1648
+ event.state === 'executing-tools' ||
1649
+ event.state === 'persisting-results' ||
1650
+ event.state === 'completed' ||
1651
+ event.state === 'cancelled') {
1652
+ this.flushAssistant();
1653
+ if (event.state === 'awaiting-permission')
1654
+ this.writeSessionState('requires_action');
1655
+ else if (event.state === 'completed' || event.state === 'cancelled') {
1656
+ this.writeSessionState('idle');
1657
+ }
1658
+ }
1659
+ return;
1660
+ }
1661
+ if (event.type === 'text-delta') {
1662
+ this.ensureTurn();
1663
+ this.turnText += event.delta;
1664
+ this.partialText(event.delta);
1665
+ return;
1666
+ }
1667
+ if (event.type === 'thinking-start') {
1668
+ this.ensureTurn();
1669
+ if (this.includePartialMessages) {
1670
+ if (this.activeThinkingIndex !== undefined) {
1671
+ throw new Error('Thinking content blocks cannot overlap');
1672
+ }
1673
+ this.activeThinkingIndex = this.nextContentIndex;
1674
+ this.nextContentIndex += 1;
1675
+ this.write({
1676
+ type: 'stream_event',
1677
+ event: {
1678
+ type: 'content_block_start',
1679
+ index: this.activeThinkingIndex,
1680
+ content_block: event.block,
1681
+ },
1682
+ parent_tool_use_id: null,
1683
+ session_id: this.sessionId,
1684
+ });
1685
+ }
1686
+ return;
1687
+ }
1688
+ if (event.type === 'thinking-delta' ||
1689
+ event.type === 'thinking-signature-delta') {
1690
+ this.ensureTurn();
1691
+ if (this.includePartialMessages) {
1692
+ if (this.activeThinkingIndex === undefined) {
1693
+ throw new Error('Thinking delta arrived without an active block');
1694
+ }
1695
+ this.write({
1696
+ type: 'stream_event',
1697
+ event: {
1698
+ type: 'content_block_delta',
1699
+ index: this.activeThinkingIndex,
1700
+ delta: event.type === 'thinking-delta'
1701
+ ? { type: 'thinking_delta', thinking: event.delta }
1702
+ : { type: 'signature_delta', signature: event.delta },
1703
+ },
1704
+ parent_tool_use_id: null,
1705
+ session_id: this.sessionId,
1706
+ });
1707
+ }
1708
+ return;
1709
+ }
1710
+ if (event.type === 'thinking-stop') {
1711
+ this.ensureTurn();
1712
+ this.turnThinking.push(event.block);
1713
+ if (this.includePartialMessages) {
1714
+ if (this.activeThinkingIndex === undefined) {
1715
+ throw new Error('Thinking block stopped without an active block');
1716
+ }
1717
+ this.write({
1718
+ type: 'stream_event',
1719
+ event: {
1720
+ type: 'content_block_stop',
1721
+ index: this.activeThinkingIndex,
1722
+ },
1723
+ parent_tool_use_id: null,
1724
+ session_id: this.sessionId,
1725
+ });
1726
+ this.activeThinkingIndex = undefined;
1727
+ }
1728
+ return;
1729
+ }
1730
+ if (event.type === 'user-message') {
1731
+ this.write({
1732
+ type: 'user_message',
1733
+ message: event.message,
1734
+ status: event.status,
1735
+ ...(event.attachments?.length
1736
+ ? { attachments: event.attachments }
1737
+ : {}),
1738
+ uuid: randomUUID(),
1739
+ session_id: this.sessionId,
1740
+ });
1741
+ return;
1742
+ }
1743
+ if (event.type === 'tool-call') {
1744
+ this.ensureTurn();
1745
+ this.turnCalls.push(event.call);
1746
+ return;
1747
+ }
1748
+ if (event.type === 'usage') {
1749
+ this.turnUsage = event.usage;
1750
+ return;
1751
+ }
1752
+ if (event.type === 'permission-decision') {
1753
+ this.flushAssistant();
1754
+ return;
1755
+ }
1756
+ if (event.type === 'tool-result') {
1757
+ this.flushAssistant();
1758
+ this.write({
1759
+ type: 'user',
1760
+ message: {
1761
+ role: 'user',
1762
+ content: [
1763
+ {
1764
+ tool_use_id: event.callId,
1765
+ type: 'tool_result',
1766
+ content: event.content,
1767
+ ...(event.isError ? { is_error: true } : {}),
1768
+ },
1769
+ ],
1770
+ },
1771
+ parent_tool_use_id: null,
1772
+ session_id: this.sessionId,
1773
+ });
1774
+ return;
1775
+ }
1776
+ if (event.type === 'warning') {
1777
+ this.write({
1778
+ type: 'system',
1779
+ subtype: 'warning',
1780
+ message: event.message,
1781
+ session_id: this.sessionId,
1782
+ });
1783
+ return;
1784
+ }
1785
+ if (event.type === 'compact-boundary') {
1786
+ this.write({
1787
+ type: 'system',
1788
+ subtype: 'compact_boundary',
1789
+ compact_metadata: {
1790
+ trigger: event.trigger,
1791
+ pre_tokens: event.preTokens,
1792
+ },
1793
+ uuid: event.uuid,
1794
+ session_id: this.sessionId,
1795
+ });
1796
+ return;
1797
+ }
1798
+ if (event.type === 'tool-progress') {
1799
+ this.write({
1800
+ type: 'tool_progress',
1801
+ tool_use_id: event.toolUseId,
1802
+ tool_name: event.toolName,
1803
+ parent_tool_use_id: null,
1804
+ elapsed_time_seconds: event.elapsedTimeSeconds,
1805
+ ...(event.taskId === undefined ? {} : { task_id: event.taskId }),
1806
+ uuid: randomUUID(),
1807
+ session_id: this.sessionId,
1808
+ });
1809
+ return;
1810
+ }
1811
+ if (event.type === 'task-started') {
1812
+ this.write({
1813
+ type: 'system',
1814
+ subtype: 'task_started',
1815
+ task_id: event.taskId,
1816
+ ...(event.toolUseId === undefined
1817
+ ? {}
1818
+ : { tool_use_id: event.toolUseId }),
1819
+ description: event.description,
1820
+ ...(event.taskType === undefined ? {} : { task_type: event.taskType }),
1821
+ ...(event.workflowName === undefined
1822
+ ? {}
1823
+ : { workflow_name: event.workflowName }),
1824
+ ...(event.prompt === undefined ? {} : { prompt: event.prompt }),
1825
+ uuid: randomUUID(),
1826
+ session_id: this.sessionId,
1827
+ });
1828
+ return;
1829
+ }
1830
+ if (event.type === 'task-progress') {
1831
+ this.write({
1832
+ type: 'system',
1833
+ subtype: 'task_progress',
1834
+ task_id: event.taskId,
1835
+ ...(event.toolUseId === undefined
1836
+ ? {}
1837
+ : { tool_use_id: event.toolUseId }),
1838
+ description: event.description,
1839
+ usage: {
1840
+ total_tokens: event.usage.totalTokens,
1841
+ tool_uses: event.usage.toolUses,
1842
+ duration_ms: event.usage.durationMs,
1843
+ },
1844
+ ...(event.lastToolName === undefined
1845
+ ? {}
1846
+ : { last_tool_name: event.lastToolName }),
1847
+ ...(event.summary === undefined ? {} : { summary: event.summary }),
1848
+ uuid: randomUUID(),
1849
+ session_id: this.sessionId,
1850
+ });
1851
+ return;
1852
+ }
1853
+ if (event.type === 'task-notification') {
1854
+ this.write({
1855
+ type: 'system',
1856
+ subtype: 'task_notification',
1857
+ task_id: event.taskId,
1858
+ ...(event.toolUseId === undefined
1859
+ ? {}
1860
+ : { tool_use_id: event.toolUseId }),
1861
+ status: event.status,
1862
+ output_file: event.outputFile,
1863
+ summary: event.summary,
1864
+ ...(event.usage === undefined
1865
+ ? {}
1866
+ : {
1867
+ usage: {
1868
+ total_tokens: event.usage.totalTokens,
1869
+ tool_uses: event.usage.toolUses,
1870
+ duration_ms: event.usage.durationMs,
1871
+ },
1872
+ }),
1873
+ uuid: randomUUID(),
1874
+ session_id: this.sessionId,
1875
+ });
1876
+ return;
1877
+ }
1878
+ if (event.type === 'session-state-changed') {
1879
+ this.write({
1880
+ type: 'system',
1881
+ subtype: 'session_state_changed',
1882
+ state: event.state,
1883
+ uuid: randomUUID(),
1884
+ session_id: this.sessionId,
1885
+ });
1886
+ return;
1887
+ }
1888
+ if (event.type === 'api-retry') {
1889
+ this.write({
1890
+ type: 'system',
1891
+ subtype: 'api_retry',
1892
+ attempt: event.attempt,
1893
+ max_retries: event.maxRetries,
1894
+ retry_delay_ms: event.retryDelayMs,
1895
+ error_status: event.errorStatus,
1896
+ error: event.error,
1897
+ uuid: randomUUID(),
1898
+ session_id: this.sessionId,
1899
+ });
1900
+ return;
1901
+ }
1902
+ if (event.type === 'elicitation-complete') {
1903
+ this.write({
1904
+ type: 'system',
1905
+ subtype: 'elicitation_complete',
1906
+ mcp_server_name: event.mcpServerName,
1907
+ elicitation_id: event.elicitationId,
1908
+ uuid: randomUUID(),
1909
+ session_id: this.sessionId,
1910
+ });
1911
+ return;
1912
+ }
1913
+ if (event.type === 'tool-use-summary') {
1914
+ this.write({
1915
+ type: 'tool_use_summary',
1916
+ summary: event.summary,
1917
+ preceding_tool_use_ids: event.precedingToolUseIds,
1918
+ uuid: randomUUID(),
1919
+ session_id: this.sessionId,
1920
+ });
1921
+ return;
1922
+ }
1923
+ if (event.type === 'hook') {
1924
+ if (!this.includeHookEvents)
1925
+ return;
1926
+ const hook = event.event;
1927
+ this.write({
1928
+ type: 'system',
1929
+ subtype: `hook_${hook.type}`,
1930
+ hook_id: hook.hookId,
1931
+ hook_name: hook.hookName,
1932
+ hook_event: hook.hookEvent,
1933
+ ...(hook.stdout === undefined ? {} : { stdout: hook.stdout }),
1934
+ ...(hook.stderr === undefined ? {} : { stderr: hook.stderr }),
1935
+ ...(hook.output === undefined ? {} : { output: hook.output }),
1936
+ ...(hook.exitCode === undefined ? {} : { exit_code: hook.exitCode }),
1937
+ ...(hook.outcome === undefined ? {} : { outcome: hook.outcome }),
1938
+ uuid: randomUUID(),
1939
+ session_id: this.sessionId,
1940
+ });
1941
+ return;
1942
+ }
1943
+ if (event.type === 'failed') {
1944
+ this.ensureTurn();
1945
+ if (this.turnText.length === 0 &&
1946
+ this.turnThinking.length === 0 &&
1947
+ this.turnCalls.length === 0) {
1948
+ this.turnText = event.message;
1949
+ this.partialText(event.message);
1950
+ }
1951
+ this.flushAssistant();
1952
+ this.writeSessionState('idle');
1953
+ }
1954
+ }
1955
+ writeSessionState(state) {
1956
+ if (this.sessionState === state)
1957
+ return;
1958
+ this.sessionState = state;
1959
+ this.write({
1960
+ type: 'system',
1961
+ subtype: 'session_state_changed',
1962
+ state,
1963
+ uuid: randomUUID(),
1964
+ session_id: this.sessionId,
1965
+ });
1966
+ }
1967
+ ensureTurn() {
1968
+ if (!this.turnActive)
1969
+ this.startTurn();
1970
+ }
1971
+ startTurn() {
1972
+ if (this.turnActive)
1973
+ this.finishTurn();
1974
+ this.turnId = randomUUID();
1975
+ this.turnText = '';
1976
+ this.turnThinking = [];
1977
+ this.turnCalls = [];
1978
+ this.turnUsage = emptyUsage();
1979
+ this.turnActive = true;
1980
+ this.assistantFlushed = false;
1981
+ this.contentStarted = false;
1982
+ this.textContentIndex = undefined;
1983
+ this.activeThinkingIndex = undefined;
1984
+ this.nextContentIndex = 0;
1985
+ this.modelTurns += 1;
1986
+ if (this.includePartialMessages) {
1987
+ this.write({
1988
+ type: 'stream_event',
1989
+ event: {
1990
+ type: 'message_start',
1991
+ message: {
1992
+ id: this.turnId,
1993
+ type: 'message',
1994
+ role: 'assistant',
1995
+ model: this.info.model,
1996
+ content: [],
1997
+ stop_reason: null,
1998
+ stop_sequence: null,
1999
+ usage: { input_tokens: 0, output_tokens: 0 },
2000
+ },
2001
+ },
2002
+ parent_tool_use_id: null,
2003
+ session_id: this.sessionId,
2004
+ });
2005
+ }
2006
+ }
2007
+ partialText(delta) {
2008
+ if (!this.includePartialMessages)
2009
+ return;
2010
+ if (!this.contentStarted) {
2011
+ this.contentStarted = true;
2012
+ this.textContentIndex = this.nextContentIndex;
2013
+ this.nextContentIndex += 1;
2014
+ this.write({
2015
+ type: 'stream_event',
2016
+ event: {
2017
+ type: 'content_block_start',
2018
+ index: this.textContentIndex,
2019
+ content_block: { type: 'text', text: '' },
2020
+ },
2021
+ parent_tool_use_id: null,
2022
+ session_id: this.sessionId,
2023
+ });
2024
+ }
2025
+ this.write({
2026
+ type: 'stream_event',
2027
+ event: {
2028
+ type: 'content_block_delta',
2029
+ index: this.textContentIndex,
2030
+ delta: { type: 'text_delta', text: delta },
2031
+ },
2032
+ parent_tool_use_id: null,
2033
+ session_id: this.sessionId,
2034
+ });
2035
+ }
2036
+ finishPartial() {
2037
+ if (!this.includePartialMessages)
2038
+ return;
2039
+ if (this.contentStarted) {
2040
+ this.write({
2041
+ type: 'stream_event',
2042
+ event: {
2043
+ type: 'content_block_stop',
2044
+ index: this.textContentIndex,
2045
+ },
2046
+ parent_tool_use_id: null,
2047
+ session_id: this.sessionId,
2048
+ });
2049
+ }
2050
+ for (const [toolIndex, call] of this.turnCalls.entries()) {
2051
+ const index = this.nextContentIndex + toolIndex;
2052
+ this.write({
2053
+ type: 'stream_event',
2054
+ event: {
2055
+ type: 'content_block_start',
2056
+ index,
2057
+ content_block: {
2058
+ type: 'tool_use',
2059
+ id: call.id,
2060
+ name: call.name,
2061
+ input: {},
2062
+ },
2063
+ },
2064
+ parent_tool_use_id: null,
2065
+ session_id: this.sessionId,
2066
+ });
2067
+ this.write({
2068
+ type: 'stream_event',
2069
+ event: {
2070
+ type: 'content_block_delta',
2071
+ index,
2072
+ delta: {
2073
+ type: 'input_json_delta',
2074
+ partial_json: JSON.stringify(call.input),
2075
+ },
2076
+ },
2077
+ parent_tool_use_id: null,
2078
+ session_id: this.sessionId,
2079
+ });
2080
+ this.write({
2081
+ type: 'stream_event',
2082
+ event: { type: 'content_block_stop', index },
2083
+ parent_tool_use_id: null,
2084
+ session_id: this.sessionId,
2085
+ });
2086
+ }
2087
+ this.write({
2088
+ type: 'stream_event',
2089
+ event: {
2090
+ type: 'message_delta',
2091
+ delta: {
2092
+ stop_reason: this.turnCalls.length > 0 ? 'tool_use' : 'end_turn',
2093
+ stop_sequence: null,
2094
+ },
2095
+ usage: { output_tokens: this.turnUsage.outputTokens },
2096
+ },
2097
+ parent_tool_use_id: null,
2098
+ session_id: this.sessionId,
2099
+ });
2100
+ this.write({
2101
+ type: 'stream_event',
2102
+ event: { type: 'message_stop' },
2103
+ parent_tool_use_id: null,
2104
+ session_id: this.sessionId,
2105
+ });
2106
+ }
2107
+ flushAssistant() {
2108
+ if (!this.turnActive || this.assistantFlushed)
2109
+ return;
2110
+ this.assistantFlushed = true;
2111
+ this.finishPartial();
2112
+ const content = [];
2113
+ content.push(...this.turnThinking);
2114
+ if (this.turnText.length > 0)
2115
+ content.push({ type: 'text', text: this.turnText });
2116
+ content.push(...this.turnCalls.map((call) => ({
2117
+ type: 'tool_use',
2118
+ id: call.id,
2119
+ name: call.name,
2120
+ input: call.input,
2121
+ })));
2122
+ this.write({
2123
+ type: 'assistant',
2124
+ message: {
2125
+ id: this.turnId,
2126
+ type: 'message',
2127
+ role: 'assistant',
2128
+ model: this.info.model,
2129
+ content,
2130
+ stop_reason: null,
2131
+ stop_sequence: null,
2132
+ usage: {
2133
+ input_tokens: this.turnUsage.inputTokens,
2134
+ output_tokens: this.turnUsage.outputTokens,
2135
+ },
2136
+ },
2137
+ parent_tool_use_id: null,
2138
+ session_id: this.sessionId,
2139
+ });
2140
+ }
2141
+ finishTurn() {
2142
+ this.flushAssistant();
2143
+ this.turnActive = false;
2144
+ }
2145
+ }
2146
+ //# sourceMappingURL=protocol.js.map