bash.test.ts 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. import { describe, expect, test } from "bun:test"
  2. import os from "os"
  3. import path from "path"
  4. import { Shell } from "../../src/shell/shell"
  5. import { BashTool } from "../../src/tool/bash"
  6. import { Instance } from "../../src/project/instance"
  7. import { Filesystem } from "../../src/util/filesystem"
  8. import { tmpdir } from "../fixture/fixture"
  9. import type { Permission } from "../../src/permission"
  10. import { Truncate } from "../../src/tool/truncate"
  11. import { SessionID, MessageID } from "../../src/session/schema"
  12. const ctx = {
  13. sessionID: SessionID.make("ses_test"),
  14. messageID: MessageID.make(""),
  15. callID: "",
  16. agent: "build",
  17. abort: AbortSignal.any([]),
  18. messages: [],
  19. metadata: () => {},
  20. ask: async () => {},
  21. }
  22. Shell.acceptable.reset()
  23. const quote = (text: string) => `"${text}"`
  24. const squote = (text: string) => `'${text}'`
  25. const projectRoot = path.join(__dirname, "../..")
  26. const bin = quote(process.execPath.replaceAll("\\", "/"))
  27. const bash = (() => {
  28. const shell = Shell.acceptable()
  29. if (Shell.name(shell) === "bash") return shell
  30. return Shell.gitbash()
  31. })()
  32. const shells = (() => {
  33. if (process.platform !== "win32") {
  34. const shell = Shell.acceptable()
  35. return [{ label: Shell.name(shell), shell }]
  36. }
  37. const list = [bash, Bun.which("pwsh"), Bun.which("powershell"), process.env.COMSPEC || Bun.which("cmd.exe")]
  38. .filter((shell): shell is string => Boolean(shell))
  39. .map((shell) => ({ label: Shell.name(shell), shell }))
  40. return list.filter(
  41. (item, i) => list.findIndex((other) => other.shell.toLowerCase() === item.shell.toLowerCase()) === i,
  42. )
  43. })()
  44. const PS = new Set(["pwsh", "powershell"])
  45. const ps = shells.filter((item) => PS.has(item.label))
  46. const sh = () => Shell.name(Shell.acceptable())
  47. const evalarg = (text: string) => (sh() === "cmd" ? quote(text) : squote(text))
  48. const fill = (mode: "lines" | "bytes", n: number) => {
  49. const code =
  50. mode === "lines"
  51. ? "console.log(Array.from({length:Number(Bun.argv[1])},(_,i)=>i+1).join(String.fromCharCode(10)))"
  52. : "process.stdout.write(String.fromCharCode(97).repeat(Number(Bun.argv[1])))"
  53. const text = `${bin} -e ${evalarg(code)} ${n}`
  54. if (PS.has(sh())) return `& ${text}`
  55. return text
  56. }
  57. const glob = (p: string) =>
  58. process.platform === "win32" ? Filesystem.normalizePathPattern(p) : p.replaceAll("\\", "/")
  59. const forms = (dir: string) => {
  60. if (process.platform !== "win32") return [dir]
  61. const full = Filesystem.normalizePath(dir)
  62. const slash = full.replaceAll("\\", "/")
  63. const root = slash.replace(/^[A-Za-z]:/, "")
  64. return Array.from(new Set([full, slash, root, root.toLowerCase()]))
  65. }
  66. const withShell = (item: { label: string; shell: string }, fn: () => Promise<void>) => async () => {
  67. const prev = process.env.SHELL
  68. process.env.SHELL = item.shell
  69. Shell.acceptable.reset()
  70. Shell.preferred.reset()
  71. try {
  72. await fn()
  73. } finally {
  74. if (prev === undefined) delete process.env.SHELL
  75. else process.env.SHELL = prev
  76. Shell.acceptable.reset()
  77. Shell.preferred.reset()
  78. }
  79. }
  80. const each = (name: string, fn: (item: { label: string; shell: string }) => Promise<void>) => {
  81. for (const item of shells) {
  82. test(
  83. `${name} [${item.label}]`,
  84. withShell(item, () => fn(item)),
  85. )
  86. }
  87. }
  88. const capture = (requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">>, stop?: Error) => ({
  89. ...ctx,
  90. ask: async (req: Omit<Permission.Request, "id" | "sessionID" | "tool">) => {
  91. requests.push(req)
  92. if (stop) throw stop
  93. },
  94. })
  95. const mustTruncate = (result: {
  96. metadata: { truncated?: boolean; exit?: number | null } & Record<string, unknown>
  97. output: string
  98. }) => {
  99. if (result.metadata.truncated) return
  100. throw new Error(
  101. [`shell: ${process.env.SHELL || ""}`, `exit: ${String(result.metadata.exit)}`, "output:", result.output].join("\n"),
  102. )
  103. }
  104. describe("tool.bash", () => {
  105. each("basic", async () => {
  106. await Instance.provide({
  107. directory: projectRoot,
  108. fn: async () => {
  109. const bash = await BashTool.init()
  110. const result = await bash.execute(
  111. {
  112. command: "echo test",
  113. description: "Echo test message",
  114. },
  115. ctx,
  116. )
  117. expect(result.metadata.exit).toBe(0)
  118. expect(result.metadata.output).toContain("test")
  119. },
  120. })
  121. })
  122. })
  123. describe("tool.bash permissions", () => {
  124. each("asks for bash permission with correct pattern", async () => {
  125. await using tmp = await tmpdir()
  126. await Instance.provide({
  127. directory: tmp.path,
  128. fn: async () => {
  129. const bash = await BashTool.init()
  130. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  131. await bash.execute(
  132. {
  133. command: "echo hello",
  134. description: "Echo hello",
  135. },
  136. capture(requests),
  137. )
  138. expect(requests.length).toBe(1)
  139. expect(requests[0].permission).toBe("bash")
  140. expect(requests[0].patterns).toContain("echo hello")
  141. },
  142. })
  143. })
  144. each("asks for bash permission with multiple commands", async () => {
  145. await using tmp = await tmpdir()
  146. await Instance.provide({
  147. directory: tmp.path,
  148. fn: async () => {
  149. const bash = await BashTool.init()
  150. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  151. await bash.execute(
  152. {
  153. command: "echo foo && echo bar",
  154. description: "Echo twice",
  155. },
  156. capture(requests),
  157. )
  158. expect(requests.length).toBe(1)
  159. expect(requests[0].permission).toBe("bash")
  160. expect(requests[0].patterns).toContain("echo foo")
  161. expect(requests[0].patterns).toContain("echo bar")
  162. },
  163. })
  164. })
  165. for (const item of ps) {
  166. test(
  167. `parses PowerShell conditionals for permission prompts [${item.label}]`,
  168. withShell(item, async () => {
  169. await Instance.provide({
  170. directory: projectRoot,
  171. fn: async () => {
  172. const bash = await BashTool.init()
  173. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  174. await bash.execute(
  175. {
  176. command: "Write-Host foo; if ($?) { Write-Host bar }",
  177. description: "Check PowerShell conditional",
  178. },
  179. capture(requests),
  180. )
  181. const bashReq = requests.find((r) => r.permission === "bash")
  182. expect(bashReq).toBeDefined()
  183. expect(bashReq!.patterns).toContain("Write-Host foo")
  184. expect(bashReq!.patterns).toContain("Write-Host bar")
  185. expect(bashReq!.always).toContain("Write-Host *")
  186. },
  187. })
  188. }),
  189. )
  190. }
  191. each("asks for external_directory permission for wildcard external paths", async () => {
  192. await Instance.provide({
  193. directory: projectRoot,
  194. fn: async () => {
  195. const bash = await BashTool.init()
  196. const err = new Error("stop after permission")
  197. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  198. const file = process.platform === "win32" ? `${process.env.WINDIR!.replaceAll("\\", "/")}/*` : "/etc/*"
  199. const want = process.platform === "win32" ? glob(path.join(process.env.WINDIR!, "*")) : "/etc/*"
  200. await expect(
  201. bash.execute(
  202. {
  203. command: `cat ${file}`,
  204. description: "Read wildcard path",
  205. },
  206. capture(requests, err),
  207. ),
  208. ).rejects.toThrow(err.message)
  209. const extDirReq = requests.find((r) => r.permission === "external_directory")
  210. expect(extDirReq).toBeDefined()
  211. expect(extDirReq!.patterns).toContain(want)
  212. },
  213. })
  214. })
  215. if (process.platform === "win32") {
  216. if (bash) {
  217. test(
  218. "asks for nested bash command permissions [bash]",
  219. withShell({ label: "bash", shell: bash }, async () => {
  220. await using outerTmp = await tmpdir({
  221. init: async (dir) => {
  222. await Bun.write(path.join(dir, "outside.txt"), "x")
  223. },
  224. })
  225. await Instance.provide({
  226. directory: projectRoot,
  227. fn: async () => {
  228. const bash = await BashTool.init()
  229. const file = path.join(outerTmp.path, "outside.txt").replaceAll("\\", "/")
  230. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  231. await bash.execute(
  232. {
  233. command: `echo $(cat "${file}")`,
  234. description: "Read nested bash file",
  235. },
  236. capture(requests),
  237. )
  238. const extDirReq = requests.find((r) => r.permission === "external_directory")
  239. const bashReq = requests.find((r) => r.permission === "bash")
  240. expect(extDirReq).toBeDefined()
  241. expect(extDirReq!.patterns).toContain(glob(path.join(outerTmp.path, "*")))
  242. expect(bashReq).toBeDefined()
  243. expect(bashReq!.patterns).toContain(`cat "${file}"`)
  244. },
  245. })
  246. }),
  247. )
  248. }
  249. }
  250. if (process.platform === "win32") {
  251. for (const item of ps) {
  252. test(
  253. `asks for external_directory permission for PowerShell paths after switches [${item.label}]`,
  254. withShell(item, async () => {
  255. await Instance.provide({
  256. directory: projectRoot,
  257. fn: async () => {
  258. const bash = await BashTool.init()
  259. const err = new Error("stop after permission")
  260. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  261. await expect(
  262. bash.execute(
  263. {
  264. command: `Copy-Item -PassThru "${process.env.WINDIR!.replaceAll("\\", "/")}/win.ini" ./out`,
  265. description: "Copy Windows ini",
  266. },
  267. capture(requests, err),
  268. ),
  269. ).rejects.toThrow(err.message)
  270. const extDirReq = requests.find((r) => r.permission === "external_directory")
  271. expect(extDirReq).toBeDefined()
  272. expect(extDirReq!.patterns).toContain(glob(path.join(process.env.WINDIR!, "*")))
  273. },
  274. })
  275. }),
  276. )
  277. }
  278. for (const item of ps) {
  279. test(
  280. `asks for nested PowerShell command permissions [${item.label}]`,
  281. withShell(item, async () => {
  282. await Instance.provide({
  283. directory: projectRoot,
  284. fn: async () => {
  285. const bash = await BashTool.init()
  286. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  287. const file = `${process.env.WINDIR!.replaceAll("\\", "/")}/win.ini`
  288. await bash.execute(
  289. {
  290. command: `Write-Output $(Get-Content ${file})`,
  291. description: "Read nested PowerShell file",
  292. },
  293. capture(requests),
  294. )
  295. const extDirReq = requests.find((r) => r.permission === "external_directory")
  296. const bashReq = requests.find((r) => r.permission === "bash")
  297. expect(extDirReq).toBeDefined()
  298. expect(extDirReq!.patterns).toContain(glob(path.join(process.env.WINDIR!, "*")))
  299. expect(bashReq).toBeDefined()
  300. expect(bashReq!.patterns).toContain(`Get-Content ${file}`)
  301. },
  302. })
  303. }),
  304. )
  305. }
  306. for (const item of ps) {
  307. test(
  308. `asks for external_directory permission for drive-relative PowerShell paths [${item.label}]`,
  309. withShell(item, async () => {
  310. await using tmp = await tmpdir()
  311. await Instance.provide({
  312. directory: tmp.path,
  313. fn: async () => {
  314. const bash = await BashTool.init()
  315. const err = new Error("stop after permission")
  316. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  317. await expect(
  318. bash.execute(
  319. {
  320. command: 'Get-Content "C:../outside.txt"',
  321. description: "Read drive-relative file",
  322. },
  323. capture(requests, err),
  324. ),
  325. ).rejects.toThrow(err.message)
  326. expect(requests[0]?.permission).toBe("external_directory")
  327. if (requests[0]?.permission !== "external_directory") return
  328. expect(requests[0].patterns).toContain(glob(path.join(path.dirname(tmp.path), "*")))
  329. },
  330. })
  331. }),
  332. )
  333. }
  334. for (const item of ps) {
  335. test(
  336. `asks for external_directory permission for $HOME PowerShell paths [${item.label}]`,
  337. withShell(item, async () => {
  338. await Instance.provide({
  339. directory: projectRoot,
  340. fn: async () => {
  341. const bash = await BashTool.init()
  342. const err = new Error("stop after permission")
  343. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  344. await expect(
  345. bash.execute(
  346. {
  347. command: 'Get-Content "$HOME/.ssh/config"',
  348. description: "Read home config",
  349. },
  350. capture(requests, err),
  351. ),
  352. ).rejects.toThrow(err.message)
  353. expect(requests[0]?.permission).toBe("external_directory")
  354. if (requests[0]?.permission !== "external_directory") return
  355. expect(requests[0].patterns).toContain(glob(path.join(os.homedir(), ".ssh", "*")))
  356. },
  357. })
  358. }),
  359. )
  360. }
  361. for (const item of ps) {
  362. test(
  363. `asks for external_directory permission for $PWD PowerShell paths [${item.label}]`,
  364. withShell(item, async () => {
  365. await using tmp = await tmpdir()
  366. await Instance.provide({
  367. directory: tmp.path,
  368. fn: async () => {
  369. const bash = await BashTool.init()
  370. const err = new Error("stop after permission")
  371. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  372. await expect(
  373. bash.execute(
  374. {
  375. command: 'Get-Content "$PWD/../outside.txt"',
  376. description: "Read pwd-relative file",
  377. },
  378. capture(requests, err),
  379. ),
  380. ).rejects.toThrow(err.message)
  381. expect(requests[0]?.permission).toBe("external_directory")
  382. if (requests[0]?.permission !== "external_directory") return
  383. expect(requests[0].patterns).toContain(glob(path.join(path.dirname(tmp.path), "*")))
  384. },
  385. })
  386. }),
  387. )
  388. }
  389. for (const item of ps) {
  390. test(
  391. `asks for external_directory permission for $PSHOME PowerShell paths [${item.label}]`,
  392. withShell(item, async () => {
  393. await Instance.provide({
  394. directory: projectRoot,
  395. fn: async () => {
  396. const bash = await BashTool.init()
  397. const err = new Error("stop after permission")
  398. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  399. await expect(
  400. bash.execute(
  401. {
  402. command: 'Get-Content "$PSHOME/outside.txt"',
  403. description: "Read pshome file",
  404. },
  405. capture(requests, err),
  406. ),
  407. ).rejects.toThrow(err.message)
  408. expect(requests[0]?.permission).toBe("external_directory")
  409. if (requests[0]?.permission !== "external_directory") return
  410. expect(requests[0].patterns).toContain(glob(path.join(path.dirname(item.shell), "*")))
  411. },
  412. })
  413. }),
  414. )
  415. }
  416. for (const item of ps) {
  417. test(
  418. `asks for external_directory permission for missing PowerShell env paths [${item.label}]`,
  419. withShell(item, async () => {
  420. const key = "OPENCODE_TEST_MISSING"
  421. const prev = process.env[key]
  422. delete process.env[key]
  423. try {
  424. await Instance.provide({
  425. directory: projectRoot,
  426. fn: async () => {
  427. const bash = await BashTool.init()
  428. const err = new Error("stop after permission")
  429. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  430. const root = path.parse(process.env.WINDIR!).root.replace(/[\\/]+$/, "")
  431. await expect(
  432. bash.execute(
  433. {
  434. command: `Get-Content -Path "${root}$env:${key}\\Windows\\win.ini"`,
  435. description: "Read Windows ini with missing env",
  436. },
  437. capture(requests, err),
  438. ),
  439. ).rejects.toThrow(err.message)
  440. const extDirReq = requests.find((r) => r.permission === "external_directory")
  441. expect(extDirReq).toBeDefined()
  442. expect(extDirReq!.patterns).toContain(glob(path.join(process.env.WINDIR!, "*")))
  443. },
  444. })
  445. } finally {
  446. if (prev === undefined) delete process.env[key]
  447. else process.env[key] = prev
  448. }
  449. }),
  450. )
  451. }
  452. for (const item of ps) {
  453. test(
  454. `asks for external_directory permission for PowerShell env paths [${item.label}]`,
  455. withShell(item, async () => {
  456. await Instance.provide({
  457. directory: projectRoot,
  458. fn: async () => {
  459. const bash = await BashTool.init()
  460. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  461. await bash.execute(
  462. {
  463. command: "Get-Content $env:WINDIR/win.ini",
  464. description: "Read Windows ini from env",
  465. },
  466. capture(requests),
  467. )
  468. const extDirReq = requests.find((r) => r.permission === "external_directory")
  469. expect(extDirReq).toBeDefined()
  470. expect(extDirReq!.patterns).toContain(
  471. Filesystem.normalizePathPattern(path.join(process.env.WINDIR!, "*")),
  472. )
  473. },
  474. })
  475. }),
  476. )
  477. }
  478. for (const item of ps) {
  479. test(
  480. `asks for external_directory permission for PowerShell FileSystem paths [${item.label}]`,
  481. withShell(item, async () => {
  482. await Instance.provide({
  483. directory: projectRoot,
  484. fn: async () => {
  485. const bash = await BashTool.init()
  486. const err = new Error("stop after permission")
  487. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  488. await expect(
  489. bash.execute(
  490. {
  491. command: `Get-Content -Path FileSystem::${process.env.WINDIR!.replaceAll("\\", "/")}/win.ini`,
  492. description: "Read Windows ini from FileSystem provider",
  493. },
  494. capture(requests, err),
  495. ),
  496. ).rejects.toThrow(err.message)
  497. expect(requests[0]?.permission).toBe("external_directory")
  498. if (requests[0]?.permission !== "external_directory") return
  499. expect(requests[0].patterns).toContain(
  500. Filesystem.normalizePathPattern(path.join(process.env.WINDIR!, "*")),
  501. )
  502. },
  503. })
  504. }),
  505. )
  506. }
  507. for (const item of ps) {
  508. test(
  509. `asks for external_directory permission for braced PowerShell env paths [${item.label}]`,
  510. withShell(item, async () => {
  511. await Instance.provide({
  512. directory: projectRoot,
  513. fn: async () => {
  514. const bash = await BashTool.init()
  515. const err = new Error("stop after permission")
  516. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  517. await expect(
  518. bash.execute(
  519. {
  520. command: "Get-Content ${env:WINDIR}/win.ini",
  521. description: "Read Windows ini from braced env",
  522. },
  523. capture(requests, err),
  524. ),
  525. ).rejects.toThrow(err.message)
  526. expect(requests[0]?.permission).toBe("external_directory")
  527. if (requests[0]?.permission !== "external_directory") return
  528. expect(requests[0].patterns).toContain(
  529. Filesystem.normalizePathPattern(path.join(process.env.WINDIR!, "*")),
  530. )
  531. },
  532. })
  533. }),
  534. )
  535. }
  536. for (const item of ps) {
  537. test(
  538. `treats Set-Location like cd for permissions [${item.label}]`,
  539. withShell(item, async () => {
  540. await Instance.provide({
  541. directory: projectRoot,
  542. fn: async () => {
  543. const bash = await BashTool.init()
  544. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  545. await bash.execute(
  546. {
  547. command: "Set-Location C:/Windows",
  548. description: "Change location",
  549. },
  550. capture(requests),
  551. )
  552. const extDirReq = requests.find((r) => r.permission === "external_directory")
  553. const bashReq = requests.find((r) => r.permission === "bash")
  554. expect(extDirReq).toBeDefined()
  555. expect(extDirReq!.patterns).toContain(
  556. Filesystem.normalizePathPattern(path.join(process.env.WINDIR!, "*")),
  557. )
  558. expect(bashReq).toBeUndefined()
  559. },
  560. })
  561. }),
  562. )
  563. }
  564. for (const item of ps) {
  565. test(
  566. `does not add nested PowerShell expressions to permission prompts [${item.label}]`,
  567. withShell(item, async () => {
  568. await Instance.provide({
  569. directory: projectRoot,
  570. fn: async () => {
  571. const bash = await BashTool.init()
  572. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  573. await bash.execute(
  574. {
  575. command: "Write-Output ('a' * 3)",
  576. description: "Write repeated text",
  577. },
  578. capture(requests),
  579. )
  580. const bashReq = requests.find((r) => r.permission === "bash")
  581. expect(bashReq).toBeDefined()
  582. expect(bashReq!.patterns).not.toContain("a * 3")
  583. expect(bashReq!.always).not.toContain("a *")
  584. },
  585. })
  586. }),
  587. )
  588. }
  589. }
  590. each("asks for external_directory permission when cd to parent", async () => {
  591. await using tmp = await tmpdir()
  592. await Instance.provide({
  593. directory: tmp.path,
  594. fn: async () => {
  595. const bash = await BashTool.init()
  596. const err = new Error("stop after permission")
  597. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  598. await expect(
  599. bash.execute(
  600. {
  601. command: "cd ../",
  602. description: "Change to parent directory",
  603. },
  604. capture(requests, err),
  605. ),
  606. ).rejects.toThrow(err.message)
  607. const extDirReq = requests.find((r) => r.permission === "external_directory")
  608. expect(extDirReq).toBeDefined()
  609. },
  610. })
  611. })
  612. each("asks for external_directory permission when workdir is outside project", async () => {
  613. await using tmp = await tmpdir()
  614. await Instance.provide({
  615. directory: tmp.path,
  616. fn: async () => {
  617. const bash = await BashTool.init()
  618. const err = new Error("stop after permission")
  619. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  620. await expect(
  621. bash.execute(
  622. {
  623. command: "echo ok",
  624. workdir: os.tmpdir(),
  625. description: "Echo from temp dir",
  626. },
  627. capture(requests, err),
  628. ),
  629. ).rejects.toThrow(err.message)
  630. const extDirReq = requests.find((r) => r.permission === "external_directory")
  631. expect(extDirReq).toBeDefined()
  632. expect(extDirReq!.patterns).toContain(glob(path.join(os.tmpdir(), "*")))
  633. },
  634. })
  635. })
  636. if (process.platform === "win32") {
  637. test("normalizes external_directory workdir variants on Windows", async () => {
  638. const err = new Error("stop after permission")
  639. await using outerTmp = await tmpdir()
  640. await using tmp = await tmpdir()
  641. await Instance.provide({
  642. directory: tmp.path,
  643. fn: async () => {
  644. const bash = await BashTool.init()
  645. const want = Filesystem.normalizePathPattern(path.join(outerTmp.path, "*"))
  646. for (const dir of forms(outerTmp.path)) {
  647. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  648. await expect(
  649. bash.execute(
  650. {
  651. command: "echo ok",
  652. workdir: dir,
  653. description: "Echo from external dir",
  654. },
  655. capture(requests, err),
  656. ),
  657. ).rejects.toThrow(err.message)
  658. const extDirReq = requests.find((r) => r.permission === "external_directory")
  659. expect({ dir, patterns: extDirReq?.patterns, always: extDirReq?.always }).toEqual({
  660. dir,
  661. patterns: [want],
  662. always: [want],
  663. })
  664. }
  665. },
  666. })
  667. })
  668. if (bash) {
  669. test(
  670. "uses Git Bash /tmp semantics for external workdir",
  671. withShell({ label: "bash", shell: bash }, async () => {
  672. await Instance.provide({
  673. directory: projectRoot,
  674. fn: async () => {
  675. const bash = await BashTool.init()
  676. const err = new Error("stop after permission")
  677. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  678. const want = glob(path.join(os.tmpdir(), "*"))
  679. await expect(
  680. bash.execute(
  681. {
  682. command: "echo ok",
  683. workdir: "/tmp",
  684. description: "Echo from Git Bash tmp",
  685. },
  686. capture(requests, err),
  687. ),
  688. ).rejects.toThrow(err.message)
  689. expect(requests[0]).toMatchObject({
  690. permission: "external_directory",
  691. patterns: [want],
  692. always: [want],
  693. })
  694. },
  695. })
  696. }),
  697. )
  698. test(
  699. "uses Git Bash /tmp semantics for external file paths",
  700. withShell({ label: "bash", shell: bash }, async () => {
  701. await Instance.provide({
  702. directory: projectRoot,
  703. fn: async () => {
  704. const bash = await BashTool.init()
  705. const err = new Error("stop after permission")
  706. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  707. const want = glob(path.join(os.tmpdir(), "*"))
  708. await expect(
  709. bash.execute(
  710. {
  711. command: "cat /tmp/opencode-does-not-exist",
  712. description: "Read Git Bash tmp file",
  713. },
  714. capture(requests, err),
  715. ),
  716. ).rejects.toThrow(err.message)
  717. expect(requests[0]).toMatchObject({
  718. permission: "external_directory",
  719. patterns: [want],
  720. always: [want],
  721. })
  722. },
  723. })
  724. }),
  725. )
  726. }
  727. }
  728. each("asks for external_directory permission when file arg is outside project", async () => {
  729. await using outerTmp = await tmpdir({
  730. init: async (dir) => {
  731. await Bun.write(path.join(dir, "outside.txt"), "x")
  732. },
  733. })
  734. await using tmp = await tmpdir()
  735. await Instance.provide({
  736. directory: tmp.path,
  737. fn: async () => {
  738. const bash = await BashTool.init()
  739. const err = new Error("stop after permission")
  740. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  741. const filepath = path.join(outerTmp.path, "outside.txt")
  742. await expect(
  743. bash.execute(
  744. {
  745. command: `cat ${filepath}`,
  746. description: "Read external file",
  747. },
  748. capture(requests, err),
  749. ),
  750. ).rejects.toThrow(err.message)
  751. const extDirReq = requests.find((r) => r.permission === "external_directory")
  752. const expected = glob(path.join(outerTmp.path, "*"))
  753. expect(extDirReq).toBeDefined()
  754. expect(extDirReq!.patterns).toContain(expected)
  755. expect(extDirReq!.always).toContain(expected)
  756. },
  757. })
  758. })
  759. each("does not ask for external_directory permission when rm inside project", async () => {
  760. await using tmp = await tmpdir({
  761. init: async (dir) => {
  762. await Bun.write(path.join(dir, "tmpfile"), "x")
  763. },
  764. })
  765. await Instance.provide({
  766. directory: tmp.path,
  767. fn: async () => {
  768. const bash = await BashTool.init()
  769. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  770. await bash.execute(
  771. {
  772. command: `rm -rf ${path.join(tmp.path, "nested")}`,
  773. description: "Remove nested dir",
  774. },
  775. capture(requests),
  776. )
  777. const extDirReq = requests.find((r) => r.permission === "external_directory")
  778. expect(extDirReq).toBeUndefined()
  779. },
  780. })
  781. })
  782. each("includes always patterns for auto-approval", async () => {
  783. await using tmp = await tmpdir()
  784. await Instance.provide({
  785. directory: tmp.path,
  786. fn: async () => {
  787. const bash = await BashTool.init()
  788. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  789. await bash.execute(
  790. {
  791. command: "git log --oneline -5",
  792. description: "Git log",
  793. },
  794. capture(requests),
  795. )
  796. expect(requests.length).toBe(1)
  797. expect(requests[0].always.length).toBeGreaterThan(0)
  798. expect(requests[0].always.some((item) => item.endsWith("*"))).toBe(true)
  799. },
  800. })
  801. })
  802. each("does not ask for bash permission when command is cd only", async () => {
  803. await using tmp = await tmpdir()
  804. await Instance.provide({
  805. directory: tmp.path,
  806. fn: async () => {
  807. const bash = await BashTool.init()
  808. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  809. await bash.execute(
  810. {
  811. command: "cd .",
  812. description: "Stay in current directory",
  813. },
  814. capture(requests),
  815. )
  816. const bashReq = requests.find((r) => r.permission === "bash")
  817. expect(bashReq).toBeUndefined()
  818. },
  819. })
  820. })
  821. each("matches redirects in permission pattern", async () => {
  822. await using tmp = await tmpdir()
  823. await Instance.provide({
  824. directory: tmp.path,
  825. fn: async () => {
  826. const bash = await BashTool.init()
  827. const err = new Error("stop after permission")
  828. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  829. await expect(
  830. bash.execute(
  831. { command: "echo test > output.txt", description: "Redirect test output" },
  832. capture(requests, err),
  833. ),
  834. ).rejects.toThrow(err.message)
  835. const bashReq = requests.find((r) => r.permission === "bash")
  836. expect(bashReq).toBeDefined()
  837. expect(bashReq!.patterns).toContain("echo test > output.txt")
  838. },
  839. })
  840. })
  841. each("always pattern has space before wildcard to not include different commands", async () => {
  842. await using tmp = await tmpdir()
  843. await Instance.provide({
  844. directory: tmp.path,
  845. fn: async () => {
  846. const bash = await BashTool.init()
  847. const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
  848. await bash.execute({ command: "ls -la", description: "List" }, capture(requests))
  849. const bashReq = requests.find((r) => r.permission === "bash")
  850. expect(bashReq).toBeDefined()
  851. expect(bashReq!.always[0]).toBe("ls *")
  852. },
  853. })
  854. })
  855. })
  856. describe("tool.bash abort", () => {
  857. test("preserves output when aborted", async () => {
  858. await Instance.provide({
  859. directory: projectRoot,
  860. fn: async () => {
  861. const bash = await BashTool.init()
  862. const controller = new AbortController()
  863. const collected: string[] = []
  864. const result = bash.execute(
  865. {
  866. command: `echo before && sleep 30`,
  867. description: "Long running command",
  868. },
  869. {
  870. ...ctx,
  871. abort: controller.signal,
  872. metadata: (input) => {
  873. const output = (input.metadata as { output?: string })?.output
  874. if (output && output.includes("before") && !controller.signal.aborted) {
  875. collected.push(output)
  876. controller.abort()
  877. }
  878. },
  879. },
  880. )
  881. const res = await result
  882. expect(res.output).toContain("before")
  883. expect(res.output).toContain("User aborted the command")
  884. expect(collected.length).toBeGreaterThan(0)
  885. },
  886. })
  887. }, 15_000)
  888. test("terminates command on timeout", async () => {
  889. await Instance.provide({
  890. directory: projectRoot,
  891. fn: async () => {
  892. const bash = await BashTool.init()
  893. const result = await bash.execute(
  894. {
  895. command: `echo started && sleep 60`,
  896. description: "Timeout test",
  897. timeout: 500,
  898. },
  899. ctx,
  900. )
  901. expect(result.output).toContain("started")
  902. expect(result.output).toContain("bash tool terminated command after exceeding timeout")
  903. },
  904. })
  905. }, 15_000)
  906. test.skipIf(process.platform === "win32")("captures stderr in output", async () => {
  907. await Instance.provide({
  908. directory: projectRoot,
  909. fn: async () => {
  910. const bash = await BashTool.init()
  911. const result = await bash.execute(
  912. {
  913. command: `echo stdout_msg && echo stderr_msg >&2`,
  914. description: "Stderr test",
  915. },
  916. ctx,
  917. )
  918. expect(result.output).toContain("stdout_msg")
  919. expect(result.output).toContain("stderr_msg")
  920. expect(result.metadata.exit).toBe(0)
  921. },
  922. })
  923. })
  924. test("returns non-zero exit code", async () => {
  925. await Instance.provide({
  926. directory: projectRoot,
  927. fn: async () => {
  928. const bash = await BashTool.init()
  929. const result = await bash.execute(
  930. {
  931. command: `exit 42`,
  932. description: "Non-zero exit",
  933. },
  934. ctx,
  935. )
  936. expect(result.metadata.exit).toBe(42)
  937. },
  938. })
  939. })
  940. test("streams metadata updates progressively", async () => {
  941. await Instance.provide({
  942. directory: projectRoot,
  943. fn: async () => {
  944. const bash = await BashTool.init()
  945. const updates: string[] = []
  946. const result = await bash.execute(
  947. {
  948. command: `echo first && sleep 0.1 && echo second`,
  949. description: "Streaming test",
  950. },
  951. {
  952. ...ctx,
  953. metadata: (input) => {
  954. const output = (input.metadata as { output?: string })?.output
  955. if (output) updates.push(output)
  956. },
  957. },
  958. )
  959. expect(result.output).toContain("first")
  960. expect(result.output).toContain("second")
  961. expect(updates.length).toBeGreaterThan(1)
  962. },
  963. })
  964. })
  965. })
  966. describe("tool.bash truncation", () => {
  967. test("truncates output exceeding line limit", async () => {
  968. await Instance.provide({
  969. directory: projectRoot,
  970. fn: async () => {
  971. const bash = await BashTool.init()
  972. const lineCount = Truncate.MAX_LINES + 500
  973. const result = await bash.execute(
  974. {
  975. command: fill("lines", lineCount),
  976. description: "Generate lines exceeding limit",
  977. },
  978. ctx,
  979. )
  980. mustTruncate(result)
  981. expect(result.output).toContain("truncated")
  982. expect(result.output).toContain("The tool call succeeded but the output was truncated")
  983. },
  984. })
  985. })
  986. test("truncates output exceeding byte limit", async () => {
  987. await Instance.provide({
  988. directory: projectRoot,
  989. fn: async () => {
  990. const bash = await BashTool.init()
  991. const byteCount = Truncate.MAX_BYTES + 10000
  992. const result = await bash.execute(
  993. {
  994. command: fill("bytes", byteCount),
  995. description: "Generate bytes exceeding limit",
  996. },
  997. ctx,
  998. )
  999. mustTruncate(result)
  1000. expect(result.output).toContain("truncated")
  1001. expect(result.output).toContain("The tool call succeeded but the output was truncated")
  1002. },
  1003. })
  1004. })
  1005. test("does not truncate small output", async () => {
  1006. await Instance.provide({
  1007. directory: projectRoot,
  1008. fn: async () => {
  1009. const bash = await BashTool.init()
  1010. const result = await bash.execute(
  1011. {
  1012. command: "echo hello",
  1013. description: "Echo hello",
  1014. },
  1015. ctx,
  1016. )
  1017. expect((result.metadata as { truncated?: boolean }).truncated).toBe(false)
  1018. expect(result.output).toContain("hello")
  1019. },
  1020. })
  1021. })
  1022. test("full output is saved to file when truncated", async () => {
  1023. await Instance.provide({
  1024. directory: projectRoot,
  1025. fn: async () => {
  1026. const bash = await BashTool.init()
  1027. const lineCount = Truncate.MAX_LINES + 100
  1028. const result = await bash.execute(
  1029. {
  1030. command: fill("lines", lineCount),
  1031. description: "Generate lines for file check",
  1032. },
  1033. ctx,
  1034. )
  1035. mustTruncate(result)
  1036. const filepath = (result.metadata as { outputPath?: string }).outputPath
  1037. expect(filepath).toBeTruthy()
  1038. const saved = await Filesystem.readText(filepath!)
  1039. const lines = saved.trim().split(/\r?\n/)
  1040. expect(lines.length).toBe(lineCount)
  1041. expect(lines[0]).toBe("1")
  1042. expect(lines[lineCount - 1]).toBe(String(lineCount))
  1043. },
  1044. })
  1045. })
  1046. })