mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
fix(core): stop an automation's timed-out shell command instead of backgrounding it (#65626)
This commit is contained in:
parent
adce0e6bfd
commit
e1fb08afc5
8 changed files with 141 additions and 15 deletions
|
|
@ -607,6 +607,7 @@ const layer = Layer.effect(
|
|||
"The session that authorized this automation's tools moved to another project",
|
||||
)
|
||||
const outcome = yield* AutomationCode.run(owner, action, {
|
||||
automationID: row.id,
|
||||
messageID: SessionMessage.ID.make(id),
|
||||
state: row.state,
|
||||
now,
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ const FORBIDDEN_TOOLS = new Set([
|
|||
])
|
||||
|
||||
export interface RunInput {
|
||||
readonly automationID: Automation.ID
|
||||
readonly messageID: SessionMessage.ID
|
||||
readonly state: Schema.Json
|
||||
readonly now: number
|
||||
|
|
@ -238,6 +239,7 @@ export const run = Effect.fnUntraced(
|
|||
agent: agent.id,
|
||||
messageID: input.messageID,
|
||||
progress: () => Effect.void,
|
||||
automation: { id: input.automationID },
|
||||
},
|
||||
})
|
||||
.pipe(Effect.provideService(Permission.Unattended, unattended))
|
||||
|
|
|
|||
|
|
@ -197,6 +197,19 @@ const notify = Effect.fnUntraced(function* (
|
|||
if (info.notificationID) yield* jobs.completeBackground(info.notificationID)
|
||||
})
|
||||
|
||||
// Waits for the command to end and reads what it printed.
|
||||
const finished = Effect.fnUntraced(function* (shell: Shell.Interface, info: ShellSchema.Info) {
|
||||
const result = yield* shell.result(info)
|
||||
if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id })
|
||||
const completed = result.info.time.completed ?? (yield* Clock.currentTimeMillis)
|
||||
return {
|
||||
...ShellResult.output(result),
|
||||
status: "completed" as const,
|
||||
wallTimeSeconds: wallTimeSeconds(result.info.time, completed),
|
||||
...(result.capture.truncated ? { outputPath: result.info.file } : {}),
|
||||
}
|
||||
})
|
||||
|
||||
// The job that waits on a command for its call (or its session, once backgrounded).
|
||||
const startJob = Effect.fnUntraced(function* (
|
||||
jobs: Job.Interface,
|
||||
|
|
@ -225,17 +238,7 @@ const startJob = Effect.fnUntraced(function* (
|
|||
},
|
||||
...(input.notificationID ? { notificationID: input.notificationID } : {}),
|
||||
background: input.background,
|
||||
run: Effect.gen(function* () {
|
||||
const result = yield* shell.result(info)
|
||||
if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id })
|
||||
const completed = result.info.time.completed ?? (yield* Clock.currentTimeMillis)
|
||||
return {
|
||||
...ShellResult.output(result),
|
||||
status: "completed" as const,
|
||||
wallTimeSeconds: wallTimeSeconds(result.info.time, completed),
|
||||
...(result.capture.truncated ? { outputPath: result.info.file } : {}),
|
||||
}
|
||||
}).pipe(
|
||||
run: finished(shell, info).pipe(
|
||||
Effect.tap((output) => Deferred.succeed(settled, output)),
|
||||
Effect.map((output) => resultMessages(output, input.timeout?.()).join("\n\n")),
|
||||
// Interrupting the job (its registry closing) stops the command too, unless the server is handing its daemon
|
||||
|
|
@ -452,6 +455,10 @@ export const Plugin = {
|
|||
Effect.fail(new ToolFailure({ message: "Command interrupted by the user before it started." })),
|
||||
),
|
||||
)
|
||||
// An automation's code has nobody to hear how a backgrounded command ends. There a timeout stops the
|
||||
// command and fails the call, and the command gets no job the session could move to the background or
|
||||
// be told about.
|
||||
const timeoutBackgrounds = !background && context.automation === undefined
|
||||
return yield* Effect.gen(function* () {
|
||||
// The same default `Shell.create` gives the hooks, so `prepare` can tell whether one moved it.
|
||||
const cwd = input.workdir ?? workingDirectory.absolute
|
||||
|
|
@ -468,7 +475,7 @@ export const Plugin = {
|
|||
timeout,
|
||||
shell: yield* compatibleShell,
|
||||
metadata: { sessionID: context.sessionID },
|
||||
waited: !background,
|
||||
waited: timeoutBackgrounds,
|
||||
toolCall: {
|
||||
sessionID: context.sessionID,
|
||||
assistantMessageID: context.messageID,
|
||||
|
|
@ -486,11 +493,20 @@ export const Plugin = {
|
|||
Effect.raceFirst(prepare(invocation, context, { cwd, target }), stoppedBeforeStart),
|
||||
)
|
||||
// A foreground timeout moves the command to the background instead of stopping it.
|
||||
if (!background) invocation.timeout = 0
|
||||
if (timeoutBackgrounds) invocation.timeout = 0
|
||||
}),
|
||||
)
|
||||
yield* context.progress({ shellID: info.id })
|
||||
|
||||
if (context.automation) {
|
||||
const output = yield* restore(finished(shell, info)).pipe(
|
||||
Effect.onInterrupt(() => shell.stop(info.id, "killed").pipe(Effect.ignore)),
|
||||
)
|
||||
if (output.timeout)
|
||||
return yield* new ToolFailure({ message: resultMessages(output, finalTimeout).join("\n\n") })
|
||||
return output
|
||||
}
|
||||
|
||||
const { job, settled } = yield* startJob(jobs, shell, {
|
||||
sessionID: context.sessionID,
|
||||
info,
|
||||
|
|
|
|||
|
|
@ -146,6 +146,14 @@ const configureAgent = Layer.effectDiscard(
|
|||
}),
|
||||
),
|
||||
})
|
||||
editor.add({
|
||||
name: "automation",
|
||||
description: "The automation making the call, if any",
|
||||
input: Schema.Struct({}),
|
||||
output: Schema.NullOr(Schema.String),
|
||||
options: { namespace: "probe" },
|
||||
execute: (_input, context) => Effect.succeed({ output: context.automation?.id ?? null }),
|
||||
})
|
||||
editor.add({
|
||||
name: "post",
|
||||
description: "Post a message",
|
||||
|
|
@ -1275,6 +1283,23 @@ describe("Automation", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
// Tools rely on this to know no model is waiting, e.g. the shell tool stops a timed-out command instead of
|
||||
// moving it to the background.
|
||||
it.effect("names the automation on each of its program's tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const automations = yield* setup()
|
||||
const automation = yield* automations.create({
|
||||
sessionID,
|
||||
name: "probe",
|
||||
trigger: every("1 minute"),
|
||||
action: code(`return { state: await tools.probe.automation({}) }`),
|
||||
})
|
||||
yield* TestClock.adjust("1 minute")
|
||||
yield* automations.tick
|
||||
expect(yield* automations.get(automation.id)).toMatchObject({ lastOutcome: "fired", state: automation.id })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("a program that returns nothing leaves state unchanged", () =>
|
||||
Effect.gen(function* () {
|
||||
const automations = yield* setup()
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { realpathSync, watch } from "node:fs"
|
|||
import os from "os"
|
||||
import path from "path"
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer, Queue, Scope, Stream, Tracer } from "effect"
|
||||
import { Cause, Deferred, Duration, Effect, Exit, Fiber, Layer, Queue, Schedule, Scope, Stream, Tracer } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { Money } from "@opencode/schema/money"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
|
|
@ -25,6 +25,7 @@ import { Model } from "@opencode/core/model"
|
|||
import { Provider } from "@opencode/core/provider"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { Automation } from "@opencode/schema/automation"
|
||||
import { Job } from "@opencode/core/job"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionEvent } from "@opencode/core/session/event"
|
||||
|
|
@ -1753,6 +1754,80 @@ describe("ShellTool", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
// Runs a program the way an automation does: no model, and the automation named on each tool call.
|
||||
const runAutomationCode = (registry: Tool.Interface, code: string) =>
|
||||
Effect.gen(function* () {
|
||||
yield* registry.transform((editor) =>
|
||||
editor.update("shell", (tool) => {
|
||||
tool.options = { ...tool.options, codemode: true }
|
||||
}),
|
||||
)
|
||||
return yield* registry.check({
|
||||
code,
|
||||
tools: ["shell"],
|
||||
bindings: {},
|
||||
permissions: [{ action: "*", resource: "*", effect: "allow" }],
|
||||
limits: { timeoutMs: 30_000, maxOutputBytes: 32 * 1024 },
|
||||
context: {
|
||||
sessionID,
|
||||
...toolIdentity,
|
||||
progress: () => Effect.void,
|
||||
automation: { id: Automation.ID.make("aut_shell_test") },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it.live("stops an automation's command at its timeout and fails the call", () =>
|
||||
withTempDir((tmp) => {
|
||||
reset()
|
||||
return withSession(tmp.path, (registry) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* runAutomationCode(
|
||||
registry,
|
||||
`try { await tools.shell({ command: ${JSON.stringify(idleCommand)}, timeout: 50 }); return "finished" }
|
||||
catch (error) { return error.message }`,
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: expect.stringMatching(
|
||||
new RegExp(`Command timed out after 0\\.05 seconds\\. [^\\n]+\\nExit code: ${timedOutExit}`),
|
||||
),
|
||||
})
|
||||
const shell = yield* Shell.Service
|
||||
expect(yield* shell.list()).toEqual([])
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("keeps an automation's command out of reach of the session's move to the background", () =>
|
||||
withTempDir((tmp) => {
|
||||
reset()
|
||||
return withSession(tmp.path, (registry) =>
|
||||
Effect.gen(function* () {
|
||||
const command = JSON.stringify(progressOverflowCommand(0, "release"))
|
||||
const running = yield* runAutomationCode(
|
||||
registry,
|
||||
`return await tools.shell({ command: ${command}, timeout: 10000 })`,
|
||||
).pipe(Effect.forkScoped({ startImmediately: true }))
|
||||
const shell = yield* Shell.Service
|
||||
const [started] = yield* shell
|
||||
.list()
|
||||
.pipe(
|
||||
Effect.repeat({ until: (shells) => shells.length > 0, schedule: Schedule.spaced("10 millis") }),
|
||||
Effect.timeout("10 seconds"),
|
||||
)
|
||||
const jobs = yield* Job.Service
|
||||
expect(yield* jobs.backgroundAll({ sessionID })).toEqual([])
|
||||
yield* Effect.promise(() => Bun.write(path.join(tmp.path, "release"), ""))
|
||||
expect(yield* Fiber.join(running)).toMatchObject({ ok: true, value: { exitCode: 0 } })
|
||||
// A finished job stays listed, so this proves the command never had one for the session to take.
|
||||
expect(yield* jobs.get(started!.id)).toBeUndefined()
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
it.live(
|
||||
"truncates the model view and points at the saved output file when output overflows",
|
||||
() =>
|
||||
|
|
|
|||
2
packages/protocol/openapi.json
generated
2
packages/protocol/openapi.json
generated
|
|
@ -16873,7 +16873,7 @@
|
|||
"code": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"description": "Code Mode JavaScript run on each trigger with no model (32 KB output cap). Call tools statically as tools.<ns>.<tool>(...) or tools[\"ns-name\"].tool(...); each is authorized once at creation to run unattended. Receives input = { state, now, runs, args } (also globals): state starts null, now is epoch ms, runs counts earlier runs. Event triggers also receive input.event = { id, timestamp, data }; data follows the event type's payloadSchema. Return nothing, or { state?, done?, send? }. JSON state is kept for the next run; done: true stops. lastOutput shows the delivery target and any logs. Return at most one send per run. { send: { prompt } } steers the creating session; { send: { prompt, to: { subagent } } } starts a permitted child that does not report back. No session IDs. Omit send to stay quiet. A rejected send commits neither state nor done. Example code string: if (runs < 2) return; return { done: true, send: { prompt: \"Three checks elapsed. Review the build.\" } }"
|
||||
"description": "Code Mode JavaScript run on each trigger with no model (32 KB output cap). Call tools statically as tools.<ns>.<tool>(...) or tools[\"ns-name\"].tool(...); each is authorized once at creation to run unattended. A shell command still running at its timeout is stopped and the call throws; it never moves to the background. Receives input = { state, now, runs, args } (also globals): state starts null, now is epoch ms, runs counts earlier runs. Event triggers also receive input.event = { id, timestamp, data }; data follows the event type's payloadSchema. Return nothing, or { state?, done?, send? }. JSON state is kept for the next run; done: true stops. lastOutput shows the delivery target and any logs. Return at most one send per run. { send: { prompt } } steers the creating session; { send: { prompt, to: { subagent } } } starts a permitted child that does not report back. No session IDs. Omit send to stay quiet. A rejected send commits neither state nor done. Example code string: if (runs < 2) return; return { done: true, send: { prompt: \"Three checks elapsed. Review the build.\" } }"
|
||||
},
|
||||
"args": {}
|
||||
},
|
||||
|
|
|
|||
|
|
@ -170,6 +170,7 @@ export const CodeActionInput = Schema.Struct({
|
|||
description: [
|
||||
"Code Mode JavaScript run on each trigger with no model (32 KB output cap).",
|
||||
'Call tools statically as tools.<ns>.<tool>(...) or tools["ns-name"].tool(...); each is authorized once at creation to run unattended.',
|
||||
"A shell command still running at its timeout is stopped and the call throws; it never moves to the background.",
|
||||
"Receives input = { state, now, runs, args } (also globals): state starts null, now is epoch ms, runs counts earlier runs.",
|
||||
"Event triggers also receive input.event = { id, timestamp, data }; data follows the event type's payloadSchema.",
|
||||
"Return nothing, or { state?, done?, send? }. JSON state is kept for the next run; done: true stops. lastOutput shows the delivery target and any logs.",
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ export * as Tool from "./tool.js"
|
|||
import { Effect, JsonSchema, Schema } from "effect"
|
||||
import type { StandardSchemaV1 } from "@standard-schema/spec"
|
||||
import type { Agent } from "./agent.js"
|
||||
import type { Automation } from "./automation.js"
|
||||
import type { Session } from "./session.js"
|
||||
import type { SessionMessage } from "./session-message.js"
|
||||
|
||||
|
|
@ -36,6 +37,11 @@ export interface Context {
|
|||
readonly cancel?: Effect.Effect<void>
|
||||
/** True when the tool is invoked from inside Code Mode (`execute`). */
|
||||
readonly codemode?: boolean
|
||||
/**
|
||||
* Set when an automation's code makes the call. No model waits on it, and nobody hears about work it leaves
|
||||
* running, so a tool must finish its work within the call.
|
||||
*/
|
||||
readonly automation?: { readonly id: Automation.ID }
|
||||
}
|
||||
|
||||
export interface Namespace {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue