bash.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. export * as BashTool from "./bash"
  2. import path from "path"
  3. import { ToolFailure } from "@kirincode-ai/llm"
  4. import { Duration, Effect, Layer, Schema } from "effect"
  5. import { ChildProcess } from "effect/unstable/process"
  6. import { Config } from "../config"
  7. import { makeLocationNode } from "../effect/app-node"
  8. import { FSUtil } from "../fs-util"
  9. import { LocationMutation } from "../location-mutation"
  10. import { AppProcess } from "../process"
  11. import { PermissionV2 } from "../permission"
  12. import { PositiveInt } from "../schema"
  13. import { ToolRegistry } from "./registry"
  14. import { Tool } from "./tool"
  15. import { Tools } from "./tools"
  16. export const name = "bash"
  17. export const DEFAULT_TIMEOUT_MS = 2 * 60 * 1_000
  18. export const MAX_TIMEOUT_MS = 10 * 60 * 1_000
  19. export const MAX_CAPTURE_BYTES = 1024 * 1024
  20. export const Input = Schema.Struct({
  21. command: Schema.String.annotate({ description: "Shell command string to execute" }),
  22. workdir: Schema.String.pipe(Schema.optional).annotate({
  23. description: "Working directory. Defaults to the active Location; relative paths resolve from that Location.",
  24. }),
  25. timeout: PositiveInt.check(Schema.isLessThanOrEqualTo(MAX_TIMEOUT_MS))
  26. .pipe(Schema.optional)
  27. .annotate({
  28. description: `Timeout in milliseconds. Defaults to ${DEFAULT_TIMEOUT_MS} and may not exceed ${MAX_TIMEOUT_MS}.`,
  29. }),
  30. })
  31. const StructuredOutput = Schema.Struct({
  32. exit: Schema.Number.pipe(Schema.optional),
  33. truncated: Schema.Boolean,
  34. timeout: Schema.Boolean.pipe(Schema.optional),
  35. })
  36. const Output = Schema.Struct({
  37. ...StructuredOutput.fields,
  38. output: Schema.String,
  39. warnings: Schema.Array(Schema.String).pipe(Schema.optional),
  40. })
  41. type Output = typeof Output.Type
  42. const defaultShell = () => (process.platform === "win32" ? (process.env.COMSPEC ?? "cmd.exe") : "/bin/sh")
  43. const modelOutput = (output: Output) => {
  44. const warnings = output.warnings?.length
  45. ? `\n\nWarnings:\n${output.warnings.map((warning) => `- ${warning}`).join("\n")}`
  46. : ""
  47. if (output.timeout) return `${warnings.trimStart()}${warnings ? "\n\n" : ""}Command timed out before completion.`
  48. return `${warnings.trimStart()}${warnings ? "\n\n" : ""}Command exited with code ${output.exit}.`
  49. }
  50. const isTimeout = (error: AppProcess.AppProcessError) =>
  51. error.cause instanceof Error && error.cause.message === "Timed out"
  52. /**
  53. * Minimal V2 core shell boundary. Keep parity debt visible without pulling the
  54. * legacy shell runtime into core.
  55. */
  56. // TODO: Port tree-sitter bash / PowerShell parser-based approval reduction.
  57. // TODO: Port BashArity reusable command-prefix approvals.
  58. // TODO: Replace token-based command-argument external-directory advisories with parser-based detection.
  59. // TODO: Restore PowerShell and cmd-specific invocation/path handling on Windows.
  60. // TODO: Add plugin shell.env environment augmentation once V2 plugin hooks exist.
  61. // TODO: Add durable/live progress metadata streaming for long-running commands once V2 tool invocation progress context is wired.
  62. // TODO: Persist background job status and define restart recovery before exposing remote observation.
  63. // TODO: Re-add model-facing background launch only with owner-bound get/wait/cancel tools and completion delivery.
  64. // TODO: Add HTTP background-job observation only after durable status, restart recovery, and authorization are defined.
  65. // TODO: Revisit process-group cleanup and platform coverage with shell-specific tests if current AppProcess semantics do not fully cover it.
  66. // TODO: Revisit binary output handling if stdout/stderr decoding is text-only.
  67. // TODO: Stream full shell output into managed storage while retaining only a bounded in-memory preview.
  68. const shellTokens = (command: string) => command.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g) ?? []
  69. const unquote = (value: string) => value.replace(/^(['"])(.*)\1$/, "$2")
  70. const externalCommandDirectories = Effect.fn("BashTool.externalCommandDirectories")(function* (
  71. fs: FSUtil.Interface,
  72. command: string,
  73. cwd: string,
  74. ) {
  75. const directories = new Set<string>()
  76. for (const token of shellTokens(command)) {
  77. const value = unquote(token).replace(/[;,|&]+$/, "")
  78. if (!path.isAbsolute(value)) continue
  79. const resolved = yield* fs.resolve(value)
  80. if (FSUtil.contains(cwd, resolved)) continue
  81. directories.add(yield* fs.resolve(path.dirname(resolved)))
  82. }
  83. return [...directories]
  84. })
  85. const layer = Layer.effectDiscard(
  86. Effect.gen(function* () {
  87. const tools = yield* Tools.Service
  88. const mutation = yield* LocationMutation.Service
  89. const fs = yield* FSUtil.Service
  90. const appProcess = yield* AppProcess.Service
  91. const config = yield* Config.Service
  92. const permission = yield* PermissionV2.Service
  93. yield* tools
  94. .register({
  95. [name]: Tool.make({
  96. description: `Execute one shell command string with the host user's filesystem, process, and network authority. The active Location is the default working directory. Relative workdir values resolve from that Location. External workdir values require external_directory approval; best-effort command-argument path warnings are advisory only. Timeout values are milliseconds (default: ${DEFAULT_TIMEOUT_MS}; maximum: ${MAX_TIMEOUT_MS}). Uses the configured shell when set; otherwise uses /bin/sh on POSIX and COMSPEC or cmd.exe on Windows.`,
  97. input: Input,
  98. output: Output,
  99. structured: StructuredOutput,
  100. toStructuredOutput: ({ output }) => ({
  101. truncated: output.truncated,
  102. ...(output.exit === undefined ? {} : { exit: output.exit }),
  103. ...(output.timeout === undefined ? {} : { timeout: output.timeout }),
  104. }),
  105. toModelOutput: ({ output }) => [
  106. { type: "text", text: output.output },
  107. { type: "text", text: modelOutput(output) },
  108. ],
  109. execute: (input, context) =>
  110. Effect.gen(function* () {
  111. const source = {
  112. type: "tool" as const,
  113. messageID: context.assistantMessageID,
  114. callID: context.toolCallID,
  115. }
  116. const target = yield* mutation.resolve({ path: input.workdir ?? ".", kind: "directory" })
  117. const external = target.externalDirectory
  118. if (external)
  119. yield* permission.assert({
  120. ...LocationMutation.externalDirectoryPermission(external),
  121. sessionID: context.sessionID,
  122. agent: context.agent,
  123. source,
  124. })
  125. const warnings = (yield* externalCommandDirectories(fs, input.command, target.canonical)).map(
  126. (directory) =>
  127. `Command argument references external directory ${path.join(directory, "*").replaceAll("\\", "/")}. Bash runs with host-user filesystem, process, and network authority; this scan is advisory only.`,
  128. )
  129. yield* permission.assert({
  130. action: name,
  131. resources: [input.command],
  132. save: [input.command],
  133. sessionID: context.sessionID,
  134. agent: context.agent,
  135. source,
  136. })
  137. if ((yield* fs.stat(target.canonical)).type !== "Directory")
  138. return yield* Effect.fail(new Error(`Working directory is not a directory: ${target.canonical}`))
  139. const entries = yield* config.entries()
  140. const shell =
  141. Object.assign({}, ...entries.flatMap((entry) => (entry.type === "document" ? [entry.info] : [])))
  142. .shell ?? defaultShell()
  143. const command = ChildProcess.make(input.command, [], {
  144. cwd: target.canonical,
  145. shell,
  146. stdin: "ignore",
  147. detached: process.platform !== "win32",
  148. forceKillAfter: Duration.seconds(3),
  149. })
  150. const timeout = input.timeout ?? DEFAULT_TIMEOUT_MS
  151. const result = yield* appProcess
  152. .run(command, {
  153. combineOutput: true,
  154. timeout: Duration.millis(timeout),
  155. maxOutputBytes: MAX_CAPTURE_BYTES,
  156. })
  157. .pipe(
  158. Effect.catchTag("AppProcessError", (error) =>
  159. isTimeout(error) ? Effect.succeed(undefined) : Effect.fail(error),
  160. ),
  161. )
  162. if (!result) {
  163. return {
  164. output: `Command exceeded timeout of ${timeout} ms. Retry with a larger timeout if the command is expected to take longer.`,
  165. truncated: false,
  166. timeout: true,
  167. ...(warnings.length ? { warnings } : {}),
  168. }
  169. }
  170. const output = result.output?.toString("utf8") || "(no output)"
  171. const notice = result.outputTruncated
  172. ? "[output capture truncated at the in-memory safety limit]"
  173. : undefined
  174. return {
  175. exit: result.exitCode,
  176. output: notice ? `${output}\n\n${notice}` : output,
  177. truncated: result.outputTruncated === true,
  178. ...(warnings.length ? { warnings } : {}),
  179. }
  180. }).pipe(Effect.mapError(() => new ToolFailure({ message: `Unable to execute command: ${input.command}` }))),
  181. }),
  182. })
  183. .pipe(Effect.orDie)
  184. }),
  185. )
  186. export const node = makeLocationNode({
  187. name: "tool/bash",
  188. layer,
  189. deps: [ToolRegistry.node, LocationMutation.node, FSUtil.node, AppProcess.node, Config.node, PermissionV2.node],
  190. })