mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(codemode): add timeout and background to execute behind full_codemode (#65266)
This commit is contained in:
parent
f691e443db
commit
a5fc5fd93d
4 changed files with 199 additions and 8 deletions
|
|
@ -1,7 +1,7 @@
|
|||
export * as CodeModeJob from "./job.js"
|
||||
|
||||
import { Identifier } from "@opencode/schema/identifier"
|
||||
import { Cause, Context, Deferred, Effect, Exit, Option, type Scope, Semaphore } from "effect"
|
||||
import { Cause, Context, Deferred, Duration, Effect, Exit, Option, type Scope, Semaphore } from "effect"
|
||||
import { extension } from "mime-types"
|
||||
import { Flag } from "../flag.js"
|
||||
import { Job } from "../job.js"
|
||||
|
|
@ -23,7 +23,9 @@ export function notice(job: Pick<Job.Info, "id" | "status" | "output" | "error">
|
|||
const BLOCK_TIMEOUT = "2 minutes"
|
||||
|
||||
type Execute = (context: Tool.Context) => Effect.Effect<Tool.NormalizedResult, Tool.Error>
|
||||
type Run = (context: Tool.Context, execute: Execute) => ReturnType<Execute>
|
||||
/** The execute call's own `timeout` and `background` inputs, which only exist with `full_codemode`. */
|
||||
export type Options = { readonly timeout?: number; readonly background?: boolean }
|
||||
type Run = (context: Tool.Context, execute: Execute, options?: Options) => ReturnType<Execute>
|
||||
|
||||
/** Only a session drain can hand off work and report its result. */
|
||||
export const Current = Context.Reference<Run | undefined>("@opencode/CodeModeJob", { defaultValue: () => undefined })
|
||||
|
|
@ -45,7 +47,7 @@ export const make = Effect.fnUntraced(function* (
|
|||
return bounded.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
|
||||
})
|
||||
|
||||
return Effect.fn("CodeModeJob.execute")(function* (context: Tool.Context, execute: Execute) {
|
||||
return Effect.fn("CodeModeJob.execute")(function* (context: Tool.Context, execute: Execute, options?: Options) {
|
||||
if (!(yield* flags.enabled("full_codemode"))) return yield* execute(context)
|
||||
const id = `cm_${Identifier.ascending()}`
|
||||
const sessionID = context.sessionID
|
||||
|
|
@ -81,9 +83,17 @@ export const make = Effect.fnUntraced(function* (
|
|||
return body
|
||||
}),
|
||||
})
|
||||
const blocked = yield* restore(jobs.block({ id, sessionID }).pipe(Effect.timeoutOption(BLOCK_TIMEOUT))).pipe(
|
||||
Effect.onInterrupt(() => jobs.cancel(id)),
|
||||
)
|
||||
const blocked = options?.background
|
||||
? Option.none()
|
||||
: yield* restore(
|
||||
jobs
|
||||
.block({ id, sessionID })
|
||||
.pipe(
|
||||
Effect.timeoutOption(
|
||||
options?.timeout === undefined ? BLOCK_TIMEOUT : Duration.millis(options.timeout),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.onInterrupt(() => jobs.cancel(id)))
|
||||
if (Option.isSome(blocked) && blocked.value?.type === "finished") return yield* Deferred.await(result)
|
||||
const job = yield* jobs.background(id)
|
||||
if (!job?.notificationID) return yield* Effect.interrupt
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import { FileMutation } from "../file-mutation.js"
|
|||
import { FileWrite } from "../file-write.js"
|
||||
import { Location } from "../location.js"
|
||||
import { Permission } from "../permission.js"
|
||||
import { PositiveInt } from "../schema.js"
|
||||
import { CodeModeBun } from "./bun.js"
|
||||
import { CodeModeCatalog } from "./catalog.js"
|
||||
import { CodeModeDiffs } from "./diffs.js"
|
||||
|
|
@ -118,8 +119,25 @@ const description = (full: boolean) =>
|
|||
'Call tools through `tools` using only exact paths and signatures from the catalog. Do not infer or normalize tool names; preserve bracket notation such as `tools.<namespace>["tool-name"](input)`.',
|
||||
"Prefer an explicit `return`; if omitted, the final top-level expression becomes the result.",
|
||||
"Await every call whose completion matters; pending calls are interrupted when execution ends. Run independent calls concurrently with `Promise.allSettled`.",
|
||||
...(full
|
||||
? [
|
||||
"Scripts still running after their timeout move to the background and keep running. Background scripts return a job ID immediately, and you will be notified when they complete; do not poll for them.",
|
||||
]
|
||||
: []),
|
||||
].join("\n")
|
||||
|
||||
// Mirrors the shell tool's `timeout` and `background`; only with `full_codemode`, where every script runs as a job.
|
||||
export const FullInput = Schema.Struct({
|
||||
...CodeMode.Input.fields,
|
||||
timeout: Schema.optionalKey(PositiveInt).annotate({
|
||||
description: `Optional time in milliseconds to wait for the script before moving it to the background (default ${2 * 60 * 1_000}). The script keeps running in the background after that; it is never stopped. With \`background: true\` the call returns immediately instead.`,
|
||||
}),
|
||||
background: Schema.optionalKey(Schema.Boolean).annotate({
|
||||
description:
|
||||
"Run the script in the background and return immediately with its job ID (useful for long-running work). You will be notified when it completes. DO NOT poll for completion.",
|
||||
}),
|
||||
})
|
||||
|
||||
export const create = (
|
||||
inventory: Inventory,
|
||||
executeTool: (name: string, tool: Info, input: unknown, context: ToolContext) => Effect.Effect<Result, Error>,
|
||||
|
|
@ -130,7 +148,7 @@ export const create = (
|
|||
return {
|
||||
name: "execute",
|
||||
description: description(services !== undefined),
|
||||
input: CodeMode.Input,
|
||||
input: services ? FullInput : CodeMode.Input,
|
||||
freeform: { type: "text" },
|
||||
output: ExecuteOutput,
|
||||
execute: ({ code }, context) =>
|
||||
|
|
|
|||
|
|
@ -393,7 +393,9 @@ const layer = Layer.effect(
|
|||
if (name === "execute" && codemode) {
|
||||
const run = (ctx: Tool.Context) => executeTool(codemode.tool, name, event.input, ctx)
|
||||
const background = yield* CodeModeJob.Current
|
||||
return yield* background ? background(context, run) : run(context)
|
||||
return yield* background
|
||||
? background(context, run, full ? executeOptions(event.input) : undefined)
|
||||
: run(context)
|
||||
}
|
||||
const tool = direct.get(name)
|
||||
if (tool) return yield* executeTool(tool, name, event.input, context)
|
||||
|
|
@ -552,3 +554,13 @@ export const node = makeLocationNode({
|
|||
layer,
|
||||
deps: [PluginHooks.node, Image.node, Permission.node, Flag.node],
|
||||
})
|
||||
|
||||
// Only read once the input has the shape the full_codemode schema accepts; the tool still validates it when it runs.
|
||||
const executeOptions = (input: unknown): CodeModeJob.Options | undefined => {
|
||||
if (typeof input !== "object" || input === null) return undefined
|
||||
const { timeout, background } = input as Record<string, unknown>
|
||||
return {
|
||||
...(typeof timeout === "number" && Number.isInteger(timeout) && timeout > 0 ? { timeout } : {}),
|
||||
...(background === true ? { background } : {}),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
151
packages/core/test/codemode-execute-options.test.ts
Normal file
151
packages/core/test/codemode-execute-options.test.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import { CodeMode } from "@opencode/codemode"
|
||||
import { Agent } from "@opencode/core/agent"
|
||||
import { CodeModeJob } from "@opencode/core/codemode/job"
|
||||
import { CodeModeTool } from "@opencode/core/codemode/tool"
|
||||
import { Database } from "@opencode/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
|
||||
import { Flag } from "@opencode/core/flag"
|
||||
import { Job } from "@opencode/core/job"
|
||||
import type { Permission } from "@opencode/core/permission"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
import { Tool } from "@opencode/core/tool"
|
||||
import { ToolOutput } from "@opencode/core/tool-output"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { Context, DateTime, Deferred, Effect, Fiber, Layer, Schema, Scope } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { testEffect } from "./lib/effect"
|
||||
|
||||
const it = testEffect(
|
||||
Layer.mergeAll(
|
||||
AppNodeBuilder.build(LayerNode.group([Job.node, Database.node, Global.node])),
|
||||
Flag.testLayer([], { overrides: "full_codemode" }),
|
||||
Layer.mock(ToolOutput.Service, { truncate: (result) => Effect.succeed(result) }),
|
||||
),
|
||||
)
|
||||
|
||||
const tool = (full: boolean) =>
|
||||
CodeModeTool.create(
|
||||
{ tools: new Map(), namespaces: new Map() },
|
||||
() => Effect.die("unused"),
|
||||
{} as Permission.Interface,
|
||||
full ? (Context.empty() as never) : undefined,
|
||||
)
|
||||
|
||||
const context = (sessionID: string): Tool.Context => ({
|
||||
sessionID: Session.ID.make(sessionID),
|
||||
agent: Agent.ID.make("build"),
|
||||
messageID: "msg_test" as never,
|
||||
id: Tool.CallID.make("call_test"),
|
||||
progress: () => Effect.void,
|
||||
})
|
||||
|
||||
const script = (ms: number) => () =>
|
||||
Effect.sleep(ms).pipe(
|
||||
Effect.as<Tool.NormalizedResult>({ content: [{ type: "text", text: "done" }], output: "done", metadata: {} }),
|
||||
)
|
||||
|
||||
const harness = Effect.gen(function* () {
|
||||
const jobs = yield* Job.Service
|
||||
const notices: Array<{ text: string; metadata?: Record<string, unknown> }> = []
|
||||
const notified = yield* Deferred.make<void>()
|
||||
const blocking = yield* Deferred.make<void>()
|
||||
const run = yield* CodeModeJob.make(
|
||||
// Resolves once the call starts its blocking wait, whose timeout is forked in the same step.
|
||||
{ ...jobs, block: (input) => Deferred.succeed(blocking, undefined).pipe(Effect.andThen(jobs.block(input))) },
|
||||
(input) =>
|
||||
Effect.sync(() => notices.push(input)).pipe(
|
||||
Effect.andThen(Deferred.succeed(notified, undefined)),
|
||||
Effect.as({
|
||||
type: "synthetic" as const,
|
||||
payload: { text: input.text, description: input.description, metadata: input.metadata },
|
||||
delivery: "queue" as const,
|
||||
id: input.id ?? SessionMessage.ID.create(),
|
||||
sessionID: input.sessionID,
|
||||
time: { created: DateTime.makeUnsafe(0) },
|
||||
}),
|
||||
),
|
||||
yield* Scope.make(),
|
||||
)
|
||||
if (!run) throw new Error("no job runner")
|
||||
return { jobs, run, notices, notified, blocking }
|
||||
})
|
||||
|
||||
describe("execute timeout and background", () => {
|
||||
it.effect("has only code without full_codemode", () =>
|
||||
Effect.sync(() => {
|
||||
expect(tool(false).input).toBe(CodeMode.Input)
|
||||
expect(Object.keys(tool(false).input.fields)).toEqual(["code"])
|
||||
expect(tool(false).description).not.toContain("background")
|
||||
expect(() =>
|
||||
Schema.decodeUnknownSync(tool(false).input, { onExcessProperty: "error" })({ code: "1", background: true }),
|
||||
).toThrow()
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("adds timeout and background with full_codemode", () =>
|
||||
Effect.sync(() => {
|
||||
expect(Object.keys(tool(true).input.fields)).toEqual(["code", "timeout", "background"])
|
||||
expect(Schema.decodeUnknownSync(CodeModeTool.FullInput)({ code: "1", timeout: 3000, background: true })).toEqual({
|
||||
code: "1",
|
||||
timeout: 3000,
|
||||
background: true,
|
||||
})
|
||||
expect(() => Schema.decodeUnknownSync(CodeModeTool.FullInput)({ code: "1", timeout: 0 })).toThrow()
|
||||
expect(() => Schema.decodeUnknownSync(CodeModeTool.FullInput)({ code: "1", timeout: 1.5 })).toThrow()
|
||||
expect(tool(true).description).toContain("do not poll")
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("background returns a job ID at once and notifies on completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness
|
||||
const result = yield* h.run(context("ses_bg"), script(300), { background: true })
|
||||
const jobID = String(result.metadata?.jobID)
|
||||
expect(jobID).toStartWith("cm_")
|
||||
expect((yield* h.jobs.get(jobID))?.status).toBe("running")
|
||||
yield* Deferred.await(h.notified)
|
||||
expect(h.notices[0]?.metadata).toMatchObject({ jobID, state: "completed" })
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("a foreground timeout moves the script to the background, where it finishes and notifies", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness
|
||||
const fiber = yield* h.run(context("ses_fg"), script(600), { timeout: 150 }).pipe(Effect.forkChild)
|
||||
yield* Deferred.await(h.blocking)
|
||||
yield* TestClock.adjust("149 millis")
|
||||
expect(fiber.pollUnsafe()).toBeUndefined()
|
||||
yield* TestClock.adjust("1 millis")
|
||||
const result = yield* Fiber.join(fiber)
|
||||
expect(result.metadata?.jobID).toBeDefined()
|
||||
expect((yield* h.jobs.get(String(result.metadata?.jobID)))?.status).toBe("running")
|
||||
yield* TestClock.adjust("600 millis")
|
||||
yield* Deferred.await(h.notified)
|
||||
expect(h.notices[0]?.metadata).toMatchObject({ jobID: result.metadata?.jobID, state: "completed" })
|
||||
expect(h.notices[0]?.text).toContain("done")
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("a foreground script that finishes within its timeout returns its result", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness
|
||||
const result = yield* h.run(context("ses_fast"), script(20), { timeout: 1000 })
|
||||
expect(result.metadata?.jobID).toBeUndefined()
|
||||
expect(result.content).toEqual([{ type: "text", text: "done" }])
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("a background script with a timeout returns at once and is not stopped", () =>
|
||||
Effect.gen(function* () {
|
||||
const h = yield* harness
|
||||
const result = yield* h.run(context("ses_bg_timeout"), script(300), { background: true, timeout: 50 })
|
||||
expect((yield* h.jobs.get(String(result.metadata?.jobID)))?.status).toBe("running")
|
||||
yield* Deferred.await(h.notified)
|
||||
expect(h.notices[0]?.metadata).toMatchObject({ jobID: result.metadata?.jobID, state: "completed" })
|
||||
expect(h.notices[0]?.text).toContain("done")
|
||||
}),
|
||||
)
|
||||
})
|
||||
Loading…
Add table
Reference in a new issue