Skip to content
Merged
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
2 changes: 1 addition & 1 deletion packages/opencode/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ const layer = Layer.effect(
review: {
name: "review",
permission: Permission.merge(defaults, reviewPermissions, user),
description: `Code reviewer. Use this proactively, without being asked, after any unit of work that changed files and when the user asks for a review.`,
description: `Code reviewer. Use this proactively when the active effort/review-loop policy requires review after file changes, or whenever the user explicitly asks for a review.`,
prompt: PROMPT_REVIEW,
options: {},
// Mandatory review must deliver its verdict before the parent can finish.
Expand Down
81 changes: 46 additions & 35 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ import { FinishTool, readTermination } from "@/tool/finish"
import PROMPT_REVIEW_LOOP from "./prompt/review-loop.txt"
import { declaresFileWrites } from "@opencode-ai/core/review-loop"

// The todo scope contract is always sent. The Review Loop policy and the effort
// block are a nudge that appears once the session has written files; before
// that, `finish` (the enforcement checkpoint) carries the same requirement in
// its description and decline feedback, so the gate is unchanged.
// The todo scope contract is always sent. The Review Loop policy and non-fast
// effort blocks wait until the session has written files; fast work guidance is
// included on the first non-review, non-Think request. `finish` remains the
// enforcement checkpoint.
const REVIEW_LOOP_SPLIT = PROMPT_REVIEW_LOOP.indexOf("## Review Loop")
const PROMPT_SCOPE_CONTRACT = PROMPT_REVIEW_LOOP.slice(0, REVIEW_LOOP_SPLIT).trimEnd()
const PROMPT_REVIEW_POLICY = PROMPT_REVIEW_LOOP.slice(REVIEW_LOOP_SPLIT)
Expand Down Expand Up @@ -478,13 +478,19 @@ const SUPPORTED_MCP_RESOURCE_ATTACHMENT_MIMES = new Set([
])

// The resolved two-switch process instructions (effort → review passes and
// validation gate) injected alongside the review-loop prompt. The text mirrors
// what finish enforces: no unconditional mandatory review, no configurable
// extra knobs, and honest delivery labels at every level.
// validation gate) composed into ordinary requests. Fast work guidance is
// surfaced before writes; other process prompts keep their existing write gate.
const EFFORT_PROCESS: Record<AgentEffort.Level, string> = {
fast: [
"## Agent effort: fast (review passes: off, validation gate: minimal)",
"No independent review is required: self-check inline and finish. Declare minimal validation evidence on finish. The result is delivered as unreviewed unless a review actually happened; finish never upgrades it to approved.",
"Start straightforward implementation from the user's first request.",
"Skip separate planning or delegation unless either materially helps.",
"No independent clean Review is required at fast, but honor explicit user review requests.",
"Match validation to the change; fast does not imply broad tests, typecheck, or parity runs.",
"Minimal evidence is one applicable syntax or smoke check that passed.",
"Mark both not-applicable only when neither fits.",
"Disclose failed and not-run checks, and do not skip verification the change needs.",
"The result is unreviewed unless a review actually happened; finish never upgrades it to approved.",
].join("\n\n"),
medium: [
"## Agent effort: medium (review passes: at most 2, validation gate: standard)",
Expand Down Expand Up @@ -2357,35 +2363,39 @@ const layer = Layer.effect(

yield* plugin.trigger("experimental.chat.messages.transform", {}, { messages: request })

const [skills, env, instructions, mcpInstructions, toolOverview, delegation] = yield* Effect.all([
const [skills, env, instructions, mcpInstructions, toolOverview, effortContext] = yield* Effect.all([
sys.skills(agent),
sys.environment(model),
instruction.system().pipe(Effect.orDie),
sys.mcp(agent, session.permission),
catalog.overview(session.id),
sys.delegation(agent, session.permission),
Effect.gen(function* () {
// Resolve like finish (session, config, then medium) from the
// current row on every step; updates affect the next request,
// while this one stays fixed. A missing row falls back to the
// session snapshot before building effort-sensitive guidance.
const effortConfig = yield* config.get()
const configEffort =
typeof effortConfig.agent?.effort === "string" ? effortConfig.agent.effort : undefined
const effortSession = yield* sessions
.get(sessionID)
.pipe(Effect.catchIf(NotFoundError.isInstance, () => Effect.succeed(session)))
const effort = AgentEffort.resolve(
readAgentEffort(effortSession.metadata),
AgentEffort.resolve(configEffort),
)
return {
effortConfig,
effort,
delegation: yield* sys.delegation(agent, session.permission, effort),
}
}),
])
const { effortConfig, effort, delegation } = effortContext
const isDefaultPrimary = yield* agents
.defaultInfo()
.pipe(Effect.map((info) => info.name === agent.name && agent.mode !== "subagent"))
.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 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 = request.some(
Expand All @@ -2396,6 +2406,10 @@ const layer = Layer.effect(
part.type === "compaction" || declaresFileWrites(part as Parameters<typeof declaresFileWrites>[0]),
),
)
const showEffortProcess =
agent.name !== "think" &&
!isReviewAgent(agent.name) &&
(sessionWroteFiles || effort === "fast")
const system = [
...env,
...instructions,
Expand All @@ -2406,14 +2420,11 @@ const layer = Layer.effect(
...(isDefaultPrimary ? [PROMPT_SCOPE_CONTRACT] : []),
...(isDefaultPrimary && sessionWroteFiles ? [PROMPT_REVIEW_POLICY] : []),
// Reviewer sessions keep their own structured-report contract and
// must not recursively review themselves.
...(isReviewAgent(agent.name) || !sessionWroteFiles ? [] : [EFFORT_PROCESS[effort]]),
// Think scales research depth and candidate count by effort, but it does
// not write code, so the write-gated process line above rarely reaches
// it. Surface the bare level whenever the process line did not fire.
...(agent.name === "think" && (isReviewAgent(agent.name) || !sessionWroteFiles)
? [`## Agent effort: ${effort}`]
: []),
// must not recursively review themselves. Think keeps its own
// effort-scaled research guidance instead of the Work process block.
...(showEffortProcess ? [EFFORT_PROCESS[effort]] : []),
// Think always receives its effective level for research depth.
...(agent.name === "think" ? [`## Agent effort: ${effort}`] : []),
]
const format = lastUser.format ?? { type: "text" as const }
if (format.type === "json_schema") system.push(STRUCTURED_OUTPUT_SYSTEM_PROMPT)
Expand Down
6 changes: 6 additions & 0 deletions packages/opencode/src/session/prompt/efficiency.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## Efficient tool use

Be fast, quick, and direct at every effort level. Depth may vary, but inefficiency is never justified. Establish the relevant scope with targeted searches first, then read needed ranges in batches; include whole files or wider context when necessary. Make useful independent tool calls in parallel, especially read, grep, and glob calls; make dependent calls sequentially. Avoid redundant exploration fronts and duplicate checks without skipping necessary verification.

For ordinary file inspection and one-off edits or creation, prefer native Read, Grep, Glob, Edit, and Write tools.

When inputs are known, batch independent operations on different files; order dependent calls and same-file writes.

Use scripts when they materially help with bulk work or native/command tools fail; not for simple file operations.
16 changes: 14 additions & 2 deletions packages/opencode/src/session/system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { LocationServiceMap, locationServiceMapLayer } from "@opencode-ai/core/l
import { Reference } from "@opencode-ai/core/reference"
import { MCP } from "@/mcp"
import { PermissionV1 } from "@opencode-ai/core/v1/permission"
import { AgentEffort } from "@opencode-ai/schema/agent-effort"

export const STE_LITE = PROMPT_STE_LITE

Expand Down Expand Up @@ -73,7 +74,11 @@ export interface Interface {
readonly environment: (model: Provider.Model) => Effect.Effect<string[]>
readonly skills: (agent: Agent.Info) => Effect.Effect<string | undefined>
readonly mcp: (agent: Agent.Info, permission?: PermissionV1.Ruleset) => Effect.Effect<string | undefined>
readonly delegation: (agent: Agent.Info, permission?: PermissionV1.Ruleset) => Effect.Effect<string | undefined>
readonly delegation: (
agent: Agent.Info,
permission?: PermissionV1.Ruleset,
effort?: AgentEffort.Level,
) => Effect.Effect<string | undefined>
}

export class Service extends Context.Service<Service, Interface>()("@opencode/SystemPrompt") {}
Expand Down Expand Up @@ -146,6 +151,7 @@ const layer = Layer.effect(
delegation: Effect.fn("SystemPrompt.delegation")(function* (
agent: Agent.Info,
permission?: PermissionV1.Ruleset,
effort?: AgentEffort.Level,
) {
// Only primary-style callers drive delegation; subagents execute.
if (agent.mode === "subagent") return
Expand All @@ -156,7 +162,13 @@ const layer = Layer.effect(
const work = yield* agents.get("work")
if (work?.native === true && agent === work)
return [
"Programming requests are best done as Think planning, then Code implementation, then a clean Review. Prefer that route for programming, including small edits; you may do the work yourself when the route is not available or would not help, and say so.",
effort === "fast"
? [
"At fast effort, handle straightforward programming directly when Think/Code handoffs add no value.",
"When they materially help, use Think for planning and Code for implementation.",
"An independent clean Review is not required at fast; honor explicit user review requests.",
].join(" ")
: "Programming requests are best done as Think planning, then Code implementation, then a clean Review. Prefer that route for programming, including small edits; you may do the work yourself when the route is not available or would not help, and say so.",
"Non-programming work should not go to Code. At fast effort, medium-sized work may be manual; complex or thorough work goes to General; medium effort balances direct work and General delegation.",
"When it is unclear whether a request changes software, carry on with the work (inspect, run commands, delegate); use the question tool only if the answer would change what you do. Do not relabel programming work to avoid its workflow.",
"Failed, cancelled or pending children are not successful stage completion. A pass budget cannot excuse reporting success with blocking findings.",
Expand Down
2 changes: 1 addition & 1 deletion packages/opencode/src/tool/task.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Launch a subagent for complex, multistep tasks (`subagent_type` required). Not for reading a known file or searching a few files; use Read, Glob or Grep.

Review handoffs: when a unit of your own work changed files, hand it to the `review` subagent instead of reviewing your own diff (see the review-loop policy): `subagent_type: "review"` (the runtime picks the matching reviewer). Pass `background: false` to ask for the verdict before you continue: the tool waits only for a reviewer whose agent is configured with `"background": false` in opencode.json, and otherwise launches the review as a background task and notifies you when the verdict is ready. When the user asks for a code review, dispatch `review` with the requirements and the diff. No review for turns that changed no files.
Review handoffs: when the current effort/review-loop policy requires a review of your own file-writing work, hand it to the `review` subagent instead of reviewing your own diff: `subagent_type: "review"` (the runtime picks the matching reviewer). Pass `background: false` to ask for the verdict before you continue: the tool waits only for a reviewer whose agent is configured with `"background": false` in opencode.json, and otherwise launches the review as a background task and notifies you when the verdict is ready. When the user asks for a code review, dispatch `review` with the requirements and the diff. Unless the user explicitly asks for a code review, do not dispatch a review for a turn that changed no files.

Launch independent agents in one message. Subagents run in the background by default; do not poll or duplicate their work. The result is not shown to the user; summarize it. Pass `task_id` to resume a session; otherwise give a detailed prompt (write code or research only, how to verify, what to return). Do not delegate edits to files you are editing.

Expand Down
Loading
Loading