ummaya 0.2.4 → 0.2.5

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 (477) hide show
  1. package/README.md +15 -2
  2. package/bin/ummaya +10 -1
  3. package/npm-shrinkwrap.json +253 -2
  4. package/package.json +5 -1
  5. package/prompts/manifest.yaml +1 -1
  6. package/prompts/system_v1.md +1 -0
  7. package/pyproject.toml +26 -2
  8. package/specs/2803-document-production-hardening/contracts/document-tools.schema.json +1043 -0
  9. package/src/ummaya/_canonical/__init__.py +2 -0
  10. package/src/ummaya/engine/engine.py +29 -132
  11. package/src/ummaya/evidence/__init__.py +21 -2
  12. package/src/ummaya/evidence/dataset_contract.py +193 -0
  13. package/src/ummaya/evidence/document_authoring_cases.py +33 -0
  14. package/src/ummaya/evidence/document_harness.py +313 -0
  15. package/src/ummaya/evidence/document_viewer_ux.py +391 -0
  16. package/src/ummaya/evidence/gates.py +70 -0
  17. package/src/ummaya/evidence/json_types.py +20 -0
  18. package/src/ummaya/evidence/models.py +88 -1
  19. package/src/ummaya/evidence/output_payload.py +89 -0
  20. package/src/ummaya/evidence/payload_documents.py +233 -0
  21. package/src/ummaya/evidence/route_contracts.py +224 -0
  22. package/src/ummaya/evidence/route_helpers.py +150 -0
  23. package/src/ummaya/evidence/runner.py +81 -212
  24. package/src/ummaya/evidence/source_provenance.py +246 -0
  25. package/src/ummaya/evidence/source_provenance_redaction.py +176 -0
  26. package/src/ummaya/evidence/tool_layer.py +39 -0
  27. package/src/ummaya/evidence/tool_layer_models.py +151 -0
  28. package/src/ummaya/ipc/adapter_manifest_emitter.py +26 -10
  29. package/src/ummaya/ipc/document_intent_normalization.py +185 -0
  30. package/src/ummaya/ipc/frame_schema.py +5 -5
  31. package/src/ummaya/ipc/route_diagnostics.py +73 -0
  32. package/src/ummaya/ipc/stdio.py +1109 -477
  33. package/src/ummaya/llm/client.py +102 -3
  34. package/src/ummaya/llm/config.py +8 -3
  35. package/src/ummaya/primitives/__init__.py +6 -2
  36. package/src/ummaya/primitives/delegation.py +1 -1
  37. package/src/ummaya/primitives/document.py +28 -0
  38. package/src/ummaya/settings.py +0 -3
  39. package/src/ummaya/tools/discovery_bridge.py +17 -1
  40. package/src/ummaya/tools/documents/__init__.py +297 -0
  41. package/src/ummaya/tools/documents/adapter_registry.py +487 -0
  42. package/src/ummaya/tools/documents/archive_container_probe.py +167 -0
  43. package/src/ummaya/tools/documents/artifact_store.py +454 -0
  44. package/src/ummaya/tools/documents/authoring.py +283 -0
  45. package/src/ummaya/tools/documents/baselines.py +114 -0
  46. package/src/ummaya/tools/documents/capability.py +331 -0
  47. package/src/ummaya/tools/documents/contracts.py +112 -0
  48. package/src/ummaya/tools/documents/conversion.py +521 -0
  49. package/src/ummaya/tools/documents/diff.py +275 -0
  50. package/src/ummaya/tools/documents/engines.py +163 -0
  51. package/src/ummaya/tools/documents/evaluation.py +291 -0
  52. package/src/ummaya/tools/documents/explicit_values.py +108 -0
  53. package/src/ummaya/tools/documents/fixtures.py +174 -0
  54. package/src/ummaya/tools/documents/format_completion_audit.py +471 -0
  55. package/src/ummaya/tools/documents/formats/__init__.py +2 -0
  56. package/src/ummaya/tools/documents/formats/archive.py +528 -0
  57. package/src/ummaya/tools/documents/formats/base.py +41 -0
  58. package/src/ummaya/tools/documents/formats/code_file.py +211 -0
  59. package/src/ummaya/tools/documents/formats/data_file.py +272 -0
  60. package/src/ummaya/tools/documents/formats/hwp.py +284 -0
  61. package/src/ummaya/tools/documents/formats/hwpx.py +1837 -0
  62. package/src/ummaya/tools/documents/formats/odf.py +435 -0
  63. package/src/ummaya/tools/documents/formats/ooxml.py +1030 -0
  64. package/src/ummaya/tools/documents/formats/passive.py +766 -0
  65. package/src/ummaya/tools/documents/formats/pdf.py +702 -0
  66. package/src/ummaya/tools/documents/formats/text_web.py +268 -0
  67. package/src/ummaya/tools/documents/hwp_conversion_probe.py +178 -0
  68. package/src/ummaya/tools/documents/hwp_direct_candidate.py +141 -0
  69. package/src/ummaya/tools/documents/inspection.py +289 -0
  70. package/src/ummaya/tools/documents/intake.py +1079 -0
  71. package/src/ummaya/tools/documents/legacy_office_promotion_probe.py +366 -0
  72. package/src/ummaya/tools/documents/models.py +1598 -0
  73. package/src/ummaya/tools/documents/odf_promotion_probe.py +167 -0
  74. package/src/ummaya/tools/documents/orchestrator.py +96 -0
  75. package/src/ummaya/tools/documents/passive_capability_probe.py +251 -0
  76. package/src/ummaya/tools/documents/patch.py +170 -0
  77. package/src/ummaya/tools/documents/pdfa_conformance.py +284 -0
  78. package/src/ummaya/tools/documents/pdfa_promotion_probe.py +198 -0
  79. package/src/ummaya/tools/documents/permissions.py +110 -0
  80. package/src/ummaya/tools/documents/planner.py +616 -0
  81. package/src/ummaya/tools/documents/registry.py +2733 -0
  82. package/src/ummaya/tools/documents/render.py +978 -0
  83. package/src/ummaya/tools/documents/render_comparison.py +113 -0
  84. package/src/ummaya/tools/documents/render_comparison_models.py +74 -0
  85. package/src/ummaya/tools/documents/render_comparison_regions.py +73 -0
  86. package/src/ummaya/tools/documents/render_comparison_style.py +161 -0
  87. package/src/ummaya/tools/documents/reread.py +157 -0
  88. package/src/ummaya/tools/documents/runtime_authoring.py +244 -0
  89. package/src/ummaya/tools/documents/runtime_authoring_bundle.py +76 -0
  90. package/src/ummaya/tools/documents/scorecard.py +184 -0
  91. package/src/ummaya/tools/documents/socratic_planner.py +193 -0
  92. package/src/ummaya/tools/documents/style.py +48 -0
  93. package/src/ummaya/tools/documents/tool_defs.py +523 -0
  94. package/src/ummaya/tools/documents/validate.py +347 -0
  95. package/src/ummaya/tools/executor.py +29 -0
  96. package/src/ummaya/tools/live_proxy.py +0 -3
  97. package/src/ummaya/tools/models.py +5 -1
  98. package/src/ummaya/tools/register_all.py +8 -0
  99. package/src/ummaya/tools/registry.py +10 -1
  100. package/src/ummaya/tools/routing/__init__.py +59 -0
  101. package/src/ummaya/tools/routing/builder.py +105 -0
  102. package/src/ummaya/tools/routing/cards.py +29 -0
  103. package/src/ummaya/tools/routing/decision_service.py +534 -0
  104. package/src/ummaya/tools/routing/decision_types.py +74 -0
  105. package/src/ummaya/tools/routing/feasibility.py +122 -0
  106. package/src/ummaya/tools/routing/intent.py +17 -0
  107. package/src/ummaya/tools/routing/intent_extractor.py +207 -0
  108. package/src/ummaya/tools/routing/intent_patterns.py +160 -0
  109. package/src/ummaya/tools/routing/intent_public_data.py +150 -0
  110. package/src/ummaya/tools/routing/intent_types.py +48 -0
  111. package/src/ummaya/tools/routing/lint.py +78 -0
  112. package/src/ummaya/tools/routing/metadata.py +174 -0
  113. package/src/ummaya/tools/routing/projection.py +340 -0
  114. package/src/ummaya/tools/routing/retrieval_policy.py +629 -0
  115. package/src/ummaya/tools/routing/schema.py +81 -0
  116. package/src/ummaya/tools/routing/types.py +96 -0
  117. package/src/ummaya/tools/routing_index.py +2 -2
  118. package/src/ummaya/tools/search.py +34 -746
  119. package/tests/fixtures/documents/public_forms/baselines.yaml +113 -0
  120. package/tui/package.json +1 -1
  121. package/tui/src/.cc-byte-identical-whitelist.yaml +266 -0
  122. package/tui/src/QueryEngine.ts +12 -8
  123. package/tui/src/bridge/inboundAttachments.ts +3 -3
  124. package/tui/src/cli/handlers/auth.ts +3 -12
  125. package/tui/src/cli/print.ts +7 -7
  126. package/tui/src/commands/insights.ts +1 -1
  127. package/tui/src/commands/install-github-app/types.ts +8 -30
  128. package/tui/src/commands/plugin/types.ts +6 -28
  129. package/tui/src/commands/plugin/unifiedTypes.ts +4 -26
  130. package/tui/src/commands/rename/generateSessionName.ts +1 -1
  131. package/tui/src/components/Feedback.tsx +1 -1
  132. package/tui/src/components/LogoV2/EmergencyTip.tsx +11 -2
  133. package/tui/src/components/LogoV2/WelcomeV2.tsx +1 -3
  134. package/tui/src/components/ScrollKeybindingHandler.tsx +6 -6
  135. package/tui/src/components/Spinner/types.ts +6 -28
  136. package/tui/src/components/agents/generateAgent.ts +1 -1
  137. package/tui/src/components/agents/new-agent-creation/types.ts +4 -26
  138. package/tui/src/components/config/EnvSecretIsolatedEditor.tsx +1 -1
  139. package/tui/src/components/mcp/types.ts +16 -38
  140. package/tui/src/components/messages/AssistantToolUseMessage.tsx +3 -2
  141. package/tui/src/components/messages/UserCrossSessionMessage.ts +16 -4
  142. package/tui/src/components/messages/UserForkBoilerplateMessage.ts +16 -4
  143. package/tui/src/components/messages/UserGitHubWebhookMessage.ts +16 -4
  144. package/tui/src/components/messages/UserToolResultMessage/utils.tsx +3 -2
  145. package/tui/src/components/permissions/MonitorPermissionRequest/MonitorPermissionRequest.ts +9 -4
  146. package/tui/src/components/permissions/ReviewArtifactPermissionRequest/ReviewArtifactPermissionRequest.ts +9 -4
  147. package/tui/src/components/primitive/DocumentSocraticReviewBlock.tsx +129 -0
  148. package/tui/src/components/primitive/DocumentToolResultCard.tsx +224 -0
  149. package/tui/src/components/primitive/documentSocraticReview.ts +215 -0
  150. package/tui/src/components/primitive/index.tsx +43 -1
  151. package/tui/src/components/primitive/types.ts +137 -0
  152. package/tui/src/components/ui/option.ts +4 -26
  153. package/tui/src/constants/common.ts +0 -2
  154. package/tui/src/constants/prompts.ts +4 -3
  155. package/tui/src/constants/querySource.ts +4 -26
  156. package/tui/src/entrypoints/sdk/controlTypes.ts +26 -48
  157. package/tui/src/entrypoints/sdk/coreTypes.generated.ts +3 -25
  158. package/tui/src/entrypoints/sdk/runtimeTypes.ts +38 -60
  159. package/tui/src/entrypoints/sdk/sdkUtilityTypes.ts +4 -26
  160. package/tui/src/entrypoints/sdk/settingsTypes.generated.ts +3 -25
  161. package/tui/src/entrypoints/sdk/toolTypes.ts +3 -25
  162. package/tui/src/hooks/toolPermission/handlers/interactiveHandler.ts +10 -0
  163. package/tui/src/hooks/useApiKeyVerification.ts +1 -1
  164. package/tui/src/hooks/useVirtualScroll.ts +1 -1
  165. package/tui/src/ink/ink.tsx +33 -14
  166. package/tui/src/ink/reconciler.ts +2 -3
  167. package/tui/src/ink/render-to-screen.ts +30 -10
  168. package/tui/src/ipc/bridge.ts +62 -15
  169. package/tui/src/ipc/bridgeSingleton.ts +5 -1
  170. package/tui/src/ipc/codec.ts +3 -3
  171. package/tui/src/ipc/frames.generated.ts +12 -12
  172. package/tui/src/ipc/llmClient.ts +151 -27
  173. package/tui/src/ipc/schema/frame.schema.json +1 -1
  174. package/tui/src/keybindings/defaultBindings.ts +4 -0
  175. package/tui/src/main.tsx +29 -11
  176. package/tui/src/native-ts/file-index/index.ts +33 -3
  177. package/tui/src/observability/surface.ts +2 -2
  178. package/tui/src/probes/toolRegistryProbe.tsx +3 -1
  179. package/tui/src/projectOnboardingState.ts +7 -6
  180. package/tui/src/query/chatMessageTypes.ts +18 -0
  181. package/tui/src/query/chatMessagesBuilder.ts +1 -1
  182. package/tui/src/query/deps.ts +1 -1
  183. package/tui/src/query/messageGuards.ts +106 -0
  184. package/tui/src/query/publicDataTerminalRepair.ts +384 -0
  185. package/tui/src/query/run.ts +1075 -0
  186. package/tui/src/query/supportBoundary.ts +168 -0
  187. package/tui/src/query/toolResultErrors.ts +103 -0
  188. package/tui/src/query/toolRunner.ts +687 -0
  189. package/tui/src/query/unavailableToolRepair.ts +118 -0
  190. package/tui/src/query.ts +9 -2186
  191. package/tui/src/screens/REPL.tsx +40 -29
  192. package/tui/src/services/api/adapterManifest.ts +4 -0
  193. package/tui/src/services/api/backendChat/events.ts +117 -0
  194. package/tui/src/services/api/backendChat/finalMessage.ts +40 -0
  195. package/tui/src/services/api/backendChat/frame.ts +9 -0
  196. package/tui/src/services/api/backendChat/streaming.ts +430 -0
  197. package/tui/src/services/api/backendChat/types.ts +62 -0
  198. package/tui/src/services/api/backendChat.ts +1 -0
  199. package/tui/src/services/api/client.ts +65 -2
  200. package/tui/src/services/api/errorUtils.ts +5 -5
  201. package/tui/src/services/api/errors.ts +1 -1
  202. package/tui/src/services/api/logging.ts +1 -1
  203. package/tui/src/services/api/ummaya/evidence.ts +194 -0
  204. package/tui/src/services/api/ummaya/messages.ts +255 -0
  205. package/tui/src/services/api/ummaya/nonStreaming.ts +66 -0
  206. package/tui/src/services/api/ummaya/provider.ts +200 -0
  207. package/tui/src/services/api/ummaya/reasoning.ts +24 -0
  208. package/tui/src/services/api/ummaya/request.ts +200 -0
  209. package/tui/src/services/api/ummaya/selectionContext.ts +240 -0
  210. package/tui/src/services/api/ummaya/streaming.ts +365 -0
  211. package/tui/src/services/api/ummaya/streamingPayload.ts +129 -0
  212. package/tui/src/services/api/ummaya/streamingReader.ts +40 -0
  213. package/tui/src/services/api/ummaya/toolSelection.ts +217 -0
  214. package/tui/src/services/api/ummaya/types.ts +110 -0
  215. package/tui/src/services/api/ummaya/usage.ts +30 -0
  216. package/tui/src/services/api/ummaya.ts +26 -418
  217. package/tui/src/services/api/withRetry.ts +1 -1
  218. package/tui/src/services/awaySummary.ts +2 -2
  219. package/tui/src/services/claudeAiLimits.ts +1 -1
  220. package/tui/src/services/compact/autoCompact.ts +1 -1
  221. package/tui/src/services/compact/compact.ts +1 -1
  222. package/tui/src/services/lsp/types.ts +8 -30
  223. package/tui/src/services/tips/types.ts +6 -28
  224. package/tui/src/services/tokenEstimation.ts +1 -1
  225. package/tui/src/services/toolRegistry/bootGuard.ts +5 -5
  226. package/tui/src/services/toolUseSummary/toolUseSummaryGenerator.ts +1 -1
  227. package/tui/src/services/tools/toolExecution.ts +94 -1
  228. package/tui/src/store/pendingPermissionSlot.ts +1 -1
  229. package/tui/src/store/session-store.ts +10 -36
  230. package/tui/src/stubs/any-stub.ts +15 -10
  231. package/tui/src/stubs/color-diff-napi.ts +37 -23
  232. package/tui/src/stubs/globals.d.ts +3 -3
  233. package/tui/src/stubs/macro-preload.ts +23 -12
  234. package/tui/src/tools/AdapterTool/AdapterTool.ts +1207 -714
  235. package/tui/src/tools/AdapterTool/routeDiagnostics.ts +75 -0
  236. package/tui/src/tools/AgentTool/AgentTool.tsx +84 -1371
  237. package/tui/src/tools/AgentTool/agentToolHandoff.ts +114 -0
  238. package/tui/src/tools/AgentTool/agentToolPartialResult.ts +16 -0
  239. package/tui/src/tools/AgentTool/agentToolProgress.ts +32 -0
  240. package/tui/src/tools/AgentTool/agentToolResolver.ts +161 -0
  241. package/tui/src/tools/AgentTool/agentToolResult.ts +163 -0
  242. package/tui/src/tools/AgentTool/agentToolUtils.ts +14 -686
  243. package/tui/src/tools/AgentTool/asyncAgentLifecycle.ts +208 -0
  244. package/tui/src/tools/AgentTool/asyncLifecycle.ts +153 -0
  245. package/tui/src/tools/AgentTool/backgroundedCompletion.ts +126 -0
  246. package/tui/src/tools/AgentTool/backgroundedLifecycle.ts +174 -0
  247. package/tui/src/tools/AgentTool/foregroundBackground.ts +83 -0
  248. package/tui/src/tools/AgentTool/foregroundDrain.tsx +133 -0
  249. package/tui/src/tools/AgentTool/foregroundFinalize.ts +98 -0
  250. package/tui/src/tools/AgentTool/foregroundLifecycle.tsx +237 -0
  251. package/tui/src/tools/AgentTool/foregroundProgress.tsx +169 -0
  252. package/tui/src/tools/AgentTool/foregroundTask.ts +89 -0
  253. package/tui/src/tools/AgentTool/forkSubagent.ts +1 -12
  254. package/tui/src/tools/AgentTool/forkSubagentGate.ts +34 -0
  255. package/tui/src/tools/AgentTool/launchRouting.ts +203 -0
  256. package/tui/src/tools/AgentTool/lifecycle.ts +244 -0
  257. package/tui/src/tools/AgentTool/mcpRouting.ts +73 -0
  258. package/tui/src/tools/AgentTool/orchestrationSupport.ts +70 -0
  259. package/tui/src/tools/AgentTool/permissions.ts +39 -0
  260. package/tui/src/tools/AgentTool/promptSetup.ts +181 -0
  261. package/tui/src/tools/AgentTool/remoteRouting.ts +62 -0
  262. package/tui/src/tools/AgentTool/resultMapping.ts +116 -0
  263. package/tui/src/tools/AgentTool/resumeAgent.ts +39 -107
  264. package/tui/src/tools/AgentTool/resumeAgentHelpers.ts +140 -0
  265. package/tui/src/tools/AgentTool/runAgent.ts +1 -1
  266. package/tui/src/tools/AgentTool/runtimeConfig.ts +57 -0
  267. package/tui/src/tools/AgentTool/schemas.ts +196 -0
  268. package/tui/src/tools/AgentTool/sourceVerificationPropagation.ts +263 -0
  269. package/tui/src/tools/AgentTool/worktreeLifecycle.ts +105 -0
  270. package/tui/src/tools/AskUserQuestionTool/AskUserQuestionTool.tsx +174 -202
  271. package/tui/src/tools/BashTool/BashTool.tsx +71 -1072
  272. package/tui/src/tools/BashTool/bashCommandHelpers.ts +12 -12
  273. package/tui/src/tools/BashTool/bashPermissions/astPreflight.ts +173 -0
  274. package/tui/src/tools/BashTool/bashPermissions/classifierChecks.ts +199 -0
  275. package/tui/src/tools/BashTool/bashPermissions/compoundGuards.ts +53 -0
  276. package/tui/src/tools/BashTool/bashPermissions/constants.ts +99 -0
  277. package/tui/src/tools/BashTool/bashPermissions/index.ts +38 -0
  278. package/tui/src/tools/BashTool/bashPermissions/legacyMisparsing.ts +62 -0
  279. package/tui/src/tools/BashTool/bashPermissions/main.ts +135 -0
  280. package/tui/src/tools/BashTool/bashPermissions/normalizedCommands.ts +33 -0
  281. package/tui/src/tools/BashTool/bashPermissions/operatorFlow.ts +98 -0
  282. package/tui/src/tools/BashTool/bashPermissions/permissionChecks.ts +200 -0
  283. package/tui/src/tools/BashTool/bashPermissions/prefixSuggestions.ts +88 -0
  284. package/tui/src/tools/BashTool/bashPermissions/promptClassifierRules.ts +125 -0
  285. package/tui/src/tools/BashTool/bashPermissions/ruleDelegates.ts +19 -0
  286. package/tui/src/tools/BashTool/bashPermissions/ruleMatching.ts +145 -0
  287. package/tui/src/tools/BashTool/bashPermissions/sandboxAutoAllow.ts +75 -0
  288. package/tui/src/tools/BashTool/bashPermissions/subcommandFlow.ts +205 -0
  289. package/tui/src/tools/BashTool/bashPermissions/subcommandGuards.ts +73 -0
  290. package/tui/src/tools/BashTool/bashPermissions/subcommandResultHelpers.ts +116 -0
  291. package/tui/src/tools/BashTool/bashPermissions/types.ts +26 -0
  292. package/tui/src/tools/BashTool/bashPermissions/wrapperStripping.ts +139 -0
  293. package/tui/src/tools/BashTool/bashPermissions.ts +26 -2621
  294. package/tui/src/tools/BashTool/call.ts +202 -0
  295. package/tui/src/tools/BashTool/callLoader.ts +35 -0
  296. package/tui/src/tools/BashTool/commandClassification.ts +151 -0
  297. package/tui/src/tools/BashTool/commandClassificationLoader.ts +40 -0
  298. package/tui/src/tools/BashTool/cwdReset.ts +33 -0
  299. package/tui/src/tools/BashTool/lineTruncation.ts +11 -0
  300. package/tui/src/tools/BashTool/modeValidation.ts +13 -1
  301. package/tui/src/tools/BashTool/outputPersistence.ts +42 -0
  302. package/tui/src/tools/BashTool/permissionClassification.ts +66 -0
  303. package/tui/src/tools/BashTool/permissionLoader.ts +44 -0
  304. package/tui/src/tools/BashTool/resultLoader.ts +29 -0
  305. package/tui/src/tools/BashTool/resultMapping.ts +83 -0
  306. package/tui/src/tools/BashTool/sandboxPolicy.ts +79 -0
  307. package/tui/src/tools/BashTool/schemas.ts +65 -0
  308. package/tui/src/tools/BashTool/sedEditExecution.ts +59 -0
  309. package/tui/src/tools/BashTool/shellExecution.tsx +245 -0
  310. package/tui/src/tools/BashTool/shellOutputUtils.ts +85 -0
  311. package/tui/src/tools/BashTool/shellPermissionGauntlet.ts +97 -0
  312. package/tui/src/tools/BashTool/uiLoader.ts +37 -0
  313. package/tui/src/tools/BriefTool/upload.ts +1 -1
  314. package/tui/src/tools/CalculatorTool/parser.ts +2 -2
  315. package/tui/src/tools/DocumentPrimitive/DocumentPrimitive.ts +262 -0
  316. package/tui/src/tools/DocumentPrimitive/dispatchNormalization.ts +270 -0
  317. package/tui/src/tools/DocumentPrimitive/documentDestinationPath.ts +18 -0
  318. package/tui/src/tools/DocumentPrimitive/documentMutationGuard.ts +22 -0
  319. package/tui/src/tools/DocumentPrimitive/documentPatchNormalization.ts +248 -0
  320. package/tui/src/tools/DocumentPrimitive/documentSourceVerification.ts +245 -0
  321. package/tui/src/tools/DocumentPrimitive/documentSourceVerificationFields.ts +103 -0
  322. package/tui/src/tools/DocumentPrimitive/modelVisibleOutput.ts +40 -0
  323. package/tui/src/tools/DocumentPrimitive/prompt.ts +35 -0
  324. package/tui/src/tools/FileEditTool/FileEditTool.ts +9 -507
  325. package/tui/src/tools/FileEditTool/call.ts +228 -0
  326. package/tui/src/tools/FileEditTool/validateInput.ts +196 -0
  327. package/tui/src/tools/FileReadTool/imageProcessor.ts +13 -0
  328. package/tui/src/tools/FileWriteTool/FileWriteTool.ts +7 -300
  329. package/tui/src/tools/FileWriteTool/call.ts +223 -0
  330. package/tui/src/tools/FileWriteTool/validateInput.ts +80 -0
  331. package/tui/src/tools/ListMcpResourcesTool/ListMcpResourcesTool.ts +19 -3
  332. package/tui/src/tools/LookupPrimitive/LookupPrimitive.ts +25 -32
  333. package/tui/src/tools/LookupPrimitive/prompt.ts +0 -2
  334. package/tui/src/tools/MCPTool/trustPolicy.ts +118 -0
  335. package/tui/src/tools/McpAuthTool/McpAuthTool.ts +21 -3
  336. package/tui/src/tools/NotebookEditTool/NotebookEditTool.ts +7 -326
  337. package/tui/src/tools/NotebookEditTool/call.ts +254 -0
  338. package/tui/src/tools/NotebookEditTool/notebookModel.ts +51 -0
  339. package/tui/src/tools/NotebookEditTool/validateInput.ts +142 -0
  340. package/tui/src/tools/PowerShellTool/PowerShellTool.tsx +46 -937
  341. package/tui/src/tools/PowerShellTool/acceptEditsCommandValidation.ts +162 -0
  342. package/tui/src/tools/PowerShellTool/call.ts +179 -0
  343. package/tui/src/tools/PowerShellTool/callLoader.ts +37 -0
  344. package/tui/src/tools/PowerShellTool/commandClassification.ts +86 -0
  345. package/tui/src/tools/PowerShellTool/modeValidation.ts +25 -332
  346. package/tui/src/tools/PowerShellTool/outputPersistence.ts +42 -0
  347. package/tui/src/tools/PowerShellTool/permissionClassification.ts +28 -0
  348. package/tui/src/tools/PowerShellTool/resultLoader.ts +31 -0
  349. package/tui/src/tools/PowerShellTool/resultMapping.ts +75 -0
  350. package/tui/src/tools/PowerShellTool/schemas.ts +40 -0
  351. package/tui/src/tools/PowerShellTool/shellExecution.tsx +258 -0
  352. package/tui/src/tools/PowerShellTool/symlinkModeValidation.ts +44 -0
  353. package/tui/src/tools/PowerShellTool/uiLoader.ts +37 -0
  354. package/tui/src/tools/PowerShellTool/validation.ts +39 -0
  355. package/tui/src/tools/ReadMcpResourceTool/ReadMcpResourceTool.ts +19 -3
  356. package/tui/src/tools/ResolveLocationPrimitive/ResolveLocationPrimitive.ts +1 -11
  357. package/tui/src/tools/ResolveLocationPrimitive/prompt.ts +2 -6
  358. package/tui/src/tools/SkillTool/SkillTool.ts +2 -2
  359. package/tui/src/tools/SubmitPrimitive/SubmitPrimitive.ts +27 -10
  360. package/tui/src/tools/TaskCreateTool/TaskCreateTool.ts +16 -2
  361. package/tui/src/tools/TaskGetTool/TaskGetTool.ts +23 -3
  362. package/tui/src/tools/TaskListTool/TaskListTool.ts +22 -4
  363. package/tui/src/tools/TaskOutputTool/TaskOutputTool.tsx +46 -547
  364. package/tui/src/tools/TaskOutputTool/lookup.ts +216 -0
  365. package/tui/src/tools/TaskOutputTool/render.tsx +257 -0
  366. package/tui/src/tools/TaskOutputTool/schemas.ts +55 -0
  367. package/tui/src/tools/TaskOutputTool/serialization.ts +36 -0
  368. package/tui/src/tools/TaskStopTool/TaskStopTool.ts +10 -0
  369. package/tui/src/tools/TaskUpdateTool/TaskUpdateTool.ts +14 -364
  370. package/tui/src/tools/TaskUpdateTool/completion.ts +62 -0
  371. package/tui/src/tools/TaskUpdateTool/schemas.ts +62 -0
  372. package/tui/src/tools/TaskUpdateTool/serialization.ts +46 -0
  373. package/tui/src/tools/TaskUpdateTool/statusUpdate.ts +247 -0
  374. package/tui/src/tools/TodoWriteTool/TodoWriteTool.ts +21 -2
  375. package/tui/src/tools/ToolSearchTool/ToolSearchTool.ts +21 -302
  376. package/tui/src/tools/ToolSearchTool/ccSupportTools.ts +223 -0
  377. package/tui/src/tools/ToolSearchTool/descriptionCache.ts +50 -0
  378. package/tui/src/tools/ToolSearchTool/keywordSearch.ts +216 -0
  379. package/tui/src/tools/ToolSearchTool/prompt.ts +10 -4
  380. package/tui/src/tools/ToolSearchTool/resultMapping.ts +30 -0
  381. package/tui/src/tools/ToolSearchTool/schemas.ts +30 -0
  382. package/tui/src/tools/ToolSearchTool/searchPool.ts +47 -0
  383. package/tui/src/tools/ToolSearchTool/supportIntentHints.ts +140 -0
  384. package/tui/src/tools/TranslateTool/TranslateTool.ts +1 -1
  385. package/tui/src/tools/VerifyPrimitive/VerifyPrimitive.ts +2 -1
  386. package/tui/src/tools/WebFetchTool/WebFetchTool.ts +43 -138
  387. package/tui/src/tools/WebFetchTool/call.ts +227 -0
  388. package/tui/src/tools/WebFetchTool/resolvedAddressSafety.ts +78 -0
  389. package/tui/src/tools/WebFetchTool/sourceVerification.ts +204 -0
  390. package/tui/src/tools/WebFetchTool/types.ts +23 -0
  391. package/tui/src/tools/WebFetchTool/urlSafety.ts +181 -0
  392. package/tui/src/tools/WebFetchTool/utils.ts +1 -1
  393. package/tui/src/tools/WebSearchTool/UI.tsx +0 -1
  394. package/tui/src/tools/WebSearchTool/WebSearchTool.ts +9 -313
  395. package/tui/src/tools/WebSearchTool/call.ts +33 -0
  396. package/tui/src/tools/WebSearchTool/responseMapping.ts +190 -0
  397. package/tui/src/tools/WebSearchTool/resultBlock.ts +47 -0
  398. package/tui/src/tools/WebSearchTool/schemas.ts +47 -0
  399. package/tui/src/tools/WebSearchTool/toolSchema.ts +12 -0
  400. package/tui/src/tools/WorkspaceToolAdapter/WorkspaceToolAdapter.ts +79 -0
  401. package/tui/src/tools/WorkspaceToolAdapter/allowedRootPolicy.ts +85 -0
  402. package/tui/src/tools/WorkspaceToolAdapter/documentFormatGuards.ts +73 -0
  403. package/tui/src/tools/WorkspaceToolAdapter/inputNormalization.ts +105 -0
  404. package/tui/src/tools/WorkspaceToolAdapter/mcpExposurePolicy.ts +64 -0
  405. package/tui/src/tools/WorkspaceToolAdapter/toolDefFactory.ts +215 -0
  406. package/tui/src/tools/WorkspaceToolAdapter/toolNames.ts +6 -0
  407. package/tui/src/tools/WorkspaceToolAdapter/workspacePolicy.ts +15 -0
  408. package/tui/src/tools/_shared/dispatchPrimitive.ts +6 -6
  409. package/tui/src/tools/_shared/documentChangeToPatch.ts +125 -0
  410. package/tui/src/tools/_shared/documentDispatchArguments.ts +87 -0
  411. package/tui/src/tools/_shared/documentPrimitiveTimeout.ts +13 -0
  412. package/tui/src/tools/_shared/documentToolResultRender.ts +98 -0
  413. package/tui/src/tools/_shared/pendingCallRegistry.ts +1 -6
  414. package/tui/src/tools/_shared/rootPrimitiveInput.ts +1 -0
  415. package/tui/src/tools/_shared/toolChoiceRepair/documentCompletionPatterns.ts +58 -0
  416. package/tui/src/tools/_shared/toolChoiceRepair/documentCompletionPrompt.ts +271 -0
  417. package/tui/src/tools/_shared/toolChoiceRepair/documentRepair.ts +452 -0
  418. package/tui/src/tools/_shared/toolChoiceRepair/messageAccess.ts +80 -0
  419. package/tui/src/tools/_shared/toolChoiceRepair/publicDataRepair.ts +92 -0
  420. package/tui/src/tools/_shared/toolChoiceRepair/supportRepair.ts +135 -0
  421. package/tui/src/tools/_shared/toolChoiceRepair.ts +55 -860
  422. package/tui/src/tools/shared/mockDisclaimer.ts +1 -1
  423. package/tui/src/tools.ts +39 -190
  424. package/tui/src/types/fileSuggestion.ts +4 -26
  425. package/tui/src/types/generated/events_mono/claude_code/v1/claude_code_internal_event.ts +186 -148
  426. package/tui/src/types/generated/events_mono/common/v1/auth.ts +25 -11
  427. package/tui/src/types/generated/events_mono/growthbook/v1/growthbook_experiment_event.ts +47 -30
  428. package/tui/src/types/generated/google/protobuf/timestamp.ts +21 -7
  429. package/tui/src/types/message.ts +80 -102
  430. package/tui/src/types/messageQueueTypes.ts +6 -28
  431. package/tui/src/types/notebook.ts +16 -38
  432. package/tui/src/types/statusLine.ts +4 -26
  433. package/tui/src/types/tools.ts +24 -46
  434. package/tui/src/types/utils.ts +6 -28
  435. package/tui/src/upstreamproxy/relay.ts +7 -3
  436. package/tui/src/upstreamproxy/upstreamproxy.ts +1 -1
  437. package/tui/src/utils/assistantMessageFactories.ts +9 -3
  438. package/tui/src/utils/auth.ts +129 -139
  439. package/tui/src/utils/bash/ast.ts +23 -23
  440. package/tui/src/utils/bash/bashParser.ts +5 -5
  441. package/tui/src/utils/billing.ts +1 -1
  442. package/tui/src/utils/collapseReadSearch.ts +3 -3
  443. package/tui/src/utils/cronTasks.ts +1 -1
  444. package/tui/src/utils/execFileNoThrow.ts +1 -1
  445. package/tui/src/utils/filePersistence/types.ts +16 -38
  446. package/tui/src/utils/forkedAgent.ts +1 -1
  447. package/tui/src/utils/gracefulShutdown.ts +4 -4
  448. package/tui/src/utils/heapDumpService.ts +12 -8
  449. package/tui/src/utils/hooks/apiQueryHookHelper.ts +1 -1
  450. package/tui/src/utils/hooks/execPromptHook.ts +1 -1
  451. package/tui/src/utils/hooks/skillImprovement.ts +1 -1
  452. package/tui/src/utils/mcp/dateTimeParser.ts +1 -1
  453. package/tui/src/utils/messages.ts +18 -0
  454. package/tui/src/utils/migrateSessions.ts +3 -3
  455. package/tui/src/utils/model/model.ts +6 -6
  456. package/tui/src/utils/permissions/yoloClassifier.ts +1 -1
  457. package/tui/src/utils/plugins/headlessPluginInstall.ts +1 -1
  458. package/tui/src/utils/plugins/mcpPluginIntegration.ts +1 -1
  459. package/tui/src/utils/plugins/mcpbHandler.ts +1 -1
  460. package/tui/src/utils/plugins/pluginLoader.ts +8 -8
  461. package/tui/src/utils/protectedNamespace.ts +5 -3
  462. package/tui/src/utils/rawJsonToolCall.ts +242 -0
  463. package/tui/src/utils/ripgrep.ts +16 -7
  464. package/tui/src/utils/sessionTitle.ts +1 -1
  465. package/tui/src/utils/settings/permissionValidation.ts +14 -2
  466. package/tui/src/utils/shell/prefix.ts +1 -1
  467. package/tui/src/utils/sideQuery.ts +1 -1
  468. package/tui/src/utils/systemThemeWatcher.ts +13 -3
  469. package/tui/src/utils/teleport.tsx +1 -1
  470. package/uv.lock +400 -14
  471. package/tui/src/services/api/claude.ts +0 -3540
  472. package/tui/src/tools/_shared/directPublicDataGuard.ts +0 -362
  473. package/tui/src/tools/_shared/kmaAnalysisGuard.ts +0 -197
  474. package/tui/src/tools/_shared/kmaAviationGuard.ts +0 -70
  475. package/tui/src/tools/_shared/nmcAedGuard.ts +0 -234
  476. package/tui/src/tools/_shared/protectedCheckGuard.ts +0 -207
  477. package/tui/src/tools/_shared/textToolCallGuard.ts +0 -91
@@ -9,112 +9,13 @@
9
9
  import type { ToolPermissionContext } from '../../Tool.js'
10
10
  import type { PermissionResult } from '../../utils/permissions/PermissionResult.js'
11
11
  import type { ParsedPowerShellCommand } from '../../utils/powershell/parser.js'
12
- import {
13
- deriveSecurityFlags,
14
- getPipelineSegments,
15
- PS_TOKENIZER_DASH_CHARS,
16
- } from '../../utils/powershell/parser.js'
17
- import {
18
- argLeaksValue,
19
- isAllowlistedPipelineTail,
20
- isCwdChangingCmdlet,
21
- isSafeOutputCommand,
22
- resolveToCanonical,
23
- } from './readOnlyValidation.js'
12
+ import { deriveSecurityFlags } from '../../utils/powershell/parser.js'
13
+ import { getBypassImmuneShellPermissionResult } from '../BashTool/shellPermissionGauntlet.js'
14
+ import { checkAcceptEditsCommands } from './acceptEditsCommandValidation.js'
15
+ import { getDestructiveCommandWarning } from './destructiveCommandWarning.js'
16
+ import { POWERSHELL_TOOL_NAME } from './toolName.js'
24
17
 
25
- /**
26
- * Filesystem-modifying cmdlets that are auto-allowed in acceptEdits mode.
27
- * Stored as canonical (lowercase) cmdlet names.
28
- *
29
- * Tier 3 cmdlets with complex parameter binding removed — they fall through to
30
- * 'ask'. Only simple write cmdlets (first positional = -Path) are auto-allowed
31
- * here, and they get path validation via CMDLET_PATH_CONFIG in pathValidation.ts.
32
- */
33
- const ACCEPT_EDITS_ALLOWED_CMDLETS = new Set([
34
- 'set-content',
35
- 'add-content',
36
- 'remove-item',
37
- 'clear-content',
38
- ])
39
-
40
- function isAcceptEditsAllowedCmdlet(name: string): boolean {
41
- // resolveToCanonical handles aliases via COMMON_ALIASES, so e.g. 'rm' → 'remove-item',
42
- // 'ac' → 'add-content'. Any alias that resolves to an allowed cmdlet is automatically
43
- // allowed. Tier 3 cmdlets (new-item, copy-item, move-item, etc.) and their aliases
44
- // (mkdir, ni, cp, mv, etc.) resolve to cmdlets NOT in the set and fall through to 'ask'.
45
- const canonical = resolveToCanonical(name)
46
- return ACCEPT_EDITS_ALLOWED_CMDLETS.has(canonical)
47
- }
48
-
49
- /**
50
- * New-Item -ItemType values that create filesystem links (reparse points or
51
- * hard links). All three redirect path resolution at runtime — symbolic links
52
- * and junctions are directory/file reparse points; hard links alias a file's
53
- * inode. Any of these let a later relative-path write land outside the
54
- * validator's view.
55
- */
56
- const LINK_ITEM_TYPES = new Set(['symboliclink', 'junction', 'hardlink'])
57
-
58
- /**
59
- * Check if a lowered, dash-normalized arg (colon-value stripped) is an
60
- * unambiguous PowerShell abbreviation of New-Item's -ItemType or -Type param.
61
- * Min prefixes: `-it` (avoids ambiguity with other New-Item params), `-ty`
62
- * (avoids `-t` colliding with `-Target`).
63
- */
64
- function isItemTypeParamAbbrev(p: string): boolean {
65
- return (
66
- (p.length >= 3 && '-itemtype'.startsWith(p)) ||
67
- (p.length >= 3 && '-type'.startsWith(p))
68
- )
69
- }
70
-
71
- /**
72
- * Detects New-Item creating a filesystem link (-ItemType SymbolicLink /
73
- * Junction / HardLink, or the -Type alias). Links poison subsequent path
74
- * resolution the same way Set-Location/New-PSDrive do: a relative path
75
- * through the link resolves to the link target, not the validator's view.
76
- * Finding #18.
77
- *
78
- * Handles PS parameter abbreviation (`-it`, `-ite`, ... `-itemtype`; `-ty`,
79
- * `-typ`, `-type`), unicode dash prefixes (en-dash/em-dash/horizontal-bar),
80
- * and colon-bound values (`-it:Junction`).
81
- */
82
- export function isSymlinkCreatingCommand(cmd: {
83
- name: string
84
- args: string[]
85
- }): boolean {
86
- const canonical = resolveToCanonical(cmd.name)
87
- if (canonical !== 'new-item') return false
88
- for (let i = 0; i < cmd.args.length; i++) {
89
- const raw = cmd.args[i] ?? ''
90
- if (raw.length === 0) continue
91
- // Normalize unicode dash prefixes (–, —, ―) and forward-slash (PS 5.1
92
- // parameter prefix) → ASCII `-` so prefix comparison works. PS tokenizer
93
- // treats all four dash chars plus `/` as parameter markers. (bug #26)
94
- const normalized =
95
- PS_TOKENIZER_DASH_CHARS.has(raw[0]!) || raw[0] === '/'
96
- ? '-' + raw.slice(1)
97
- : raw
98
- const lower = normalized.toLowerCase()
99
- // Split colon-bound value: -it:SymbolicLink → param='-it', val='symboliclink'
100
- const colonIdx = lower.indexOf(':', 1)
101
- const paramRaw = colonIdx > 0 ? lower.slice(0, colonIdx) : lower
102
- // Strip backtick escapes: -Item`Type → -ItemType (bug #22)
103
- const param = paramRaw.replace(/`/g, '')
104
- if (!isItemTypeParamAbbrev(param)) continue
105
- const rawVal =
106
- colonIdx > 0
107
- ? lower.slice(colonIdx + 1)
108
- : (cmd.args[i + 1]?.toLowerCase() ?? '')
109
- // Strip backtick escapes from colon-bound value: -it:Sym`bolicLink → symboliclink
110
- // Mirrors the param-name strip at L103. Space-separated args use .value
111
- // (backtick-resolved by .NET parser), but colon-bound uses .text (raw source).
112
- // Strip surrounding quotes: -it:'SymbolicLink' or -it:"Junction" (bug #6)
113
- const val = rawVal.replace(/`/g, '').replace(/^['"]|['"]$/g, '')
114
- if (LINK_ITEM_TYPES.has(val)) return true
115
- }
116
- return false
117
- }
18
+ export { isSymlinkCreatingCommand } from './symlinkModeValidation.js'
118
19
 
119
20
  /**
120
21
  * Checks if commands should be handled differently based on the current permission mode.
@@ -134,11 +35,24 @@ export function checkPermissionMode(
134
35
  parsed: ParsedPowerShellCommand,
135
36
  toolPermissionContext: ToolPermissionContext,
136
37
  ): PermissionResult {
137
- // Skip bypass and dontAsk modes (handled elsewhere)
138
- if (
139
- toolPermissionContext.mode === 'bypassPermissions' ||
140
- toolPermissionContext.mode === 'dontAsk'
141
- ) {
38
+ if (toolPermissionContext.mode === 'bypassPermissions') {
39
+ const bypassImmuneResult = getBypassImmuneShellPermissionResult(
40
+ input.command,
41
+ POWERSHELL_TOOL_NAME,
42
+ toolPermissionContext,
43
+ getDestructiveCommandWarning,
44
+ )
45
+ if (bypassImmuneResult !== null) {
46
+ return bypassImmuneResult
47
+ }
48
+
49
+ return {
50
+ behavior: 'passthrough',
51
+ message: 'Mode is handled in main permission flow',
52
+ }
53
+ }
54
+
55
+ if (toolPermissionContext.mode === 'dontAsk') {
142
56
  return {
143
57
  behavior: 'passthrough',
144
58
  message: 'Mode is handled in main permission flow',
@@ -179,226 +93,5 @@ export function checkPermissionMode(
179
93
  }
180
94
  }
181
95
 
182
- const segments = getPipelineSegments(parsed)
183
-
184
- // SECURITY: Empty segments with valid parse = no commands to check, don't auto-allow
185
- if (segments.length === 0) {
186
- return {
187
- behavior: 'passthrough',
188
- message: 'No commands found to validate for acceptEdits mode',
189
- }
190
- }
191
-
192
- // SECURITY: Compound cwd desync guard — BashTool parity.
193
- // When any statement in a compound contains Set-Location/Push-Location/Pop-Location
194
- // (or aliases like cd, sl, chdir, pushd, popd), the cwd changes between statements.
195
- // Path validation resolves relative paths against the stale process cwd, so a write
196
- // cmdlet in a later statement targets a different directory than the validator checked.
197
- // Example: `Set-Location ./.claude; Set-Content ./settings.json '...'` — the validator
198
- // sees ./settings.json as /project/settings.json, but PowerShell writes to
199
- // /project/.claude/settings.json. Refuse to auto-allow any write operation in a
200
- // compound that contains a cwd-changing command. This matches BashTool's
201
- // compoundCommandHasCd guard (BashTool/pathValidation.ts:630-655).
202
- const totalCommands = segments.reduce(
203
- (sum, seg) => sum + seg.commands.length,
204
- 0,
205
- )
206
- if (totalCommands > 1) {
207
- let hasCdCommand = false
208
- let hasSymlinkCreate = false
209
- let hasWriteCommand = false
210
- for (const seg of segments) {
211
- for (const cmd of seg.commands) {
212
- if (cmd.elementType !== 'CommandAst') continue
213
- if (isCwdChangingCmdlet(cmd.name)) hasCdCommand = true
214
- if (isSymlinkCreatingCommand(cmd)) hasSymlinkCreate = true
215
- if (isAcceptEditsAllowedCmdlet(cmd.name)) hasWriteCommand = true
216
- }
217
- }
218
- if (hasCdCommand && hasWriteCommand) {
219
- return {
220
- behavior: 'passthrough',
221
- message:
222
- 'Compound command contains a directory-changing command (Set-Location/Push-Location/Pop-Location) with a write operation — cannot auto-allow because path validation uses stale cwd',
223
- }
224
- }
225
- // SECURITY: Link-create compound guard (finding #18). Mirrors the cd
226
- // guard above. `New-Item -ItemType SymbolicLink -Path ./link -Value /etc;
227
- // Get-Content ./link/passwd` — path validation resolves ./link/passwd
228
- // against cwd (no link there at validation time), but runtime follows
229
- // the just-created link to /etc/passwd. Same TOCTOU shape as cwd desync.
230
- // Applies to SymbolicLink, Junction, and HardLink — all three redirect
231
- // path resolution at runtime.
232
- // No `hasWriteCommand` requirement: read-through-symlink is equally
233
- // dangerous (exfil via Get-Content ./link/etc/shadow), and any other
234
- // command using paths after a just-created link is unvalidatable.
235
- if (hasSymlinkCreate) {
236
- return {
237
- behavior: 'passthrough',
238
- message:
239
- 'Compound command creates a filesystem link (New-Item -ItemType SymbolicLink/Junction/HardLink) — cannot auto-allow because path validation cannot follow just-created links',
240
- }
241
- }
242
- }
243
-
244
- for (const segment of segments) {
245
- for (const cmd of segment.commands) {
246
- if (cmd.elementType !== 'CommandAst') {
247
- // SECURITY: This guard is load-bearing for THREE cases. Do not narrow it.
248
- //
249
- // 1. Expression pipeline sources (designed): '/etc/passwd' | Remove-Item
250
- // — the string literal is CommandExpressionAst, piped value binds to
251
- // -Path. We cannot statically know what path it represents.
252
- //
253
- // 2. Control-flow statements (accidental but relied upon):
254
- // foreach ($x in ...) { Remove-Item $x }. Non-PipelineAst statements
255
- // produce a synthetic CommandExpressionAst entry in segment.commands
256
- // (parser.ts transformStatement). Without this guard, Remove-Item $x
257
- // in nestedCommands would be checked below and auto-allowed — but $x
258
- // is a loop-bound variable we cannot validate.
259
- //
260
- // 3. Non-PipelineAst redirection coverage (accidental): cmd && cmd2 > /tmp
261
- // also produces a synthetic element here. isReadOnlyCommand relies on
262
- // the same accident (its allowlist rejects the synthetic element's
263
- // full-text name), so both paths fail safe together.
264
- return {
265
- behavior: 'passthrough',
266
- message: `Pipeline contains expression source (${cmd.elementType}) that cannot be statically validated`,
267
- }
268
- }
269
- // SECURITY: nameType is computed from the raw name before stripModulePrefix.
270
- // 'application' = raw name had path chars (. \\ /). scripts\\Remove-Item
271
- // strips to Remove-Item and would match ACCEPT_EDITS_ALLOWED_CMDLETS below,
272
- // but PowerShell runs scripts\\Remove-Item.ps1. Same gate as isAllowlistedCommand.
273
- if (cmd.nameType === 'application') {
274
- return {
275
- behavior: 'passthrough',
276
- message: `Command '${cmd.name}' resolved from a path-like name and requires approval`,
277
- }
278
- }
279
- // SECURITY: elementTypes whitelist — same as isAllowlistedCommand.
280
- // deriveSecurityFlags above checks hasSubExpressions/etc. but does NOT
281
- // flag bare Variable/Other elementTypes. `Remove-Item $env:PATH`:
282
- // elementTypes = ['StringConstant', 'Variable']
283
- // deriveSecurityFlags: no subexpression → passes
284
- // checkPathConstraints: resolves literal text '$env:PATH' as relative
285
- // path → cwd/$env:PATH → inside cwd → allow
286
- // RUNTIME: PowerShell expands $env:PATH → deletes actual env value path
287
- // isAllowlistedCommand rejects non-StringConstant/Parameter; this is the
288
- // acceptEdits parity gate.
289
- //
290
- // Also check colon-bound expression metachars (same as isAllowlistedCommand's
291
- // colon-bound check). `Remove-Item -Path:(1 > /tmp/x)`:
292
- // elementTypes = ['StringConstant', 'Parameter'] — passes whitelist above
293
- // deriveSecurityFlags: ParenExpressionAst in .Argument not detected by
294
- // Get-SecurityPatterns (ParenExpressionAst not in FindAll filter)
295
- // checkPathConstraints: literal text '-Path:(1 > /tmp/x)' not a path
296
- // RUNTIME: paren evaluates, redirection writes /tmp/x → arbitrary write
297
- if (cmd.elementTypes) {
298
- for (let i = 1; i < cmd.elementTypes.length; i++) {
299
- const t = cmd.elementTypes[i]
300
- if (t !== 'StringConstant' && t !== 'Parameter') {
301
- return {
302
- behavior: 'passthrough',
303
- message: `Command argument has unvalidatable type (${t}) — variable paths cannot be statically resolved`,
304
- }
305
- }
306
- if (t === 'Parameter') {
307
- // elementTypes[i] ↔ args[i-1] (elementTypes[0] is the command name).
308
- const arg = cmd.args[i - 1] ?? ''
309
- const colonIdx = arg.indexOf(':')
310
- if (colonIdx > 0 && /[$(@{[]/.test(arg.slice(colonIdx + 1))) {
311
- return {
312
- behavior: 'passthrough',
313
- message:
314
- 'Colon-bound parameter contains an expression that cannot be statically validated',
315
- }
316
- }
317
- }
318
- }
319
- }
320
- // Safe output cmdlets (Out-Null, etc.) and allowlisted pipeline-tail
321
- // transformers (Format-*, Measure-Object, Select-Object, etc.) don't
322
- // affect the semantics of the preceding command. Skip them so
323
- // `Remove-Item ./foo | Out-Null` or `Set-Content ./foo hi | Format-Table`
324
- // auto-allows the same as the bare write cmdlet. isAllowlistedPipelineTail
325
- // is the narrow fallback for cmdlets moved from SAFE_OUTPUT_CMDLETS to
326
- // CMDLET_ALLOWLIST (argLeaksValue validates their args).
327
- if (
328
- isSafeOutputCommand(cmd.name) ||
329
- isAllowlistedPipelineTail(cmd, input.command)
330
- ) {
331
- continue
332
- }
333
- if (!isAcceptEditsAllowedCmdlet(cmd.name)) {
334
- return {
335
- behavior: 'passthrough',
336
- message: `No mode-specific handling for '${cmd.name}' in acceptEdits mode`,
337
- }
338
- }
339
- // SECURITY: Reject commands with unclassifiable argument types. 'Other'
340
- // covers HashtableAst, ConvertExpressionAst, BinaryExpressionAst — all
341
- // can contain nested redirections or code that the parser cannot fully
342
- // decompose. isAllowlistedCommand (readOnlyValidation.ts) already
343
- // enforces this whitelist via argLeaksValue; this closes the same gap
344
- // in acceptEdits mode. Without this, @{k='payload' > ~/.bashrc} as a
345
- // -Value argument passes because HashtableAst maps to 'Other'.
346
- // argLeaksValue also catches colon-bound variables (-Flag:$env:SECRET).
347
- if (argLeaksValue(cmd.name, cmd)) {
348
- return {
349
- behavior: 'passthrough',
350
- message: `Arguments in '${cmd.name}' cannot be statically validated in acceptEdits mode`,
351
- }
352
- }
353
- }
354
-
355
- // Also check nested commands from control flow statements
356
- if (segment.nestedCommands) {
357
- for (const cmd of segment.nestedCommands) {
358
- if (cmd.elementType !== 'CommandAst') {
359
- // SECURITY: Same as above — non-CommandAst element in nested commands
360
- // (control flow bodies) cannot be statically validated as a path source.
361
- return {
362
- behavior: 'passthrough',
363
- message: `Nested expression element (${cmd.elementType}) cannot be statically validated`,
364
- }
365
- }
366
- if (cmd.nameType === 'application') {
367
- return {
368
- behavior: 'passthrough',
369
- message: `Nested command '${cmd.name}' resolved from a path-like name and requires approval`,
370
- }
371
- }
372
- if (
373
- isSafeOutputCommand(cmd.name) ||
374
- isAllowlistedPipelineTail(cmd, input.command)
375
- ) {
376
- continue
377
- }
378
- if (!isAcceptEditsAllowedCmdlet(cmd.name)) {
379
- return {
380
- behavior: 'passthrough',
381
- message: `No mode-specific handling for '${cmd.name}' in acceptEdits mode`,
382
- }
383
- }
384
- // SECURITY: Same argLeaksValue check as the main command loop above.
385
- if (argLeaksValue(cmd.name, cmd)) {
386
- return {
387
- behavior: 'passthrough',
388
- message: `Arguments in nested '${cmd.name}' cannot be statically validated in acceptEdits mode`,
389
- }
390
- }
391
- }
392
- }
393
- }
394
-
395
- // All commands are filesystem-modifying cmdlets -- auto-allow
396
- return {
397
- behavior: 'allow',
398
- updatedInput: input,
399
- decisionReason: {
400
- type: 'mode',
401
- mode: 'acceptEdits',
402
- },
403
- }
96
+ return checkAcceptEditsCommands(input, parsed)
404
97
  }
@@ -0,0 +1,42 @@
1
+ import { copyFile, link, stat as fsStat, truncate as fsTruncate } from 'fs/promises';
2
+ import type { ExecResult } from '../../utils/ShellCommand.js';
3
+ import { ensureToolResultsDir, getToolResultPath } from '../../utils/toolResultStorage.js';
4
+
5
+ const MAX_PERSISTED_SIZE = 64 * 1024 * 1024;
6
+
7
+ type PersistedOutput = {
8
+ readonly path?: string;
9
+ readonly size?: number;
10
+ };
11
+
12
+ export async function persistLargePowerShellOutput(result: ExecResult): Promise<PersistedOutput> {
13
+ if (!result.outputFilePath || !result.outputTaskId) {
14
+ return {};
15
+ }
16
+ try {
17
+ const fileStat = await fsStat(result.outputFilePath);
18
+ await ensureToolResultsDir();
19
+ const dest = getToolResultPath(result.outputTaskId, false);
20
+ if (fileStat.size > MAX_PERSISTED_SIZE) {
21
+ await fsTruncate(result.outputFilePath, MAX_PERSISTED_SIZE);
22
+ }
23
+ try {
24
+ await link(result.outputFilePath, dest);
25
+ } catch (error) {
26
+ if (error instanceof Error) {
27
+ await copyFile(result.outputFilePath, dest);
28
+ } else {
29
+ throw error;
30
+ }
31
+ }
32
+ return {
33
+ path: dest,
34
+ size: fileStat.size
35
+ };
36
+ } catch (error) {
37
+ if (error instanceof Error) {
38
+ return {};
39
+ }
40
+ throw error;
41
+ }
42
+ }
@@ -0,0 +1,28 @@
1
+ import type { ToolUseContext } from '../../Tool.js';
2
+ import type { PermissionResult } from '../../utils/permissions/PermissionResult.js';
3
+ import { getBypassImmuneShellPermissionResult } from '../BashTool/shellPermissionGauntlet.js';
4
+ import { getDestructiveCommandWarning } from './destructiveCommandWarning.js';
5
+ import { powershellToolHasPermission } from './powershellPermissions.js';
6
+ import { hasSyncSecurityConcerns, isReadOnlyCommand } from './readOnlyValidation.js';
7
+ import { POWERSHELL_TOOL_NAME } from './toolName.js';
8
+ import type { PowerShellToolInput } from './schemas.js';
9
+
10
+ export function isPowerShellReadOnly(input: PowerShellToolInput): boolean {
11
+ if (hasSyncSecurityConcerns(input.command)) {
12
+ return false;
13
+ }
14
+ return isReadOnlyCommand(input.command);
15
+ }
16
+
17
+ export async function checkPowerShellPermissions(input: PowerShellToolInput, context: ToolUseContext): Promise<PermissionResult> {
18
+ const bypassImmuneResult = getBypassImmuneShellPermissionResult(
19
+ input.command,
20
+ POWERSHELL_TOOL_NAME,
21
+ context.getAppState().toolPermissionContext,
22
+ getDestructiveCommandWarning
23
+ );
24
+ if (bypassImmuneResult !== null) {
25
+ return bypassImmuneResult;
26
+ }
27
+ return powershellToolHasPermission(input, context);
28
+ }
@@ -0,0 +1,31 @@
1
+ import { createRequire } from 'node:module'
2
+ import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs'
3
+ import type { Out } from './schemas.js'
4
+
5
+ type PowerShellResultRuntime = {
6
+ readonly mapPowerShellToolResultToBlock: (
7
+ output: Out,
8
+ toolUseID: string,
9
+ ) => ToolResultBlockParam
10
+ }
11
+
12
+ const requireModule = createRequire(import.meta.url)
13
+ let cachedRuntime: PowerShellResultRuntime | undefined
14
+
15
+ function isPowerShellResultRuntime(
16
+ value: unknown,
17
+ ): value is PowerShellResultRuntime {
18
+ if (typeof value !== 'object' || value === null) return false
19
+ const module = value as Partial<Record<keyof PowerShellResultRuntime, unknown>>
20
+ return typeof module.mapPowerShellToolResultToBlock === 'function'
21
+ }
22
+
23
+ export function loadPowerShellResultRuntime(): PowerShellResultRuntime {
24
+ if (cachedRuntime !== undefined) return cachedRuntime
25
+ const loaded: unknown = requireModule('./resultMapping.js')
26
+ if (!isPowerShellResultRuntime(loaded)) {
27
+ throw new Error('PowerShell result module did not expose expected mapper')
28
+ }
29
+ cachedRuntime = loaded
30
+ return loaded
31
+ }
@@ -0,0 +1,75 @@
1
+ import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs';
2
+ import { getTaskOutputPath } from '../../utils/task/diskOutput.js';
3
+ import { buildLargeToolResultMessage, generatePreview, PREVIEW_SIZE_BYTES } from '../../utils/toolResultStorage.js';
4
+ import { buildImageToolResult } from '../BashTool/shellOutputUtils.js';
5
+ import type { Out } from './schemas.js';
6
+
7
+ const EOL = '\n';
8
+ const ASSISTANT_BLOCKING_BUDGET_MS = 15_000;
9
+
10
+ export function mapPowerShellToolResultToBlock({
11
+ interrupted,
12
+ stdout,
13
+ stderr,
14
+ isImage,
15
+ persistedOutputPath,
16
+ persistedOutputSize,
17
+ backgroundTaskId,
18
+ backgroundedByUser,
19
+ assistantAutoBackgrounded
20
+ }: Out, toolUseID: string): ToolResultBlockParam {
21
+ if (isImage) {
22
+ const block = buildImageToolResult(stdout, toolUseID);
23
+ if (block) return block;
24
+ }
25
+ let processedStdout = stdout;
26
+ if (persistedOutputPath) {
27
+ const trimmed = stdout ? stdout.replace(/^(\s*\n)+/, '').trimEnd() : '';
28
+ const preview = generatePreview(trimmed, PREVIEW_SIZE_BYTES);
29
+ processedStdout = buildLargeToolResultMessage({
30
+ filepath: persistedOutputPath,
31
+ originalSize: persistedOutputSize ?? 0,
32
+ isJson: false,
33
+ preview: preview.preview,
34
+ hasMore: preview.hasMore
35
+ });
36
+ } else if (stdout) {
37
+ processedStdout = stdout.replace(/^(\s*\n)+/, '').trimEnd();
38
+ }
39
+ let errorMessage = stderr.trim();
40
+ if (interrupted) {
41
+ if (stderr) errorMessage += EOL;
42
+ errorMessage += '<error>Command was aborted before completion</error>';
43
+ }
44
+ const backgroundInfo = formatBackgroundInfo({
45
+ backgroundTaskId,
46
+ backgroundedByUser,
47
+ assistantAutoBackgrounded
48
+ });
49
+ return {
50
+ tool_use_id: toolUseID,
51
+ type: 'tool_result' as const,
52
+ content: [processedStdout, errorMessage, backgroundInfo].filter(Boolean).join('\n'),
53
+ is_error: interrupted
54
+ };
55
+ }
56
+
57
+ type BackgroundInfoInput = Pick<Out, 'backgroundTaskId' | 'backgroundedByUser' | 'assistantAutoBackgrounded'>;
58
+
59
+ function formatBackgroundInfo({
60
+ backgroundTaskId,
61
+ backgroundedByUser,
62
+ assistantAutoBackgrounded
63
+ }: BackgroundInfoInput): string {
64
+ if (!backgroundTaskId) {
65
+ return '';
66
+ }
67
+ const outputPath = getTaskOutputPath(backgroundTaskId);
68
+ if (assistantAutoBackgrounded) {
69
+ return `Command exceeded the assistant-mode blocking budget (${ASSISTANT_BLOCKING_BUDGET_MS / 1000}s) and was moved to the background with ID: ${backgroundTaskId}. It is still running — you will be notified when it completes. Output is being written to: ${outputPath}. In assistant mode, delegate long-running work to a subagent or use run_in_background to keep this conversation responsive.`;
70
+ }
71
+ if (backgroundedByUser) {
72
+ return `Command was manually backgrounded by user with ID: ${backgroundTaskId}. Output is being written to: ${outputPath}`;
73
+ }
74
+ return `Command running in background with ID: ${backgroundTaskId}. Output is being written to: ${outputPath}`;
75
+ }
@@ -0,0 +1,40 @@
1
+ import { z } from 'zod/v4';
2
+ import { isEnvTruthy } from '../../utils/envUtils.js';
3
+ import { lazySchema } from '../../utils/lazySchema.js';
4
+ import { semanticBoolean } from '../../utils/semanticBoolean.js';
5
+ import { semanticNumber } from '../../utils/semanticNumber.js';
6
+ import { getMaxBashTimeoutMs } from '../../utils/timeouts.js';
7
+
8
+ export const isBackgroundTasksDisabled =
9
+ // eslint-disable-next-line custom-rules/no-process-env-top-level -- Intentional: schema must be defined at module load
10
+ isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS);
11
+
12
+ export const fullInputSchema = lazySchema(() => z.strictObject({
13
+ command: z.string().describe('The PowerShell command to execute'),
14
+ timeout: semanticNumber(z.number().optional()).describe(`Optional timeout in milliseconds (max ${getMaxBashTimeoutMs()})`),
15
+ description: z.string().optional().describe('Clear, concise description of what this command does in active voice.'),
16
+ run_in_background: semanticBoolean(z.boolean().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),
17
+ dangerouslyDisableSandbox: semanticBoolean(z.boolean().optional()).describe('Set this to true to dangerously override sandbox mode and run commands without sandboxing.')
18
+ }));
19
+
20
+ export const inputSchema = lazySchema(() => isBackgroundTasksDisabled ? fullInputSchema().omit({
21
+ run_in_background: true
22
+ }) : fullInputSchema());
23
+
24
+ export const outputSchema = lazySchema(() => z.object({
25
+ stdout: z.string().describe('The standard output of the command'),
26
+ stderr: z.string().describe('The standard error output of the command'),
27
+ interrupted: z.boolean().describe('Whether the command was interrupted'),
28
+ returnCodeInterpretation: z.string().optional().describe('Semantic interpretation for non-error exit codes with special meaning'),
29
+ isImage: z.boolean().optional().describe('Flag to indicate if stdout contains image data'),
30
+ persistedOutputPath: z.string().optional().describe('Path to persisted full output when too large for inline'),
31
+ persistedOutputSize: z.number().optional().describe('Total output size in bytes when persisted'),
32
+ backgroundTaskId: z.string().optional().describe('ID of the background task if command is running in background'),
33
+ backgroundedByUser: z.boolean().optional().describe('True if the user manually backgrounded the command with Ctrl+B'),
34
+ assistantAutoBackgrounded: z.boolean().optional().describe('True if the command was auto-backgrounded by the assistant-mode blocking budget')
35
+ }));
36
+
37
+ export type InputSchema = ReturnType<typeof inputSchema>;
38
+ export type PowerShellToolInput = z.infer<ReturnType<typeof fullInputSchema>>;
39
+ export type OutputSchema = ReturnType<typeof outputSchema>;
40
+ export type Out = z.infer<OutputSchema>;