tool-shell.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. { timeout: 15_000 },
  290. )
  291. it.live("rejects a workdir that stops being a directory during approval", () =>
  292. Effect.acquireUseRelease(
  293. Effect.promise(() => tmpdir()),
  294. (tmp) => {
  295. reset()
  296. const workdir = path.join(tmp.path, "src")
  297. afterPermission = (input) =>
  298. input.action === "shell"
  299. ? Effect.promise(async () => {
  300. await fs.rm(workdir, { recursive: true })
  301. await fs.writeFile(workdir, "not a directory")
  302. }).pipe(Effect.orDie)
  303. : Effect.void
  304. return Effect.promise(() => fs.mkdir(workdir)).pipe(
  305. Effect.andThen(
  306. withSession(tmp.path, (registry) => executeTool(registry, call({ command: cwdCommand, workdir: "src" }))),
  307. ),
  308. Effect.andThen(Effect.sync(() => expect(assertions.map((input) => input.action)).toEqual(["shell"]))),
  309. )
  310. },
  311. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  312. ),
  313. )
  314. it.live("approves an explicit external workdir before shell execution", () =>
  315. Effect.acquireUseRelease(
  316. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  317. ([active, outside]) => {
  318. reset()
  319. return withSession(active.path, (registry) =>
  320. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  321. ).pipe(
  322. Effect.andThen(
  323. Effect.sync(() => {
  324. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  325. expect(assertions[0]).toMatchObject({
  326. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  327. })
  328. }),
  329. ),
  330. )
  331. },
  332. ([active, outside]) =>
  333. Effect.promise(() =>
  334. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  335. ),
  336. ),
  337. )
  338. it.live("approves an external directory used by a directory-change command", () =>
  339. Effect.acquireUseRelease(
  340. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  341. ([active, outside]) => {
  342. reset()
  343. const command = isWindows
  344. ? `Set-Location -LiteralPath '${outside.path}'; (Get-Location).Path`
  345. : `cd '${outside.path}' && pwd`
  346. return withSession(active.path, (registry) => executeTool(registry, call({ command }, "call-external-cd"))).pipe(
  347. Effect.andThen(
  348. Effect.sync(() => {
  349. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  350. expect(assertions[0]).toMatchObject({
  351. resources: [path.join(realpathSync(outside.path), "*").replaceAll("\\", "/")],
  352. })
  353. }),
  354. ),
  355. )
  356. },
  357. ([active, outside]) =>
  358. Effect.promise(() =>
  359. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  360. ),
  361. ),
  362. )
  363. it.live("approves an expanded external home directory", () =>
  364. Effect.acquireUseRelease(
  365. Effect.promise(() => tmpdir()),
  366. (tmp) => {
  367. reset()
  368. const command = isWindows ? "Set-Location $HOME; (Get-Location).Path" : "cd ~ && pwd"
  369. return withSession(tmp.path, (registry) => executeTool(registry, call({ command }, "call-external-home"))).pipe(
  370. Effect.andThen(
  371. Effect.sync(() => {
  372. expect(assertions.map((item) => item.action)).toEqual(["external_directory", "shell"])
  373. expect(assertions[0]?.resources[0]).toStartWith(os.homedir().replaceAll("\\", "/"))
  374. }),
  375. ),
  376. )
  377. },
  378. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  379. ),
  380. )
  381. it.live("does not execute after external-directory or shell denial", () =>
  382. Effect.acquireUseRelease(
  383. Effect.promise(() => Promise.all([tmpdir(), tmpdir()])),
  384. ([active, outside]) =>
  385. Effect.gen(function* () {
  386. reset()
  387. denyAction = "external_directory"
  388. yield* withSession(active.path, (registry) =>
  389. executeTool(registry, call({ command: cwdCommand, workdir: outside.path })),
  390. )
  391. expect(assertions.map((item) => item.action)).toEqual(["external_directory"])
  392. reset()
  393. denyAction = "shell"
  394. yield* withSession(active.path, (registry) => executeTool(registry, call({ command: cwdCommand })))
  395. expect(assertions.map((item) => item.action)).toEqual(["shell"])
  396. }),
  397. ([active, outside]) =>
  398. Effect.promise(() =>
  399. Promise.all([active[Symbol.asyncDispose](), outside[Symbol.asyncDispose]()]).then(() => undefined),
  400. ),
  401. ),
  402. )
  403. it.live("keeps non-zero exits useful", () =>
  404. Effect.acquireUseRelease(
  405. Effect.promise(() => tmpdir()),
  406. (tmp) => {
  407. reset()
  408. return withSession(tmp.path, (registry) =>
  409. executeTool(registry, call({ command: bodyExitCommand }, "call-nonzero")),
  410. ).pipe(
  411. Effect.andThen((settled) =>
  412. Effect.sync(() => {
  413. expect(settled.status).toBe("completed")
  414. expect(settled.metadata).toMatchObject({ exit: 7, truncated: false })
  415. expect(settled.content?.[0]).toEqual({ type: "text", text: "body" })
  416. expect(settled.content?.[1]).toMatchObject({
  417. type: "text",
  418. text: expect.stringContaining("Command exited with code 7"),
  419. })
  420. }),
  421. ),
  422. )
  423. },
  424. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  425. ),
  426. )
  427. it.live("truncates the model view and points at the saved output file when output overflows", () =>
  428. Effect.acquireUseRelease(
  429. Effect.promise(() => tmpdir()),
  430. (tmp) => {
  431. reset()
  432. const bytes = ShellTool.MAX_CAPTURE_BYTES + 1024
  433. return withSession(tmp.path, (registry) =>
  434. executeTool(registry, call({ command: overflowCommand(bytes) }, "call-overflow")),
  435. ).pipe(
  436. Effect.andThen((settled) =>
  437. Effect.sync(() => {
  438. expect(settled.metadata).toMatchObject({ exit: 0, truncated: true })
  439. const content = settled.content?.[0]
  440. if (!content || content.type !== "text") throw new Error("Expected text content")
  441. expect(content.text.includes("output-start")).toBe(false)
  442. expect(content.text.includes("output-end")).toBe(true)
  443. expect(content).toMatchObject({
  444. type: "text",
  445. text: expect.stringContaining("output truncated; full output saved to:"),
  446. })
  447. }),
  448. ),
  449. )
  450. },
  451. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  452. ),
  453. { timeout: 15_000 },
  454. )
  455. it.live(
  456. "reports the shell ID for a running command",
  457. () =>
  458. Effect.acquireUseRelease(
  459. Effect.promise(() => tmpdir()),
  460. (tmp) => {
  461. reset()
  462. const release = "shell-progress-release"
  463. const releasePath = path.join(tmp.path, release)
  464. return withSession(tmp.path, (registry) =>
  465. Effect.gen(function* () {
  466. const observed = yield* Deferred.make<string>()
  467. yield* executeTool(registry, {
  468. ...call(
  469. { command: progressOverflowCommand(ShellTool.MAX_CAPTURE_BYTES + 1024, release) },
  470. "call-progress",
  471. ),
  472. progress: (update) =>
  473. Effect.gen(function* () {
  474. if (typeof update.shellID !== "string") return
  475. yield* Deferred.succeed(observed, update.shellID)
  476. yield* Effect.promise(() => fs.writeFile(releasePath, ""))
  477. }),
  478. })
  479. expect(yield* Deferred.await(observed)).toMatch(/^sh_/)
  480. }).pipe(Effect.ensuring(Effect.promise(() => fs.writeFile(releasePath, "")).pipe(Effect.ignore))),
  481. )
  482. },
  483. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  484. ),
  485. { timeout: 15_000 },
  486. )
  487. it.live(
  488. "does not repeat shell ID progress",
  489. () =>
  490. Effect.acquireUseRelease(
  491. Effect.promise(() => tmpdir()),
  492. (tmp) => {
  493. reset()
  494. return withSession(tmp.path, (registry) =>
  495. Effect.gen(function* () {
  496. const updates: Tool.Metadata[] = []
  497. yield* executeTool(registry, {
  498. ...call({ command: steadyProgressCommand }, "call-steady-progress"),
  499. progress: (update) => Effect.sync(() => updates.push(update)),
  500. })
  501. expect(updates).toHaveLength(1)
  502. expect(updates[0]?.shellID).toMatch(/^sh_/)
  503. }),
  504. )
  505. },
  506. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  507. ),
  508. { timeout: 10_000 },
  509. )
  510. it.live("returns a useful timeout outcome", () =>
  511. Effect.acquireUseRelease(
  512. Effect.promise(() => tmpdir()),
  513. (tmp) => {
  514. reset()
  515. return withSession(tmp.path, (registry) =>
  516. executeTool(registry, call({ command: timeoutOutputCommand, timeout: isWindows ? 3_000 : 50 })),
  517. ).pipe(
  518. Effect.andThen((settled) =>
  519. Effect.sync(() => {
  520. expect(settled.metadata).toMatchObject({ timeout: true, truncated: false })
  521. expect(settled.content?.[0]).toMatchObject({
  522. type: "text",
  523. text: expect.stringContaining("before timeout"),
  524. })
  525. expect(settled.content?.[1]).toMatchObject({
  526. type: "text",
  527. text: expect.stringContaining("Command timed out"),
  528. })
  529. }),
  530. ),
  531. )
  532. },
  533. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  534. ),
  535. { timeout: 15_000 },
  536. )
  537. it.live("returns the shell id for a background command", () =>
  538. Effect.acquireUseRelease(
  539. Effect.promise(() => tmpdir()),
  540. (tmp) => {
  541. reset()
  542. return withSession(tmp.path, (registry) =>
  543. Effect.gen(function* () {
  544. const bus = yield* Bus.Service
  545. const admitted = yield* bus.subscribe(SessionEvent.InputAdmitted).pipe(
  546. Stream.filter((event) => event.data.sessionID === sessionID && event.data.input.type === "synthetic"),
  547. Stream.runHead,
  548. Effect.forkScoped({ startImmediately: true }),
  549. )
  550. const settled = yield* executeTool(registry, call({ command: idleCommand, timeout: 50, background: true }))
  551. const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined
  552. expect(settled.metadata).toMatchObject({ truncated: false })
  553. expect(shellID).toStartWith("sh_")
  554. const shell = yield* Shell.Service
  555. if (!shellID) return
  556. const id = ShellSchema.ID.make(shellID)
  557. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  558. expect((yield* shell.wait(id)).status).toBe("timeout")
  559. expect((yield* Fiber.join(admitted)).valueOrUndefined?.data.input.data).toMatchObject({
  560. description: idleCommand,
  561. metadata: {
  562. source: "shell",
  563. state: "completed",
  564. },
  565. })
  566. }),
  567. )
  568. },
  569. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  570. ),
  571. )
  572. it.live("updates and clears a running shell timeout", () =>
  573. Effect.acquireUseRelease(
  574. Effect.promise(() => tmpdir()),
  575. (tmp) => {
  576. reset()
  577. return withSession(tmp.path, (registry) =>
  578. Effect.gen(function* () {
  579. const shell = yield* Shell.Service
  580. const timed = yield* executeTool(
  581. registry,
  582. call({ command: idleCommand, background: true }, "call-updated-timeout"),
  583. )
  584. const timedID = timed.metadata?.shellID
  585. expect(typeof timedID).toBe("string")
  586. if (typeof timedID !== "string") return
  587. const timedShellID = ShellSchema.ID.make(timedID)
  588. yield* shell.timeout(timedShellID, 50)
  589. expect((yield* shell.wait(timedShellID)).status).toBe("timeout")
  590. const cleared = yield* executeTool(
  591. registry,
  592. call({ command: idleCommand, timeout: 50, background: true }, "call-cleared-timeout"),
  593. )
  594. const clearedID = cleared.metadata?.shellID
  595. expect(typeof clearedID).toBe("string")
  596. if (typeof clearedID !== "string") return
  597. const clearedShellID = ShellSchema.ID.make(clearedID)
  598. yield* shell.timeout(clearedShellID, 0)
  599. yield* Effect.sleep(Duration.millis(100))
  600. expect((yield* shell.get(clearedShellID)).status).toBe("running")
  601. yield* shell.remove(clearedShellID)
  602. }),
  603. )
  604. },
  605. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  606. ),
  607. )
  608. it.live("backgrounds a foreground command when the session is signaled", () =>
  609. Effect.acquireUseRelease(
  610. Effect.promise(() => tmpdir()),
  611. (tmp) => {
  612. reset()
  613. return withSession(tmp.path, (registry) =>
  614. Effect.gen(function* () {
  615. const jobs = yield* Job.Service
  616. const scope = yield* Scope.Scope
  617. const waiting = yield* executeTool(
  618. registry,
  619. call({ command: idleCommand, timeout: 50 }, "call-background-signal"),
  620. ).pipe(Effect.forkIn(scope, { startImmediately: true }))
  621. const backgroundWhenReady = (remaining = 1000): Effect.Effect<Job.Info[], Error> =>
  622. Effect.gen(function* () {
  623. const backgrounded = yield* jobs.backgroundAll({ sessionID })
  624. if (backgrounded.length > 0) return backgrounded
  625. if (remaining <= 0) return yield* Effect.fail(new Error("Timed out waiting for foreground shell job"))
  626. yield* Effect.promise(() => Bun.sleep(1))
  627. return yield* backgroundWhenReady(remaining - 1)
  628. })
  629. expect(yield* backgroundWhenReady()).toMatchObject([{ id: "call-background-signal", type: "shell" }])
  630. const settled = yield* Fiber.join(waiting)
  631. const shellID = typeof settled.metadata?.shellID === "string" ? settled.metadata.shellID : undefined
  632. expect(settled.metadata).toMatchObject({ truncated: false })
  633. expect(settled.content?.[0]).toEqual({
  634. type: "text",
  635. text: "The command was moved to the background.",
  636. })
  637. expect(settled.content?.[1]).toMatchObject({
  638. type: "text",
  639. text: expect.stringContaining("DO NOT sleep, poll"),
  640. })
  641. expect(shellID).toStartWith("sh_")
  642. const shell = yield* Shell.Service
  643. if (!shellID) return
  644. const id = ShellSchema.ID.make(shellID)
  645. yield* Effect.sleep(Duration.millis(100))
  646. expect((yield* shell.get(id)).status).toBe("running")
  647. expect((yield* shell.list()).map((info) => info.id)).toContain(id)
  648. yield* shell.remove(id)
  649. }),
  650. )
  651. },
  652. (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]().then(() => undefined)),
  653. ),
  654. )
  655. })