Skip to content

Commit 3f07396

Browse files
authored
refactor(core): expose shell exit code, elapsed time, and log path (#63647)
1 parent 7e441d3 commit 3f07396

2 files changed

Lines changed: 98 additions & 31 deletions

File tree

‎packages/core/src/tool/plugin/shell.ts‎

Lines changed: 48 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import type { SessionHooks } from "@opencode/plugin/effect/session"
66
import type { ShellCreateBefore } from "@opencode/plugin/effect/shell"
77
import type { Shell as ShellSchema } from "@opencode/schema/shell"
88
import type { Tool } from "@opencode/schema/tool"
9-
import { Deferred, Effect, Fiber, Option, Schema } from "effect"
9+
import { Clock, Deferred, Effect, Fiber, Option, Schema, Struct } from "effect"
1010
import { Environment } from "../../environment/index.js"
1111
import { Job } from "../../job.js"
1212
import { FileAccess } from "../../file-access.js"
@@ -67,22 +67,22 @@ export const Input = Schema.Struct({
6767
})
6868

6969
const StructuredOutput = Schema.Struct({
70-
exit: Schema.optionalKey(Schema.Number),
70+
output: Schema.String,
71+
exitCode: Schema.NullOr(Schema.Number),
72+
wallTimeSeconds: Schema.Number,
73+
outputPath: Schema.optionalKey(Schema.String),
7174
signal: Schema.optionalKey(Schema.String),
7275
shellID: Schema.optionalKey(Schema.String),
7376
pid: Schema.optionalKey(NonNegativeInt),
74-
truncated: Schema.Boolean,
75-
timeout: Schema.optionalKey(Schema.Boolean),
76-
killed: Schema.optionalKey(Schema.String),
77-
})
78-
79-
const Output = Schema.Struct({
80-
...StructuredOutput.fields,
81-
output: Schema.String,
82-
status: Schema.optionalKey(Schema.Literals(["completed", "running"])),
8377
})
8478

85-
type Output = typeof Output.Type
79+
type Output = ReturnType<typeof ShellResult.output> & {
80+
status: "completed" | "running"
81+
wallTimeSeconds: number
82+
outputPath?: string
83+
shellID?: string
84+
pid?: number
85+
}
8686

8787
const resultMessages = (output: Output, timeout?: number) => {
8888
const notice = output.status === "running" ? BACKGROUND_INSTRUCTION : ShellResult.notice(output, timeout)
@@ -91,8 +91,14 @@ const resultMessages = (output: Output, timeout?: number) => {
9191

9292
const toolResult = (output: Output, timeout?: number) => {
9393
return {
94-
output,
95-
content: resultMessages(output, timeout).map((text) => ({ type: "text" as const, text })),
94+
output: {
95+
...Struct.omit(output, ["exit", "status", "truncated", "timeout", "killed"]),
96+
exitCode: output.exit ?? null,
97+
},
98+
content: resultMessages(output, timeout).map((text) => ({
99+
type: "text" as const,
100+
text,
101+
})),
96102
metadata: {
97103
status: output.status,
98104
...ShellResult.metadata(output),
@@ -102,8 +108,10 @@ const toolResult = (output: Output, timeout?: number) => {
102108
}
103109
}
104110

105-
const backgroundResult = (info: ShellResult.Result["info"], timeout?: number) => ({
106-
output: [
111+
const wallTimeSeconds = (time: ShellSchema.Time, end: number) => Math.max(0, end - time.started) / 1_000
112+
113+
const backgroundText = (info: ShellSchema.Info, timeout?: number) =>
114+
[
107115
`Command moved to the background (shell ID: ${info.id}).`,
108116
...(info.pid === undefined ? [] : [`PID: ${info.pid}`]),
109117
`Output is streaming to: ${info.file}`,
@@ -113,8 +121,13 @@ const backgroundResult = (info: ShellResult.Result["info"], timeout?: number) =>
113121
"",
114122
`The command did not finish within its timeout of ${timeout / 1_000} seconds and was moved to the background. Do not start another copy while it is running.`,
115123
]),
116-
].join("\n"),
124+
].join("\n")
125+
126+
const backgroundResult = (info: ShellSchema.Info, now: number, timeout?: number) => ({
127+
output: backgroundText(info, timeout),
128+
wallTimeSeconds: wallTimeSeconds(info.time, now),
117129
shellID: info.id,
130+
outputPath: info.file,
118131
...(info.pid === undefined ? {} : { pid: info.pid }),
119132
truncated: false,
120133
status: "running" as const,
@@ -186,7 +199,13 @@ const startJob = Effect.fnUntraced(function* (
186199
run: Effect.gen(function* () {
187200
const result = yield* shell.result(info)
188201
if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id })
189-
return { ...ShellResult.output(result), status: "completed" as const }
202+
const completed = result.info.time.completed ?? (yield* Clock.currentTimeMillis)
203+
return {
204+
...ShellResult.output(result),
205+
status: "completed" as const,
206+
wallTimeSeconds: wallTimeSeconds(result.info.time, completed),
207+
...(result.capture.truncated ? { outputPath: result.info.file } : {}),
208+
}
190209
}).pipe(
191210
Effect.tap((output) => Deferred.succeed(settled, output)),
192211
Effect.map((output) => resultMessages(output, input.timeout?.()).join("\n\n")),
@@ -204,15 +223,20 @@ const startJob = Effect.fnUntraced(function* (
204223

205224
/** The tool result of a call whose command moved to the background. */
206225
export const backgroundToolResult = (info: ShellSchema.Info) => {
207-
const result = toolResult(backgroundResult(info))
208226
// Narrowed to what a backgrounded command reports, so it can be published as is.
209227
const metadata = {
210228
shellID: info.id,
211229
status: "running" as const,
212-
truncated: result.metadata.truncated,
230+
truncated: false,
213231
...(info.pid === undefined ? {} : { pid: info.pid }),
214232
}
215-
return { content: result.content, metadata }
233+
return {
234+
content: [backgroundText(info), BACKGROUND_INSTRUCTION].map((text) => ({
235+
type: "text" as const,
236+
text,
237+
})),
238+
metadata,
239+
}
216240
}
217241

218242
/**
@@ -328,7 +352,7 @@ export const Plugin = {
328352
options: { codemode: false },
329353
description: description(undefined, autoBackground),
330354
input: Input,
331-
output: Output,
355+
output: StructuredOutput,
332356
execute: (input, context) => {
333357
const timeout = input.background === true ? (input.timeout ?? 0) : (input.timeout ?? DEFAULT_TIMEOUT_MS)
334358
let finalTimeout = timeout
@@ -395,7 +419,7 @@ export const Plugin = {
395419
if (input.background === true) {
396420
yield* jobs.background(job.id)
397421
yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled)
398-
return backgroundResult(info)
422+
return backgroundResult(info, yield* Clock.currentTimeMillis)
399423
}
400424

401425
const waiting = jobs.block({ id: job.id, sessionID: context.sessionID })
@@ -436,7 +460,7 @@ export const Plugin = {
436460
const elapsed = "timedOut" in result ? finalTimeout : undefined
437461
finalTimeout = 0
438462
yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled)
439-
return backgroundResult(info, elapsed)
463+
return backgroundResult(info, yield* Clock.currentTimeMillis, elapsed)
440464
}
441465
if (result?.info.status === "error")
442466
return yield* Effect.fail(new Error(result.info.error ?? "Command failed"))

‎packages/core/test/tool-shell.test.ts‎

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -905,8 +905,8 @@ describe("ShellTool", () => {
905905
}).pipe(Effect.timeout("3 seconds"))
906906
expect(result.status).toBe("completed")
907907
expect(JSON.parse(result.output.output)).toEqual([
908-
{ output: "one", exit: 0, truncated: false, status: "completed" },
909-
{ output: "two", exit: 0, truncated: false, status: "completed" },
908+
{ output: "one", exitCode: 0, wallTimeSeconds: expect.any(Number) },
909+
{ output: "two", exitCode: 0, wallTimeSeconds: expect.any(Number) },
910910
])
911911
}),
912912
)
@@ -1365,7 +1365,16 @@ describe("ShellTool", () => {
13651365
).pipe(
13661366
Effect.andThen((settled) =>
13671367
Effect.sync(() => {
1368-
expect(settled.metadata).toMatchObject({ exit: 3, truncated: true })
1368+
expect(settled.metadata).toMatchObject({
1369+
exit: 3,
1370+
truncated: true,
1371+
})
1372+
expect(settled.output).toEqual({
1373+
output: expect.stringContaining(`full output saved to ${settled.output.outputPath}]`),
1374+
outputPath: expect.any(String),
1375+
exitCode: 3,
1376+
wallTimeSeconds: expect.any(Number),
1377+
})
13691378
expect(settled.content).toEqual([
13701379
Expected.text(
13711380
expect.stringMatching(
@@ -1394,6 +1403,11 @@ describe("ShellTool", () => {
13941403
Effect.andThen((settled) =>
13951404
Effect.sync(() => {
13961405
expect(settled.metadata).toMatchObject({ timeout: true })
1406+
expect(settled.output).not.toHaveProperty("timeout")
1407+
expect(settled.output).toMatchObject({
1408+
exitCode: settled.metadata?.exit ?? null,
1409+
})
1410+
if (!isWindows) expect(settled.output.signal).toBe("SIGTERM")
13971411
expect(settled.content).toEqual([
13981412
{ type: "text", text: "server starting" },
13991413
Expected.text(
@@ -1434,8 +1448,21 @@ describe("ShellTool", () => {
14341448
const info = yield* shell.get(id)
14351449
expect(result.status).toBe("completed")
14361450
expect(info.pid).toBeGreaterThan(0)
1437-
expect(result.metadata).toMatchObject({ status: "running", shellID: id, pid: info.pid, truncated: false })
1438-
expect(result.output).toMatchObject({ shellID: id, pid: info.pid })
1451+
expect(result.metadata).toMatchObject({
1452+
status: "running",
1453+
shellID: id,
1454+
pid: info.pid,
1455+
truncated: false,
1456+
})
1457+
expect(result.output).toEqual({
1458+
shellID: id,
1459+
pid: info.pid,
1460+
outputPath: info.file,
1461+
exitCode: null,
1462+
output: expect.any(String),
1463+
wallTimeSeconds: expect.any(Number),
1464+
})
1465+
expect(result.output.wallTimeSeconds).toBeGreaterThanOrEqual(0.01)
14391466
expect(result.metadata).not.toHaveProperty("timeout")
14401467
expect(result.content?.[0]).toEqual({
14411468
type: "text",
@@ -1445,10 +1472,20 @@ describe("ShellTool", () => {
14451472
expect((yield* shell.list()).map((item) => item.id)).toEqual([id])
14461473

14471474
yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), ""))
1448-
expect(yield* shell.wait(id)).toMatchObject({ status: "exited", exit: 0, pid: info.pid })
1475+
const finished = yield* shell.wait(id)
1476+
expect(finished).toMatchObject({
1477+
status: "exited",
1478+
exit: 0,
1479+
pid: info.pid,
1480+
})
14491481
expect(yield* Queue.take(notices)).toMatchObject({
14501482
text: expect.stringContaining("xxxxxx"),
1451-
metadata: { source: "shell", shellID: id, state: "completed", exit: 0 },
1483+
metadata: {
1484+
source: "shell",
1485+
shellID: id,
1486+
state: "completed",
1487+
exit: 0,
1488+
},
14521489
})
14531490
expect(yield* Queue.size(notices)).toBe(0)
14541491
expect(yield* shell.list()).toEqual([])
@@ -1584,6 +1621,12 @@ describe("ShellTool", () => {
15841621
)
15851622
const id = ID.make(String(result.metadata?.shellID))
15861623
const shell = yield* Shell.Service
1624+
const info = yield* shell.get(id)
1625+
expect(result.output).toMatchObject({
1626+
exitCode: null,
1627+
outputPath: info.file,
1628+
wallTimeSeconds: expect.any(Number),
1629+
})
15871630
yield* TestClock.adjust("1 second")
15881631
expect((yield* shell.get(id)).status).toBe("running")
15891632
yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), ""))

0 commit comments

Comments
 (0)