mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 00:03:13 +03:00
feat(core): background slow Code Mode scripts behind full_codemode (#64343)
This commit is contained in:
committed by
GitHub
Unverified
parent
9bc417603d
commit
30654dae6c
@@ -277,8 +277,9 @@ export async function runNonInteractivePrompt(input: Input) {
|
||||
const ended = state.ended.promise
|
||||
await input.client.experimental.session.wait({ sessionID: input.sessionID })
|
||||
const pending = await background()
|
||||
// Image jobs can't be cancelled through the API, so waiting on them would only hold the exit.
|
||||
if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image"))) return
|
||||
// Image and Code Mode jobs can't be cancelled through the API, so waiting on them would only hold the exit.
|
||||
if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image" || job.kind === "codemode")))
|
||||
return
|
||||
await ended
|
||||
}
|
||||
}
|
||||
|
||||
+11
-2
@@ -996,6 +996,15 @@ export type JobImage = {
|
||||
model: string
|
||||
}
|
||||
|
||||
export type JobCodeMode = {
|
||||
kind: "codemode"
|
||||
id: string
|
||||
sessionID: SessionID
|
||||
status: JobStatus
|
||||
title?: string
|
||||
time: JobTime
|
||||
}
|
||||
|
||||
export type VcsInfo = { provider?: string; branch: VcsBranch }
|
||||
|
||||
export type WebSearchProvider = { id: WebSearchID; name: string }
|
||||
@@ -2294,7 +2303,7 @@ export type AutomationTrigger =
|
||||
|
||||
export type ArtifactContent = { info: ArtifactInfo; files: { [x: string]: string } }
|
||||
|
||||
export type JobInfo = JobShell | JobSubagent | JobImage
|
||||
export type JobInfo = JobShell | JobSubagent | JobImage | JobCodeMode
|
||||
|
||||
export type SessionInboxMove = {
|
||||
id: SessionMessageID
|
||||
@@ -4778,7 +4787,7 @@ export type ExperimentalArtifactsViewOutput = globalThis.Uint8Array
|
||||
|
||||
export type ExperimentalJobListInput = {
|
||||
readonly sessionID?: string | undefined
|
||||
readonly kind?: ("shell" | "subagent" | "image") | undefined
|
||||
readonly kind?: ("shell" | "subagent" | "image" | "codemode") | undefined
|
||||
readonly status?: ("running" | "completed" | "error" | "cancelled") | undefined
|
||||
readonly descendants?: boolean | undefined
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
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 { extension } from "mime-types"
|
||||
import { Flag } from "../flag.js"
|
||||
import { Job } from "../job.js"
|
||||
import type { Session } from "../session.js"
|
||||
import type { Tool } from "../tool.js"
|
||||
import { ToolOutput } from "../tool-output.js"
|
||||
|
||||
export function notice(job: Pick<Job.Info, "id" | "status" | "output" | "error">) {
|
||||
const state = job.status === "running" ? "cancelled" : job.status
|
||||
const body = job.status === "running" ? "Interrupted by server restart." : (job.output ?? job.error ?? state)
|
||||
return {
|
||||
description: "Code Mode script",
|
||||
text: `<codemode id="${job.id}" state="${state}">\n${body}\n</codemode>`,
|
||||
metadata: { source: "codemode", jobID: job.id, state },
|
||||
}
|
||||
}
|
||||
|
||||
type Execute = (context: Tool.Context) => Effect.Effect<Tool.NormalizedResult, Tool.Error>
|
||||
type Run = (context: Tool.Context, execute: Execute) => 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 })
|
||||
|
||||
export const make = Effect.fnUntraced(function* (
|
||||
jobs: Job.Interface,
|
||||
synthetic: Session.Interface["synthetic"],
|
||||
scope: Scope.Scope,
|
||||
) {
|
||||
// A custom session runner can drain without installing the Location's tool services.
|
||||
const services = Option.all({
|
||||
flags: yield* Effect.serviceOption(Flag.Service),
|
||||
output: yield* Effect.serviceOption(ToolOutput.Service),
|
||||
})
|
||||
if (Option.isNone(services)) return
|
||||
const { flags, output } = services.value
|
||||
const truncate = Effect.fnUntraced(function* (text: string) {
|
||||
const bounded = yield* output.truncate({ content: [{ type: "text", text }] })
|
||||
return bounded.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
|
||||
})
|
||||
|
||||
return Effect.fn("CodeModeJob.execute")(function* (context: Tool.Context, execute: Execute) {
|
||||
if (!(yield* flags.enabled("full_codemode"))) return yield* execute(context)
|
||||
const id = `cm_${Identifier.ascending()}`
|
||||
const sessionID = context.sessionID
|
||||
const result = yield* Deferred.make<Tool.NormalizedResult, Tool.Error>()
|
||||
const detached = yield* Deferred.make<void>()
|
||||
const progress = Semaphore.makeUnsafe(1)
|
||||
return yield* Effect.uninterruptibleMask((restore) =>
|
||||
Effect.gen(function* () {
|
||||
yield* jobs.start({
|
||||
id,
|
||||
type: "codemode",
|
||||
title: "Code Mode script",
|
||||
recovery: { kind: "codemode", sessionID, jobID: id },
|
||||
run: Effect.gen(function* () {
|
||||
const exit = yield* execute({
|
||||
...context,
|
||||
progress: (update) =>
|
||||
progress.withPermit(
|
||||
Deferred.isDone(detached).pipe(
|
||||
Effect.flatMap((done) => (done ? Effect.void : context.progress(update))),
|
||||
),
|
||||
),
|
||||
}).pipe(Effect.provideService(Job.BlockingParent, id), Effect.interruptible, Effect.exit)
|
||||
yield* Deferred.done(result, exit)
|
||||
if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause)
|
||||
const text = Exit.isFailure(exit)
|
||||
? Cause.pretty(exit.cause)
|
||||
: exit.value.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n")
|
||||
const body = yield* truncate(text)
|
||||
if (Exit.isFailure(exit) || exit.value.metadata?.error === true) return yield* Effect.fail(new Error(body))
|
||||
return body
|
||||
}),
|
||||
})
|
||||
const blocked = yield* restore(jobs.block({ id, sessionID }).pipe(Effect.timeoutOption("10 seconds"))).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
|
||||
const notificationID = job.notificationID
|
||||
// Drain the last progress publication before the tool row becomes terminal.
|
||||
yield* progress.withPermit(Deferred.succeed(detached, undefined))
|
||||
yield* Effect.gen(function* () {
|
||||
const { info } = yield* jobs.wait({ id })
|
||||
// Session removal cancels the job and removes its outbox row.
|
||||
if (!info || info.status === "cancelled") return
|
||||
// Synthetic messages carry text. Keep the script's file results accessible without putting base64 in its inbox.
|
||||
const exit = yield* Deferred.await(result).pipe(Effect.exit)
|
||||
const files = Exit.isSuccess(exit) ? exit.value.content.filter((part) => part.type === "file") : []
|
||||
const paths = yield* Effect.forEach(files, (file) => {
|
||||
const prefix = `data:${file.mime};base64,`
|
||||
if (!file.uri.startsWith(prefix)) return Effect.succeed(file.uri)
|
||||
const ext = extension(file.mime)
|
||||
return output
|
||||
.save(Buffer.from(file.uri.slice(prefix.length), "base64"), ext ? `.${ext}` : "")
|
||||
.pipe(Effect.catchDefect(() => Effect.succeed(`Could not save ${file.mime} attachment.`)))
|
||||
})
|
||||
const message = notice(
|
||||
paths.length
|
||||
? { ...info, output: yield* truncate([info.output ?? info.error, ...paths].join("\n")) }
|
||||
: info,
|
||||
)
|
||||
yield* synthetic({ id: notificationID, sessionID, ...message }).pipe(
|
||||
Effect.catchTag("Session.NotFoundError", () => Effect.void),
|
||||
)
|
||||
yield* jobs.completeBackground(notificationID)
|
||||
}).pipe(Effect.interruptible, Effect.forkIn(scope))
|
||||
const text = `Script ${id} is still running; its result will arrive in this session.`
|
||||
return {
|
||||
content: [{ type: "text" as const, text }],
|
||||
output: { output: text, toolCalls: [], files: [] },
|
||||
metadata: { jobID: id },
|
||||
}
|
||||
}),
|
||||
)
|
||||
}) satisfies Run
|
||||
})
|
||||
@@ -25,6 +25,11 @@ import { SessionSchema } from "./session/schema.js"
|
||||
|
||||
export type { Recovery }
|
||||
|
||||
/** A session-wide background request releases the outer blocker; its nested waits keep their own deadlines. */
|
||||
export const BlockingParent = Context.Reference<string | undefined>("@opencode/Job/BlockingParent", {
|
||||
defaultValue: () => undefined,
|
||||
})
|
||||
|
||||
const Background = Schema.Struct({
|
||||
id: Schema.String,
|
||||
notificationID: SessionMessage.ID,
|
||||
@@ -196,6 +201,7 @@ function recoveryTitle(job: Active, recovery: Recovery): string | null {
|
||||
if (job.info.title !== undefined) return job.info.title
|
||||
if (recovery.kind === "shell") return recovery.command
|
||||
if (recovery.kind === "subagent") return recovery.description
|
||||
if (recovery.kind === "codemode") return "Code Mode script"
|
||||
return recovery.path
|
||||
}
|
||||
|
||||
@@ -440,6 +446,8 @@ export const make = Effect.gen(function* () {
|
||||
})
|
||||
|
||||
const block: Interface["block"] = Effect.fnUntraced(function* (input) {
|
||||
const parent = yield* BlockingParent
|
||||
const tracksSession = parent === undefined || parent === input.id
|
||||
const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [BlockStart, Map<string, Active>] => {
|
||||
const job = jobs.get(input.id)
|
||||
if (!job) return [{ type: "missing" }, jobs]
|
||||
@@ -447,10 +455,12 @@ export const make = Effect.gen(function* () {
|
||||
if (job.isBackgrounded) return [{ type: "backgrounded", info: snapshot(job) }, jobs]
|
||||
return [
|
||||
{ type: "wait", wait: { done: job.done, backgrounded: job.backgrounded, generation: job.scope } },
|
||||
new Map(jobs).set(input.id, {
|
||||
...job,
|
||||
blockingSessions: incrementSession(job.blockingSessions, input.sessionID),
|
||||
}),
|
||||
tracksSession
|
||||
? new Map(jobs).set(input.id, {
|
||||
...job,
|
||||
blockingSessions: incrementSession(job.blockingSessions, input.sessionID),
|
||||
})
|
||||
: jobs,
|
||||
]
|
||||
})
|
||||
if (result.type === "missing") return undefined
|
||||
@@ -464,7 +474,7 @@ export const make = Effect.gen(function* () {
|
||||
Deferred.await(result.wait.backgrounded).pipe(Effect.map((info) => ({ type: "backgrounded" as const, info }))),
|
||||
).pipe(
|
||||
Effect.tap((outcome) => (outcome.type === "finished" ? consume(input.id, result.wait.generation) : Effect.void)),
|
||||
Effect.ensuring(removeBlock(input)),
|
||||
Effect.ensuring(tracksSession ? removeBlock(input) : Effect.void),
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -32,6 +32,15 @@ function toItem(input: {
|
||||
...(input.completed !== undefined ? { completed: input.completed } : {}),
|
||||
}
|
||||
const recovery = input.recovery
|
||||
if (recovery.kind === "codemode")
|
||||
return {
|
||||
kind: "codemode",
|
||||
id: input.id,
|
||||
sessionID: recovery.sessionID,
|
||||
status: input.status,
|
||||
time,
|
||||
...(title !== undefined ? { title } : {}),
|
||||
}
|
||||
if (recovery.kind === "shell") {
|
||||
return {
|
||||
kind: "shell",
|
||||
|
||||
@@ -20,10 +20,17 @@ const subagent = {
|
||||
description: Schema.String,
|
||||
}
|
||||
|
||||
const OutstandingItem = Schema.Union([Shell, Image, Schema.Struct({ ...subagent, sessionID: SessionSchema.ID })])
|
||||
const CodeMode = Schema.Struct({ kind: Schema.Literal("codemode"), sessionID: SessionSchema.ID, jobID: Schema.String })
|
||||
const OutstandingItem = Schema.Union([
|
||||
Shell,
|
||||
Image,
|
||||
CodeMode,
|
||||
Schema.Struct({ ...subagent, sessionID: SessionSchema.ID }),
|
||||
])
|
||||
export type OutstandingItem = typeof OutstandingItem.Type
|
||||
|
||||
export const RecoverySchema = Schema.Union([
|
||||
CodeMode,
|
||||
Shell,
|
||||
Image,
|
||||
Schema.Struct({
|
||||
|
||||
@@ -339,6 +339,7 @@ const layer = Layer.effect(
|
||||
pending.delete(input.requestID)
|
||||
for (const [id, item] of pending) {
|
||||
if (item.request.sessionID !== existing.request.sessionID) continue
|
||||
if (item.request.source?.messageID !== existing.request.source?.messageID) continue
|
||||
yield* bus.publish(Permission.Event.Replied, {
|
||||
sessionID: item.request.sessionID,
|
||||
requestID: item.request.id,
|
||||
|
||||
@@ -145,10 +145,14 @@ export const Plugin = define({
|
||||
if (goal?.status !== "active") return
|
||||
if (goal.boot !== boot())
|
||||
return yield* settle(sessionID, goal, "paused", "The server restarted while the goal was active")
|
||||
// The Session's own running subagent or image job wakes it with its notice, and the hook runs again then. A
|
||||
// The Session's own running subagent, image or script wakes it with its notice, and the hook runs again then. A
|
||||
// grandchild reports to its own parent, so it would never wake this Session.
|
||||
if (
|
||||
background.some((work) => (work.kind === "subagent" || work.kind === "image") && work.sessionID === sessionID)
|
||||
background.some(
|
||||
(work) =>
|
||||
(work.kind === "subagent" || work.kind === "image" || work.kind === "codemode") &&
|
||||
work.sessionID === sessionID,
|
||||
)
|
||||
)
|
||||
return
|
||||
if (goal.rounds >= goal.maxRounds)
|
||||
|
||||
@@ -43,6 +43,7 @@ export const outstanding = Effect.fnUntraced(function* (
|
||||
descends(store, parents, recovery.kind === "subagent" ? recovery.parentSessionID : recovery.sessionID, sessionID),
|
||||
)
|
||||
const items: OutstandingItem[] = owned.map((recovery) => {
|
||||
if (recovery.kind === "codemode") return recovery
|
||||
if (recovery.kind === "shell")
|
||||
return {
|
||||
kind: "shell" as const,
|
||||
|
||||
@@ -2,6 +2,7 @@ export * as SessionExecution from "./execution.js"
|
||||
|
||||
import { Cause, Context, Effect, Exit, Layer } from "effect"
|
||||
import { Bus } from "../bus.js"
|
||||
import { CodeModeJob } from "../codemode/job.js"
|
||||
import { Database } from "../database/database.js"
|
||||
import { Job } from "../job.js"
|
||||
import { Instance } from "../instance/service.js"
|
||||
@@ -13,6 +14,7 @@ import { SessionRunCoordinator } from "./run-coordinator.js"
|
||||
import { SessionRunner } from "./runner/index.js"
|
||||
import { SessionSchema } from "./schema.js"
|
||||
import { SessionStore } from "./store.js"
|
||||
import { SessionSynthetic } from "./synthetic.js"
|
||||
import { toSessionError } from "./to-session-error.js"
|
||||
|
||||
export interface Interface {
|
||||
@@ -60,6 +62,7 @@ export const layer = Layer.effect(
|
||||
const bus = yield* Bus.Service
|
||||
const jobs = yield* Job.Service
|
||||
const inbox = yield* SessionInbox.Service
|
||||
const scope = yield* Effect.scope
|
||||
const db = (yield* Database.Service).db
|
||||
const reportLifecycle = <A>(sessionID: SessionSchema.ID, effect: Effect.Effect<A>) =>
|
||||
effect.pipe(
|
||||
@@ -85,12 +88,14 @@ export const layer = Layer.effect(
|
||||
const holder: {
|
||||
coordinator?: SessionRunCoordinator.Coordinator<SessionSchema.ID, SessionRunner.RunError, InterruptReason>
|
||||
} = {}
|
||||
const wake = (sessionID: SessionSchema.ID) =>
|
||||
Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void))
|
||||
const background = CodeModeJob.make(jobs, SessionSynthetic.make(store, inbox, wake), scope)
|
||||
const subagentReport = SubagentReport.make({
|
||||
store,
|
||||
jobs,
|
||||
inbox,
|
||||
wake: (sessionID) =>
|
||||
Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void)),
|
||||
wake,
|
||||
draining: Effect.suspend<ReadonlySet<SessionSchema.ID>, never, never>(() =>
|
||||
holder.coordinator ? holder.coordinator.draining : Effect.succeed(new Set<SessionSchema.ID>()),
|
||||
),
|
||||
@@ -116,6 +121,7 @@ export const layer = Layer.effect(
|
||||
interruption: () => interruption(sessionID),
|
||||
}),
|
||||
).pipe(
|
||||
Effect.provideServiceEffect(CodeModeJob.Current, background),
|
||||
instances.provide(session),
|
||||
Effect.tapCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Bus } from "../../bus.js"
|
||||
import { Database } from "../../database/database.js"
|
||||
import { Instance } from "../../instance/service.js"
|
||||
import { Job } from "../../job.js"
|
||||
import { CodeModeJob } from "../../codemode/job.js"
|
||||
import { Session } from "../../session.js"
|
||||
import { Shell } from "../../shell.js"
|
||||
import { ShellTool } from "../../tool/plugin/shell.js"
|
||||
@@ -117,6 +118,7 @@ export const layer = (options?: Options) =>
|
||||
})
|
||||
|
||||
const restartMessage = (background: Job.Background, recovery: Exclude<Job.Recovery, { kind: "subagent" }>) => {
|
||||
if (recovery.kind === "codemode") return CodeModeJob.notice(background)
|
||||
const state = background.status === "running" ? "cancelled" : background.status
|
||||
if (recovery.kind === "shell") {
|
||||
const text =
|
||||
|
||||
@@ -11,14 +11,7 @@ import { Database } from "../database/database.js"
|
||||
import { Instance } from "../instance/service.js"
|
||||
import { ShellResult } from "../shell/result.js"
|
||||
import type { Skill } from "../skill.js"
|
||||
import {
|
||||
BusyError,
|
||||
CompactionConflictError,
|
||||
InboxConflictError,
|
||||
NotFoundError,
|
||||
PromptConflictError,
|
||||
SyntheticConflictError,
|
||||
} from "./error.js"
|
||||
import { BusyError, CompactionConflictError, InboxConflictError, NotFoundError, PromptConflictError } from "./error.js"
|
||||
import { SessionEvent } from "./event.js"
|
||||
import { SessionExecution } from "./execution.js"
|
||||
import { SessionInbox } from "./inbox.js"
|
||||
@@ -29,6 +22,7 @@ import { SessionShell } from "./shell.js"
|
||||
import { SessionSkill } from "./skill.js"
|
||||
import { SessionSchema } from "./schema.js"
|
||||
import { SessionStore } from "./store.js"
|
||||
import { SessionSynthetic } from "./synthetic.js"
|
||||
|
||||
type PromptRequest = SessionPrompt.Input & {
|
||||
id?: SessionMessage.ID
|
||||
@@ -286,48 +280,9 @@ export const make = Effect.fn("Session.make")(function* () {
|
||||
yield* get(sessionID)
|
||||
yield* execution.resume(sessionID)
|
||||
})
|
||||
const synthetic = Effect.fn("Session.synthetic")(
|
||||
(
|
||||
sessionID: SessionSchema.ID,
|
||||
input: {
|
||||
id?: SessionMessage.ID
|
||||
text: string
|
||||
description?: string
|
||||
metadata?: Record<string, unknown>
|
||||
delivery?: SessionInbox.Delivery
|
||||
resume?: boolean
|
||||
},
|
||||
) =>
|
||||
Effect.uninterruptible(
|
||||
Effect.gen(function* () {
|
||||
yield* get(sessionID)
|
||||
const inputID = input.id ?? SessionMessage.ID.create()
|
||||
const admittedInput = {
|
||||
type: "synthetic",
|
||||
payload: SessionInbox.SyntheticPayload.make({
|
||||
text: input.text,
|
||||
description: input.description,
|
||||
metadata: input.metadata,
|
||||
}),
|
||||
delivery: input.delivery ?? "steer",
|
||||
} satisfies SessionInbox.Item
|
||||
const admitted = yield* admission
|
||||
.admit({
|
||||
id: inputID,
|
||||
sessionID,
|
||||
item: admittedInput,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTag(
|
||||
"SessionInbox.LifecycleConflict",
|
||||
() => new SyntheticConflictError({ sessionID, inputID }),
|
||||
),
|
||||
)
|
||||
if (input.resume !== false && !(yield* get(sessionID)).revert) yield* execution.wake(sessionID)
|
||||
return admitted
|
||||
}),
|
||||
),
|
||||
)
|
||||
const admitSynthetic = SessionSynthetic.make(store, admission, execution.wake)
|
||||
const synthetic = (sessionID: SessionSchema.ID, input: Omit<Parameters<typeof admitSynthetic>[0], "sessionID">) =>
|
||||
admitSynthetic({ ...input, sessionID })
|
||||
const interrupt = Effect.fn("Session.interrupt")(
|
||||
(sessionID: SessionSchema.ID, options?: { readonly resume?: boolean }) =>
|
||||
Effect.uninterruptible(execution.interrupt(sessionID, options)),
|
||||
|
||||
@@ -43,10 +43,10 @@ export function formatBody(
|
||||
): string {
|
||||
if (!background || background.length === 0) return body
|
||||
const lines = background.map((item) => {
|
||||
if (item.kind === "shell")
|
||||
return `- shell (${item.shellID}${item.sessionID !== childSessionID ? `, in ${item.sessionID}` : ""}): ${clean(item.command)}`
|
||||
if (item.kind === "image")
|
||||
return `- image (${item.model}${item.sessionID !== childSessionID ? `, in ${item.sessionID}` : ""}): ${item.path}`
|
||||
const location = item.sessionID !== childSessionID ? `, in ${item.sessionID}` : ""
|
||||
if (item.kind === "codemode") return `- Code Mode script (${item.jobID}${location})`
|
||||
if (item.kind === "shell") return `- shell (${item.shellID}${location}): ${clean(item.command)}`
|
||||
if (item.kind === "image") return `- image (${item.model}${location}): ${item.path}`
|
||||
return `- subagent (${item.agent}, sessionID: ${item.childSessionID}): ${clean(item.description)}`
|
||||
})
|
||||
return `${body}${STILL_RUNNING}${lines.join("\n")}`
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
export * as SessionSynthetic from "./synthetic.js"
|
||||
|
||||
import { Effect } from "effect"
|
||||
import { NotFoundError, SyntheticConflictError } from "./error.js"
|
||||
import { SessionInbox } from "./inbox.js"
|
||||
import { SessionMessage } from "./message.js"
|
||||
import type { SessionSchema } from "./schema.js"
|
||||
import type { SessionStore } from "./store.js"
|
||||
|
||||
export const make = (
|
||||
store: SessionStore.Interface,
|
||||
inbox: SessionInbox.Interface,
|
||||
wake: (id: SessionSchema.ID) => Effect.Effect<void>,
|
||||
) =>
|
||||
Effect.fn("Session.synthetic")(function* (input: {
|
||||
sessionID: SessionSchema.ID
|
||||
id?: SessionMessage.ID
|
||||
text: string
|
||||
description?: string
|
||||
metadata?: Record<string, unknown>
|
||||
delivery?: SessionInbox.Delivery
|
||||
resume?: boolean
|
||||
}) {
|
||||
const sessionID = input.sessionID
|
||||
const get = store
|
||||
.get(sessionID)
|
||||
.pipe(Effect.flatMap((session) => (session ? Effect.succeed(session) : new NotFoundError({ sessionID }))))
|
||||
yield* get
|
||||
const id = input.id ?? SessionMessage.ID.create()
|
||||
const admitted = yield* inbox
|
||||
.admit({
|
||||
id,
|
||||
sessionID,
|
||||
item: {
|
||||
type: "synthetic",
|
||||
delivery: input.delivery ?? "steer",
|
||||
payload: SessionInbox.SyntheticPayload.make({
|
||||
text: input.text,
|
||||
description: input.description,
|
||||
metadata: input.metadata,
|
||||
}),
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTag("SessionInbox.LifecycleConflict", () => new SyntheticConflictError({ sessionID, inputID: id })),
|
||||
)
|
||||
if (input.resume !== false && !(yield* get).revert) yield* wake(sessionID)
|
||||
return admitted
|
||||
}, Effect.uninterruptible)
|
||||
@@ -9,6 +9,7 @@ import { Context, Effect, Layer, Ref, Result, Schema, SchemaIssue, Types } from
|
||||
import { makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import type { Agent } from "./agent.js"
|
||||
import { CodeModeCatalog } from "./codemode/catalog.js"
|
||||
import { CodeModeJob } from "./codemode/job.js"
|
||||
import { CodeModeTool } from "./codemode/tool.js"
|
||||
import { Image } from "./image.js"
|
||||
import { Permission } from "./permission.js"
|
||||
@@ -325,8 +326,11 @@ const layer = Layer.effect(
|
||||
if (!requested && input.definitions && (direct.has(event.tool) || codeModeTool?.name === event.tool))
|
||||
return yield* new Tool.Error({ message: `Tool is not available for this request: ${event.tool}` })
|
||||
const name = requested?.name ?? event.tool
|
||||
if (name === "execute" && codeModeTool)
|
||||
return yield* executeTool(codeModeTool, name, event.input, context)
|
||||
if (name === "execute" && codeModeTool) {
|
||||
const run = (ctx: Tool.Context) => executeTool(codeModeTool, name, event.input, ctx)
|
||||
const background = yield* CodeModeJob.Current
|
||||
return yield* background ? background(context, run) : run(context)
|
||||
}
|
||||
const tool = direct.get(name)
|
||||
if (tool) return yield* executeTool(tool, name, event.input, context)
|
||||
return yield* new Tool.Error({
|
||||
|
||||
@@ -381,6 +381,25 @@ describe("Permission", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("rejects sibling requests in the same step and leaves another step's request pending", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setup()
|
||||
const service = yield* Permission.Service
|
||||
const ask = (call: string, messageID: string) =>
|
||||
service.ask(
|
||||
assertion({
|
||||
id: Permission.ID.create(`per_${call}`),
|
||||
source: { type: "tool", messageID, id: `call_${call}` },
|
||||
}),
|
||||
)
|
||||
const first = yield* ask("first", "msg_one")
|
||||
yield* ask("sibling", "msg_one")
|
||||
const other = yield* ask("other", "msg_two")
|
||||
yield* service.reply({ requestID: first.id, reply: "reject" })
|
||||
expect((yield* service.list()).map((request) => request.id)).toEqual([other.id])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("stores and removes saved resources for a project", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* setup()
|
||||
|
||||
@@ -20,6 +20,7 @@ import { Provider } from "@opencode/core/provider"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
import { SessionExecution } from "@opencode/core/session/execution"
|
||||
import { SessionEvent } from "@opencode/core/session/event"
|
||||
import { SessionRestart } from "@opencode/core/session/execution/restart"
|
||||
import { SessionInbox } from "@opencode/core/session/inbox"
|
||||
import { SessionMessage } from "@opencode/core/session/message"
|
||||
@@ -42,7 +43,8 @@ import { ShellSelect } from "@opencode/core/shell/select"
|
||||
import { makeGlobalNode, makeLocationNode } from "@opencode/util/effect/app-node"
|
||||
import { LayerNode } from "@opencode/util/effect/layer-node"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import { Context, Deferred, Effect, Exit, Layer, Logger, Ref, Schedule, Schema, Scope } from "effect"
|
||||
import { Context, Deferred, Effect, Exit, Fiber, Layer, Logger, Ref, Schedule, Schema, Scope, Stream } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { tempGlobalLayer } from "./fixture/global"
|
||||
import { offlineModels } from "./fixture/models"
|
||||
import { tmpdirScoped } from "./fixture/tmpdir"
|
||||
@@ -305,6 +307,99 @@ const waitForReports = Effect.fnUntraced(function* (
|
||||
yield* app.sessions.wait(sessionID)
|
||||
})
|
||||
|
||||
describe("Code Mode session jobs", () => {
|
||||
const launch = Effect.fnUntraced(function* (enabled: boolean) {
|
||||
const h = yield* harness({ config: { experimental: { full_codemode: enabled } } })
|
||||
const started = yield* Deferred.make<void>()
|
||||
const release = yield* Deferred.make<void>()
|
||||
yield* h.registry.transform((editor) =>
|
||||
editor.add({
|
||||
name: "hold",
|
||||
description: "Wait for release",
|
||||
input: Schema.Struct({}),
|
||||
execute: () =>
|
||||
Deferred.succeed(started, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(release)),
|
||||
Effect.as({ content: "done" }),
|
||||
),
|
||||
}),
|
||||
)
|
||||
yield* h.llm.push(
|
||||
TestLLM.toolCall("call-execute", "execute", {
|
||||
code: 'const prefix = "result: "; return prefix + await tools.hold({})',
|
||||
}),
|
||||
TestLLM.text("Finished the step", "receipt"),
|
||||
TestLLM.text("Received the result", "ack"),
|
||||
)
|
||||
yield* h.sessions.prompt({ sessionID: h.parent.id, text: "Run the script" })
|
||||
yield* Deferred.await(started)
|
||||
const state = h.sessions
|
||||
.context(h.parent.id)
|
||||
.pipe(
|
||||
Effect.map((messages) =>
|
||||
messages
|
||||
.flatMap((message) => (message.type === "assistant" ? message.content : []))
|
||||
.find((part) => part.type === "tool" && part.id === "call-execute"),
|
||||
),
|
||||
)
|
||||
return { h, state, release: Deferred.succeed(release, undefined), idle: h.sessions.wait(h.parent.id) }
|
||||
})
|
||||
|
||||
for (const [name, enabled] of [
|
||||
["a fast script returns normally", true],
|
||||
["a slow script stays in the foreground with the flag off", false],
|
||||
] as const) {
|
||||
e2e.effect(name, () =>
|
||||
Effect.gen(function* () {
|
||||
const s = yield* launch(enabled)
|
||||
if (!enabled) {
|
||||
yield* TestClock.adjust("11 seconds")
|
||||
expect(yield* s.state).toMatchObject({ state: { status: "running" } })
|
||||
}
|
||||
yield* s.release
|
||||
yield* s.idle
|
||||
expect(yield* s.state).toMatchObject({
|
||||
state: { status: "completed", content: [{ type: "text", text: "result: done" }] },
|
||||
})
|
||||
expect(yield* s.h.jobs.pendingBackground).toEqual([])
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
e2e.effect("a slow script returns a receipt, then wakes its session with the result", () =>
|
||||
Effect.gen(function* () {
|
||||
const s = yield* launch(true)
|
||||
yield* TestClock.adjust("10 seconds")
|
||||
yield* s.idle
|
||||
const [job] = yield* s.h.jobs.pendingBackground
|
||||
expect(job).toMatchObject({ status: "running", recovery: { kind: "codemode", sessionID: s.h.parent.id } })
|
||||
expect(yield* s.state).toMatchObject({
|
||||
state: {
|
||||
status: "completed",
|
||||
content: [
|
||||
{ type: "text", text: `Script ${job.id} is still running; its result will arrive in this session.` },
|
||||
],
|
||||
},
|
||||
})
|
||||
const delivered = yield* Context.get(s.h.context, Bus.Service)
|
||||
.subscribe(SessionEvent.InboxDelivered)
|
||||
.pipe(
|
||||
Stream.filter((event) => event.data.inboxID === job.notificationID),
|
||||
Stream.runHead,
|
||||
Effect.forkScoped({ startImmediately: true }),
|
||||
)
|
||||
yield* s.release
|
||||
yield* Fiber.join(delivered)
|
||||
yield* s.idle
|
||||
expect(yield* s.h.jobs.pendingBackground).toEqual([])
|
||||
const text = `<codemode id="${job.id}" state="completed">\nresult: done\n</codemode>`
|
||||
expect((yield* s.h.llm.requests()).at(-1)?.messages).toContainEqual(
|
||||
expect.objectContaining({ content: expect.arrayContaining([expect.objectContaining({ type: "text", text })]) }),
|
||||
)
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
describe("subagent idle reports end to end", () => {
|
||||
e2e.live(
|
||||
"reports immediately with running background work and again after the shell exits",
|
||||
|
||||
@@ -161,6 +161,7 @@ export interface SessionRetry {
|
||||
* the Session that owns the job: the idle Session itself, or a descendant such as a subagent child.
|
||||
*/
|
||||
export type SessionIdleBackground =
|
||||
| { readonly kind: "codemode"; readonly sessionID: Session.ID; readonly jobID: string }
|
||||
| {
|
||||
readonly kind: "shell"
|
||||
readonly sessionID: Session.ID
|
||||
|
||||
@@ -161,6 +161,7 @@ export interface SessionRetry {
|
||||
* the Session that owns the job: the idle Session itself, or a descendant such as a subagent child.
|
||||
*/
|
||||
export type SessionIdleBackground =
|
||||
| { readonly kind: "codemode"; readonly sessionID: Session.ID; readonly jobID: string }
|
||||
| {
|
||||
readonly kind: "shell"
|
||||
readonly sessionID: Session.ID
|
||||
|
||||
Generated
+31
-2
@@ -13659,7 +13659,7 @@
|
||||
"$ref": "#/components/schemas/Job.Kind"
|
||||
}
|
||||
],
|
||||
"description": "Filter by background job kind (shell, subagent, or image)."
|
||||
"description": "Filter by background job kind."
|
||||
},
|
||||
"required": false
|
||||
},
|
||||
@@ -20812,6 +20812,32 @@
|
||||
"required": ["_tag", "message"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"Job.CodeMode": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"kind": {
|
||||
"type": "string",
|
||||
"enum": ["codemode"]
|
||||
},
|
||||
"id": {
|
||||
"type": "string"
|
||||
},
|
||||
"sessionID": {
|
||||
"$ref": "#/components/schemas/Session.ID"
|
||||
},
|
||||
"status": {
|
||||
"$ref": "#/components/schemas/Job.Status"
|
||||
},
|
||||
"title": {
|
||||
"type": "string"
|
||||
},
|
||||
"time": {
|
||||
"$ref": "#/components/schemas/Job.Time"
|
||||
}
|
||||
},
|
||||
"required": ["kind", "id", "sessionID", "status", "time"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"Job.Image": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -20854,12 +20880,15 @@
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/Job.Image"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/Job.CodeMode"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Job.Kind": {
|
||||
"type": "string",
|
||||
"enum": ["shell", "subagent", "image"]
|
||||
"enum": ["shell", "subagent", "image", "codemode"]
|
||||
},
|
||||
"Job.Shell": {
|
||||
"type": "object",
|
||||
|
||||
@@ -16,7 +16,7 @@ export const ListQuery = Schema.Struct({
|
||||
description: "Filter to background jobs owned by this session.",
|
||||
}),
|
||||
kind: Schema.optional(Job.Kind).annotate({
|
||||
description: "Filter by background job kind (shell, subagent, or image).",
|
||||
description: "Filter by background job kind.",
|
||||
}),
|
||||
status: Schema.optional(Job.Status).annotate({
|
||||
description: "Filter by job status (running, completed, error, or cancelled).",
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Schema } from "effect"
|
||||
import { optional } from "./schema.js"
|
||||
import { SessionID } from "./session-id.js"
|
||||
|
||||
export const Kind = Schema.Literals(["shell", "subagent", "image"]).annotate({ identifier: "Job.Kind" })
|
||||
export const Kind = Schema.Literals(["shell", "subagent", "image", "codemode"]).annotate({ identifier: "Job.Kind" })
|
||||
export type Kind = typeof Kind.Type
|
||||
|
||||
export const Status = Schema.Literals(["running", "completed", "error", "cancelled"]).annotate({
|
||||
@@ -53,7 +53,12 @@ export const Image = Schema.Struct({
|
||||
model: Schema.String,
|
||||
}).annotate({ identifier: "Job.Image" })
|
||||
|
||||
export const Info = Schema.Union([Shell, Subagent, Image]).pipe(
|
||||
export interface CodeMode extends Schema.Schema.Type<typeof CodeMode> {}
|
||||
export const CodeMode = Schema.Struct({ kind: Schema.tag("codemode"), ...Base }).annotate({
|
||||
identifier: "Job.CodeMode",
|
||||
})
|
||||
|
||||
export const Info = Schema.Union([Shell, Subagent, Image, CodeMode]).pipe(
|
||||
Schema.toTaggedUnion("kind"),
|
||||
Schema.annotate({ identifier: "Job.Info" }),
|
||||
)
|
||||
|
||||
@@ -208,7 +208,6 @@ export function Session(props: {
|
||||
return data.session.family(route.sessionID).filter((id) => id !== route.sessionID)
|
||||
})
|
||||
const permissions = createMemo(() => {
|
||||
if (session()?.parentID) return []
|
||||
return [route.sessionID, ...descendantSessionIDs()].flatMap(
|
||||
(sessionID) => data.session.permission.list(sessionID) ?? [],
|
||||
)
|
||||
@@ -234,6 +233,9 @@ export function Session(props: {
|
||||
open: false,
|
||||
tab: undefined as string | undefined,
|
||||
})
|
||||
const composerVisible = createMemo(
|
||||
() => promptedPermissions().length === 0 && (composer.open || (!!session()?.parentID && forms().length === 0)),
|
||||
)
|
||||
props.onTerminalPicker?.(() => setComposer({ open: true, tab: "terminals" }))
|
||||
onCleanup(() => props.onTerminalPicker?.(undefined))
|
||||
createEffect(() => {
|
||||
@@ -1602,7 +1604,7 @@ export function Session(props: {
|
||||
<Slot path="session.composer.top" input={{ sessionID: route.sessionID }} />
|
||||
<Composer
|
||||
sessionID={route.sessionID}
|
||||
open={composer.open || (!!session()?.parentID && forms().length === 0)}
|
||||
open={composerVisible()}
|
||||
defaultTab={composer.tab ?? (session()?.parentID ? "subagents" : undefined)}
|
||||
onClose={() => {
|
||||
const parent = session()?.parentID
|
||||
@@ -1616,7 +1618,7 @@ export function Session(props: {
|
||||
visibleTerminalID={props.visibleTerminalID}
|
||||
/>
|
||||
<Switch>
|
||||
<Match when={composer.open || (!!session()?.parentID && forms().length === 0)}>{null}</Match>
|
||||
<Match when={composerVisible()}>{null}</Match>
|
||||
<Match when={promptedPermissions().length > 0}>
|
||||
<Show when={promptedPermissions()[0]?.id} keyed>
|
||||
{(_) => {
|
||||
|
||||
Reference in New Issue
Block a user