@aria-cli/tools 1.0.9 → 1.0.11

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 (241) hide show
  1. package/package.json +9 -5
  2. package/src/__tests__/web-fetch-download.test.ts +0 -433
  3. package/src/__tests__/web-tools.test.ts +0 -619
  4. package/src/ask-user-interaction.ts +0 -33
  5. package/src/cache/web-cache.ts +0 -110
  6. package/src/definitions/arion.ts +0 -118
  7. package/src/definitions/browser/browser.ts +0 -502
  8. package/src/definitions/browser/index.ts +0 -5
  9. package/src/definitions/browser/pw-downloads.ts +0 -142
  10. package/src/definitions/browser/pw-interactions.ts +0 -282
  11. package/src/definitions/browser/pw-responses.ts +0 -98
  12. package/src/definitions/browser/pw-session.ts +0 -405
  13. package/src/definitions/browser/pw-shared.ts +0 -85
  14. package/src/definitions/browser/pw-snapshot.ts +0 -383
  15. package/src/definitions/browser/pw-state.ts +0 -101
  16. package/src/definitions/browser/types.ts +0 -203
  17. package/src/definitions/code-intelligence.ts +0 -526
  18. package/src/definitions/core.ts +0 -118
  19. package/src/definitions/delegation.ts +0 -567
  20. package/src/definitions/deploy.ts +0 -73
  21. package/src/definitions/filesystem.ts +0 -217
  22. package/src/definitions/frg.ts +0 -67
  23. package/src/definitions/index.ts +0 -28
  24. package/src/definitions/memory.ts +0 -150
  25. package/src/definitions/messaging.ts +0 -734
  26. package/src/definitions/meta.ts +0 -392
  27. package/src/definitions/network.ts +0 -179
  28. package/src/definitions/outlook.ts +0 -318
  29. package/src/definitions/patch/apply-patch.ts +0 -235
  30. package/src/definitions/patch/fuzzy-match.ts +0 -217
  31. package/src/definitions/patch/index.ts +0 -1
  32. package/src/definitions/patch/patch-parser.ts +0 -297
  33. package/src/definitions/patch/sandbox-paths.ts +0 -129
  34. package/src/definitions/process/index.ts +0 -5
  35. package/src/definitions/process/process-registry.ts +0 -303
  36. package/src/definitions/process/process.ts +0 -456
  37. package/src/definitions/process/pty-keys.ts +0 -298
  38. package/src/definitions/process/session-slug.ts +0 -147
  39. package/src/definitions/quip.ts +0 -225
  40. package/src/definitions/search.ts +0 -67
  41. package/src/definitions/session-history.ts +0 -79
  42. package/src/definitions/shell.ts +0 -202
  43. package/src/definitions/slack.ts +0 -211
  44. package/src/definitions/web.ts +0 -119
  45. package/src/executors/apply-patch.ts +0 -1035
  46. package/src/executors/arion.ts +0 -199
  47. package/src/executors/code-intelligence.ts +0 -1179
  48. package/src/executors/deploy.ts +0 -1066
  49. package/src/executors/filesystem.ts +0 -1428
  50. package/src/executors/frg-freshness.ts +0 -743
  51. package/src/executors/frg.ts +0 -394
  52. package/src/executors/index.ts +0 -280
  53. package/src/executors/learning-meta.ts +0 -1367
  54. package/src/executors/lsp-client.ts +0 -355
  55. package/src/executors/memory.ts +0 -978
  56. package/src/executors/meta.ts +0 -293
  57. package/src/executors/process-registry.ts +0 -570
  58. package/src/executors/pty-session-store.ts +0 -43
  59. package/src/executors/pty.ts +0 -342
  60. package/src/executors/restart.ts +0 -133
  61. package/src/executors/search-freshness.ts +0 -249
  62. package/src/executors/search-types.ts +0 -98
  63. package/src/executors/search.ts +0 -89
  64. package/src/executors/self-diagnose.ts +0 -552
  65. package/src/executors/session-history.ts +0 -435
  66. package/src/executors/shell-safety.ts +0 -519
  67. package/src/executors/shell.ts +0 -1243
  68. package/src/executors/utils.ts +0 -40
  69. package/src/executors/web.ts +0 -786
  70. package/src/extraction/content-extraction.ts +0 -281
  71. package/src/extraction/index.ts +0 -5
  72. package/src/headless-control-contract.ts +0 -1149
  73. package/src/index.ts +0 -788
  74. package/src/local-control-http-auth.ts +0 -2
  75. package/src/mcp/client.ts +0 -218
  76. package/src/mcp/connection.ts +0 -568
  77. package/src/mcp/index.ts +0 -11
  78. package/src/mcp/jsonrpc.ts +0 -195
  79. package/src/mcp/types.ts +0 -199
  80. package/src/network-control-adapter.ts +0 -88
  81. package/src/network-runtime/address-types.ts +0 -218
  82. package/src/network-runtime/db-owner-fencing.ts +0 -91
  83. package/src/network-runtime/delivery-receipts.ts +0 -372
  84. package/src/network-runtime/direct-endpoint-authority.ts +0 -35
  85. package/src/network-runtime/index.ts +0 -316
  86. package/src/network-runtime/local-control-contract.ts +0 -784
  87. package/src/network-runtime/node-store-contract.ts +0 -46
  88. package/src/network-runtime/pair-route-contract.ts +0 -97
  89. package/src/network-runtime/peer-capabilities.ts +0 -48
  90. package/src/network-runtime/peer-principal-ref.ts +0 -20
  91. package/src/network-runtime/peer-state-machine.ts +0 -160
  92. package/src/network-runtime/protocol-schemas.ts +0 -265
  93. package/src/network-runtime/runtime-bootstrap-contract.ts +0 -83
  94. package/src/outlook/desktop-session.ts +0 -409
  95. package/src/policy.ts +0 -171
  96. package/src/providers/brave.ts +0 -80
  97. package/src/providers/duckduckgo.ts +0 -199
  98. package/src/providers/exa.ts +0 -85
  99. package/src/providers/firecrawl.ts +0 -77
  100. package/src/providers/index.ts +0 -8
  101. package/src/providers/jina.ts +0 -70
  102. package/src/providers/router.ts +0 -121
  103. package/src/providers/search-provider.ts +0 -74
  104. package/src/providers/tavily.ts +0 -74
  105. package/src/quip/desktop-session.ts +0 -435
  106. package/src/registry/index.ts +0 -1
  107. package/src/registry/registry.ts +0 -905
  108. package/src/runtime-socket-local-control-client.ts +0 -632
  109. package/src/security/dns-normalization.ts +0 -34
  110. package/src/security/dns-pinning.ts +0 -138
  111. package/src/security/external-content.ts +0 -129
  112. package/src/security/ssrf.ts +0 -207
  113. package/src/slack/desktop-session.ts +0 -493
  114. package/src/tool-factory.ts +0 -91
  115. package/src/types.ts +0 -1341
  116. package/src/utils/retry.ts +0 -163
  117. package/src/utils/safe-parse-json.ts +0 -176
  118. package/src/utils/url.ts +0 -20
  119. package/tests/benchmarks/registry.bench.ts +0 -57
  120. package/tests/cache/web-cache.test.ts +0 -147
  121. package/tests/critical-integration.test.ts +0 -1465
  122. package/tests/definitions/apply-patch.test.ts +0 -586
  123. package/tests/definitions/browser.test.ts +0 -495
  124. package/tests/definitions/delegation-pause-resume.test.ts +0 -758
  125. package/tests/definitions/execution.test.ts +0 -671
  126. package/tests/definitions/messaging-inbox-scope.test.ts +0 -229
  127. package/tests/definitions/messaging.test.ts +0 -1468
  128. package/tests/definitions/outlook.test.ts +0 -30
  129. package/tests/definitions/process.test.ts +0 -469
  130. package/tests/definitions/slack.test.ts +0 -28
  131. package/tests/definitions/tool-inventory.test.ts +0 -218
  132. package/tests/e2e/delegation-quest-orchestration.e2e.test.ts +0 -433
  133. package/tests/e2e/memory-tool-discovery-contract.e2e.test.ts +0 -81
  134. package/tests/executors/apply-patch.test.ts +0 -538
  135. package/tests/executors/arion.test.ts +0 -309
  136. package/tests/executors/conversation-primitives.test.ts +0 -250
  137. package/tests/executors/deploy.test.ts +0 -746
  138. package/tests/executors/filesystem-tools.test.ts +0 -357
  139. package/tests/executors/filesystem.test.ts +0 -959
  140. package/tests/executors/frg-freshness.test.ts +0 -136
  141. package/tests/executors/frg-merge.test.ts +0 -70
  142. package/tests/executors/frg-session-content.test.ts +0 -40
  143. package/tests/executors/frg.test.ts +0 -56
  144. package/tests/executors/memory-bugfixes.test.ts +0 -257
  145. package/tests/executors/memory-real-memoria.integration.test.ts +0 -316
  146. package/tests/executors/memory.test.ts +0 -853
  147. package/tests/executors/meta-tools.test.ts +0 -411
  148. package/tests/executors/meta.test.ts +0 -683
  149. package/tests/executors/path-containment.test.ts +0 -51
  150. package/tests/executors/process-registry.test.ts +0 -505
  151. package/tests/executors/pty.test.ts +0 -664
  152. package/tests/executors/quest-security.test.ts +0 -249
  153. package/tests/executors/read-file-media.test.ts +0 -230
  154. package/tests/executors/recall-knowledge-schema.test.ts +0 -209
  155. package/tests/executors/recall-tags.test.ts +0 -278
  156. package/tests/executors/remember-null-safety.contract.test.ts +0 -41
  157. package/tests/executors/restart.test.ts +0 -67
  158. package/tests/executors/search-unified.test.ts +0 -381
  159. package/tests/executors/session-history.test.ts +0 -340
  160. package/tests/executors/session-transcript.test.ts +0 -561
  161. package/tests/executors/shell-abort.test.ts +0 -416
  162. package/tests/executors/shell-env-blocklist.test.ts +0 -648
  163. package/tests/executors/shell-env-process.test.ts +0 -245
  164. package/tests/executors/shell-process-registry.test.ts +0 -334
  165. package/tests/executors/shell-tools.test.ts +0 -393
  166. package/tests/executors/shell.test.ts +0 -690
  167. package/tests/executors/web-abort-vs-timeout.test.ts +0 -213
  168. package/tests/executors/web-integration.test.ts +0 -633
  169. package/tests/executors/web-symlink.test.ts +0 -18
  170. package/tests/executors/web.test.ts +0 -1400
  171. package/tests/executors/write-stdin.test.ts +0 -145
  172. package/tests/extraction/content-extraction.test.ts +0 -153
  173. package/tests/guards/tools-default-test-lane.integration.test.ts +0 -21
  174. package/tests/guards/tools-package-test-commands.e2e.test.ts +0 -43
  175. package/tests/guards/tools-test-lane-manifest.contract.test.ts +0 -76
  176. package/tests/guards/tools-vitest-workspace-alias.contract.test.ts +0 -63
  177. package/tests/helpers/async-waits.ts +0 -53
  178. package/tests/integration/headless-control-contract.integration.test.ts +0 -153
  179. package/tests/integration/memory-tool-schema-parity.integration.test.ts +0 -67
  180. package/tests/integration/meta-tools-round-trip.integration.test.ts +0 -506
  181. package/tests/integration/quest-round-trip.test.ts +0 -303
  182. package/tests/integration/registry-executor-flow.test.ts +0 -85
  183. package/tests/integration.test.ts +0 -177
  184. package/tests/loading-tier.test.ts +0 -126
  185. package/tests/mcp/client-reconnect.test.ts +0 -267
  186. package/tests/mcp/connection.test.ts +0 -846
  187. package/tests/mcp/injectable-logger.test.ts +0 -83
  188. package/tests/mcp/jsonrpc.test.ts +0 -109
  189. package/tests/mcp/lifecycle.test.ts +0 -879
  190. package/tests/network-runtime/address-types.contract.test.ts +0 -143
  191. package/tests/network-runtime/continuity-bind-schema.contract.test.ts +0 -203
  192. package/tests/network-runtime/local-control-contract.test.ts +0 -869
  193. package/tests/network-runtime/local-control-invite-token.contract.test.ts +0 -146
  194. package/tests/network-runtime/node-store-contract.test.ts +0 -11
  195. package/tests/network-runtime/pair-protocol-nodeid.contract.test.ts +0 -15
  196. package/tests/network-runtime/peer-state-machine.contract.test.ts +0 -148
  197. package/tests/network-runtime/protocol-schemas.contract.test.ts +0 -512
  198. package/tests/network-runtime/relay-pending-nodeid.contract.test.ts +0 -62
  199. package/tests/network-runtime/runtime-bootstrap-contract.test.ts +0 -227
  200. package/tests/network-runtime/runtime-socket-local-control-client.test.ts +0 -621
  201. package/tests/network-runtime/wait-for-message-script.test.ts +0 -288
  202. package/tests/parallel.test.ts +0 -71
  203. package/tests/policy.test.ts +0 -184
  204. package/tests/print-default-test-lane.ts +0 -14
  205. package/tests/print-test-lane-manifest.ts +0 -22
  206. package/tests/providers/brave.test.ts +0 -159
  207. package/tests/providers/duckduckgo.test.ts +0 -207
  208. package/tests/providers/exa.test.ts +0 -175
  209. package/tests/providers/firecrawl.test.ts +0 -168
  210. package/tests/providers/jina.test.ts +0 -144
  211. package/tests/providers/router.test.ts +0 -328
  212. package/tests/providers/tavily.test.ts +0 -165
  213. package/tests/registry/discovery.test.ts +0 -154
  214. package/tests/registry/injectable-logger.test.ts +0 -230
  215. package/tests/registry/input-validation.test.ts +0 -361
  216. package/tests/registry/interface-completeness.test.ts +0 -85
  217. package/tests/registry/mcp-integration.test.ts +0 -103
  218. package/tests/registry/mcp-read-only-hint.test.ts +0 -60
  219. package/tests/registry/memoria-discovery.test.ts +0 -390
  220. package/tests/registry/nested-validation.test.ts +0 -283
  221. package/tests/registry/pseudo-tool-filtering.test.ts +0 -258
  222. package/tests/registry/registration-lifecycle.test.ts +0 -133
  223. package/tests/registry-validation.test.ts +0 -424
  224. package/tests/registry.test.ts +0 -460
  225. package/tests/security/dns-pinning.test.ts +0 -162
  226. package/tests/security/external-content.test.ts +0 -144
  227. package/tests/security/ssrf.test.ts +0 -118
  228. package/tests/shell-safety-integration.test.ts +0 -32
  229. package/tests/shell-safety.test.ts +0 -365
  230. package/tests/slack/desktop-session.test.ts +0 -50
  231. package/tests/test-lane-manifest.ts +0 -440
  232. package/tests/test-utils.ts +0 -27
  233. package/tests/tool-factory.test.ts +0 -188
  234. package/tests/utils/retry.test.ts +0 -231
  235. package/tests/utils/url.test.ts +0 -63
  236. package/tsconfig.cjs.json +0 -24
  237. package/tsconfig.json +0 -12
  238. package/vitest.config.ts +0 -55
  239. package/vitest.e2e.config.ts +0 -24
  240. package/vitest.integration.config.ts +0 -24
  241. package/vitest.native.config.ts +0 -24
@@ -1,1243 +0,0 @@
1
- /**
2
- * @aria/tools - Shell tool executors
3
- *
4
- * Implementation of shell operations for ARIA tool system.
5
- */
6
-
7
- import { spawn } from "node:child_process";
8
- import { constants as osConstants } from "node:os";
9
- import type {
10
- ProcessInfoRef,
11
- ProcessRegistryRef,
12
- ToolContext,
13
- ToolResult,
14
- WaitProcessResultRef,
15
- } from "../types.js";
16
- import type { PTYSession } from "./pty.js";
17
- import { success, fail, getErrorMessage } from "./utils.js";
18
- import { classifyCommand, classifyExecInvocation } from "./shell-safety.js";
19
-
20
- /**
21
- * Environment variables that are dangerous in ALL contexts — including
22
- * the host's own process.env. These enable code injection or library
23
- * hijacking and should never reach child processes.
24
- */
25
- export const BLOCKED_ENV_VARS = new Set([
26
- "LD_PRELOAD",
27
- "LD_LIBRARY_PATH",
28
- "DYLD_INSERT_LIBRARIES",
29
- "DYLD_FRAMEWORK_PATH",
30
- "DYLD_LIBRARY_PATH",
31
- "BASH_ENV",
32
- "ENV",
33
- "CDPATH",
34
- "GLOBIGNORE",
35
- "PROMPT_COMMAND",
36
- "SHELLOPTS",
37
- "BASHOPTS",
38
- // Git context hijacks: inherited vars can redirect repository resolution.
39
- "GIT_DIR",
40
- "GIT_WORK_TREE",
41
- "GIT_INDEX_FILE",
42
- "GIT_OBJECT_DIRECTORY",
43
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
44
- "GIT_COMMON_DIR",
45
- "GIT_PREFIX",
46
- "GIT_INTERNAL_SUPER_PREFIX",
47
- "GIT_CONFIG",
48
- "GIT_CONFIG_GLOBAL",
49
- "GIT_CONFIG_SYSTEM",
50
- "GIT_CONFIG_COUNT",
51
- "GIT_CEILING_DIRECTORIES",
52
- ]);
53
-
54
- /**
55
- * Git environment keys that can redirect repository/config context or mutate
56
- * commit identity unexpectedly when inherited by child processes.
57
- *
58
- * NOTE: We intentionally keep transport/debug keys like GIT_SSH_COMMAND and
59
- * GIT_TRACE untouched to avoid breaking legitimate workflows.
60
- */
61
- const GIT_BLOCKED_EXACT_KEYS = new Set([
62
- "GIT_DIR",
63
- "GIT_WORK_TREE",
64
- "GIT_INDEX_FILE",
65
- "GIT_INDEX_VERSION",
66
- "GIT_COMMON_DIR",
67
- "GIT_OBJECT_DIRECTORY",
68
- "GIT_ALTERNATE_OBJECT_DIRECTORIES",
69
- "GIT_CEILING_DIRECTORIES",
70
- "GIT_DISCOVERY_ACROSS_FILESYSTEM",
71
- "GIT_NAMESPACE",
72
- "GIT_CONFIG",
73
- "GIT_CONFIG_GLOBAL",
74
- "GIT_CONFIG_SYSTEM",
75
- "GIT_CONFIG_NOSYSTEM",
76
- "GIT_CONFIG_COUNT",
77
- "GIT_CONFIG_PARAMETERS",
78
- ]);
79
-
80
- const GIT_BLOCKED_PREFIXES = [
81
- "GIT_CONFIG_KEY_",
82
- "GIT_CONFIG_VALUE_",
83
- "GIT_AUTHOR_",
84
- "GIT_COMMITTER_",
85
- ];
86
-
87
- export function isBlockedGitEnvVar(key: string): boolean {
88
- const upper = key.toUpperCase();
89
- if (GIT_BLOCKED_EXACT_KEYS.has(upper)) {
90
- return true;
91
- }
92
- return GIT_BLOCKED_PREFIXES.some((prefix) => upper.startsWith(prefix));
93
- }
94
-
95
- /**
96
- * Strip git-context env keys from a source env object.
97
- */
98
- export function sanitizeGitEnv(
99
- env: NodeJS.ProcessEnv | Record<string, string | undefined> = process.env,
100
- ): Record<string, string> {
101
- const sanitized: Record<string, string> = {};
102
- for (const [key, value] of Object.entries(env)) {
103
- if (value === undefined) continue;
104
- if (isBlockedGitEnvVar(key)) continue;
105
- sanitized[key] = value;
106
- }
107
- return sanitized;
108
- }
109
-
110
- /**
111
- * Additional variables blocked from tool-injected input (inputEnv, ctx.env)
112
- * but NOT from process.env. The host's PATH/HOME/SHELL are legitimate —
113
- * only tool-provided overrides are dangerous (hijacking resolution paths).
114
- */
115
- export const BLOCKED_INPUT_ENV_VARS = new Set([
116
- ...BLOCKED_ENV_VARS,
117
- // Executable/module resolution hijacks (aria-mx5)
118
- "PATH",
119
- "NODE_OPTIONS",
120
- "NODE_PATH",
121
- "PYTHONPATH",
122
- // Shell/environment manipulation
123
- "IFS",
124
- "HOME",
125
- "SHELL",
126
- "EDITOR",
127
- "VISUAL",
128
- // Java runtime hijacks (aria-skg)
129
- "JAVA_TOOL_OPTIONS",
130
- "_JAVA_OPTIONS",
131
- "CLASSPATH",
132
- // Ruby runtime hijacks (aria-skg)
133
- "RUBYOPT",
134
- "GEM_HOME",
135
- "GEM_PATH",
136
- // Perl runtime hijacks (aria-skg)
137
- "PERL5OPT",
138
- "PERL5LIB",
139
- // Python startup hijack (aria-skg) — PYTHONPATH already covered above
140
- "PYTHONSTARTUP",
141
- ]);
142
-
143
- function isBlockedProcessEnvVar(key: string): boolean {
144
- return BLOCKED_ENV_VARS.has(key.toUpperCase()) || isBlockedGitEnvVar(key);
145
- }
146
-
147
- function isBlockedInputEnvVar(key: string): boolean {
148
- return BLOCKED_INPUT_ENV_VARS.has(key.toUpperCase()) || isBlockedGitEnvVar(key);
149
- }
150
-
151
- /**
152
- * Merges environment variables from context and input.
153
- *
154
- * Three-tier filtering:
155
- * - process.env: filtered through BLOCKED_ENV_VARS (injection-only vars like LD_PRELOAD)
156
- * - ctx.env / inputEnv: filtered through BLOCKED_INPUT_ENV_VARS (also blocks PATH/HOME/SHELL hijacking)
157
- */
158
- export function mergeEnv(
159
- ctx: ToolContext,
160
- inputEnv?: Record<string, string>,
161
- ): Record<string, string> {
162
- let sanitizedInput = inputEnv;
163
- if (inputEnv) {
164
- sanitizedInput = {};
165
- for (const [key, value] of Object.entries(inputEnv)) {
166
- if (isBlockedInputEnvVar(key)) {
167
- continue;
168
- }
169
- sanitizedInput[key] = value;
170
- }
171
- }
172
- let sanitizedCtxEnv = ctx.env;
173
- if (ctx.env) {
174
- sanitizedCtxEnv = {};
175
- for (const [key, value] of Object.entries(ctx.env)) {
176
- if (isBlockedInputEnvVar(key)) {
177
- continue;
178
- }
179
- sanitizedCtxEnv[key] = value;
180
- }
181
- }
182
- // Filter process.env through the base blocklist only — the host's
183
- // PATH/HOME/SHELL are legitimate and needed by child processes.
184
- const sanitizedProcessEnv: Record<string, string> = {};
185
- for (const [key, value] of Object.entries(process.env)) {
186
- if (value === undefined) continue;
187
- if (isBlockedProcessEnvVar(key)) {
188
- continue;
189
- }
190
- sanitizedProcessEnv[key] = value;
191
- }
192
- return {
193
- ...sanitizedProcessEnv,
194
- ...sanitizedCtxEnv,
195
- ...sanitizedInput,
196
- } as Record<string, string>;
197
- }
198
-
199
- /**
200
- * Sanitize environment for child processes without requiring a ToolContext.
201
- *
202
- * Applies the same two-tier filtering as mergeEnv:
203
- * - process.env is filtered through BLOCKED_ENV_VARS
204
- * - inputEnv (caller-supplied overrides) is filtered through BLOCKED_INPUT_ENV_VARS
205
- *
206
- * Intended for executors (e.g. PTY) that do not have a ToolContext.
207
- */
208
- export function sanitizeEnv(inputEnv?: Record<string, string>): Record<string, string> {
209
- // Filter process.env through the base blocklist
210
- const sanitizedProcessEnv: Record<string, string> = {};
211
- for (const [key, value] of Object.entries(process.env)) {
212
- if (value === undefined) continue;
213
- if (isBlockedProcessEnvVar(key)) {
214
- continue;
215
- }
216
- sanitizedProcessEnv[key] = value;
217
- }
218
-
219
- // Filter inputEnv through the stricter input blocklist
220
- let sanitizedInput: Record<string, string> | undefined;
221
- if (inputEnv) {
222
- sanitizedInput = {};
223
- for (const [key, value] of Object.entries(inputEnv)) {
224
- if (isBlockedInputEnvVar(key)) {
225
- continue;
226
- }
227
- sanitizedInput[key] = value;
228
- }
229
- }
230
-
231
- return {
232
- ...sanitizedProcessEnv,
233
- ...sanitizedInput,
234
- };
235
- }
236
-
237
- // ============================================================================
238
- // Bash Executor
239
- // ============================================================================
240
-
241
- export interface BashInput {
242
- /** Shell command to execute */
243
- command: string;
244
- /** Working directory override */
245
- cwd?: string;
246
- /** Additional environment variables */
247
- env?: Record<string, string>;
248
- /** Timeout in milliseconds */
249
- timeout?: number;
250
- }
251
-
252
- export interface BashOutput {
253
- stdout: string;
254
- stderr: string;
255
- exitCode: number;
256
- }
257
-
258
- /**
259
- * Executes a command through bash shell.
260
- * Supports shell features like pipes, redirection, and variable expansion.
261
- */
262
- export async function executeBash(input: BashInput, ctx: ToolContext): Promise<ToolResult> {
263
- // Shell safety: block catastrophic commands before any execution
264
- const risk = classifyCommand(input.command);
265
- if (risk === "blocked") {
266
- return fail(`Command blocked by shell safety policy: ${input.command}`);
267
- }
268
-
269
- // Check if already aborted before starting
270
- if (ctx.abortSignal?.aborted) {
271
- return fail("Command cancelled");
272
- }
273
-
274
- const cwd = input.cwd ?? ctx.workingDir;
275
- const env = mergeEnv(ctx, input.env);
276
- const timeout = input.timeout ?? 120_000;
277
- return executeExec(
278
- {
279
- program: "/bin/bash",
280
- args: ["-lc", input.command],
281
- cwd,
282
- env: input.env,
283
- timeout,
284
- },
285
- {
286
- ...ctx,
287
- workingDir: cwd,
288
- env,
289
- },
290
- );
291
- }
292
-
293
- // ============================================================================
294
- // Exec Executor
295
- // ============================================================================
296
-
297
- export interface ExecInput {
298
- /** Program to execute */
299
- program: string;
300
- /** Arguments to pass to the program */
301
- args?: string[];
302
- /** Working directory override */
303
- cwd?: string;
304
- /** Additional environment variables */
305
- env?: Record<string, string>;
306
- /** Timeout in milliseconds */
307
- timeout?: number;
308
- }
309
-
310
- export interface ExecOutput {
311
- stdout: string;
312
- stderr: string;
313
- exitCode: number;
314
- }
315
-
316
- function signalExecProcessTree(
317
- pid: number | undefined,
318
- signal: NodeJS.Signals,
319
- detachedProcessGroup: boolean,
320
- ): void {
321
- if (!pid) {
322
- return;
323
- }
324
-
325
- if (detachedProcessGroup) {
326
- try {
327
- process.kill(-pid, signal);
328
- return;
329
- } catch {
330
- // Fall back to the leader PID if the process group is already gone or unsupported.
331
- }
332
- }
333
-
334
- try {
335
- process.kill(pid, signal);
336
- } catch {
337
- // Process may already be dead.
338
- }
339
- }
340
-
341
- function isExecProcessTreeAlive(pid: number | undefined, detachedProcessGroup: boolean): boolean {
342
- if (!pid) {
343
- return false;
344
- }
345
-
346
- if (detachedProcessGroup) {
347
- try {
348
- process.kill(-pid, 0);
349
- return true;
350
- } catch {
351
- // Fall through to the leader PID check in case the group probe is unsupported.
352
- }
353
- }
354
-
355
- try {
356
- process.kill(pid, 0);
357
- return true;
358
- } catch {
359
- return false;
360
- }
361
- }
362
-
363
- async function waitForExecProcessTreeExit(
364
- pid: number | undefined,
365
- detachedProcessGroup: boolean,
366
- timeoutMs = 1_000,
367
- ): Promise<void> {
368
- if (!pid) {
369
- return;
370
- }
371
-
372
- const deadline = Date.now() + timeoutMs;
373
- while (Date.now() < deadline) {
374
- if (!isExecProcessTreeAlive(pid, detachedProcessGroup)) {
375
- return;
376
- }
377
- await new Promise((resolve) => setTimeout(resolve, 25));
378
- }
379
- }
380
-
381
- /**
382
- * Executes a program directly without shell interpretation.
383
- * Safer than bash as it doesn't expand shell metacharacters.
384
- */
385
- export async function executeExec(input: ExecInput, ctx: ToolContext): Promise<ToolResult> {
386
- const args = input.args ?? [];
387
-
388
- // Shell safety: block catastrophic commands before any execution.
389
- // For explicit shell wrappers (e.g. bash -c ...), classify payload command.
390
- const reconstructed = [input.program, ...args].join(" ");
391
- const risk = classifyExecInvocation(input.program, args);
392
- if (risk === "blocked") {
393
- return fail(`Command blocked by shell safety policy: ${reconstructed}`, {
394
- stdout: "",
395
- stderr: "",
396
- exitCode: 1,
397
- } satisfies ExecOutput);
398
- }
399
-
400
- // Check if already aborted before starting
401
- if (ctx.abortSignal?.aborted) {
402
- return fail("Command cancelled", {
403
- stdout: "",
404
- stderr: "",
405
- exitCode: 1,
406
- } satisfies ExecOutput);
407
- }
408
-
409
- const cwd = input.cwd ?? ctx.workingDir;
410
- const env = mergeEnv(ctx, input.env);
411
- const timeout = input.timeout ?? 120_000;
412
-
413
- return new Promise((resolve) => {
414
- const detachedProcessGroup = process.platform !== "win32";
415
- const proc = spawn(input.program, args, {
416
- cwd,
417
- env,
418
- detached: detachedProcessGroup,
419
- });
420
-
421
- // Track PID in process registry for cleanup on session close
422
- if (proc.pid && ctx.processRegistry) {
423
- ctx.processRegistry.add(proc.pid, {
424
- command: input.program,
425
- args,
426
- cwd,
427
- interactive: false,
428
- });
429
- }
430
-
431
- let stdout = "";
432
- let stderr = "";
433
- let timedOut = false;
434
- let cancelled = false;
435
- let resolved = false;
436
- let timeoutId: NodeJS.Timeout | undefined;
437
- let killTimeoutId: NodeJS.Timeout | undefined;
438
-
439
- const doResolve = (
440
- result: ToolResult,
441
- exit?: { exitCode?: number | null; signal?: string | null },
442
- ) => {
443
- if (resolved) return;
444
- resolved = true;
445
- if (timeoutId) clearTimeout(timeoutId);
446
- if (killTimeoutId) clearTimeout(killTimeoutId);
447
- // Clean up abort listener
448
- if (ctx.abortSignal && onAbort) {
449
- ctx.abortSignal.removeEventListener("abort", onAbort);
450
- }
451
- // Keep detached process groups tracked until the whole group is gone.
452
- ctx.processRegistry?.recordExitMetadata?.(proc.pid ?? 0, exit);
453
- if (
454
- proc.pid &&
455
- ctx.processRegistry &&
456
- !(detachedProcessGroup && isExecProcessTreeAlive(proc.pid, detachedProcessGroup))
457
- ) {
458
- ctx.processRegistry.remove(proc.pid, exit);
459
- }
460
- resolve(result);
461
- };
462
-
463
- // Wire abort signal to kill the process
464
- let onAbort: (() => void) | undefined;
465
- if (ctx.abortSignal) {
466
- onAbort = () => {
467
- cancelled = true;
468
- signalExecProcessTree(proc.pid, "SIGTERM", detachedProcessGroup);
469
- // Follow up with SIGKILL if SIGTERM doesn't work
470
- killTimeoutId = setTimeout(() => {
471
- signalExecProcessTree(proc.pid, "SIGKILL", detachedProcessGroup);
472
- }, 1000);
473
- };
474
- ctx.abortSignal.addEventListener("abort", onAbort, { once: true });
475
- }
476
-
477
- if (timeout) {
478
- timeoutId = setTimeout(() => {
479
- timedOut = true;
480
- signalExecProcessTree(proc.pid, "SIGTERM", detachedProcessGroup);
481
- // If SIGTERM doesn't work, follow up with SIGKILL after 1 second
482
- killTimeoutId = setTimeout(() => {
483
- signalExecProcessTree(proc.pid, "SIGKILL", detachedProcessGroup);
484
- }, 1000);
485
- }, timeout);
486
- }
487
-
488
- proc.stdout?.on("data", (data: Buffer) => {
489
- stdout += data.toString();
490
- });
491
-
492
- proc.stderr?.on("data", (data: Buffer) => {
493
- stderr += data.toString();
494
- });
495
-
496
- proc.on("error", (err) => {
497
- const exitCode =
498
- typeof err === "object" &&
499
- err &&
500
- "code" in err &&
501
- (err as { code?: unknown }).code === "ENOENT"
502
- ? 127
503
- : 1;
504
- doResolve(
505
- fail(getErrorMessage(err), {
506
- stdout: "",
507
- stderr,
508
- exitCode,
509
- } satisfies ExecOutput),
510
- );
511
- });
512
-
513
- proc.on("close", (code, signal) => {
514
- void (async () => {
515
- if (cancelled || timedOut) {
516
- if (killTimeoutId) {
517
- clearTimeout(killTimeoutId);
518
- killTimeoutId = undefined;
519
- }
520
- signalExecProcessTree(proc.pid, "SIGKILL", detachedProcessGroup);
521
- await waitForExecProcessTreeExit(proc.pid, detachedProcessGroup);
522
- }
523
-
524
- if (cancelled) {
525
- doResolve(
526
- fail("Command cancelled", {
527
- stdout,
528
- stderr,
529
- exitCode: code ?? 1,
530
- } satisfies ExecOutput),
531
- { exitCode: code, signal },
532
- );
533
- return;
534
- }
535
-
536
- if (timedOut) {
537
- doResolve(
538
- fail("Command timed out", {
539
- stdout,
540
- stderr,
541
- exitCode: code ?? 1,
542
- } satisfies ExecOutput),
543
- { exitCode: code, signal },
544
- );
545
- return;
546
- }
547
-
548
- if (signal) {
549
- const signaledExitCode = osConstants.signals[signal] ?? 1;
550
- doResolve(
551
- fail(`Command exited due to signal ${signal}`, {
552
- stdout,
553
- stderr,
554
- exitCode: code ?? signaledExitCode,
555
- } satisfies ExecOutput),
556
- { exitCode: code, signal },
557
- );
558
- return;
559
- }
560
-
561
- const exitCode = code ?? 0;
562
- if (exitCode === 0) {
563
- doResolve(
564
- success("Command executed successfully", {
565
- stdout,
566
- stderr,
567
- exitCode,
568
- } satisfies ExecOutput),
569
- { exitCode, signal },
570
- );
571
- } else {
572
- doResolve(
573
- fail(`Command exited with code ${exitCode}`, {
574
- stdout,
575
- stderr,
576
- exitCode,
577
- } satisfies ExecOutput),
578
- { exitCode, signal },
579
- );
580
- }
581
- })();
582
- });
583
- });
584
- }
585
-
586
- // ============================================================================
587
- // Spawn Executor
588
- // ============================================================================
589
-
590
- export interface SpawnInput {
591
- /** Program to execute */
592
- program: string;
593
- /** Arguments to pass to the program */
594
- args?: string[];
595
- /** Working directory override */
596
- cwd?: string;
597
- /** Additional environment variables */
598
- env?: Record<string, string>;
599
- /** Start as interactive PTY session (enables write_stdin). Default: false */
600
- interactive?: boolean;
601
- }
602
-
603
- export interface SpawnOutput {
604
- pid: number;
605
- }
606
-
607
- /**
608
- * Spawns a background process and returns immediately with its PID.
609
- * The process is detached and will continue running after the parent exits.
610
- */
611
- export async function executeSpawn(input: SpawnInput, ctx: ToolContext): Promise<ToolResult> {
612
- // Shell safety: block catastrophic commands before spawning.
613
- // Detached processes are especially dangerous — they outlive the session.
614
- // For explicit shell wrappers (e.g. bash -c ...), classify payload command.
615
- const args = input.args ?? [];
616
- const reconstructed = [input.program, ...args].join(" ");
617
- const risk = classifyExecInvocation(input.program, args);
618
- if (risk === "blocked") {
619
- return fail(`Command blocked by shell safety policy: ${reconstructed}`);
620
- }
621
-
622
- // Check if already aborted before spawning
623
- if (ctx.abortSignal?.aborted) {
624
- return fail("Command cancelled");
625
- }
626
-
627
- // Check for interactive mode — use PTY instead of detached spawn
628
- if (input.interactive === true) {
629
- if (!ctx.ptySessionStore) {
630
- return fail("PTY session store not available — interactive mode requires runner wiring");
631
- }
632
-
633
- // Import createPTYSession dynamically to avoid circular deps at module level
634
- const { createPTYSession } = await import("./pty.js");
635
- const session = await createPTYSession({
636
- command: input.program,
637
- args: input.args,
638
- cwd: input.cwd ?? ctx.workingDir,
639
- env: mergeEnv(ctx, input.env),
640
- });
641
-
642
- const pid = session.pid;
643
- if (!pid) {
644
- session.close();
645
- return fail("Failed to start interactive session: no PID");
646
- }
647
-
648
- // Register in both stores
649
- ctx.ptySessionStore.add(pid, session);
650
- if (ctx.processRegistry) {
651
- ctx.processRegistry.add(pid, {
652
- command: input.program,
653
- args: input.args ?? [],
654
- cwd: input.cwd ?? ctx.workingDir,
655
- interactive: true,
656
- });
657
- }
658
-
659
- const deregisterInteractiveSession = (): void => {
660
- ctx.ptySessionStore?.remove(pid);
661
- if (ctx.processRegistry?.has(pid)) {
662
- ctx.processRegistry.remove(pid, {
663
- exitCode: session.exitCode ?? null,
664
- });
665
- }
666
- };
667
-
668
- if (!session.isRunning) {
669
- deregisterInteractiveSession();
670
- } else {
671
- const lifecycleCheckInterval = setInterval(() => {
672
- if (!session.isRunning) {
673
- clearInterval(lifecycleCheckInterval);
674
- deregisterInteractiveSession();
675
- }
676
- }, 50);
677
- lifecycleCheckInterval.unref?.();
678
-
679
- // Wire abort signal to PTY cleanup so ESC/Ctrl+C kills the session
680
- if (ctx.abortSignal) {
681
- const onAbort = () => {
682
- clearInterval(lifecycleCheckInterval);
683
- session.close();
684
- deregisterInteractiveSession();
685
- };
686
- ctx.abortSignal.addEventListener("abort", onAbort, { once: true });
687
- }
688
- }
689
-
690
- return success(`Started interactive session with PID ${pid}`, { pid } satisfies SpawnOutput);
691
- }
692
-
693
- const cwd = input.cwd ?? ctx.workingDir;
694
- const env = mergeEnv(ctx, input.env);
695
-
696
- return new Promise((resolve) => {
697
- let resolved = false;
698
- let fallbackTimeoutId: NodeJS.Timeout | undefined;
699
-
700
- const doResolve = (result: ToolResult) => {
701
- if (resolved) return;
702
- resolved = true;
703
- if (fallbackTimeoutId) clearTimeout(fallbackTimeoutId);
704
- resolve(result);
705
- };
706
-
707
- // Wire abort signal to kill the spawned process.
708
- // The listener is NOT removed in doResolve because the spawned process
709
- // outlives the function call. The { once: true } option auto-cleans it.
710
- let spawnedPid: number | undefined;
711
- if (ctx.abortSignal) {
712
- ctx.abortSignal.addEventListener(
713
- "abort",
714
- () => {
715
- if (spawnedPid) {
716
- try {
717
- // Kill the process group (negative PID) since process is detached
718
- process.kill(-spawnedPid, "SIGTERM");
719
- } catch {
720
- try {
721
- process.kill(spawnedPid, "SIGTERM");
722
- } catch {
723
- // Process may already be dead
724
- }
725
- }
726
- }
727
- },
728
- { once: true },
729
- );
730
- }
731
-
732
- try {
733
- const proc = spawn(input.program, args, {
734
- cwd,
735
- env,
736
- detached: true,
737
- stdio: "ignore",
738
- });
739
-
740
- // Handle spawn errors (e.g., program not found)
741
- proc.on("error", (err) => {
742
- doResolve(fail(getErrorMessage(err)));
743
- });
744
-
745
- // If we have a PID, the spawn was successful
746
- if (proc.pid) {
747
- spawnedPid = proc.pid;
748
- proc.on("exit", (code, signal) => {
749
- ctx.processRegistry?.recordExitMetadata?.(proc.pid!, {
750
- exitCode: code,
751
- signal,
752
- });
753
- if (ctx.processRegistry && !isExecProcessTreeAlive(proc.pid, true)) {
754
- ctx.processRegistry.remove(proc.pid!, {
755
- exitCode: code,
756
- signal,
757
- });
758
- }
759
- });
760
- // Track PID in process registry for cleanup on session close.
761
- // Spawned (detached) processes are never deregistered here —
762
- // they live until exit, killAll(), or the user explicitly kills them.
763
- if (ctx.processRegistry) {
764
- ctx.processRegistry.add(proc.pid, {
765
- command: input.program,
766
- args,
767
- cwd,
768
- interactive: false,
769
- });
770
- }
771
- // Unref to allow parent to exit independently
772
- proc.unref();
773
- doResolve(
774
- success(`Spawned process with PID ${proc.pid}`, {
775
- pid: proc.pid,
776
- } satisfies SpawnOutput),
777
- );
778
- } else {
779
- // This shouldn't normally happen, but handle it just in case
780
- // Wait briefly for error event
781
- fallbackTimeoutId = setTimeout(() => {
782
- doResolve(fail("Failed to spawn process: no PID returned"));
783
- }, 100);
784
- }
785
- } catch (err) {
786
- doResolve(fail(getErrorMessage(err)));
787
- }
788
- });
789
- }
790
-
791
- // ============================================================================
792
- // Kill Executor
793
- // ============================================================================
794
-
795
- export interface KillInput {
796
- /** Process ID to kill */
797
- pid: number;
798
- /** Signal to send (default: SIGTERM) */
799
- signal?: string;
800
- }
801
-
802
- export interface KillOutput {
803
- pid: number;
804
- signal: string;
805
- }
806
-
807
- /**
808
- * Sends a signal to terminate a process by PID.
809
- */
810
- export async function executeKill(input: KillInput, ctx: ToolContext): Promise<ToolResult> {
811
- const signal = input.signal ?? "SIGTERM";
812
-
813
- try {
814
- // Validate and normalize the signal
815
- const validatedSignal = validateSignal(signal);
816
- if (validatedSignal === undefined) {
817
- return fail(`Invalid signal: ${signal}`);
818
- }
819
-
820
- // Use process-tree signaling only for ARIA-tracked processes. Generic pid
821
- // kills must preserve pid-only semantics for foreign process groups.
822
- if (ctx.processRegistry?.has(input.pid)) {
823
- signalProcessTree(input.pid, validatedSignal);
824
- } else {
825
- process.kill(input.pid, validatedSignal);
826
- }
827
-
828
- // Keep tracked processes authoritative until exit is actually observed.
829
- const registry = ctx.processRegistry;
830
- if (registry?.waitForExit && shouldUntrackAfterSignal(validatedSignal)) {
831
- await registry.waitForExit(input.pid, 2_000);
832
- }
833
-
834
- const signalName = typeof validatedSignal === "number" ? signal : validatedSignal;
835
- return success(`Sent ${signalName} to process ${input.pid}`, {
836
- pid: input.pid,
837
- signal: signalName,
838
- } satisfies KillOutput);
839
- } catch (err: unknown) {
840
- if (err instanceof Error && "code" in err) {
841
- const nodeErr = err as NodeJS.ErrnoException;
842
- if (nodeErr.code === "ESRCH") {
843
- return fail(`Process not found: ${input.pid}`);
844
- }
845
- if (nodeErr.code === "EPERM") {
846
- return fail(`Permission denied to kill process: ${input.pid}`);
847
- }
848
- }
849
- return fail(getErrorMessage(err));
850
- }
851
- }
852
-
853
- /**
854
- * Valid signal names that can be used with process.kill.
855
- */
856
- const VALID_SIGNALS = [
857
- "SIGHUP",
858
- "SIGINT",
859
- "SIGQUIT",
860
- "SIGILL",
861
- "SIGTRAP",
862
- "SIGABRT",
863
- "SIGBUS",
864
- "SIGFPE",
865
- "SIGKILL",
866
- "SIGUSR1",
867
- "SIGSEGV",
868
- "SIGUSR2",
869
- "SIGPIPE",
870
- "SIGALRM",
871
- "SIGTERM",
872
- "SIGSTKFLT",
873
- "SIGCHLD",
874
- "SIGCONT",
875
- "SIGSTOP",
876
- "SIGTSTP",
877
- "SIGTTIN",
878
- "SIGTTOU",
879
- "SIGURG",
880
- "SIGXCPU",
881
- "SIGXFSZ",
882
- "SIGVTALRM",
883
- "SIGPROF",
884
- "SIGWINCH",
885
- "SIGIO",
886
- "SIGPWR",
887
- "SIGSYS",
888
- ] as const;
889
-
890
- type ValidSignal = (typeof VALID_SIGNALS)[number];
891
-
892
- const NON_TERMINATING_SIGNALS = new Set<NodeJS.Signals>([
893
- "SIGCHLD",
894
- "SIGCONT",
895
- "SIGSTOP",
896
- "SIGTSTP",
897
- "SIGTTIN",
898
- "SIGTTOU",
899
- "SIGURG",
900
- "SIGWINCH",
901
- ]);
902
-
903
- /**
904
- * Type guard to check if a string is a valid signal name.
905
- */
906
- function isValidSignalName(signal: string): signal is ValidSignal {
907
- return VALID_SIGNALS.includes(signal.toUpperCase() as ValidSignal);
908
- }
909
-
910
- /**
911
- * Validates a signal and returns either the validated signal name or number.
912
- * Returns undefined for invalid signals.
913
- */
914
- function validateSignal(signal: string): NodeJS.Signals | number | undefined {
915
- // Handle numeric signal
916
- if (/^\d+$/.test(signal)) {
917
- const num = parseInt(signal, 10);
918
- if (num >= 1 && num <= 31) {
919
- return num;
920
- }
921
- return undefined;
922
- }
923
-
924
- // Handle signal names
925
- const upperSignal = signal.toUpperCase();
926
- if (isValidSignalName(upperSignal)) {
927
- return upperSignal as NodeJS.Signals;
928
- }
929
-
930
- return undefined;
931
- }
932
-
933
- function shouldUntrackAfterSignal(signal: NodeJS.Signals | number): boolean {
934
- if (typeof signal === "number") {
935
- const signalName = resolveSignalName(signal);
936
- if (!signalName) {
937
- // Unknown numeric signals are treated conservatively.
938
- return false;
939
- }
940
- return !NON_TERMINATING_SIGNALS.has(signalName);
941
- }
942
-
943
- return !NON_TERMINATING_SIGNALS.has(signal);
944
- }
945
-
946
- function signalProcessTree(pid: number, signal: NodeJS.Signals | number): void {
947
- try {
948
- if (pid > 0) {
949
- process.kill(-pid, signal);
950
- return;
951
- }
952
- } catch {
953
- // Fall back to the tracked pid itself when there is no process group to target.
954
- }
955
-
956
- process.kill(pid, signal);
957
- }
958
-
959
- function resolveSignalName(signal: number): NodeJS.Signals | undefined {
960
- for (const [name, value] of Object.entries(osConstants.signals)) {
961
- if (value === signal) {
962
- return name as NodeJS.Signals;
963
- }
964
- }
965
- return undefined;
966
- }
967
-
968
- // ============================================================================
969
- // Process Observability Executors
970
- // ============================================================================
971
-
972
- export interface ListProcessesInput {
973
- /** Include exited process snapshots from recent registry history */
974
- includeExited?: boolean;
975
- }
976
-
977
- export interface ListProcessesOutput {
978
- processes: ProcessInfoRef[];
979
- count: number;
980
- }
981
-
982
- function hasLegacyGetAll(
983
- registry: ProcessRegistryRef,
984
- ): registry is ProcessRegistryRef & { getAll(): number[] } {
985
- return typeof (registry as { getAll?: unknown }).getAll === "function";
986
- }
987
-
988
- export async function executeListProcesses(
989
- rawInput: unknown,
990
- ctx: ToolContext,
991
- ): Promise<ToolResult> {
992
- const input = toRecord(rawInput);
993
- const includeExited = typeof input?.includeExited === "boolean" ? input.includeExited : false;
994
-
995
- if (!ctx.processRegistry) {
996
- return fail("Process registry not available");
997
- }
998
-
999
- const registry = ctx.processRegistry;
1000
- const processes =
1001
- typeof registry.listProcesses === "function"
1002
- ? registry.listProcesses({ includeExited })
1003
- : hasLegacyGetAll(registry)
1004
- ? registry.getAll().map(
1005
- (pid): ProcessInfoRef => ({
1006
- pid,
1007
- command: null,
1008
- args: [],
1009
- cwd: null,
1010
- interactive: false,
1011
- startedAt: new Date().toISOString(),
1012
- runtimeMs: 0,
1013
- status: "running",
1014
- exitCode: null,
1015
- signal: null,
1016
- endedAt: null,
1017
- }),
1018
- )
1019
- : [];
1020
-
1021
- return success(`Found ${processes.length} tracked process${processes.length === 1 ? "" : "es"}`, {
1022
- processes,
1023
- count: processes.length,
1024
- } satisfies ListProcessesOutput);
1025
- }
1026
-
1027
- export interface WaitProcessInput {
1028
- /** PID to wait on */
1029
- pid: number;
1030
- /** Max wait duration in milliseconds (max 300000, default 30000) */
1031
- timeoutMs?: number;
1032
- /** Deprecated alias for timeoutMs */
1033
- timeout?: number;
1034
- }
1035
-
1036
- export interface WaitProcessOutput {
1037
- pid: number;
1038
- status: "running" | "exited";
1039
- exited: boolean;
1040
- timedOut: boolean;
1041
- waitedMs: number;
1042
- command: string | null;
1043
- args: string[];
1044
- cwd: string | null;
1045
- interactive: boolean;
1046
- startedAt: string;
1047
- endedAt: string | null;
1048
- runtimeMs: number;
1049
- exitCode: number | null;
1050
- signal: string | null;
1051
- }
1052
-
1053
- export async function executeWaitProcess(rawInput: unknown, ctx: ToolContext): Promise<ToolResult> {
1054
- const input = toRecord(rawInput);
1055
- if (!input) {
1056
- return fail("Invalid input: expected an object");
1057
- }
1058
-
1059
- const pid = typeof input.pid === "number" ? input.pid : NaN;
1060
- if (!pid || pid <= 0 || !Number.isInteger(pid)) {
1061
- return fail("Invalid PID: must be a positive integer");
1062
- }
1063
- if (pid === process.pid) {
1064
- return fail("Cannot wait on own process");
1065
- }
1066
-
1067
- const timeoutMsInput = input.timeoutMs;
1068
- if (
1069
- timeoutMsInput !== undefined &&
1070
- (typeof timeoutMsInput !== "number" || Number.isNaN(timeoutMsInput))
1071
- ) {
1072
- return fail("Invalid timeoutMs: must be a number");
1073
- }
1074
-
1075
- const timeoutInput = input.timeout;
1076
- if (
1077
- timeoutInput !== undefined &&
1078
- (typeof timeoutInput !== "number" || Number.isNaN(timeoutInput))
1079
- ) {
1080
- return fail("Invalid timeout: must be a number");
1081
- }
1082
- const timeoutMs = Math.min(Math.max(0, timeoutMsInput ?? timeoutInput ?? 30_000), 300_000);
1083
-
1084
- if (!ctx.processRegistry) {
1085
- return fail("Process registry not available");
1086
- }
1087
- if (typeof ctx.processRegistry.waitForExit !== "function") {
1088
- return fail("Process registry does not support waiting");
1089
- }
1090
-
1091
- const startedAt = Date.now();
1092
- const waitResult = await ctx.processRegistry.waitForExit(pid, timeoutMs);
1093
- const waitedMs = Math.max(0, Date.now() - startedAt);
1094
- if (waitResult.status === "not_found" || !waitResult.process) {
1095
- return fail(`Process not tracked: ${pid}`, {
1096
- pid,
1097
- exited: false,
1098
- status: "not_found",
1099
- timedOut: false,
1100
- waitedMs,
1101
- });
1102
- }
1103
-
1104
- const data = mapWaitResult(waitResult, waitedMs);
1105
- if (waitResult.status === "running" || waitResult.timedOut) {
1106
- return fail(`Timed out waiting for process ${pid}`, data);
1107
- }
1108
-
1109
- return success(`Process ${pid} exited`, data);
1110
- }
1111
-
1112
- function mapWaitResult(waitResult: WaitProcessResultRef, waitedMs: number): WaitProcessOutput {
1113
- const processInfo = waitResult.process!;
1114
- const status = waitResult.status === "exited" ? "exited" : "running";
1115
- return {
1116
- pid: waitResult.pid,
1117
- status,
1118
- exited: status === "exited",
1119
- timedOut: waitResult.timedOut,
1120
- waitedMs,
1121
- command: processInfo.command,
1122
- args: processInfo.args,
1123
- cwd: processInfo.cwd,
1124
- interactive: processInfo.interactive,
1125
- startedAt: processInfo.startedAt,
1126
- endedAt: processInfo.endedAt,
1127
- runtimeMs: processInfo.runtimeMs,
1128
- exitCode: processInfo.exitCode,
1129
- signal: processInfo.signal,
1130
- };
1131
- }
1132
-
1133
- function toRecord(rawInput: unknown): Record<string, unknown> | undefined {
1134
- if (!rawInput || typeof rawInput !== "object") {
1135
- return undefined;
1136
- }
1137
- return rawInput as Record<string, unknown>;
1138
- }
1139
-
1140
- // ============================================================================
1141
- // WriteStdin Executor
1142
- // ============================================================================
1143
-
1144
- export interface WriteStdinInput {
1145
- /** PID of the interactive process to write to */
1146
- pid: number;
1147
- /** Input string to send to the process */
1148
- input: string;
1149
- /** Milliseconds to wait for output after writing (max 30000) */
1150
- timeout?: number;
1151
- }
1152
-
1153
- export interface WriteStdinOutput {
1154
- /** Recent output from the session after writing */
1155
- output: string;
1156
- }
1157
-
1158
- /**
1159
- * Sends input to an interactive PTY session by PID.
1160
- * Requires the process to have been spawned with interactive=true.
1161
- */
1162
- export async function executeWriteStdin(rawInput: unknown, ctx: ToolContext): Promise<ToolResult> {
1163
- // Validate input shape at runtime
1164
- if (!rawInput || typeof rawInput !== "object") {
1165
- return fail("Invalid input: expected an object");
1166
- }
1167
- const input = rawInput as Record<string, unknown>;
1168
-
1169
- const pid = typeof input.pid === "number" ? input.pid : NaN;
1170
- const inputStr = typeof input.input === "string" ? input.input : undefined;
1171
- const timeout = typeof input.timeout === "number" ? input.timeout : undefined;
1172
-
1173
- // Validate PID
1174
- if (!pid || pid <= 0 || !Number.isInteger(pid)) {
1175
- return fail("Invalid PID: must be a positive integer");
1176
- }
1177
- if (pid === process.pid) {
1178
- return fail("Cannot write to own process");
1179
- }
1180
-
1181
- // Validate input string
1182
- if (inputStr === undefined) {
1183
- return fail("Input must be a string");
1184
- }
1185
-
1186
- // Look up PTY session store
1187
- if (!ctx.ptySessionStore) {
1188
- return fail("PTY session store not available");
1189
- }
1190
-
1191
- if (!ctx.ptySessionStore.has(pid)) {
1192
- return fail(
1193
- `No interactive session found for PID ${pid}. Use spawn with interactive=true first.`,
1194
- );
1195
- }
1196
-
1197
- // The ptySessionStore ref uses `unknown` return to avoid circular deps,
1198
- // but the concrete store returns PTYSession instances.
1199
- const session = ctx.ptySessionStore.get(pid) as PTYSession | undefined;
1200
- if (!session) {
1201
- return fail(
1202
- `No interactive session found for PID ${pid}. Use spawn with interactive=true first.`,
1203
- );
1204
- }
1205
-
1206
- if (!session.isRunning) {
1207
- return fail(`Process ${pid} has exited (code: ${session.exitCode ?? "unknown"})`);
1208
- }
1209
-
1210
- try {
1211
- // Capture output length before write to extract new output after
1212
- const outputLenBefore = session.output.length;
1213
-
1214
- // Write input to the PTY session
1215
- session.write(inputStr);
1216
-
1217
- // If timeout specified, poll for new output with early return
1218
- if (timeout && timeout > 0) {
1219
- const waitMs = Math.min(timeout, 30_000);
1220
- const deadline = Date.now() + waitMs;
1221
- const pollInterval = 50; // Check every 50ms
1222
- while (Date.now() < deadline) {
1223
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
1224
- if (session.output.length > outputLenBefore) break;
1225
- if (!session.isRunning) break;
1226
- }
1227
- }
1228
-
1229
- // Extract output produced after the write
1230
- const fullOutput = session.output;
1231
- const newOutput = fullOutput.slice(outputLenBefore);
1232
-
1233
- // Cap returned output to 10KB to avoid bloating tool results
1234
- const cappedOutput = newOutput.length > 10_000 ? newOutput.slice(-10_000) : newOutput;
1235
-
1236
- return success(`Wrote ${inputStr.length} bytes to PID ${pid}`, {
1237
- output: cappedOutput,
1238
- } satisfies WriteStdinOutput);
1239
- } catch (error) {
1240
- const msg = error instanceof Error ? error.message : String(error);
1241
- return fail(`Failed to write to PID ${pid}: ${msg}`);
1242
- }
1243
- }