tool-shell.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import fs from "fs/promises"
  2. import { realpathSync } from "node:fs"
  3. import os from "os"
  4. import path from "path"
  5. import { describe, expect } from "bun:test"
  6. import { DateTime, Deferred, Duration, Effect, Fiber, Layer, Scope, Stream } from "effect"
  7. import { Money } from "@opencode-ai/schema/money"
  8. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  9. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  10. import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
  11. import { filesystem } from "@opencode-ai/util/effect/app-node-platform"
  12. import { Database } from "@opencode-ai/core/database/database"
  13. import { Bus } from "@opencode-ai/core/bus"
  14. import { FSUtil } from "@opencode-ai/util/fs-util"
  15. import { Global } from "@opencode-ai/util/global"
  16. import { Location } from "@opencode-ai/core/location"
  17. import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
  18. import { Model } from "@opencode-ai/core/model"
  19. import { Provider } from "@opencode-ai/core/provider"
  20. import { AbsolutePath } from "@opencode-ai/core/schema"
  21. import { Agent } from "@opencode-ai/core/agent"
  22. import { Job } from "@opencode-ai/core/job"
  23. import { Session } from "@opencode-ai/core/session"
  24. import { SessionEvent } from "@opencode-ai/core/session/event"
  25. import { SessionExecution } from "@opencode-ai/core/session/execution"
  26. import { SessionMessage } from "@opencode-ai/core/session/message"
  27. import { SessionStore } from "@opencode-ai/core/session/store"
  28. import { Permission } from "@opencode-ai/core/permission"
  29. import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
  30. import { Shell } from "@opencode-ai/core/shell"
  31. import { Shell as ShellSchema } from "@opencode-ai/schema/shell"
  32. import { ShellTool } from "@opencode-ai/core/tool/plugin/shell"
  33. import { Tool } from "@opencode-ai/core/tool"
  34. import { tmpdir } from "./fixture/tmpdir"
  35. import { testEffect } from "./lib/effect"
  36. import { toolIdentity, executeTool, toolDefinitions, waitForTool } from "./lib/tool"
  37. const sessionID = Session.ID.make("ses_shell_tool_test")
  38. const sessionModel = Model.Ref.make({ id: Model.ID.make("test"), providerID: Provider.ID.make("test") })
  39. const assertions: Permission.AssertInput[] = []
  40. let denyAction: string | undefined
  41. let afterPermission = (_input: Permission.AssertInput): Effect.Effect<void> => Effect.void
  42. const permission = Layer.succeed(
  43. Permission.Service,
  44. Permission.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 Permission.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 bus = yield* Bus.Service
  78. const store = yield* SessionStore.Service
  79. const complete = Effect.fn("ShellTest.complete")(function* (id: Session.ID) {
  80. const session = yield* store.get(id)
  81. if (!session) return
  82. const assistantMessageID = SessionMessage.ID.create()
  83. yield* bus.publish(SessionEvent.Step.Started, {
  84. sessionID: id,
  85. assistantMessageID,
  86. agent: session.agent ?? Agent.ID.make("code"),
  87. model: sessionModel,
  88. })
  89. yield* bus.publish(SessionEvent.Text.Started, {
  90. sessionID: id,
  91. assistantMessageID,
  92. ordinal: 0,
  93. })
  94. yield* bus.publish(SessionEvent.Text.Ended, {
  95. sessionID: id,
  96. assistantMessageID,
  97. ordinal: 0,
  98. text: "ok",
  99. })
  100. yield* bus.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: [Bus.node, SessionStore.node],
  118. })
  119. const layer = AppNodeBuilder.build(
  120. LayerNode.group([
  121. Database.node,
  122. Bus.node,
  123. Job.node,
  124. Session.node,
  125. SessionExecution.node,
  126. PluginRuntime.providerNode,
  127. LocationServiceMap.node,
  128. filesystem,
  129. FSUtil.node,
  130. Global.node,
  131. ]),
  132. [
  133. [SessionExecution.node, executionNode],
  134. [Permission.node, permission],
  135. ],
  136. )
  137. const it = testEffect(layer)
  138. const call = (input: typeof ShellTool.Input.Type, id = "call-shell") => ({
  139. sessionID,
  140. ...toolIdentity,
  141. call: { type: "tool-call" as const, id, name: "shell", input },
  142. })
  143. const isWindows = process.platform === "win32"
  144. const cwdCommand = isWindows ? "(Get-Location).Path; Start-Sleep -Milliseconds 100" : "pwd"
  145. const helloCommand = isWindows ? "[Console]::Out.Write('hello'); Start-Sleep -Milliseconds 100" : "printf hello"
  146. const stderrCommand = isWindows
  147. ? "[Console]::Error.Write('stderr only'); Start-Sleep -Milliseconds 100"
  148. : "printf 'stderr only' >&2"
  149. const mixedOutputCommand = isWindows
  150. ? "[Console]::Out.Write('stdout'); Start-Sleep -Milliseconds 50; [Console]::Error.Write('stderr'); Start-Sleep -Milliseconds 100"
  151. : "printf stdout; sleep 0.05; printf stderr >&2"
  152. const idleCommand = isWindows ? "Start-Sleep -Seconds 60" : "sleep 60"
  153. const timeoutOutputCommand = isWindows
  154. ? "[Console]::Out.Write('before timeout'); Start-Sleep -Seconds 60"
  155. : "printf 'before timeout'; sleep 60"
  156. const steadyProgressCommand = isWindows
  157. ? "[Console]::Out.Write('steady'); Start-Sleep -Milliseconds 3400"
  158. : "printf steady; sleep 3.4"
  159. const bodyExitCommand = isWindows
  160. ? "[Console]::Out.Write('body'); Start-Sleep -Milliseconds 100; exit 7"
  161. : "printf body && exit 7"
  162. const overflowCommand = (bytes: number) =>
  163. isWindows
  164. ? `[Console]::Out.Write('output-start' + ('x' * ${bytes}) + 'output-end'); Start-Sleep -Milliseconds 100`
  165. : `printf output-start; head -c ${bytes} /dev/zero | tr '\\0' 'x'; printf output-end`
  166. const progressOverflowCommand = (bytes: number, release: string) =>
  167. isWindows
  168. ? `[Console]::Out.Write(('x' * ${bytes})); while (!(Test-Path -LiteralPath '${release}')) { Start-Sleep -Milliseconds 50 }`
  169. : `head -c ${bytes} /dev/zero | tr '\\0' 'x'; while [ ! -e '${release}' ]; do sleep 0.05; done`
  170. const withSession = <A, E, R>(directory: string, body: (registry: Tool.Interface) => Effect.Effect<A, E, R>) =>
  171. Effect.gen(function* () {
  172. const sessions = yield* Session.Service
  173. const location = Location.Ref.make({ directory: AbsolutePath.make(directory) })
  174. yield* sessions.create({
  175. id: sessionID,
  176. title: "shell test",
  177. location,
  178. model: sessionModel,
  179. })
  180. const locations = yield* LocationServiceMap.Service
  181. const locationLayer = locations.get(location)
  182. return yield* Effect.gen(function* () {
  183. const registry = yield* Tool.Service
  184. yield* waitForTool(registry, ShellTool.name)
  185. return yield* body(registry)
  186. }).pipe(Effect.provide(locationLayer), Effect.ensuring(locations.invalidate(location)))
  187. })
  188. describe("ShellTool", () => {
  189. it.live("registers and returns real successful output from the active Location", () =>
  190. Effect.acquireUseRelease(
  191. Effect.promise(() => tmpdir()),
  192. (tmp) => {
  193. reset()
  194. return withSession(tmp.path, (registry) =>
  195. Effect.gen(function* () {
  196. const definitions = yield* toolDefinitions(registry)
  197. const definition = definitions.find((tool) => tool.name === "shell")
  198. expect(definition?.description).toStartWith("Execute a shell command and return its output.")
  199. expect(definition?.inputSchema).not.toHaveProperty("properties.timeout.maximum")
  200. // Code Mode receives the declared output schema, including the command output text.
  201. expect(definition?.outputSchema).toHaveProperty("properties.output")
  202. expect(
  203. (yield* toolDefinitions(registry, [{ action: "shell", resource: "*", effect: "deny" }])).map(
  204. (tool) => tool.name,
  205. ),
  206. ).not.toContain("shell")
  207. const settled = yield* executeTool(registry, call({ command: helloCommand }))
  208. expect(settled.status).toBe("completed")
  209. expect(settled.metadata).toMatchObject({ exit: 0, truncated: false })
  210. expect(settled.content?.[0]).toEqual({ type: "text", text: "hello" })
  211. expect(settled.content?.[1]).toMatchObject({
  212. type: "text",
  213. text: expect.stringContaining("Command exited with code 0."),
  214. })
  215. expect(assertions).toMatchObject([
  216. { sessionID, action: "shell", resources: [isWindows ? "Start-Sleep -Milliseconds 100" : helloCommand] },
  217. ])
  218. expect(assertions[0]?.save).toEqual([isWindows ? "Start-Sleep *" : "printf *"])
  219. }),
  220. )
  221. },
  222. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  223. ),
  224. )
  225. it.live("resolves a relative workdir from the active Location", () =>
  226. Effect.acquireUseRelease(
  227. Effect.promise(() => tmpdir()),
  228. (tmp) => {
  229. reset()
  230. return Effect.promise(() => fs.mkdir(path.join(tmp.path, "src"))).pipe(
  231. Effect.andThen(
  232. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  233. ),
  234. Effect.andThen((settled) =>
  235. Effect.sync(() =>
  236. expect(settled.content?.[0]).toMatchObject({
  237. type: "text",
  238. text: expect.stringContaining(realpathSync(path.join(tmp.path, "src"))),
  239. }),
  240. ),
  241. ),
  242. )
  243. },
  244. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  245. ),
  246. )
  247. it.live("permissions compound commands separately", () =>
  248. Effect.acquireUseRelease(
  249. Effect.promise(() => tmpdir()),
  250. (tmp) => {
  251. reset()
  252. return withSession(tmp.path, (registry) =>
  253. executeTool(registry, call({ command: "printf one && printf two" }, "call-compound")),
  254. ).pipe(
  255. Effect.andThen(
  256. Effect.sync(() => {
  257. expect(assertions).toHaveLength(1)
  258. expect(assertions[0]).toMatchObject({
  259. resources: ["printf one", "printf two"],
  260. save: ["printf *", "printf *"],
  261. })
  262. }),
  263. ),
  264. )
  265. },
  266. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  267. ),
  268. )
  269. it.live("captures stderr-only and mixed stdout/stderr output", () =>
  270. Effect.acquireUseRelease(
  271. Effect.promise(() => tmpdir()),
  272. (tmp) => {
  273. reset()
  274. return withSession(tmp.path, (registry) =>
  275. Effect.gen(function* () {
  276. const stderr = yield* executeTool(registry, call({ command: stderrCommand }, "call-stderr"))
  277. expect(stderr.metadata).toMatchObject({ exit: 0, truncated: false })
  278. expect(stderr.content?.[0]).toEqual({ type: "text", text: "stderr only" })
  279. const mixed = yield* executeTool(registry, call({ command: mixedOutputCommand }, "call-mixed"))
  280. expect(mixed.metadata).toMatchObject({ exit: 0, truncated: false })
  281. const output = mixed.content?.[0]?.type === "text" ? mixed.content[0].text : ""
  282. expect(output).toContain("stdout")
  283. expect(output).toContain("stderr")
  284. }),
  285. )
  286. },
  287. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  288. ),
  289. )
  290. it.live("rejects a workdir that stops being a directory during approval", () =>
  291. Effect.acquireUseRelease(
  292. Effect.promise(() => tmpdir()),
  293. (tmp) => {
  294. reset()
  295. const workdir = path.join(tmp.path, "src")
  296. afterPermission = (input) =>
  297. input.action === "shell"
  298. ? Effect.promise(async () => {
  299. await fs.rm(workdir, { recursive: true })
  300. await fs.writeFile(workdir, "not a directory")
  301. }).pipe(Effect.orDie)
  302. : Effect.void
  303. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  304. Effect.andThen(
  305. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  306. ),
  307. Effect.andThen(Effect.sync(() => expect(assertions.map((input) => input.action)).toEqual(["shell"]))),
  308. )
  309. },
  310. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  311. ),
  312. )
  313. it.live("approves an explicit external workdir before shell execution", () =>
  314. Effect.acquireUseRelease(
  315. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  316. ([active, outside]) => {
  317. reset()
  318. return withSession(active.path, (registry) =>
  319. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  320. ).pipe(
  321. Effect.andThen(
  322. Effect.sync(() => {
  323. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  324. expect(assertions[0]).toMatchObject({
  325. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  326. })
  327. }),
  328. ),
  329. )
  330. },
  331. ([active, outside]) =>
  332. Effect.promise(() =>
  333. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  334. ),
  335. ),
  336. )
  337. it.live("approves an external directory used by a directory-change command", () =>
  338. Effect.acquireUseRelease(
  339. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  340. ([active, outside]) => {
  341. reset()
  342. const command = isWindows
  343. ? `Set-Location -LiteralPath '${outside.path}'; (Get-Location).Path`
  344. : `cd '${outside.path}' && pwd`
  345. return withSession(active.path, (registry) => executeTool(registry, call({ command }, "call-external-cd"))).pipe(
  346. Effect.andThen(
  347. Effect.sync(() => {
  348. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  349. expect(assertions[0]).toMatchObject({
  350. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  351. })
  352. }),
  353. ),
  354. )
  355. },
  356. ([active, outside]) =>
  357. Effect.promise(() =>
  358. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  359. ),
  360. ),
  361. )
  362. it.live("approves an expanded external home directory", () =>
  363. Effect.acquireUseRelease(
  364. Effect.promise(() => tmpdir()),
  365. (tmp) => {
  366. reset()
  367. const command = isWindows ? "Set-Location $HOME; (Get-Location).Path" : "cd ~ && pwd"
  368. return withSession(tmp.path, (registry) => executeTool(registry, call({ command }, "call-external-home"))).pipe(
  369. Effect.andThen(
  370. Effect.sync(() => {
  371. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  372. expect(assertions[0]?.resources[0]).toStartWith(os.homedir().replaceAll("\\", "/"))
  373. }),
  374. ),
  375. )
  376. },
  377. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  378. ),
  379. )
  380. it.live("does not execute after external-directory or shell denial", () =>
  381. Effect.acquireUseRelease(
  382. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  383. ([active, outside]) =>
  384. Effect.gen(function* () {
  385. reset()
  386. denyAction = "external_directory"
  387. yield* withSession(active.path, (registry) =>
  388. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  389. )
  390. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  391. reset()
  392. denyAction = "shell"
  393. yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand })))
  394. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  395. }),
  396. ([active, outside]) =>
  397. Effect.promise(() =>
  398. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  399. ),
  400. ),
  401. )
  402. it.live("keeps non-zero exits useful", () =>
  403. Effect.acquireUseRelease(
  404. Effect.promise(() => tmpdir()),
  405. (tmp) => {
  406. reset()
  407. return withSession(tmp.path, (registry) =>
  408. executeTool(registry, call({ command: bodyExitCommand }, "call-nonzero")),
  409. ).pipe(
  410. Effect.andThen((settled) =>
  411. Effect.sync(() => {
  412. expect(settled.status).toBe("completed")
  413. expect(settled.metadata).toMatchObject({ exit: 7, truncated: false })
  414. expect(settled.content?.[0]).toEqual({ type: "text", text: "body" })
  415. expect(settled.content?.[1]).toMatchObject({
  416. type: "text",
  417. text: expect.stringContaining("Command exited with code 7"),
  418. })
  419. }),
  420. ),
  421. )
  422. },
  423. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  424. ),
  425. )
  426. it.live("truncates the model view and points at the saved output file when output overflows", () =>
  427. Effect.acquireUseRelease(
  428. Effect.promise(() => tmpdir()),
  429. (tmp) => {
  430. reset()
  431. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  432. return withSession(tmp.path, (registry) =>
  433. executeTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
  434. ).pipe(
  435. Effect.andThen((settled) =>
  436. Effect.sync(() => {
  437. expect(settled.metadata).toMatchObject({ exit: 0, truncated: true })
  438. const content = settled.content?.[0]
  439. if (!content || content.type !== "text") throw new Error("Expected text content")
  440. expect(content.text.includes("output-start")).toBe(false)
  441. expect(content.text.includes("output-end")).toBe(true)
  442. expect(content).toMatchObject({
  443. type: "text",
  444. text: expect.stringContaining("output truncated; full output saved to:"),
  445. })
  446. }),
  447. ),
  448. )
  449. },
  450. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  451. ),
  452. )
  453. it.live(
  454. "reports the shell ID for a running command",
  455. () =>
  456. Effect.acquireUseRelease(
  457. Effect.promise(() => tmpdir()),
  458. (tmp) => {
  459. reset()
  460. const release = "shell-progress-release"
  461. const releasePath = path.join(tmp.path, release)
  462. return withSession(tmp.path, (registry) =>
  463. Effect.gen(function* () {
  464. const observed = yield* Deferred.make<string>()
  465. yield* executeTool(registry, {
  466. ...call(
  467. { command: progressOverflowCommand(ShellTool.MAX_CAPTURE_BYTES + 1024, release) },
  468. "call-progress",
  469. ),
  470. progress: (update) =>
  471. Effect.gen(function* () {
  472. if (typeof update.shellID !== "string") return
  473. yield* Deferred.succeed(observed, update.shellID)
  474. yield* Effect.promise(() => fs.writeFile(releasePath, ""))
  475. }),
  476. })
  477. expect(yield* Deferred.await(observed)).toMatch(/^sh_/)
  478. }).pipe(Effect.ensuring(Effect.promise(() => fs.writeFile(releasePath, "")).pipe(Effect.ignore))),
  479. )
  480. },
  481. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  482. ),
  483. { timeout: 15_000 },
  484. )
  485. it.live(
  486. "does not repeat shell ID progress",
  487. () =>
  488. Effect.acquireUseRelease(
  489. Effect.promise(() => tmpdir()),
  490. (tmp) => {
  491. reset()
  492. return withSession(tmp.path, (registry) =>
  493. Effect.gen(function* () {
  494. const updates: Tool.Metadata[] = []
  495. yield* executeTool(registry, {
  496. ...call({ command: steadyProgressCommand }, "call-steady-progress"),
  497. progress: (update) => Effect.sync(() => updates.push(update)),
  498. })
  499. expect(updates).toHaveLength(1)
  500. expect(updates[0]?.shellID).toMatch(/^sh_/)
  501. }),
  502. )
  503. },
  504. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  505. ),
  506. { timeout: 10_000 },
  507. )
  508. it.live("returns a useful timeout outcome", () =>
  509. Effect.acquireUseRelease(
  510. Effect.promise(() => tmpdir()),
  511. (tmp) => {
  512. reset()
  513. return withSession(tmp.path, (registry) =>
  514. executeTool(registry, call({ command: timeoutOutputCommand, timeout: isWindows ? 500 : 50 })),
  515. ).pipe(
  516. Effect.andThen((settled) =>
  517. Effect.sync(() => {
  518. expect(settled.metadata).toMatchObject({ timeout: true, truncated: false })
  519. expect(settled.content?.[0]).toMatchObject({
  520. type: "text",
  521. text: expect.stringContaining("before timeout"),
  522. })
  523. expect(settled.content?.[1]).toMatchObject({
  524. type: "text",
  525. text: expect.stringContaining("Command timed out"),
  526. })
  527. }),
  528. ),
  529. )
  530. },
  531. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  532. ),
  533. )
  534. it.live("returns the shell id for a background command", () =>
  535. Effect.acquireUseRelease(
  536. Effect.promise(() => tmpdir()),
  537. (tmp) => {
  538. reset()
  539. return withSession(tmp.path, (registry) =>
  540. Effect.gen(function* () {
  541. const bus = yield* Bus.Service
  542. const admitted = yield* bus.subscribe(SessionEvent.InputAdmitted).pipe(
  543. Stream.filter((event) => event.data.sessionID === sessionID && event.data.input.type === "synthetic"),
  544. Stream.runHead,
  545. Effect.forkScoped({ startImmediately: true }),
  546. )
  547. const settled = yield* executeTool(registry, call({ command: idleCommand, timeout: 50, background: true }))
  548. const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined
  549. expect(settled.metadata).toMatchObject({ truncated: false })
  550. expect(shellID).toStartWith("sh_")
  551. const shell = yield* Shell.Service
  552. if (!shellID) return
  553. const id = ShellSchema.ID.make(shellID)
  554. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  555. expect((yield* shell.wait(id)).status).toBe("timeout")
  556. expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.input.data).toMatchObject({
  557. description: idleCommand,
  558. metadata: {
  559. source: "shell",
  560. state: "completed",
  561. },
  562. })
  563. }),
  564. )
  565. },
  566. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  567. ),
  568. )
  569. it.live("updates and clears a running shell timeout", () =>
  570. Effect.acquireUseRelease(
  571. Effect.promise(() => tmpdir()),
  572. (tmp) => {
  573. reset()
  574. return withSession(tmp.path, (registry) =>
  575. Effect.gen(function* () {
  576. const shell = yield* Shell.Service
  577. const timed = yield* executeTool(
  578. registry,
  579. call({ command: idleCommand, background: true }, "call-updated-timeout"),
  580. )
  581. const timedID = timed.metadata?.shellID
  582. expect(typeof timedID).toBe("string")
  583. if (typeof timedID !== "string") return
  584. const timedShellID = ShellSchema.ID.make(timedID)
  585. yield* shell.timeout(timedShellID, 50)
  586. expect((yield* shell.wait(timedShellID)).status).toBe("timeout")
  587. const cleared = yield* executeTool(
  588. registry,
  589. call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"),
  590. )
  591. const clearedID = cleared.metadata?.shellID
  592. expect(typeof clearedID).toBe("string")
  593. if (typeof clearedID !== "string") return
  594. const clearedShellID = ShellSchema.ID.make(clearedID)
  595. yield* shell.timeout(clearedShellID, 0)
  596. yield* Effect.sleep(Duration.millis(100))
  597. expect((yield* shell.get(clearedShellID)).status).toBe("running")
  598. yield* shell.remove(clearedShellID)
  599. }),
  600. )
  601. },
  602. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  603. ),
  604. )
  605. it.live("backgrounds a foreground command when the session is signaled", () =>
  606. Effect.acquireUseRelease(
  607. Effect.promise(() => tmpdir()),
  608. (tmp) => {
  609. reset()
  610. return withSession(tmp.path, (registry) =>
  611. Effect.gen(function* () {
  612. const jobs = yield* Job.Service
  613. const scope = yield* Scope.Scope
  614. const waiting = yield* executeTool(
  615. registry,
  616. call({ command: idleCommand, timeout: 50 }, "call-background-signal"),
  617. ).pipe(Effect.forkIn(scope, { startImmediately: true }))
  618. const backgroundWhenReady = (remaining = 1000): Effect.Effect<Job.Info[], Error> =>
  619. Effect.gen(function* () {
  620. const backgrounded = yield* jobs.backgroundAll({ sessionID })
  621. if (backgrounded.length > 0) return backgrounded
  622. if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job"))
  623. yield* Effect.promise(() => Bun.sleep(1))
  624. return yield* backgroundWhenReady(remaining - 1)
  625. })
  626. expect(yield* backgroundWhenReady()).toMatchObject([{ id: "call-background-signal", type: "shell" }])
  627. const settled = yield* Fiber.join(waiting)
  628. const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined
  629. expect(settled.metadata).toMatchObject({ truncated: false })
  630. expect(settled.content?.[0]).toEqual({
  631. type: "text",
  632. text: "The command was moved to the background.",
  633. })
  634. expect(settled.content?.[1]).toMatchObject({
  635. type: "text",
  636. text: expect.stringContaining("DO NOT sleep, poll"),
  637. })
  638. expect(shellID).toStartWith("sh_")
  639. const shell = yield* Shell.Service
  640. if (!shellID) return
  641. const id = ShellSchema.ID.make(shellID)
  642. yield* Effect.sleep(Duration.millis(100))
  643. expect((yield* shell.get(id)).status).toBe("running")
  644. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  645. yield* shell.remove(id)
  646. }),
  647. )
  648. },
  649. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  650. ),
  651. )
  652. })