tool-shell.test.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  1. import fs from "fs/promises"
  2. import { realpathSync } from "node:fs"
  3. import path from "path"
  4. import { describe, expect } from "bun:test"
  5. import { DateTime, Deferred, 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/util/effect/layer-node"
  9. import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
  10. import { filesystem } from "@opencode-ai/util/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/util/fs-util"
  14. import { Global } from "@opencode-ai/util/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 steadyProgressCommand = isWindows
  155. ? "[Console]::Out.Write('steady'); Start-Sleep -Milliseconds 3400"
  156. : "printf steady; sleep 3.4"
  157. const bodyExitCommand = isWindows
  158. ? "[Console]::Out.Write('body'); Start-Sleep -Milliseconds 100; exit 7"
  159. : "printf body && exit 7"
  160. const overflowCommand = (bytes: number) =>
  161. isWindows
  162. ? `[Console]::Out.Write(('x' * ${bytes})); Start-Sleep -Milliseconds 100`
  163. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'`
  164. const progressOverflowCommand = (bytes: number, release: string) =>
  165. isWindows
  166. ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }`
  167. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; while [ ! -e '${release}' ]; do sleep 0.05; done`
  168. const withSession = <A, E, R>(directory: string, body: (registry: ToolRegistry.Interface) => Effect.Effect<A, E, R>) =>
  169. Effect.gen(function* () {
  170. const sessions = yield* SessionV2.Service
  171. const location = Location.Ref.make({ directory: AbsolutePath.make(directory) })
  172. yield* sessions.create({
  173. id: sessionID,
  174. title: "shell test",
  175. location,
  176. model: sessionModel,
  177. })
  178. const locations = yield* LocationServiceMap.Service
  179. const locationLayer = locations.get(location)
  180. return yield* Effect.gen(function* () {
  181. const registry = yield* ToolRegistry.Service
  182. yield* waitForTool(registry, ShellTool.name)
  183. return yield* body(registry)
  184. }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location)))
  185. })
  186. describe("ShellTool", () => {
  187. it.live("registers and returns real successful output from the active Location", () =>
  188. Effect.acquireUseRelease(
  189. Effect.promise(() => tmpdir()),
  190. (tmp) => {
  191. reset()
  192. return withSession(tmp.path, (registry) =>
  193. Effect.gen(function* () {
  194. const definitions = yield* toolDefinitions(registry)
  195. const shell = definitions.find((tool) => tool.name === "shell")
  196. expect(shell).toBeDefined()
  197. expect(shell?.outputSchema).not.toHaveProperty("properties.output")
  198. expect(
  199. (yield* toolDefinitions(registry, [{ action: "shell", resource: "*", effect: "deny" }])).map(
  200. (tool) => tool.name,
  201. ),
  202. ).not.toContain("shell")
  203. const settled = yield* settleTool(registry, call({ command: helloCommand }))
  204. expect(settled.output?.structured).toMatchObject({ exit: 0, truncated: false })
  205. expect(settled.output?.content[0]).toEqual({ type: "text", text: "hello" })
  206. expect(settled.output?.content[1]).toMatchObject({
  207. type: "text",
  208. text: expect.stringContaining("Command exited with code 0."),
  209. })
  210. expect(assertions).toMatchObject([{ sessionID, action: "shell", resources: [helloCommand] }])
  211. }),
  212. )
  213. },
  214. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  215. ),
  216. )
  217. it.live("resolves a relative workdir from the active Location", () =>
  218. Effect.acquireUseRelease(
  219. Effect.promise(() => tmpdir()),
  220. (tmp) => {
  221. reset()
  222. return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe(
  223. Effect.andThen(
  224. withSession(tmp.path, (registry) => settleTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  225. ),
  226. Effect.andThen((settled) =>
  227. Effect.sync(() =>
  228. expect(settled.output?.content[0]).toMatchObject({
  229. type: "text",
  230. text: expect.stringContaining(realpathSync(path.join(tmp.path, "src"))),
  231. }),
  232. ),
  233. ),
  234. )
  235. },
  236. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  237. ),
  238. )
  239. it.live("captures stderr-only and mixed stdout/stderr output", () =>
  240. Effect.acquireUseRelease(
  241. Effect.promise(() => tmpdir()),
  242. (tmp) => {
  243. reset()
  244. return withSession(tmp.path, (registry) =>
  245. Effect.gen(function* () {
  246. const stderr = yield* settleTool(registry, call({ command: stderrCommand }, "call-stderr"))
  247. expect(stderr.output?.structured).toMatchObject({ exit: 0, truncated: false })
  248. expect(stderr.output?.content[0]).toEqual({ type: "text", text: "stderr only" })
  249. const mixed = yield* settleTool(registry, call({ command: mixedOutputCommand }, "call-mixed"))
  250. expect(mixed.output?.structured).toMatchObject({ exit: 0, truncated: false })
  251. const output = mixed.output?.content[0]?.type === "text" ? mixed.output.content[0].text : ""
  252. expect(output).toContain("stdout")
  253. expect(output).toContain("stderr")
  254. }),
  255. )
  256. },
  257. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  258. ),
  259. )
  260. it.live("rejects a workdir that stops being a directory during approval", () =>
  261. Effect.acquireUseRelease(
  262. Effect.promise(() => tmpdir()),
  263. (tmp) => {
  264. reset()
  265. const workdir = path.join(tmp.path, "src")
  266. afterPermission = (input) =>
  267. input.action === "shell"
  268. ? Effect.promise(async () => {
  269. await fs.rm(workdir, { recursive: true })
  270. await fs.writeFile(workdir, "not a directory")
  271. }).pipe(Effect.orDie)
  272. : Effect.void
  273. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  274. Effect.andThen(
  275. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  276. ),
  277. Effect.andThen(Effect.sync(() => expect(assertions.map((input) => input.action)).toEqual(["shell"]))),
  278. )
  279. },
  280. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  281. ),
  282. )
  283. it.live("approves an explicit external workdir before shell execution", () =>
  284. Effect.acquireUseRelease(
  285. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  286. ([active, outside]) => {
  287. reset()
  288. return withSession(active.path, (registry) =>
  289. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  290. ).pipe(
  291. Effect.andThen(
  292. Effect.sync(() => {
  293. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  294. expect(assertions[0]).toMatchObject({
  295. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  296. })
  297. }),
  298. ),
  299. )
  300. },
  301. ([active, outside]) =>
  302. Effect.promise(() =>
  303. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  304. ),
  305. ),
  306. )
  307. it.live("does not execute after external-directory or shell denial", () =>
  308. Effect.acquireUseRelease(
  309. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  310. ([active, outside]) =>
  311. Effect.gen(function* () {
  312. reset()
  313. denyAction = "external_directory"
  314. yield* withSession(active.path, (registry) =>
  315. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  316. )
  317. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  318. reset()
  319. denyAction = "shell"
  320. yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand })))
  321. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  322. }),
  323. ([active, outside]) =>
  324. Effect.promise(() =>
  325. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  326. ),
  327. ),
  328. )
  329. it.live("reports external command arguments as advisory warnings without enforcing approval", () =>
  330. Effect.acquireUseRelease(
  331. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  332. ([active, outside]) => {
  333. reset()
  334. denyAction = "external_directory"
  335. const target = path.join(outside.path, "secret.txt")
  336. return withSession(active.path, (registry) => settleTool(registry, call({ command: `cat ${target}` }))).pipe(
  337. Effect.andThen((settled) =>
  338. Effect.sync(() => {
  339. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  340. expect(settled.output?.structured).not.toHaveProperty("warnings")
  341. expect(settled.output?.content[1]).toMatchObject({
  342. type: "text",
  343. text: expect.stringContaining("Warnings:"),
  344. })
  345. }),
  346. ),
  347. )
  348. },
  349. ([active, outside]) =>
  350. Effect.promise(() =>
  351. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  352. ),
  353. ),
  354. )
  355. it.live("keeps non-zero exits useful", () =>
  356. Effect.acquireUseRelease(
  357. Effect.promise(() => tmpdir()),
  358. (tmp) => {
  359. reset()
  360. return withSession(tmp.path, (registry) =>
  361. settleTool(registry, call({ command: bodyExitCommand }, "call-nonzero")),
  362. ).pipe(
  363. Effect.andThen((settled) =>
  364. Effect.sync(() => {
  365. expect(settled.output?.structured).toMatchObject({ exit: 7, truncated: false })
  366. expect(settled.output?.content[0]).toEqual({ type: "text", text: "body" })
  367. expect(settled.output?.content[1]).toMatchObject({
  368. type: "text",
  369. text: expect.stringContaining("Command exited with code 7"),
  370. })
  371. }),
  372. ),
  373. )
  374. },
  375. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  376. ),
  377. )
  378. it.live("truncates the model view and points at the saved output file when output overflows", () =>
  379. Effect.acquireUseRelease(
  380. Effect.promise(() => tmpdir()),
  381. (tmp) => {
  382. reset()
  383. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  384. return withSession(tmp.path, (registry) =>
  385. settleTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
  386. ).pipe(
  387. Effect.andThen((settled) =>
  388. Effect.sync(() => {
  389. expect(settled.output?.structured).toMatchObject({ exit: 0, truncated: true })
  390. expect(settled.output?.content[0]).toMatchObject({
  391. type: "text",
  392. text: expect.stringContaining("output truncated; full output saved to:"),
  393. })
  394. }),
  395. ),
  396. )
  397. },
  398. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  399. ),
  400. )
  401. it.live(
  402. "reports bounded output progress for a running command",
  403. () =>
  404. Effect.acquireUseRelease(
  405. Effect.promise(() => tmpdir()),
  406. (tmp) => {
  407. reset()
  408. const release = "shell-progress-release"
  409. const releasePath = path.join(tmp.path, release)
  410. return withSession(tmp.path, (registry) =>
  411. Effect.gen(function* () {
  412. const observed = yield* Deferred.make<ToolRegistry.Progress>()
  413. yield* settleTool(registry, {
  414. ...call(
  415. { command: progressOverflowCommand(ShellTool.MAX_CAPTURE_BYTES + 1024, release) },
  416. "call-progress",
  417. ),
  418. progress: (update) =>
  419. Effect.gen(function* () {
  420. if (update.structured.truncated !== true) return
  421. const content = update.content[0]
  422. if (content?.type !== "text") return
  423. if (content.text.indexOf("\n\n[output truncated; full output saved to:") !== ShellTool.MAX_CAPTURE_BYTES)
  424. return
  425. yield* Deferred.succeed(observed, update)
  426. yield* Effect.promise(() => fs.writeFile(releasePath, ""))
  427. }),
  428. })
  429. const progress = yield* Deferred.await(observed)
  430. expect(progress.structured).toEqual({ truncated: true })
  431. const content = progress.content[0]
  432. expect(content?.type).toBe("text")
  433. if (content?.type !== "text") return
  434. expect(content.text.indexOf("\n\n[output truncated; full output saved to:")).toBe(
  435. ShellTool.MAX_CAPTURE_BYTES,
  436. )
  437. }).pipe(Effect.ensuring(Effect.promise(() => fs.writeFile(releasePath, "")).pipe(Effect.ignore))),
  438. )
  439. },
  440. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  441. ),
  442. { timeout: 15_000 },
  443. )
  444. it.live(
  445. "does not repeat unchanged shell progress",
  446. () =>
  447. Effect.acquireUseRelease(
  448. Effect.promise(() => tmpdir()),
  449. (tmp) => {
  450. reset()
  451. return withSession(tmp.path, (registry) =>
  452. Effect.gen(function* () {
  453. const updates: ToolRegistry.Progress[] = []
  454. yield* settleTool(registry, {
  455. ...call({ command: steadyProgressCommand }, "call-steady-progress"),
  456. progress: (update) => Effect.sync(() => updates.push(update)),
  457. })
  458. expect(updates).toEqual([
  459. {
  460. structured: { truncated: false },
  461. content: [{ type: "text", text: "steady" }],
  462. },
  463. ])
  464. }),
  465. )
  466. },
  467. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  468. ),
  469. { timeout: 10_000 },
  470. )
  471. it.live("returns a useful timeout settlement", () =>
  472. Effect.acquireUseRelease(
  473. Effect.promise(() => tmpdir()),
  474. (tmp) => {
  475. reset()
  476. return withSession(tmp.path, (registry) =>
  477. settleTool(registry, call({ command: idleCommand, timeout: 50 })),
  478. ).pipe(
  479. Effect.andThen((settled) =>
  480. Effect.sync(() => {
  481. expect(settled.output?.structured).toMatchObject({ timeout: true, truncated: false })
  482. expect(settled.output?.content[1]).toMatchObject({
  483. type: "text",
  484. text: expect.stringContaining("Command timed out"),
  485. })
  486. }),
  487. ),
  488. )
  489. },
  490. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  491. ),
  492. )
  493. it.live("returns the shell id for a background command", () =>
  494. Effect.acquireUseRelease(
  495. Effect.promise(() => tmpdir()),
  496. (tmp) => {
  497. reset()
  498. return withSession(tmp.path, (registry) =>
  499. Effect.gen(function* () {
  500. const events = yield* EventV2.Service
  501. const admitted = yield* events.subscribe(SessionEvent.InputAdmitted).pipe(
  502. Stream.filter((event) => event.data.sessionID === sessionID && event.data.input.type === "synthetic"),
  503. Stream.runHead,
  504. Effect.forkScoped({ startImmediately: true }),
  505. )
  506. const settled = yield* settleTool(registry, call({ command: idleCommand, timeout: 50, background: true }))
  507. const structured = settled.output?.structured as Record<string, unknown> | undefined
  508. const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined
  509. expect(settled.output?.structured).toMatchObject({ truncated: false })
  510. expect(shellID).toStartWith("sh_")
  511. const shell = yield* Shell.Service
  512. if (!shellID) return
  513. const id = ShellSchema.ID.make(shellID)
  514. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  515. expect((yield* shell.wait(id)).status).toBe("timeout")
  516. expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.input.data).toMatchObject({
  517. description: idleCommand,
  518. metadata: {
  519. source: "shell",
  520. state: "completed",
  521. },
  522. })
  523. }),
  524. )
  525. },
  526. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  527. ),
  528. )
  529. it.live("updates and clears a running shell timeout", () =>
  530. Effect.acquireUseRelease(
  531. Effect.promise(() => tmpdir()),
  532. (tmp) => {
  533. reset()
  534. return withSession(tmp.path, (registry) =>
  535. Effect.gen(function* () {
  536. const shell = yield* Shell.Service
  537. const timed = yield* settleTool(
  538. registry,
  539. call({ command: idleCommand, background: true }, "call-updated-timeout"),
  540. )
  541. const timedID = (timed.output?.structured as Record<string, unknown> | undefined)?.shellID
  542. expect(typeof timedID).toBe("string")
  543. if (typeof timedID !== "string") return
  544. const timedShellID = ShellSchema.ID.make(timedID)
  545. yield* shell.timeout(timedShellID, 50)
  546. expect((yield* shell.wait(timedShellID)).status).toBe("timeout")
  547. const cleared = yield* settleTool(
  548. registry,
  549. call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"),
  550. )
  551. const clearedID = (cleared.output?.structured as Record<string, unknown> | undefined)?.shellID
  552. expect(typeof clearedID).toBe("string")
  553. if (typeof clearedID !== "string") return
  554. const clearedShellID = ShellSchema.ID.make(clearedID)
  555. yield* shell.timeout(clearedShellID, 0)
  556. yield* Effect.sleep(Duration.millis(100))
  557. expect((yield* shell.get(clearedShellID)).status).toBe("running")
  558. yield* shell.remove(clearedShellID)
  559. }),
  560. )
  561. },
  562. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  563. ),
  564. )
  565. it.live("backgrounds a foreground command when the session is signaled", () =>
  566. Effect.acquireUseRelease(
  567. Effect.promise(() => tmpdir()),
  568. (tmp) => {
  569. reset()
  570. return withSession(tmp.path, (registry) =>
  571. Effect.gen(function* () {
  572. const jobs = yield* Job.Service
  573. const scope = yield* Scope.Scope
  574. const waiting = yield* settleTool(
  575. registry,
  576. call({ command: idleCommand, timeout: 50 }, "call-background-signal"),
  577. ).pipe(Effect.forkIn(scope, { startImmediately: true }))
  578. const backgroundWhenReady = (remaining = 1000): Effect.Effect<Job.Info[], Error> =>
  579. Effect.gen(function* () {
  580. const backgrounded = yield* jobs.backgroundAll({ sessionID })
  581. if (backgrounded.length > 0) return backgrounded
  582. if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job"))
  583. yield* Effect.promise(() => Bun.sleep(1))
  584. return yield* backgroundWhenReady(remaining - 1)
  585. })
  586. expect(yield* backgroundWhenReady()).toMatchObject([{ id: "call-background-signal", type: "shell" }])
  587. const settled = yield* Fiber.join(waiting)
  588. const structured = settled.output?.structured as Record<string, unknown> | undefined
  589. const shellID = typeof structured?.shellID === "string" ? structured.shellID : undefined
  590. expect(settled.output?.structured).toMatchObject({ truncated: false })
  591. expect(settled.output?.content[0]).toEqual({
  592. type: "text",
  593. text: "The command was moved to the background.",
  594. })
  595. expect(settled.output?.content[1]).toMatchObject({
  596. type: "text",
  597. text: expect.stringContaining("DO NOT sleep, poll"),
  598. })
  599. expect(shellID).toStartWith("sh_")
  600. const shell = yield* Shell.Service
  601. if (!shellID) return
  602. const id = ShellSchema.ID.make(shellID)
  603. yield* Effect.sleep(Duration.millis(100))
  604. expect((yield* shell.get(id)).status).toBe("running")
  605. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  606. yield* shell.remove(id)
  607. }),
  608. )
  609. },
  610. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  611. ),
  612. )
  613. })