GeezerVison is showing github.com — feat(core): background slow Code Mode scripts behind full_codemode (#… · yusha/opencode@30654da
File treeExpand file treeCollapse file tree Open diff view settings client/src/promise/generated
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/cli/src/run/noninteractive.ts +3-2Lines changed: 3 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -277,8 +277,9 @@ export async function runNonInteractivePrompt(input: Input) { | 277 | 277 | const ended = state.ended.promise | 278 | 278 | await input.client.experimental.session.wait({ sessionID: input.sessionID }) | 279 | 279 | const pending = await background() | 280 | | - // Image jobs can't be cancelled through the API, so waiting on them would only hold the exit. | 281 | | - if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image"))) return | | 280 | + // Image and Code Mode jobs can't be cancelled through the API, so waiting on them would only hold the exit. | | 281 | + if (!pending || (pending.length > 0 && pending.every((job) => job.kind === "image" || job.kind === "codemode"))) | | 282 | + return | 282 | 283 | await ended | 283 | 284 | } | 284 | 285 | } | |
Collapse file Copy file name to clipboardExpand all lines: packages/client/src/promise/generated/types.ts +11-2Lines changed: 11 additions & 2 deletions Collapse file Copy file name to clipboard +122Lines changed: 122 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +export * as CodeModeJob from "./job.js" | | 2 | + | | 3 | +import { Identifier } from "@opencode/schema/identifier" | | 4 | +import { Cause, Context, Deferred, Effect, Exit, Option, type Scope, Semaphore } from "effect" | | 5 | +import { extension } from "mime-types" | | 6 | +import { Flag } from "../flag.js" | | 7 | +import { Job } from "../job.js" | | 8 | +import type { Session } from "../session.js" | | 9 | +import type { Tool } from "../tool.js" | | 10 | +import { ToolOutput } from "../tool-output.js" | | 11 | + | | 12 | +export function notice(job: Pick<Job.Info, "id" | "status" | "output" | "error">) { | | 13 | + const state = job.status === "running" ? "cancelled" : job.status | | 14 | + const body = job.status === "running" ? "Interrupted by server restart." : (job.output ?? job.error ?? state) | | 15 | + return { | | 16 | + description: "Code Mode script", | | 17 | + text: `<codemode id="${job.id}" state="${state}">\n${body}\n</codemode>`, | | 18 | + metadata: { source: "codemode", jobID: job.id, state }, | | 19 | + } | | 20 | +} | | 21 | + | | 22 | +type Execute = (context: Tool.Context) => Effect.Effect<Tool.NormalizedResult, Tool.Error> | | 23 | +type Run = (context: Tool.Context, execute: Execute) => ReturnType<Execute> | | 24 | + | | 25 | +/** Only a session drain can hand off work and report its result. */ | | 26 | +export const Current = Context.Reference<Run | undefined>("@opencode/CodeModeJob", { defaultValue: () => undefined }) | | 27 | + | | 28 | +export const make = Effect.fnUntraced(function* ( | | 29 | + jobs: Job.Interface, | | 30 | + synthetic: Session.Interface["synthetic"], | | 31 | + scope: Scope.Scope, | | 32 | +) { | | 33 | + // A custom session runner can drain without installing the Location's tool services. | | 34 | + const services = Option.all({ | | 35 | + flags: yield* Effect.serviceOption(Flag.Service), | | 36 | + output: yield* Effect.serviceOption(ToolOutput.Service), | | 37 | + }) | | 38 | + if (Option.isNone(services)) return | | 39 | + const { flags, output } = services.value | | 40 | + const truncate = Effect.fnUntraced(function* (text: string) { | | 41 | + const bounded = yield* output.truncate({ content: [{ type: "text", text }] }) | | 42 | + return bounded.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") | | 43 | + }) | | 44 | + | | 45 | + return Effect.fn("CodeModeJob.execute")(function* (context: Tool.Context, execute: Execute) { | | 46 | + if (!(yield* flags.enabled("full_codemode"))) return yield* execute(context) | | 47 | + const id = `cm_${Identifier.ascending()}` | | 48 | + const sessionID = context.sessionID | | 49 | + const result = yield* Deferred.make<Tool.NormalizedResult, Tool.Error>() | | 50 | + const detached = yield* Deferred.make<void>() | | 51 | + const progress = Semaphore.makeUnsafe(1) | | 52 | + return yield* Effect.uninterruptibleMask((restore) => | | 53 | + Effect.gen(function* () { | | 54 | + yield* jobs.start({ | | 55 | + id, | | 56 | + type: "codemode", | | 57 | + title: "Code Mode script", | | 58 | + recovery: { kind: "codemode", sessionID, jobID: id }, | | 59 | + run: Effect.gen(function* () { | | 60 | + const exit = yield* execute({ | | 61 | + ...context, | | 62 | + progress: (update) => | | 63 | + progress.withPermit( | | 64 | + Deferred.isDone(detached).pipe( | | 65 | + Effect.flatMap((done) => (done ? Effect.void : context.progress(update))), | | 66 | + ), | | 67 | + ), | | 68 | + }).pipe(Effect.provideService(Job.BlockingParent, id), Effect.interruptible, Effect.exit) | | 69 | + yield* Deferred.done(result, exit) | | 70 | + if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause) | | 71 | + const text = Exit.isFailure(exit) | | 72 | + ? Cause.pretty(exit.cause) | | 73 | + : exit.value.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n") | | 74 | + const body = yield* truncate(text) | | 75 | + if (Exit.isFailure(exit) || exit.value.metadata?.error === true) return yield* Effect.fail(new Error(body)) | | 76 | + return body | | 77 | + }), | | 78 | + }) | | 79 | + const blocked = yield* restore(jobs.block({ id, sessionID }).pipe(Effect.timeoutOption("10 seconds"))).pipe( | | 80 | + Effect.onInterrupt(() => jobs.cancel(id)), | | 81 | + ) | | 82 | + if (Option.isSome(blocked) && blocked.value?.type === "finished") return yield* Deferred.await(result) | | 83 | + const job = yield* jobs.background(id) | | 84 | + if (!job?.notificationID) return yield* Effect.interrupt | | 85 | + const notificationID = job.notificationID | | 86 | + // Drain the last progress publication before the tool row becomes terminal. | | 87 | + yield* progress.withPermit(Deferred.succeed(detached, undefined)) | | 88 | + yield* Effect.gen(function* () { | | 89 | + const { info } = yield* jobs.wait({ id }) | | 90 | + // Session removal cancels the job and removes its outbox row. | | 91 | + if (!info || info.status === "cancelled") return | | 92 | + // Synthetic messages carry text. Keep the script's file results accessible without putting base64 in its inbox. | | 93 | + const exit = yield* Deferred.await(result).pipe(Effect.exit) | | 94 | + const files = Exit.isSuccess(exit) ? exit.value.content.filter((part) => part.type === "file") : [] | | 95 | + const paths = yield* Effect.forEach(files, (file) => { | | 96 | + const prefix = `data:${file.mime};base64,` | | 97 | + if (!file.uri.startsWith(prefix)) return Effect.succeed(file.uri) | | 98 | + const ext = extension(file.mime) | | 99 | + return output | | 100 | + .save(Buffer.from(file.uri.slice(prefix.length), "base64"), ext ? `.${ext}` : "") | | 101 | + .pipe(Effect.catchDefect(() => Effect.succeed(`Could not save ${file.mime} attachment.`))) | | 102 | + }) | | 103 | + const message = notice( | | 104 | + paths.length | | 105 | + ? { ...info, output: yield* truncate([info.output ?? info.error, ...paths].join("\n")) } | | 106 | + : info, | | 107 | + ) | | 108 | + yield* synthetic({ id: notificationID, sessionID, ...message }).pipe( | | 109 | + Effect.catchTag("Session.NotFoundError", () => Effect.void), | | 110 | + ) | | 111 | + yield* jobs.completeBackground(notificationID) | | 112 | + }).pipe(Effect.interruptible, Effect.forkIn(scope)) | | 113 | + const text = `Script ${id} is still running; its result will arrive in this session.` | | 114 | + return { | | 115 | + content: [{ type: "text" as const, text }], | | 116 | + output: { output: text, toolCalls: [], files: [] }, | | 117 | + metadata: { jobID: id }, | | 118 | + } | | 119 | + }), | | 120 | + ) | | 121 | + }) satisfies Run | | 122 | +}) |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/job.ts +15-5Lines changed: 15 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -25,6 +25,11 @@ import { SessionSchema } from "./session/schema.js" | 25 | 25 |
| 26 | 26 | export type { Recovery } | 27 | 27 |
| | 28 | +/** A session-wide background request releases the outer blocker; its nested waits keep their own deadlines. */ | | 29 | +export const BlockingParent = Context.Reference<string | undefined>("@opencode/Job/BlockingParent", { | | 30 | + defaultValue: () => undefined, | | 31 | +}) | | 32 | + | 28 | 33 | const Background = Schema.Struct({ | 29 | 34 | id: Schema.String, | 30 | 35 | notificationID: SessionMessage.ID, | @@ -196,6 +201,7 @@ function recoveryTitle(job: Active, recovery: Recovery): string | null { | 196 | 201 | if (job.info.title !== undefined) return job.info.title | 197 | 202 | if (recovery.kind === "shell") return recovery.command | 198 | 203 | if (recovery.kind === "subagent") return recovery.description | | 204 | + if (recovery.kind === "codemode") return "Code Mode script" | 199 | 205 | return recovery.path | 200 | 206 | } | 201 | 207 |
| @@ -440,17 +446,21 @@ export const make = Effect.gen(function* () { | 440 | 446 | }) | 441 | 447 |
| 442 | 448 | const block: Interface["block"] = Effect.fnUntraced(function* (input) { | | 449 | + const parent = yield* BlockingParent | | 450 | + const tracksSession = parent === undefined || parent === input.id | 443 | 451 | const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [BlockStart, Map<string, Active>] => { | 444 | 452 | const job = jobs.get(input.id) | 445 | 453 | if (!job) return [{ type: "missing" }, jobs] | 446 | 454 | if (job.info.status !== "running") return [{ type: "finished", info: snapshot(job), generation: job.scope }, jobs] | 447 | 455 | if (job.isBackgrounded) return [{ type: "backgrounded", info: snapshot(job) }, jobs] | 448 | 456 | return [ | 449 | 457 | { type: "wait", wait: { done: job.done, backgrounded: job.backgrounded, generation: job.scope } }, | 450 | | - new Map(jobs).set(input.id, { | 451 | | - ...job, | 452 | | - blockingSessions: incrementSession(job.blockingSessions, input.sessionID), | 453 | | - }), | | 458 | + tracksSession | | 459 | + ? new Map(jobs).set(input.id, { | | 460 | + ...job, | | 461 | + blockingSessions: incrementSession(job.blockingSessions, input.sessionID), | | 462 | + }) | | 463 | + : jobs, | 454 | 464 | ] | 455 | 465 | }) | 456 | 466 | if (result.type === "missing") return undefined | @@ -464,7 +474,7 @@ export const make = Effect.gen(function* () { | 464 | 474 | Deferred.await(result.wait.backgrounded).pipe(Effect.map((info) => ({ type: "backgrounded" as const, info }))), | 465 | 475 | ).pipe( | 466 | 476 | Effect.tap((outcome) => (outcome.type === "finished" ? consume(input.id, result.wait.generation) : Effect.void)), | 467 | | - Effect.ensuring(removeBlock(input)), | | 477 | + Effect.ensuring(tracksSession ? removeBlock(input) : Effect.void), | 468 | 478 | ) | 469 | 479 | }) | 470 | 480 |
| |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/job/list.ts +9Lines changed: 9 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -32,6 +32,15 @@ function toItem(input: { | 32 | 32 | ...(input.completed !== undefined ? { completed: input.completed } : {}), | 33 | 33 | } | 34 | 34 | const recovery = input.recovery | | 35 | + if (recovery.kind === "codemode") | | 36 | + return { | | 37 | + kind: "codemode", | | 38 | + id: input.id, | | 39 | + sessionID: recovery.sessionID, | | 40 | + status: input.status, | | 41 | + time, | | 42 | + ...(title !== undefined ? { title } : {}), | | 43 | + } | 35 | 44 | if (recovery.kind === "shell") { | 36 | 45 | return { | 37 | 46 | kind: "shell", | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/job/recovery.ts +8-1Lines changed: 8 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -20,10 +20,17 @@ const subagent = { | 20 | 20 | description: Schema.String, | 21 | 21 | } | 22 | 22 |
| 23 | | -const OutstandingItem = Schema.Union([Shell, Image, Schema.Struct({ ...subagent, sessionID: SessionSchema.ID })]) | | 23 | +const CodeMode = Schema.Struct({ kind: Schema.Literal("codemode"), sessionID: SessionSchema.ID, jobID: Schema.String }) | | 24 | +const OutstandingItem = Schema.Union([ | | 25 | + Shell, | | 26 | + Image, | | 27 | + CodeMode, | | 28 | + Schema.Struct({ ...subagent, sessionID: SessionSchema.ID }), | | 29 | +]) | 24 | 30 | export type OutstandingItem = typeof OutstandingItem.Type | 25 | 31 |
| 26 | 32 | export const RecoverySchema = Schema.Union([ | | 33 | + CodeMode, | 27 | 34 | Shell, | 28 | 35 | Image, | 29 | 36 | Schema.Struct({ | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/permission.ts +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -339,6 +339,7 @@ const layer = Layer.effect( | 339 | 339 | pending.delete(input.requestID) | 340 | 340 | for (const [id, item] of pending) { | 341 | 341 | if (item.request.sessionID !== existing.request.sessionID) continue | | 342 | + if (item.request.source?.messageID !== existing.request.source?.messageID) continue | 342 | 343 | yield* bus.publish(Permission.Event.Replied, { | 343 | 344 | sessionID: item.request.sessionID, | 344 | 345 | requestID: item.request.id, | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/plugin/goal.ts +6-2Lines changed: 6 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -145,10 +145,14 @@ export const Plugin = define({ | 145 | 145 | if (goal?.status !== "active") return | 146 | 146 | if (goal.boot !== boot()) | 147 | 147 | return yield* settle(sessionID, goal, "paused", "The server restarted while the goal was active") | 148 | | - // The Session's own running subagent or image job wakes it with its notice, and the hook runs again then. A | | 148 | + // The Session's own running subagent, image or script wakes it with its notice, and the hook runs again then. A | 149 | 149 | // grandchild reports to its own parent, so it would never wake this Session. | 150 | 150 | if ( | 151 | | - background.some((work) => (work.kind === "subagent" || work.kind === "image") && work.sessionID === sessionID) | | 151 | + background.some( | | 152 | + (work) => | | 153 | + (work.kind === "subagent" || work.kind === "image" || work.kind === "codemode") && | | 154 | + work.sessionID === sessionID, | | 155 | + ) | 152 | 156 | ) | 153 | 157 | return | 154 | 158 | if (goal.rounds >= goal.maxRounds) | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/session/background.ts +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -43,6 +43,7 @@ export const outstanding = Effect.fnUntraced(function* ( | 43 | 43 | descends(store, parents, recovery.kind === "subagent" ? recovery.parentSessionID : recovery.sessionID, sessionID), | 44 | 44 | ) | 45 | 45 | const items: OutstandingItem[] = owned.map((recovery) => { | | 46 | + if (recovery.kind === "codemode") return recovery | 46 | 47 | if (recovery.kind === "shell") | 47 | 48 | return { | 48 | 49 | kind: "shell" as const, | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/session/execution.ts +8-2Lines changed: 8 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2,6 +2,7 @@ export * as SessionExecution from "./execution.js" | 2 | 2 |
| 3 | 3 | import { Cause, Context, Effect, Exit, Layer } from "effect" | 4 | 4 | import { Bus } from "../bus.js" | | 5 | +import { CodeModeJob } from "../codemode/job.js" | 5 | 6 | import { Database } from "../database/database.js" | 6 | 7 | import { Job } from "../job.js" | 7 | 8 | import { Instance } from "../instance/service.js" | @@ -13,6 +14,7 @@ import { SessionRunCoordinator } from "./run-coordinator.js" | 13 | 14 | import { SessionRunner } from "./runner/index.js" | 14 | 15 | import { SessionSchema } from "./schema.js" | 15 | 16 | import { SessionStore } from "./store.js" | | 17 | +import { SessionSynthetic } from "./synthetic.js" | 16 | 18 | import { toSessionError } from "./to-session-error.js" | 17 | 19 |
| 18 | 20 | export interface Interface { | @@ -60,6 +62,7 @@ export const layer = Layer.effect( | 60 | 62 | const bus = yield* Bus.Service | 61 | 63 | const jobs = yield* Job.Service | 62 | 64 | const inbox = yield* SessionInbox.Service | | 65 | + const scope = yield* Effect.scope | 63 | 66 | const db = (yield* Database.Service).db | 64 | 67 | const reportLifecycle = <A>(sessionID: SessionSchema.ID, effect: Effect.Effect<A>) => | 65 | 68 | effect.pipe( | @@ -85,12 +88,14 @@ export const layer = Layer.effect( | 85 | 88 | const holder: { | 86 | 89 | coordinator?: SessionRunCoordinator.Coordinator<SessionSchema.ID, SessionRunner.RunError, InterruptReason> | 87 | 90 | } = {} | | 91 | + const wake = (sessionID: SessionSchema.ID) => | | 92 | + Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void)) | | 93 | + const background = CodeModeJob.make(jobs, SessionSynthetic.make(store, inbox, wake), scope) | 88 | 94 | const subagentReport = SubagentReport.make({ | 89 | 95 | store, | 90 | 96 | jobs, | 91 | 97 | inbox, | 92 | | - wake: (sessionID) => | 93 | | - Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void)), | | 98 | + wake, | 94 | 99 | draining: Effect.suspend<ReadonlySet<SessionSchema.ID>, never, never>(() => | 95 | 100 | holder.coordinator ? holder.coordinator.draining : Effect.succeed(new Set<SessionSchema.ID>()), | 96 | 101 | ), | @@ -116,6 +121,7 @@ export const layer = Layer.effect( | 116 | 121 | interruption: () => interruption(sessionID), | 117 | 122 | }), | 118 | 123 | ).pipe( | | 124 | + Effect.provideServiceEffect(CodeModeJob.Current, background), | 119 | 125 | instances.provide(session), | 120 | 126 | Effect.tapCause((cause) => | 121 | 127 | Cause.hasInterruptsOnly(cause) | |
|