tool-shell.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. import fs from "fs/promises"
  2. import { realpathSync } from "node:fs"
  3. import path from "path"
  4. import { describe, expect, test } from "bun:test"
  5. import { DateTime, Duration, Effect, Fiber, Layer, Scope, Stream } from "effect"
  6. import { Money } from "@opencode-ai/schema/money"
  7. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  8. import { LayerNode } from "@opencode-ai/core/effect/layer-node"
  9. import { makeGlobalNode } from "@opencode-ai/core/effect/app-node"
  10. import { filesystem } from "@opencode-ai/core/effect/app-node-platform"
  11. import { Database } from "@opencode-ai/core/database/database"
  12. import { EventV2 } from "@opencode-ai/core/event"
  13. import { FSUtil } from "@opencode-ai/core/fs-util"
  14. import { Global } from "@opencode-ai/core/global"
  15. import { Location } from "@opencode-ai/core/location"
  16. import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
  17. import { ModelV2 } from "@opencode-ai/core/model"
  18. import { ProviderV2 } from "@opencode-ai/core/provider"
  19. import { AbsolutePath } from "@opencode-ai/core/schema"
  20. import { AgentV2 } from "@opencode-ai/core/agent"
  21. import { Job } from "@opencode-ai/core/job"
  22. import { SessionV2 } from "@opencode-ai/core/session"
  23. import { SessionEvent } from "@opencode-ai/core/session/event"
  24. import { SessionExecution } from "@opencode-ai/core/session/execution"
  25. import { SessionMessage } from "@opencode-ai/core/session/message"
  26. import { SessionStore } from "@opencode-ai/core/session/store"
  27. import { PermissionV2 } from "@opencode-ai/core/permission"
  28. import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
  29. import { Shell } from "@opencode-ai/core/shell"
  30. import { Shell as ShellSchema } from "@opencode-ai/schema/shell"
  31. import { ShellTool } from "@opencode-ai/core/tool/shell"
  32. import { ToolRegistry } from "@opencode-ai/core/tool/registry"
  33. import { ToolOutputStore } from "@opencode-ai/core/tool-output-store"
  34. import { tmpdir } from "./fixture/tmpdir"
  35. import { testEffect } from "./lib/effect"
  36. import { toolIdentity, executeTool, settleTool, toolDefinitions, waitForTool } from "./lib/tool"
  37. const sessionID = SessionV2.ID.make("ses_shell_tool_test")
  38. const sessionModel = ModelV2.Ref.make({ id: ModelV2.ID.make("test"), providerID: ProviderV2.ID.make("test") })
  39. const assertions: PermissionV2.AssertInput[] = []
  40. let denyAction: string | undefined
  41. let afterPermission = (_input: PermissionV2.AssertInput): Effect.Effect<void> => Effect.void
  42. const permission = Layer.succeed(
  43. PermissionV2.Service,
  44. PermissionV2.Service.of({
  45. assert: (input) =>
  46. Effect.sync(() => assertions.push(input)).pipe(
  47. Effect.andThen(Effect.suspend(() => afterPermission(input))),
  48. Effect.andThen(
  49. input.action === denyAction
  50. ? Effect.fail(
  51. new PermissionV2.BlockedError({
  52. rules: [],
  53. permission: input.action,
  54. resources: input.resources,
  55. }),
  56. )
  57. : Effect.void,
  58. ),
  59. ),
  60. ask: () => Effect.die("unused"),
  61. reply: () => Effect.die("unused"),
  62. get: () => Effect.die("unused"),
  63. forSession: () => Effect.die("unused"),
  64. list: () => Effect.die("unused"),
  65. }),
  66. )
  67. const reset = () => {
  68. assertions.length = 0
  69. denyAction = undefined
  70. afterPermission = () => Effect.void
  71. }
  72. const executionNode = makeGlobalNode({
  73. service: SessionExecution.Service,
  74. layer: Layer.effect(
  75. SessionExecution.Service,
  76. Effect.gen(function* () {
  77. const events = yield* EventV2.Service
  78. const store = yield* SessionStore.Service
  79. const complete = Effect.fn("ShellTest.complete")(function* (id: SessionV2.ID) {
  80. const session = yield* store.get(id)
  81. if (!session) return
  82. const assistantMessageID = SessionMessage.ID.create()
  83. yield* events.publish(SessionEvent.Step.Started, {
  84. sessionID: id,
  85. assistantMessageID,
  86. agent: session.agent ?? AgentV2.ID.make("code"),
  87. model: sessionModel,
  88. })
  89. yield* events.publish(SessionEvent.Text.Started, {
  90. sessionID: id,
  91. assistantMessageID,
  92. ordinal: 0,
  93. })
  94. yield* events.publish(SessionEvent.Text.Ended, {
  95. sessionID: id,
  96. assistantMessageID,
  97. ordinal: 0,
  98. text: "ok",
  99. })
  100. yield* events.publish(SessionEvent.Step.Ended, {
  101. sessionID: id,
  102. assistantMessageID,
  103. finish: "stop",
  104. cost: Money.USD.zero,
  105. tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
  106. })
  107. })
  108. return SessionExecution.Service.of({
  109. active: Effect.succeed(new Set()),
  110. resume: complete,
  111. wake: () => Effect.void,
  112. interrupt: () => Effect.void,
  113. awaitIdle: (id) => complete(id).pipe(Effect.exit, Effect.asVoid),
  114. })
  115. }),
  116. ),
  117. deps: [EventV2.node, SessionStore.node],
  118. })
  119. const layer = AppNodeBuilder.build(
  120. LayerNode.group([
  121. Database.node,
  122. EventV2.node,
  123. Job.node,
  124. ToolOutputStore.cleanupNode,
  125. SessionV2.node,
  126. SessionExecution.node,
  127. PluginRuntime.providerNode,
  128. LocationServiceMap.node,
  129. filesystem,
  130. FSUtil.node,
  131. Global.node,
  132. ]),
  133. [
  134. [SessionExecution.node, executionNode],
  135. [PermissionV2.node, permission],
  136. ],
  137. )
  138. const it = testEffect(layer)
  139. const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({
  140. sessionID,
  141. ...toolIdentity,
  142. call: { type: "tool-call" as const, id, name: "shell", input },
  143. })
  144. const isWindows = process.platform === "win32"
  145. const cwdCommand = isWindows ? "(Get-Location).Path; Start-Sleep -Milliseconds 100" : "pwd"
  146. const helloCommand = isWindows ? "[Console]::Out.Write('hello'); Start-Sleep -Milliseconds 100" : "printf hello"
  147. const stderrCommand = isWindows
  148. ? "[Console]::Error.Write('stderr only'); Start-Sleep -Milliseconds 100"
  149. : "printf 'stderr only' >&2"
  150. const mixedOutputCommand = isWindows
  151. ? "[Console]::Out.Write('stdout'); Start-Sleep -Milliseconds 50; [Console]::Error.Write('stderr'); Start-Sleep -Milliseconds 100"
  152. : "printf stdout; sleep 0.05; printf stderr >&2"
  153. const idleCommand = isWindows ? "Start-Sleep -Seconds 60" : "sleep 60"
  154. const bodyExitCommand = isWindows
  155. ? "[Console]::Out.Write('body'); Start-Sleep -Milliseconds 100; exit 7"
  156. : "printf body && exit 7"
  157. const overflowCommand = (bytes: number) =>
  158. isWindows
  159. ? `[Console]::Out.Write(('x' * ${bytes})); Start-Sleep -Milliseconds 100`
  160. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'`
  161. const withSession = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) =>
  162. Effect.gen(function* () {
  163. const sessions = yield* SessionV2.Service
  164. const location = Location.Ref.make({ directory: AbsolutePath.make(directory) })
  165. yield* sessions.create({
  166. id: sessionID,
  167. title: "shell test",
  168. location,
  169. model: sessionModel,
  170. })
  171. const locations = yield* LocationServiceMap.Service
  172. const locationLayer = locations.get(location)
  173. return yield* Effect.gen(function* () {
  174. const registry = yield* ToolRegistry.Service
  175. yield* waitForTool(registry, ShellTool.name)
  176. return yield* body(registry)
  177. }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location)))
  178. })
  179. describe("ShellTool", () => {
  180. it.live("registers and returns real successful output from the active Location", () =>
  181. Effect.acquireUseRelease(
  182. Effect.promise(() => tmpdir()),
  183. (tmp) => {
  184. reset()
  185. return withSession(tmp.path, (registry) =>
  186. Effect.gen(function* () {
  187. const definitions = yield* toolDefinitions(registry)
  188. const shell = definitions.find((tool) => tool.name === "shell")
  189. expect(shell).toBeDefined()
  190. expect(shell?.outputSchema).not.toHaveProperty("properties.output")
  191. expect(
  192. (yield* toolDefinitions(registry, [{ action: "shell", resource: "*", effect: "deny" }])).map(
  193. (tool) => tool.name,
  194. ),
  195. ).not.toContain("shell")
  196. const settled = yield* settleTool(registry, call({ command: helloCommand }))
  197. expect(settled.output?.structured).toMatchObject({ exit: 0, truncated: false })
  198. expect(settled.output?.content[0]).toEqual({ type: "text", text: "hello" })
  199. expect(settled.output?.content[1]).toMatchObject({
  200. type: "text",
  201. text: expect.stringContaining("Command exited with code 0."),
  202. })
  203. expect(assertions).toMatchObject([{ sessionID, action: "shell", resources: [helloCommand] }])
  204. }),
  205. )
  206. },
  207. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  208. ),
  209. )
  210. it.live("resolves a relative workdir from the active Location", () =>
  211. Effect.acquireUseRelease(
  212. Effect.promise(() => tmpdir()),
  213. (tmp) => {
  214. reset()
  215. return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe(
  216. Effect.andThen(
  217. withSession(tmp.path, (registry) => settleTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  218. ),
  219. Effect.andThen((settled) =>
  220. Effect.sync(() =>
  221. expect(settled.output?.content[0]).toMatchObject({
  222. type: "text",
  223. text: expect.stringContaining(realpathSync(path.join(tmp.path, "src"))),
  224. }),
  225. ),
  226. ),
  227. )
  228. },
  229. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  230. ),
  231. )
  232. it.live("captures stderr-only and mixed stdout/stderr output", () =>
  233. Effect.acquireUseRelease(
  234. Effect.promise(() => tmpdir()),
  235. (tmp) => {
  236. reset()
  237. return withSession(tmp.path, (registry) =>
  238. Effect.gen(function* () {
  239. const stderr = yield* settleTool(registry, call({ command: stderrCommand }, "call-stderr"))
  240. expect(stderr.output?.structured).toMatchObject({ exit: 0, truncated: false })
  241. expect(stderr.output?.content[0]).toEqual({ type: "text", text: "stderr only" })
  242. const mixed = yield* settleTool(registry, call({ command: mixedOutputCommand }, "call-mixed"))
  243. expect(mixed.output?.structured).toMatchObject({ exit: 0, truncated: false })
  244. const output = mixed.output?.content[0]?.type === "text" ? mixed.output.content[0].text : ""
  245. expect(output).toContain("stdout")
  246. expect(output).toContain("stderr")
  247. }),
  248. )
  249. },
  250. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  251. ),
  252. )
  253. it.live("rejects a workdir that stops being a directory during approval", () =>
  254. Effect.acquireUseRelease(
  255. Effect.promise(() => tmpdir()),
  256. (tmp) => {
  257. reset()
  258. const workdir = path.join(tmp.path, "src")
  259. afterPermission = (input) =>
  260. input.action === "shell"
  261. ? Effect.promise(async () => {
  262. await fs.rm(workdir, { recursive: true })
  263. await fs.writeFile(workdir, "not a directory")
  264. }).pipe(Effect.orDie)
  265. : Effect.void
  266. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  267. Effect.andThen(
  268. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  269. ),
  270. Effect.andThen(Effect.sync(() => expect(assertions.map((input) => input.action)).toEqual(["shell"]))),
  271. )
  272. },
  273. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  274. ),
  275. )
  276. it.live("approves an explicit external workdir before shell execution", () =>
  277. Effect.acquireUseRelease(
  278. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  279. ([active, outside]) => {
  280. reset()
  281. return withSession(active.path, (registry) =>
  282. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  283. ).pipe(
  284. Effect.andThen(
  285. Effect.sync(() => {
  286. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  287. expect(assertions[0]).toMatchObject({
  288. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  289. })
  290. }),
  291. ),
  292. )
  293. },
  294. ([active, outside]) =>
  295. Effect.promise(() =>
  296. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  297. ),
  298. ),
  299. )
  300. it.live("does not execute after external-directory or shell denial", () =>
  301. Effect.acquireUseRelease(
  302. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  303. ([active, outside]) =>
  304. Effect.gen(function* () {
  305. reset()
  306. denyAction = "external_directory"
  307. yield* withSession(active.path, (registry) =>
  308. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  309. )
  310. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  311. reset()
  312. denyAction = "shell"
  313. yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand })))
  314. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  315. }),
  316. ([active, outside]) =>
  317. Effect.promise(() =>
  318. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  319. ),
  320. ),
  321. )
  322. it.live("reports external command arguments as advisory warnings without enforcing approval", () =>
  323. Effect.acquireUseRelease(
  324. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  325. ([active, outside]) => {
  326. reset()
  327. denyAction = "external_directory"
  328. const target = path.join(outside.path, "secret.txt")
  329. return withSession(active.path, (registry) => settleTool(registry, call({ command: `cat ${target}` }))).pipe(
  330. Effect.andThen((settled) =>
  331. Effect.sync(() => {
  332. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  333. expect(settled.output?.structured).not.toHaveProperty("warnings")
  334. expect(settled.output?.content[1]).toMatchObject({
  335. type: "text",
  336. text: expect.stringContaining("Warnings:"),
  337. })
  338. }),
  339. ),
  340. )
  341. },
  342. ([active, outside]) =>
  343. Effect.promise(() =>
  344. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  345. ),
  346. ),
  347. )
  348. it.live("keeps non-zero exits useful", () =>
  349. Effect.acquireUseRelease(
  350. Effect.promise(() => tmpdir()),
  351. (tmp) => {
  352. reset()
  353. return withSession(tmp.path, (registry) =>
  354. settleTool(registry, call({ command: bodyExitCommand }, "call-nonzero")),
  355. ).pipe(
  356. Effect.andThen((settled) =>
  357. Effect.sync(() => {
  358. expect(settled.output?.structured).toMatchObject({ exit: 7, truncated: false })
  359. expect(settled.output?.content[0]).toEqual({ type: "text", text: "body" })
  360. expect(settled.output?.content[1]).toMatchObject({
  361. type: "text",
  362. text: expect.stringContaining("Command exited with code 7"),
  363. })
  364. }),
  365. ),
  366. )
  367. },
  368. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  369. ),
  370. )
  371. it.live("truncates the model view and points at the saved output file when output overflows", () =>
  372. Effect.acquireUseRelease(
  373. Effect.promise(() => tmpdir()),
  374. (tmp) => {
  375. reset()
  376. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  377. return withSession(tmp.path, (registry) =>
  378. settleTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
  379. ).pipe(
  380. Effect.andThen((settled) =>
  381. Effect.sync(() => {
  382. expect(settled.output?.structured).toMatchObject({ exit: 0, truncated: true })
  383. expect(settled.output?.content[0]).toMatchObject({
  384. type: "text",
  385. text: expect.stringContaining("output truncated; full output saved to:"),
  386. })
  387. }),
  388. ),
  389. )
  390. },
  391. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  392. ),
  393. )
  394. it.live("returns a useful timeout settlement", () =>
  395. Effect.acquireUseRelease(
  396. Effect.promise(() => tmpdir()),
  397. (tmp) => {
  398. reset()
  399. return withSession(tmp.path, (registry) =>
  400. settleTool(registry, call({ command: idleCommand, timeout: 50 })),
  401. ).pipe(
  402. Effect.andThen((settled) =>
  403. Effect.sync(() => {
  404. expect(settled.output?.structured).toMatchObject({ timeout: true, truncated: false })
  405. expect(settled.output?.content[1]).toMatchObject({
  406. type: "text",
  407. text: expect.stringContaining("Command timed out"),
  408. })
  409. }),
  410. ),
  411. )
  412. },
  413. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  414. ),
  415. )
  416. it.live("returns the shell id for a background command", () =>
  417. Effect.acquireUseRelease(
  418. Effect.promise(() => tmpdir()),
  419. (tmp) => {
  420. reset()
  421. return withSession(tmp.path, (registry) =>
  422. Effect.gen(function* () {
  423. const events = yield* EventV2.Service
  424. const admitted = yield* events.subscribe(SessionEvent.InputAdmitted).pipe(
  425. Stream.filter((event) => event.data.sessionID === sessionID && event.data.input.type === "synthetic"),
  426. Stream.runHead,
  427. Effect.forkScoped({ startImmediately: true }),
  428. )
  429. const settled = yield* settleTool(registry, call({ command: idleCommand, timeout: 50, background: true }))
  430. const structured = settled.output?.structured as Record<string, unknown> | undefined
  431. const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined
  432. expect(settled.output?.structured).toMatchObject({ truncated: false })
  433. expect(shellID).toStartWith("sh_")
  434. const shell = yield* Shell.Service
  435. if (!shellID) return
  436. const id = ShellSchema.ID.make(shellID)
  437. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  438. expect((yield* shell.wait(id)).status).toBe("timeout")
  439. expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.input.data).toMatchObject({
  440. description: idleCommand,
  441. metadata: {
  442. source: "shell",
  443. state: "completed",
  444. },
  445. })
  446. }),
  447. )
  448. },
  449. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  450. ),
  451. )
  452. it.live("updates and clears a running shell timeout", () =>
  453. Effect.acquireUseRelease(
  454. Effect.promise(() => tmpdir()),
  455. (tmp) => {
  456. reset()
  457. return withSession(tmp.path, (registry) =>
  458. Effect.gen(function* () {
  459. const shell = yield* Shell.Service
  460. const timed = yield* settleTool(
  461. registry,
  462. call({ command: idleCommand, background: true }, "call-updated-timeout"),
  463. )
  464. const timedID = (timed.output?.structured as Record<string, unknown> | undefined)?.shellID
  465. expect(typeof timedID).toBe("string")
  466. if (typeof timedID !== "string") return
  467. const timedShellID = ShellSchema.ID.make(timedID)
  468. yield* shell.timeout(timedShellID, 50)
  469. expect((yield* shell.wait(timedShellID)).status).toBe("timeout")
  470. const cleared = yield* settleTool(
  471. registry,
  472. call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"),
  473. )
  474. const clearedID = (cleared.output?.structured as Record<string, unknown> | undefined)?.shellID
  475. expect(typeof clearedID).toBe("string")
  476. if (typeof clearedID !== "string") return
  477. const clearedShellID = ShellSchema.ID.make(clearedID)
  478. yield* shell.timeout(clearedShellID, 0)
  479. yield* Effect.sleep(Duration.millis(100))
  480. expect((yield* shell.get(clearedShellID)).status).toBe("running")
  481. yield* shell.remove(clearedShellID)
  482. }),
  483. )
  484. },
  485. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  486. ),
  487. )
  488. it.live("backgrounds a foreground command when the session is signaled", () =>
  489. Effect.acquireUseRelease(
  490. Effect.promise(() => tmpdir()),
  491. (tmp) => {
  492. reset()
  493. return withSession(tmp.path, (registry) =>
  494. Effect.gen(function* () {
  495. const jobs = yield* Job.Service
  496. const scope = yield* Scope.Scope
  497. const waiting = yield* settleTool(
  498. registry,
  499. call({ command: idleCommand, timeout: 50 }, "call-background-signal"),
  500. ).pipe(Effect.forkIn(scope, { startImmediately: true }))
  501. const backgroundWhenReady = (remaining = 1000): Effect.Effect<Job.Info[], Error> =>
  502. Effect.gen(function* () {
  503. const backgrounded = yield* jobs.backgroundAll({ sessionID })
  504. if (backgrounded.length > 0) return backgrounded
  505. if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job"))
  506. yield* Effect.promise(() => Bun.sleep(1))
  507. return yield* backgroundWhenReady(remaining - 1)
  508. })
  509. expect(yield* backgroundWhenReady()).toMatchObject([{ id: "call-background-signal", type: "shell" }])
  510. const settled = yield* Fiber.join(waiting)
  511. const structured = settled.output?.structured as Record<string, unknown> | undefined
  512. const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined
  513. expect(settled.output?.structured).toMatchObject({ truncated: false })
  514. expect(settled.output?.content[0]).toEqual({
  515. type: "text",
  516. text: "The command was moved to the background.",
  517. })
  518. expect(settled.output?.content[1]).toMatchObject({
  519. type: "text",
  520. text: expect.stringContaining("DO NOT sleep, poll"),
  521. })
  522. expect(shellID).toStartWith("sh_")
  523. const shell = yield* Shell.Service
  524. if (!shellID) return
  525. const id = ShellSchema.ID.make(shellID)
  526. yield* Effect.sleep(Duration.millis(100))
  527. expect((yield* shell.get(id)).status).toBe("running")
  528. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  529. yield* shell.remove(id)
  530. }),
  531. )
  532. },
  533. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  534. ),
  535. )
  536. })
  537. test("keeps locked deferred parity TODOs visible", async () => {
  538. const source = await fs.readFile(new URL("../src/tool/shell.ts", import.meta.url), "utf8")
  539. for (const todo of [
  540. "Port tree-sitter bash / PowerShell parser-based approval reduction.",
  541. "Port BashArity reusable command-prefix approvals.",
  542. "Replace token-based command-argument external-directory advisories with parser-based detection.",
  543. "Restore PowerShell and cmd-specific invocation/path handling on Windows.",
  544. "Add plugin shell.env environment augmentation once V2 plugin hooks exist.",
  545. "Add durable/live progress metadata streaming for long-running commands once V2 tool invocation progress context is wired.",
  546. "Persist job status and define restart recovery before exposing remote observation.",
  547. "Revisit process-group cleanup and platform coverage with shell-specific tests if current AppProcess semantics do not fully cover it.",
  548. "Revisit binary output handling if stdout/stderr decoding is text-only.",
  549. "Stream full shell output into managed storage while retaining only a bounded in-memory preview.",
  550. ]) {
  551. expect(source).toContain(`TODO: ${todo}`)
  552. }
  553. })