GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(core): background slow Code Mode scripts behind full_codemode (#… · yusha/opencode@30654da

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages
    • client/src/promise/generated
      • types.ts
    • cli/src/run
      • noninteractive.ts
    • core
      • src
        • codemode
          • job.ts
        • job.ts
        • job
          • list.ts
          • recovery.ts
        • permission.ts
        • plugin
          • goal.ts
        • session
          • background.ts
          • execution.ts
          • execution
            • restart.ts
          • session.ts
          • subagent-completion.ts
          • synthetic.ts
        • tool.ts
      • test
        • permission.test.ts
        • subagent-idle-e2e.test.ts
    • plugin/src
      • effect
        • session.ts
      • promise
        • session.ts
    • protocol
      • openapi.json
      • src/groups
        • job.ts
    • schema/src
      • job.ts
    • tui/src/routes/session
      • index.tsx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/cli/src/run/noninteractive.ts‎

Copy file name to clipboardExpand all lines: packages/cli/src/run/noninteractive.ts
+3-2Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -277,8 +277,9 @@ export async function runNonInteractivePrompt(input: Input) {
277277
const ended = state.ended.promise
278278
await input.client.experimental.session.wait({ sessionID: input.sessionID })
279279
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
282283
await ended
283284
}
284285
}
Collapse file

‎packages/client/src/promise/generated/types.ts‎

Copy file name to clipboardExpand all lines: packages/client/src/promise/generated/types.ts
+11-2Lines changed: 11 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Collapse file

‎packages/core/src/codemode/job.ts‎

Copy file name to clipboard
+122Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
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

‎packages/core/src/job.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/job.ts
+15-5Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ import { SessionSchema } from "./session/schema.js"
2525

2626
export type { Recovery }
2727

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+
2833
const Background = Schema.Struct({
2934
id: Schema.String,
3035
notificationID: SessionMessage.ID,
@@ -196,6 +201,7 @@ function recoveryTitle(job: Active, recovery: Recovery): string | null {
196201
if (job.info.title !== undefined) return job.info.title
197202
if (recovery.kind === "shell") return recovery.command
198203
if (recovery.kind === "subagent") return recovery.description
204+
if (recovery.kind === "codemode") return "Code Mode script"
199205
return recovery.path
200206
}
201207

@@ -440,17 +446,21 @@ export const make = Effect.gen(function* () {
440446
})
441447

442448
const block: Interface["block"] = Effect.fnUntraced(function* (input) {
449+
const parent = yield* BlockingParent
450+
const tracksSession = parent === undefined || parent === input.id
443451
const result = yield* SynchronizedRef.modify(state.jobs, (jobs): readonly [BlockStart, Map<string, Active>] => {
444452
const job = jobs.get(input.id)
445453
if (!job) return [{ type: "missing" }, jobs]
446454
if (job.info.status !== "running") return [{ type: "finished", info: snapshot(job), generation: job.scope }, jobs]
447455
if (job.isBackgrounded) return [{ type: "backgrounded", info: snapshot(job) }, jobs]
448456
return [
449457
{ 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,
454464
]
455465
})
456466
if (result.type === "missing") return undefined
@@ -464,7 +474,7 @@ export const make = Effect.gen(function* () {
464474
Deferred.await(result.wait.backgrounded).pipe(Effect.map((info) => ({ type: "backgrounded" as const, info }))),
465475
).pipe(
466476
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),
468478
)
469479
})
470480

Collapse file

‎packages/core/src/job/list.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/job/list.ts
+9Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,15 @@ function toItem(input: {
3232
...(input.completed !== undefined ? { completed: input.completed } : {}),
3333
}
3434
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+
}
3544
if (recovery.kind === "shell") {
3645
return {
3746
kind: "shell",
Collapse file

‎packages/core/src/job/recovery.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/job/recovery.ts
+8-1Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,17 @@ const subagent = {
2020
description: Schema.String,
2121
}
2222

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+
])
2430
export type OutstandingItem = typeof OutstandingItem.Type
2531

2632
export const RecoverySchema = Schema.Union([
33+
CodeMode,
2734
Shell,
2835
Image,
2936
Schema.Struct({
Collapse file

‎packages/core/src/permission.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/permission.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,7 @@ const layer = Layer.effect(
339339
pending.delete(input.requestID)
340340
for (const [id, item] of pending) {
341341
if (item.request.sessionID !== existing.request.sessionID) continue
342+
if (item.request.source?.messageID !== existing.request.source?.messageID) continue
342343
yield* bus.publish(Permission.Event.Replied, {
343344
sessionID: item.request.sessionID,
344345
requestID: item.request.id,
Collapse file

‎packages/core/src/plugin/goal.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/plugin/goal.ts
+6-2Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,10 +145,14 @@ export const Plugin = define({
145145
if (goal?.status !== "active") return
146146
if (goal.boot !== boot())
147147
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
149149
// grandchild reports to its own parent, so it would never wake this Session.
150150
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+
)
152156
)
153157
return
154158
if (goal.rounds >= goal.maxRounds)
Collapse file

‎packages/core/src/session/background.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/background.ts
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ export const outstanding = Effect.fnUntraced(function* (
4343
descends(store, parents, recovery.kind === "subagent" ? recovery.parentSessionID : recovery.sessionID, sessionID),
4444
)
4545
const items: OutstandingItem[] = owned.map((recovery) => {
46+
if (recovery.kind === "codemode") return recovery
4647
if (recovery.kind === "shell")
4748
return {
4849
kind: "shell" as const,
Collapse file

‎packages/core/src/session/execution.ts‎

Copy file name to clipboardExpand all lines: packages/core/src/session/execution.ts
+8-2Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ export * as SessionExecution from "./execution.js"
22

33
import { Cause, Context, Effect, Exit, Layer } from "effect"
44
import { Bus } from "../bus.js"
5+
import { CodeModeJob } from "../codemode/job.js"
56
import { Database } from "../database/database.js"
67
import { Job } from "../job.js"
78
import { Instance } from "../instance/service.js"
@@ -13,6 +14,7 @@ import { SessionRunCoordinator } from "./run-coordinator.js"
1314
import { SessionRunner } from "./runner/index.js"
1415
import { SessionSchema } from "./schema.js"
1516
import { SessionStore } from "./store.js"
17+
import { SessionSynthetic } from "./synthetic.js"
1618
import { toSessionError } from "./to-session-error.js"
1719

1820
export interface Interface {
@@ -60,6 +62,7 @@ export const layer = Layer.effect(
6062
const bus = yield* Bus.Service
6163
const jobs = yield* Job.Service
6264
const inbox = yield* SessionInbox.Service
65+
const scope = yield* Effect.scope
6366
const db = (yield* Database.Service).db
6467
const reportLifecycle = <A>(sessionID: SessionSchema.ID, effect: Effect.Effect<A>) =>
6568
effect.pipe(
@@ -85,12 +88,14 @@ export const layer = Layer.effect(
8588
const holder: {
8689
coordinator?: SessionRunCoordinator.Coordinator<SessionSchema.ID, SessionRunner.RunError, InterruptReason>
8790
} = {}
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)
8894
const subagentReport = SubagentReport.make({
8995
store,
9096
jobs,
9197
inbox,
92-
wake: (sessionID) =>
93-
Effect.suspend(() => (holder.coordinator ? holder.coordinator.wake(sessionID) : Effect.void)),
98+
wake,
9499
draining: Effect.suspend<ReadonlySet<SessionSchema.ID>, never, never>(() =>
95100
holder.coordinator ? holder.coordinator.draining : Effect.succeed(new Set<SessionSchema.ID>()),
96101
),
@@ -116,6 +121,7 @@ export const layer = Layer.effect(
116121
interruption: () => interruption(sessionID),
117122
}),
118123
).pipe(
124+
Effect.provideServiceEffect(CodeModeJob.Current, background),
119125
instances.provide(session),
120126
Effect.tapCause((cause) =>
121127
Cause.hasInterruptsOnly(cause)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.