Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import { decodeDataUrl } from "@/util/data-url"
import { Process } from "@/util/process"
import { Cause, DateTime, Effect, Exit, Fiber, Latch, Layer, Option, Scope, Context, Schema, Types } from "effect"
import { InstanceState } from "@/effect/instance-state"
import { NotFoundError } from "@/storage/storage"
import { TaskTool, type TaskPromptOps } from "@/tool/task"
import { FinishTool, readTermination } from "@/tool/finish"
import PROMPT_REVIEW_LOOP from "./prompt/review-loop.txt"
Expand Down Expand Up @@ -1742,9 +1743,18 @@ const layer = Layer.effect(
.pipe(Effect.catchCause(() => Effect.succeed(false)))
// Resolve the effective effort exactly like finish does:
// session-persisted selection, then configuration, then medium.
// The selection is read from the persisted session row for every
// step, never from the run's opening snapshot: a level changed in
// the same session applies to the next step built after it (the
// request already in flight keeps the prompt it was sent with), and
// finish reads that same row at its own execution point. A row that
// disappears mid-run falls back to the snapshot instead of dying.
const effortConfig = yield* config.get()
const configEffort = typeof effortConfig.agent?.effort === "string" ? effortConfig.agent.effort : undefined
const effort = AgentEffort.resolve(readAgentEffort(session.metadata), AgentEffort.resolve(configEffort))
const effortSession = yield* sessions
.get(sessionID)
.pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(session)))
const effort = AgentEffort.resolve(readAgentEffort(effortSession.metadata), AgentEffort.resolve(configEffort))
// Compaction can drop the write markers from the visible history, so a
// compacted session keeps the policy on: it was long enough to compact.
const sessionWroteFiles = msgs.some(
Expand Down
158 changes: 157 additions & 1 deletion packages/opencode/test/session/prompt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { Image } from "../../src/image/image"

import { Question } from "../../src/question"
import { Todo } from "../../src/session/todo"
import { Session } from "@/session/session"
import { Session, withAgentEffort } from "@/session/session"
import { SessionMessageTable } from "@opencode-ai/core/session/sql"
import { LLM } from "../../src/session/llm"
import { MessageV2 } from "../../src/session/message-v2"
Expand Down Expand Up @@ -6300,3 +6300,159 @@ it.instance(
10_000,
)


// Mid-session agent effort (#748): the selector persists a level on the
// session row, and every generation step must consume the persisted level it
// sees when it builds its request. A change made while a request is already in
// flight therefore applies to the next step (and to the finish call made from
// it), never retroactively to the request that was already sent, and it never
// restarts the run or replays completed tool effects.
for (const [initial, changed] of [
["thorough", "fast"],
["fast", "thorough"],
] as const) {
it.instance(
`mid-session effort ${initial} -> ${changed} reaches the next generation step, not the in-flight request`,
() =>
Effect.gen(function* () {
const { dir, llm } = yield* useServerConfig(providerCfg)
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const session = yield* sessions.create({
title: "Effort switch",
permission: [{ permission: "*", pattern: "*", action: "allow" }],
metadata: withAgentEffort({}, initial),
})
const first = path.join(dir, "effort-step-1.txt")
const second = path.join(dir, "effort-step-2.txt")
yield* prompt.prompt({
sessionID: session.id,
agent: "work",
noReply: true,
parts: [{ type: "text", text: "Write two files, one per step." }],
})
// Step 1 writes the marker that enables the effort policy block.
yield* llm.tool("write", { filePath: first, content: "first" })
// Step 2 is held open so the selection can change while its request is
// already in flight. Step 3's reply is queued up front: the fake server
// pulls it when that request arrives.
const held = defer<void>()
yield* llm.push(reply().tool("write", { filePath: second, content: "second" }).wait(held.promise))
yield* llm.push(reply().text("Both files written.").stop())

const fiber = yield* prompt.loop({ sessionID: session.id }).pipe(Effect.forkChild)
yield* awaitWithTimeout(llm.wait(1), "timed out waiting for step 1", "10 seconds")
yield* awaitWithTimeout(llm.wait(2), "timed out waiting for step 2", "10 seconds")

// The request already on the wire keeps the effort it was built with.
const inFlight = JSON.stringify((yield* llm.hits)[1]?.body)
expect(inFlight).toContain(`## Agent effort: ${initial}`)
expect(inFlight).not.toContain(`## Agent effort: ${changed}`)

// Change the persisted selection in the same session, mid-run.
yield* sessions.setMetadata({ sessionID: session.id, metadata: withAgentEffort({}, changed) })
held.resolve()

yield* awaitWithTimeout(llm.wait(3), "timed out waiting for step 3", "10 seconds")
const next = JSON.stringify((yield* llm.hits)[2]?.body)
expect(next).toContain(`## Agent effort: ${changed}`)
expect(next).not.toContain(`## Agent effort: ${initial}`)

const exit = yield* Fiber.await(fiber)
expect(Exit.isSuccess(exit)).toBe(true)

// One turn, one run, no replay: three requests and the two writes from
// before the change landed exactly once.
expect(yield* llm.calls).toBe(3)
expect(yield* Effect.promise(() => readFile(first, "utf8"))).toBe("first")
expect(yield* Effect.promise(() => readFile(second, "utf8"))).toBe("second")
const messages = yield* sessions.messages({ sessionID: session.id })
expect(messages.filter((message) => message.info.role === "user")).toHaveLength(1)
const writes = messages
.flatMap((message) => message.parts)
.filter((part): part is SessionV1.ToolPart => part.type === "tool" && part.tool === "write")
expect(writes).toHaveLength(2)
expect(writes.map((part) => part.state.status)).toEqual(["completed", "completed"])
// The change stays persisted; nothing reset it back while the run ended.
expect((yield* sessions.get(session.id)).metadata?.agentEffort).toBe(changed)

// The next turn of the same persisted session starts from the changed
// level as well: nothing is cached per session across runs.
yield* prompt.prompt({
sessionID: session.id,
agent: "work",
noReply: true,
parts: [{ type: "text", text: "Confirm the change." }],
})
yield* llm.text("Confirmed.")
yield* prompt.loop({ sessionID: session.id })
const followingTurn = JSON.stringify((yield* llm.hits)[3]?.body)
expect(followingTurn).toContain(`## Agent effort: ${changed}`)
expect(followingTurn).not.toContain(`## Agent effort: ${initial}`)
expect(yield* llm.calls).toBe(4)
expect(yield* Effect.promise(() => readFile(first, "utf8"))).toBe("first")
expect(yield* Effect.promise(() => readFile(second, "utf8"))).toBe("second")
}),
20_000,
)
}

// The finish checkpoint reads the effective level at its own execution point,
// so a selection changed mid-turn governs the delivery the model asks for next
// (#748). Old effects are untouched and the turn is not restarted.
it.instance(
"mid-session effort change is consumed by the finish checkpoint of the same turn",
() =>
Effect.gen(function* () {
const { dir, llm } = yield* useServerConfig((url) => ({
...providerCfg(url),
agent: { work: { finishTool: true } },
}))
const prompt = yield* SessionPrompt.Service
const sessions = yield* Session.Service
const session = yield* sessions.create({
title: "Effort finish switch",
permission: [{ permission: "*", pattern: "*", action: "allow" }],
metadata: withAgentEffort({}, "thorough"),
})
const file = path.join(dir, "effort-finish.txt")
yield* prompt.prompt({
sessionID: session.id,
agent: "work",
noReply: true,
parts: [{ type: "text", text: "Write a file and finish." }],
})
yield* llm.tool("write", { filePath: file, content: "done" })
const held = defer<void>()
const extra = path.join(dir, "effort-finish-2.txt")
yield* llm.push(reply().tool("write", { filePath: extra, content: "done" }).wait(held.promise))
yield* llm.push(reply().text("Delivered.").tool("finish", { reason: "success", result: "Wrote the file." }).stop())

const fiber = yield* prompt.loop({ sessionID: session.id }).pipe(Effect.forkChild)
yield* awaitWithTimeout(llm.wait(1), "timed out waiting for step 1", "10 seconds")
yield* awaitWithTimeout(llm.wait(2), "timed out waiting for step 2", "10 seconds")
expect(JSON.stringify((yield* llm.hits)[1]?.body)).toContain("## Agent effort: thorough")

// Downgrade while step 2 is in flight: the in-flight request keeps its
// thorough prompt, and the finish the model calls next is judged fast.
yield* sessions.setMetadata({ sessionID: session.id, metadata: withAgentEffort({}, "fast") })
held.resolve()
const exit = yield* Fiber.await(fiber)
expect(Exit.isSuccess(exit)).toBe(true)

const messages = yield* sessions.messages({ sessionID: session.id })
const finish = messages
.flatMap((message) => message.parts)
.find((part): part is SessionV1.ToolPart => part.type === "tool" && part.tool === "finish")
expect(finish?.state.status).toBe("completed")
if (finish?.state.status !== "completed") return
// Fast requires no review: the delivery is labelled by the new level and
// is not the thorough UNREVIEWED demand the old prompt carried.
expect(finish.state.output).toContain("effort fast")
expect(finish.state.output).not.toContain("effort thorough")
expect(finish.state.metadata?.review).toMatchObject({ effort: "fast" })
expect(yield* Effect.promise(() => readFile(file, "utf8"))).toBe("done")
expect(yield* llm.calls).toBe(3)
}),
20_000,
)
20 changes: 20 additions & 0 deletions specs/agent-effort.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,26 @@ another. A task dispatched by a parent that does not own the child (for
example, a `task_id` from another parent) neither reads nor writes that child's
selection, and no effort is published for it in the task metadata.

## Changing the level in an existing session

The persisted selection is read at execution time, not captured when a session
or a run starts, so changing it in an existing session changes what runs next:

- Each generation step resolves the level from the session row when it builds
its request. A change made while a request is already in flight applies to the
next step built after it; the request already sent keeps the system prompt it
was sent with, because a provider call cannot be rewritten retroactively.
- `finish` resolves the level from the same row when it is called. A change that
lands before the call is therefore enforced by that call. On an upgrade made
mid-generation this can make the `finish` stricter than the prompt the model
saw for the generation that requested it; the level in effect at the call is
the one enforced, and the delivery is labelled with it.
- The next user turn in the same session resolves the current level again; the
selection is not cached per session or per run.

Switching needs no cancellation, restart, new session or replay: completed tool
effects and the transcript are preserved, and the run continues in place.

## TUI default for new sessions

The TUI's home screen owns one extra piece of state: the default a newly created
Expand Down
Loading