fix(core): start every Location with the built-in agents

This commit is contained in:
Kit Langton 2026-10-20 16:36:30 -07:00
parent 6eb956b5b8
commit 2cbce540f6
18 changed files with 263 additions and 339 deletions

View file

@ -209,33 +209,6 @@ test("a prompt sent before the agents load waits and sends once they do", async
}
})
test("a prompt sent while the server still lists no agents sends once it lists them", async ({ page }) => {
const sessionID = "ses_send_empty_agents"
await mockWorkspace(page, {
name: "SendEmptyAgents",
sessions: [{ id: sessionID, agent: "build", model: { id: "alpha", providerID: "opencode" } }],
provider: provider({ id: "alpha", name: "Alpha" }),
emptyAgentReads: 1,
})
const emptied = page.waitForResponse((response) => new URL(response.url()).pathname === "/api/agent")
await page.goto(sessionHref(sessionID))
const editor = page.locator('[data-component="composer-editor"]')
await expect(editor).toBeEditable()
await emptied
const sent = page.waitForRequest(
(request) => request.method() === "POST" && new URL(request.url()).pathname === `/api/session/${sessionID}/prompt`,
)
await editor.click()
await page.keyboard.type("ship it")
await page.keyboard.press("Enter")
expect((await sent).postDataJSON()).toMatchObject({ text: "ship it", metadata: { agent: "build" } })
await expect(editor).toHaveText("")
await expect(page.getByText("Select an agent and model")).toHaveCount(0)
})
test("an opened session in another Location names its model from a loaded catalog before its agents load", async ({
page,
}) => {

View file

@ -74,8 +74,6 @@ export interface MockServerConfig {
// directory it resolves.
onLocationGet?: (directory: string) => void
sessions: MockSession[]
// Answers this many agent lists empty first, like a server whose Location is still activating its plugins.
emptyAgentReads?: number
pageMessages: (
sessionId: string,
limit: number,
@ -536,7 +534,6 @@ export function createMockServerHandler(config: MockServerConfig, emit: (events:
emit,
mcp: new Map<string, MockMcpStatus>(),
attempts: new Map<string, number>(),
agentReads: 0,
}),
),
Layer.provide(HttpServer.layerServices),
@ -721,7 +718,6 @@ function mockHandlers(
// MCP status overrides by `<directory>\n<server>`, and OAuth attempt creation times by attempt ID.
mcp: Map<string, MockMcpStatus>
attempts: Map<string, number>
agentReads: number
},
) {
const noContent = Effect.succeed(HttpApiSchema.NoContent.make())
@ -866,22 +862,19 @@ function mockHandlers(
config: () => Effect.succeed(configEntries),
reference: () => Effect.succeed({ location: location(config), data: [] }),
agent: (ctx) =>
Effect.sync(() => ({
Effect.succeed({
location: location(config, requestDirectory(config, ctx.request)),
data:
state.agentReads++ < (config.emptyAgentReads ?? 0)
? []
: [
{
id: "build",
name: "Build",
mode: "primary",
hidden: false,
request: { settings: {}, headers: {}, body: {} },
permissions: [],
},
],
})),
data: [
{
id: "build",
name: "Build",
mode: "primary",
hidden: false,
request: { settings: {}, headers: {}, body: {} },
permissions: [],
},
],
}),
provider: () =>
Effect.succeed({ location: location(config), data: currentProviders(resolve(config.provider)) }),
model: () => Effect.succeed({ location: location(config), data: currentModels(resolve(config.provider)) }),

View file

@ -1,4 +1,4 @@
import { batch, createEffect, createMemo, on, onCleanup } from "solid-js"
import { batch, createEffect, createMemo, on } from "solid-js"
import { createStore } from "solid-js/store"
import type { ComposerControls } from "./adapter"
import { useLocal, type ModelKey, type ModelSelection } from "@/providers/models/selection"
@ -21,49 +21,12 @@ export function createComposerControls(input: { model?: ModelSelection } = {}) {
const models = useGlobal().models
const providerName = (providerID: string, catalog = providers.all()) => composerProviderName(providerID, catalog)
const [agents, setAgents] = createStore({ retrying: false })
const noAgents = createMemo(() => data.location.agent.list({ directory: sdk().directory })?.length === 0)
// A server older than this client answers with no agents while its Location's plugins activate. Ask again a few
// times before believing the Location has none.
createEffect(() => {
const directory = sdk().directory
if (!noAgents()) return setAgents("retrying", false)
setAgents("retrying", true)
let attempt = 0
let timer: ReturnType<typeof setTimeout> | undefined
let stale = false
const retry = () => {
if (stale) return
const delay = agentRetryDelays[attempt++]
if (delay === undefined) return setAgents("retrying", false)
timer = setTimeout(() => {
data.location.agent.invalidate({ directory })
void data.location.agent
.sync({ directory })
.catch(() => undefined)
.finally(retry)
}, delay)
}
retry()
onCleanup(() => {
stale = true
clearTimeout(timer)
})
})
const loading = () => {
const selection = input.model ?? local.model
return (
!selection.ready() ||
data.location.agent.list({ directory: sdk().directory }) === undefined ||
(noAgents() && agents.retrying) ||
!providers.ready()
!selection.ready() || data.location.agent.list({ directory: sdk().directory }) === undefined || !providers.ready()
)
}
@ -130,8 +93,6 @@ export function createComposerControls(input: { model?: ModelSelection } = {}) {
})
}
const agentRetryDelays = [250, 500, 1_000, 2_000, 4_000, 8_000]
// Like the model picker, a Console-managed provider drops its "Workspace / " prefix unless the
// same provider is also connected directly and the workspace is what tells them apart.
export function composerProviderName(providerID: string, catalog: ReturnType<typeof normalizeProviderList>["all"]) {

View file

@ -479,7 +479,7 @@ export function make(options: ClientOptions) {
path: `/api/agent`,
query: { location: input?.["location"] },
successStatus: 200,
declaredStatuses: [400, 401, 404, 503],
declaredStatuses: [400, 401, 404],
empty: false,
},
requestOptions,
@ -491,7 +491,7 @@ export function make(options: ClientOptions) {
path: `/api/agent/${encodeURIComponent(input.agentID)}`,
query: { location: input["location"] },
successStatus: 200,
declaredStatuses: [400, 401, 404, 503],
declaredStatuses: [400, 401, 404],
empty: false,
},
requestOptions,

View file

@ -0,0 +1,152 @@
export * as AgentBuiltins from "./agent-builtins.js"
import { Agent } from "@opencode/schema/agent"
import type { Global } from "@opencode/util/global"
import path from "path"
import type { Editor } from "./agent.js"
const PROMPT_EXPLORE = `You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
Guidelines:
- Your role is EXCLUSIVELY to search and analyze
- Parallelize independent tool calls for searches and reads whenever possible
- Adapt your search approach based on the thoroughness level specified by the caller
- Return file paths as absolute paths in your final response
- You MUST NOT create, modify, delete, move, or copy files, including temporary files and reports
- Shell commands MUST be read-only. NEVER run commands that write files or change system state
Complete the user's search request efficiently and report your findings clearly.`
const PROMPT_TITLE = `You are a title generator. You output ONLY a thread title. Nothing else.
<task>
Generate a brief title that would help the user find this conversation later.
Follow all rules in <rules>
Use the <examples> so you know what a good title looks like.
Your output must be:
- A single line
- <=50 characters
- No explanations
</task>
<rules>
- you MUST use the same language as the user message you are summarizing
- Title must be grammatically correct and read naturally - no word salad
- Never include tool names in the title (e.g. "read tool", "bash tool", "edit tool")
- Focus on the main topic or question the user needs to retrieve
- Vary your phrasing - avoid repetitive patterns like always starting with "Analyzing"
- When a file is mentioned, focus on WHAT the user wants to do WITH the file, not just that they shared it
- Keep exact: technical terms, numbers, filenames, HTTP codes
- Remove: the, this, my, a, an
- Never assume tech stack
- Never use tools
- NEVER respond to questions, just generate a title for the conversation
- The title should NEVER include "summarizing" or "generating" when generating a title
- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
- Always output something meaningful, even if the input is minimal.
- If the user message is short or conversational (e.g. "hello", "lol", "what's up", "hey"):
-> create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
</rules>
<examples>
"debug 500 errors in production" -> Debugging production 500 errors
"refactor user service" -> Refactoring user service
"why is app.js failing" -> app.js failure investigation
"implement rate limiting" -> Rate limiting implementation
"how do I connect postgres to my API" -> Postgres API connection
"best practices for React hooks" -> React hooks best practices
"@src/credential.ts can you add refresh token support" -> Credential refresh token support
"@utils/parser.ts this is broken" -> Parser bug fix
"look at @config.json" -> Config review
"@App.tsx add dark mode toggle" -> Dark mode toggle in App
</examples>`
const PROMPT_SUMMARY = `Summarize what was done in this conversation. Write like a pull request description.
Rules:
- 2-3 sentences max
- Describe the changes made, not the process
- Do not mention running tests, builds, or other validation steps
- Do not explain what the user asked for
- Write in first person (I added..., I fixed...)
- Never ask questions or add new questions
- If the conversation ends with an unanswered question to the user, preserve that exact question
- If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary`
/** Plan mode may write plans only here. */
export const planDirectory = (global: Global.Interface) => path.join(global.home, ".opencode", "plan")
/** Every Location starts with these; plugins and config edit or remove them afterwards. */
export function seed(editor: Editor, global: Global.Interface) {
editor.update(Agent.ID.make("build"), (item) => {
item.name = Agent.Name.make("Build")
item.description = "The default agent. Executes tools based on configured permissions."
item.mode = "primary"
item.permissions.push({ action: "question", resource: "*", effect: "allow" })
})
editor.update(Agent.ID.make("general"), (item) => {
item.name = Agent.Name.make("General")
item.description =
"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel."
item.mode = "subagent"
item.permissions.push(
{ action: "question", resource: "*", effect: "deny" },
{ action: "subagent", resource: "*", effect: "deny" },
)
})
editor.update(Agent.ID.make("explore"), (item) => {
item.name = Agent.Name.make("Explore")
item.description =
'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.'
item.system = PROMPT_EXPLORE
item.mode = "subagent"
item.permissions.push(
{ action: "*", resource: "*", effect: "deny" },
{ action: "shell", resource: "*", effect: "allow" },
{ action: "grep", resource: "*", effect: "allow" },
{ action: "glob", resource: "*", effect: "allow" },
{ action: "webfetch", resource: "*", effect: "allow" },
{ action: "websearch", resource: "*", effect: "allow" },
{ action: "read", resource: "*", effect: "allow" },
{ action: "read", resource: "*.env", effect: "ask" },
{ action: "read", resource: "*.env.*", effect: "ask" },
{ action: "read", resource: "*.env.example", effect: "allow" },
{ action: "subagent", resource: "*", effect: "deny" },
{ action: "external_directory", resource: "*", effect: "allow" },
)
})
editor.update(Agent.ID.make("compaction"), (item) => {
item.name = Agent.Name.make("Compaction")
item.mode = "primary"
item.hidden = true
})
editor.update(Agent.ID.make("title"), (item) => {
item.name = Agent.Name.make("Title")
item.mode = "primary"
item.hidden = true
item.system = PROMPT_TITLE
item.permissions.push({ action: "*", resource: "*", effect: "deny" })
})
editor.update(Agent.ID.make("summary"), (item) => {
item.name = Agent.Name.make("Summary")
item.mode = "primary"
item.hidden = true
item.system = PROMPT_SUMMARY
item.permissions.push({ action: "*", resource: "*", effect: "deny" })
})
editor.update(Agent.ID.make("plan"), (item) => {
item.name = Agent.Name.make("Plan")
item.description = "Read-only agent for exploring the codebase and planning work before implementation."
item.mode = "primary"
item.permissions.push({ action: "question", resource: "*", effect: "allow" })
item.permissions.push({ action: "edit", resource: "*", effect: "deny" })
item.permissions.push({ action: "edit", resource: path.join(planDirectory(global), "*"), effect: "allow" })
})
}

View file

@ -3,6 +3,8 @@ export * as Agent from "./agent.js"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { Array, Context, Effect, Layer, Types } from "effect"
import { Agent } from "@opencode/schema/agent"
import { Global } from "@opencode/util/global"
import { AgentBuiltins } from "./agent-builtins.js"
import { Bus } from "./bus.js"
import { State } from "./state.js"
@ -50,6 +52,7 @@ const layer = Layer.effect(
Service,
Effect.gen(function* () {
const bus = yield* Bus.Service
const global = yield* Global.Service
const selectable = (agent: Info | undefined) =>
agent && agent.mode !== "subagent" && !agent.hidden ? agent : undefined
const selectedDefault = (data: Data) => {
@ -68,25 +71,31 @@ const layer = Layer.effect(
if (!selected) return agents
return [selected, ...agents.filter((agent) => agent.id !== selected.id)]
}
const edit = (editor: Data): Editor => ({
list: () => Array.fromIterable(editor.agents.values()) as Info[],
get: (id) => editor.agents.get(id),
default: (id) => {
editor.default = id
},
update: (id, fn) => {
const current = editor.agents.get(id) ?? (Info.default(id) as Types.DeepMutable<Info>)
if (!editor.agents.has(id)) editor.agents.set(id, current)
fn(current)
current.id = id
},
remove: (id) => {
editor.agents.delete(id)
},
})
const state = State.create<Data, Editor>({
name: "agent",
initial: () => ({ agents: new Map() }),
editor: (editor) => ({
list: () => Array.fromIterable(editor.agents.values()) as Info[],
get: (id) => editor.agents.get(id),
default: (id) => {
editor.default = id
},
update: (id, fn) => {
const current = editor.agents.get(id) ?? (Info.default(id) as Types.DeepMutable<Info>)
if (!editor.agents.has(id)) editor.agents.set(id, current)
fn(current)
current.id = id
},
remove: (id) => {
editor.agents.delete(id)
},
}),
// Built-ins exist before plugins activate, so a booting Location never lists no agents.
initial: () => {
const data: Data = { agents: new Map() }
AgentBuiltins.seed(edit(data), global)
return data
},
editor: edit,
notify: State.changes(list, () => bus.publish(Agent.Event.Updated, {}).pipe(Effect.asVoid)),
})
@ -115,4 +124,4 @@ const layer = Layer.effect(
}),
)
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node] })
export const node = makeLocationNode({ service: Service, layer, deps: [Bus.node, Global.node] })

View file

@ -1,143 +0,0 @@
export * as AgentPlugin from "./agent.js"
import { define } from "@opencode/plugin/effect/plugin"
import { Effect } from "effect"
import { Agent } from "../agent.js"
const PROMPT_EXPLORE = `You are a file search specialist. You excel at thoroughly navigating and exploring codebases.
Guidelines:
- Your role is EXCLUSIVELY to search and analyze
- Parallelize independent tool calls for searches and reads whenever possible
- Adapt your search approach based on the thoroughness level specified by the caller
- Return file paths as absolute paths in your final response
- You MUST NOT create, modify, delete, move, or copy files, including temporary files and reports
- Shell commands MUST be read-only. NEVER run commands that write files or change system state
Complete the user's search request efficiently and report your findings clearly.`
const PROMPT_TITLE = `You are a title generator. You output ONLY a thread title. Nothing else.
<task>
Generate a brief title that would help the user find this conversation later.
Follow all rules in <rules>
Use the <examples> so you know what a good title looks like.
Your output must be:
- A single line
- <=50 characters
- No explanations
</task>
<rules>
- you MUST use the same language as the user message you are summarizing
- Title must be grammatically correct and read naturally - no word salad
- Never include tool names in the title (e.g. "read tool", "bash tool", "edit tool")
- Focus on the main topic or question the user needs to retrieve
- Vary your phrasing - avoid repetitive patterns like always starting with "Analyzing"
- When a file is mentioned, focus on WHAT the user wants to do WITH the file, not just that they shared it
- Keep exact: technical terms, numbers, filenames, HTTP codes
- Remove: the, this, my, a, an
- Never assume tech stack
- Never use tools
- NEVER respond to questions, just generate a title for the conversation
- The title should NEVER include "summarizing" or "generating" when generating a title
- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
- Always output something meaningful, even if the input is minimal.
- If the user message is short or conversational (e.g. "hello", "lol", "what's up", "hey"):
-> create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
</rules>
<examples>
"debug 500 errors in production" -> Debugging production 500 errors
"refactor user service" -> Refactoring user service
"why is app.js failing" -> app.js failure investigation
"implement rate limiting" -> Rate limiting implementation
"how do I connect postgres to my API" -> Postgres API connection
"best practices for React hooks" -> React hooks best practices
"@src/credential.ts can you add refresh token support" -> Credential refresh token support
"@utils/parser.ts this is broken" -> Parser bug fix
"look at @config.json" -> Config review
"@App.tsx add dark mode toggle" -> Dark mode toggle in App
</examples>`
const PROMPT_SUMMARY = `Summarize what was done in this conversation. Write like a pull request description.
Rules:
- 2-3 sentences max
- Describe the changes made, not the process
- Do not mention running tests, builds, or other validation steps
- Do not explain what the user asked for
- Write in first person (I added..., I fixed...)
- Never ask questions or add new questions
- If the conversation ends with an unanswered question to the user, preserve that exact question
- If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary`
export const Plugin = define({
id: "opencode.agent",
effect: Effect.fn(function* (ctx) {
yield* ctx.agent.transform((editor) => {
editor.update(Agent.defaultID, (item) => {
item.name = Agent.Name.make("Build")
item.description = "The default agent. Executes tools based on configured permissions."
item.mode = "primary"
item.permissions.push({ action: "question", resource: "*", effect: "allow" })
})
editor.update(Agent.ID.make("general"), (item) => {
item.name = Agent.Name.make("General")
item.description =
"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel."
item.mode = "subagent"
item.permissions.push(
{ action: "question", resource: "*", effect: "deny" },
{ action: "subagent", resource: "*", effect: "deny" },
)
})
editor.update(Agent.ID.make("explore"), (item) => {
item.name = Agent.Name.make("Explore")
item.description =
'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.'
item.system = PROMPT_EXPLORE
item.mode = "subagent"
item.permissions.push(
{ action: "*", resource: "*", effect: "deny" },
{ action: "shell", resource: "*", effect: "allow" },
{ action: "grep", resource: "*", effect: "allow" },
{ action: "glob", resource: "*", effect: "allow" },
{ action: "webfetch", resource: "*", effect: "allow" },
{ action: "websearch", resource: "*", effect: "allow" },
{ action: "read", resource: "*", effect: "allow" },
{ action: "read", resource: "*.env", effect: "ask" },
{ action: "read", resource: "*.env.*", effect: "ask" },
{ action: "read", resource: "*.env.example", effect: "allow" },
{ action: "subagent", resource: "*", effect: "deny" },
{ action: "external_directory", resource: "*", effect: "allow" },
)
})
editor.update(Agent.ID.make("compaction"), (item) => {
item.name = Agent.Name.make("Compaction")
item.mode = "primary"
item.hidden = true
})
editor.update(Agent.ID.make("title"), (item) => {
item.name = Agent.Name.make("Title")
item.mode = "primary"
item.hidden = true
item.system = PROMPT_TITLE
item.permissions.push({ action: "*", resource: "*", effect: "deny" })
})
editor.update(Agent.ID.make("summary"), (item) => {
item.name = Agent.Name.make("Summary")
item.mode = "primary"
item.hidden = true
item.system = PROMPT_SUMMARY
item.permissions.push({ action: "*", resource: "*", effect: "deny" })
})
})
}),
})

View file

@ -86,7 +86,6 @@ import { WebFetchTool } from "../tool/plugin/webfetch.js"
import { WebSearchTool } from "../tool/plugin/websearch.js"
import { WellKnown } from "../wellknown.js"
import { WriteTool } from "../tool/plugin/write.js"
import { AgentPlugin } from "./agent.js"
import BrowserPlugin from "@opencode/plugin-browser"
import GenUIPlugin from "@opencode/plugin-genui"
import { CommandPlugin } from "./command.js"
@ -221,7 +220,6 @@ const pre = [
McpCodeModeDefaultsPlugin.Plugin,
WellKnownPlugin.Plugin,
VcsGitPlugin.Plugin,
AgentPlugin.Plugin,
PlanPlugin.Plugin,
CommandPlugin.Plugin,
SkillPlugin.Plugin,

View file

@ -6,7 +6,7 @@ import { Agent } from "@opencode/schema/agent"
import type { SessionEvent } from "@opencode/schema/session-event"
import { Global } from "@opencode/util/global"
import { Effect, Stream } from "effect"
import path from "path"
import { AgentBuiltins } from "../agent-builtins.js"
import { Permission } from "../permission.js"
const plan = Agent.ID.make("plan")
@ -28,19 +28,8 @@ export const Plugin = define({
id: "opencode.plan",
effect: Effect.fn(function* (ctx) {
const global = yield* Global.Service
const directory = path.join(global.home, ".opencode", "plan")
const directory = AgentBuiltins.planDirectory(global)
const enterReminder = enter(directory)
yield* ctx.agent.transform((editor) => {
editor.update(plan, (item) => {
item.name = Agent.Name.make("Plan")
item.description = "Read-only agent for exploring the codebase and planning work before implementation."
item.mode = "primary"
item.permissions.push({ action: "question", resource: "*", effect: "allow" })
item.permissions.push({ action: "edit", resource: "*", effect: "deny" })
item.permissions.push({ action: "edit", resource: path.join(directory, "*"), effect: "allow" })
})
})
yield* ctx.tool.hook("execute.after", (event) => {
if (event.agent !== plan) return Effect.void
if (event.status !== "error") return Effect.void

View file

@ -7,12 +7,10 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { Location } from "@opencode/core/location"
import { Permission } from "@opencode/core/permission"
import { AgentPlugin } from "@opencode/core/plugin/agent"
import { AbsolutePath } from "@opencode/core/schema"
import { Global } from "@opencode/util/global"
import { location } from "./fixture/location"
import { testEffect } from "./lib/effect"
import { agentHost, host } from "./plugin/host"
const testLocation = location({ directory: AbsolutePath.make("/project") })
const locationLayer = Layer.succeed(Location.Service, Location.Service.of(testLocation))
@ -42,12 +40,19 @@ describe("Agent", () => {
}),
)
it.effect("starts without agents", () =>
it.effect("starts with the built-in agents before any plugin runs", () =>
Effect.gen(function* () {
const agent = yield* Agent.Service
expect(yield* agent.list()).toEqual([])
expect(yield* agent.get(Agent.ID.make("build"))).toBeUndefined()
expect((yield* agent.list()).map((item) => String(item.id))).toEqual([
"build",
"general",
"explore",
"compaction",
"title",
"summary",
"plan",
])
}),
)
@ -63,7 +68,7 @@ describe("Agent", () => {
)
expect(yield* agent.get(id)).toMatchObject({ id, description: "Reviews code", mode: "subagent" })
expect((yield* agent.list()).map((info) => info.id)).toEqual([id])
expect((yield* agent.list()).map((info) => info.id)).toContain(id)
}),
)
@ -83,7 +88,12 @@ describe("Agent", () => {
editor.default(Agent.ID.make("reviewer"))
})
expect((yield* agent.list()).map((info) => String(info.id))).toEqual(["reviewer", "build", "explore"])
expect((yield* agent.list()).map((info) => String(info.id)).slice(0, 4)).toEqual([
"reviewer",
"build",
"general",
"explore",
])
}),
)
@ -170,11 +180,6 @@ describe("Agent", () => {
it.effect("allows external directories without opting built-in agents into bash", () =>
Effect.gen(function* () {
const agent = yield* Agent.Service
yield* AgentPlugin.Plugin.effect(
host({
agent: agentHost(agent),
}),
)
const agents = yield* agent.list()
expect(agents.map((item) => String(item.id)).sort()).toEqual([
@ -182,6 +187,7 @@ describe("Agent", () => {
"compaction",
"explore",
"general",
"plan",
"summary",
"title",
])
@ -220,11 +226,6 @@ describe("Agent", () => {
it.effect("denies the subagent tool for built-in subagents", () =>
Effect.gen(function* () {
const agent = yield* Agent.Service
yield* AgentPlugin.Plugin.effect(
host({
agent: agentHost(agent),
}),
)
yield* Effect.forEach(["general", "explore"], (id) =>
Effect.gen(function* () {

View file

@ -13,7 +13,6 @@ import { LayerNode } from "@opencode/util/effect/layer-node"
import { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
import { Permission } from "@opencode/core/permission"
import { AgentPlugin } from "@opencode/core/plugin/agent"
import { AbsolutePath } from "@opencode/core/schema"
import { ConfigNormalize } from "@opencode/core/config/normalize"
import { ConfigAgentV1 } from "@opencode/core/v1/config/agent"
@ -61,6 +60,30 @@ test("keeps schema fields and name out of legacy agent options", () => {
})
describe("ConfigAgentPlugin.Plugin", () => {
it.effect("removes a built-in agent that config disables and announces the change", () =>
Effect.gen(function* () {
const agents = yield* Agent.Service
const bus = yield* Bus.Service
expect(yield* agents.get(Agent.ID.make("plan"))).toBeDefined()
const updated = yield* bus
.subscribe(Agent.Event.Updated)
.pipe(Stream.take(1), Stream.runCollect, Effect.forkScoped)
yield* Effect.yieldNow
yield* ConfigAgentPlugin.Plugin.effect(host({ agent: agentHost(agents) })).pipe(
Effect.provide(
Config.testLayer([
new Document({ type: "document", info: decode({ agents: { plan: { disabled: true } } }) }),
]),
),
)
expect(yield* Fiber.join(updated)).toHaveLength(1)
expect(yield* agents.get(Agent.ID.make("plan"))).toBeUndefined()
expect((yield* agents.list()).map((item) => String(item.id))).toContain("build")
}),
)
for (const item of [
{ name: "separate legacy variant", frontmatter: "model: example/chat\nvariant: high", model: "example/chat#high" },
{ name: "unqualified model", frontmatter: "model: example/chat", model: "example/chat" },
@ -174,7 +197,6 @@ permissions:
Effect.gen(function* () {
const agents = yield* Agent.Service
const global = yield* Global.Service
yield* AgentPlugin.Plugin.effect(host({ agent: agentHost(agents) }))
const entries = [
new Document({
@ -316,6 +338,7 @@ permissions:
if (!buildAgent) throw new Error("expected configured build agent")
expect(buildAgent.permissions).toEqual([
...defaultPermissions,
{ action: "question", resource: "*", effect: "allow" },
{ action: "bash", resource: "*", effect: "allow" },
{ action: "bash", resource: "*", effect: "ask" },
{ action: "read", resource: "*", effect: "allow" },

View file

@ -209,8 +209,7 @@ describe("Permission", () => {
.pipe(Effect.orDie)
const agents = yield* Agent.Service
yield* agents.transform((editor) => {
editor.remove(Agent.ID.make("test"))
editor.remove(Agent.ID.make("build"))
editor.list().forEach((agent) => editor.remove(agent.id))
})
const service = yield* Permission.Service

View file

@ -4,6 +4,7 @@ import { DateTime, Effect, Option, Stream, Types } from "effect"
import type { SessionContext } from "@opencode/plugin/effect/session"
import type { ToolHooks } from "@opencode/plugin/effect/tool"
import { Agent } from "@opencode/core/agent"
import { AgentBuiltins } from "@opencode/core/agent-builtins"
import { Environment } from "@opencode/core/environment/index"
import { Event } from "@opencode/schema/event"
import { Model } from "@opencode/core/model"
@ -44,6 +45,19 @@ const run = Effect.fnUntraced(function* (events: ReadonlyArray<SessionEvent.Agen
...defaults,
permissions: [...defaults.permissions],
} satisfies Types.DeepMutable<Agent.Info>
// The plan agent is a built-in; the plugin owns only its tools and reminders.
AgentBuiltins.seed(
{
list: () => [planAgent],
get: (id) => (id === plan ? planAgent : undefined),
default: () => {},
update: (id, update) => {
if (id === plan) update(planAgent)
},
remove: () => {},
},
{ ...Global.make(), home },
)
const driver = Environment.makeMemoryDriver()
yield* PlanPlugin.Plugin.effect(
host({
@ -51,18 +65,7 @@ const run = Effect.fnUntraced(function* (events: ReadonlyArray<SessionEvent.Agen
get: () => Effect.die("unused agent.get"),
list: () => Effect.die("unused agent.list"),
reload: () => Effect.die("unused agent.reload"),
transform: (callback) => {
callback({
list: () => [planAgent],
get: (id) => (id === plan ? planAgent : undefined),
default: () => {},
update: (id, update) => {
if (id === plan) update(planAgent)
},
remove: () => {},
})
return Effect.succeed({ dispose: Effect.void })
},
transform: () => Effect.die("unused agent.transform"),
},
tool: {
transform: () => Effect.die("unused tool.transform"),

View file

@ -1850,7 +1850,7 @@ describe("SessionRunnerLLM", () => {
scenario("fails before the model request when the selected agent is unavailable", function* (s) {
yield* s.db
.update(SessionTable)
.set({ agent: "explore" })
.set({ agent: "missing" })
.where(eq(SessionTable.id, sessionID))
.run()
.pipe(Effect.orDie)
@ -1863,7 +1863,7 @@ describe("SessionRunnerLLM", () => {
expect(failure).toMatchObject({
_tag: "Session.AgentNotFoundError",
sessionID,
agent: "explore",
agent: "missing",
})
expect(s.requests).toHaveLength(0)
})

View file

@ -416,6 +416,8 @@ it.effect("generates a title for an explicitly requested child session", () =>
it.effect("does not generate when the title agent is removed", () =>
Effect.gen(function* () {
const sessionID = Session.ID.make("ses_title_no_agent")
const agents = yield* Agent.Service
yield* agents.transform((editor) => editor.remove(Agent.ID.make("title")))
yield* insertSession(sessionID)
yield* prompt(sessionID, "Help me debug the failing build")

View file

@ -3,14 +3,13 @@ import { Location } from "@opencode/schema/location"
import { Schema } from "effect"
import { HttpApiEndpoint, HttpApiGroup, OpenApi } from "effect/http-api"
import { LocationQuery, locationQueryOpenApi } from "./location.js"
import { AgentNotFoundError, ServiceUnavailableError } from "../errors.js"
import { AgentNotFoundError } from "../errors.js"
export const AgentGroup = HttpApiGroup.make("server.agent")
.add(
HttpApiEndpoint.get("agent.list", "/api/agent", {
query: LocationQuery,
success: Location.response(Schema.Array(Agent.Info)),
error: ServiceUnavailableError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(
@ -26,7 +25,7 @@ export const AgentGroup = HttpApiGroup.make("server.agent")
params: { agentID: Agent.ID },
query: LocationQuery,
success: Location.response(Agent.Info),
error: [AgentNotFoundError, ServiceUnavailableError],
error: AgentNotFoundError,
})
.annotateMerge(locationQueryOpenApi)
.annotateMerge(

View file

@ -2,22 +2,19 @@ import { Agent } from "@opencode/core/agent"
import { Effect } from "effect"
import { HttpApiBuilder } from "effect/http-api"
import { Api } from "../api"
import { awaitPlugins, response } from "../location"
import { response } from "../location"
import { AgentNotFoundError } from "@opencode/protocol/errors"
export const AgentHandler = HttpApiBuilder.group(Api, "server.agent", (handlers) =>
handlers
.handle("agent.list", () =>
Effect.gen(function* () {
// Plugins register every agent, including the built-ins, after the Location boots.
yield* awaitPlugins
return yield* response(Agent.Service.use((agent) => agent.list()))
}),
)
.handle(
"agent.get",
Effect.fn(function* (ctx) {
yield* awaitPlugins
const agent = yield* Agent.Service.use((service) => service.get(ctx.params.agentID))
if (!agent)
return yield* new AgentNotFoundError({

View file

@ -1,32 +0,0 @@
import fs from "node:fs/promises"
import path from "node:path"
import { expect } from "bun:test"
import { Effect } from "effect"
import { tmpdir } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { startServer } from "./fixture/server"
it.live("waits for plugin initialization before listing agents", () =>
Effect.gen(function* () {
const tmp = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-agent-endpoint-")))
yield* Effect.promise(() =>
fs.writeFile(path.join(tmp.path, "opencode.json"), JSON.stringify({ agents: { reviewer: { mode: "primary" } } })),
)
const server = yield* startServer(tmp.path)
const url = new URL("/api/agent", server.base)
url.searchParams.set("location[directory]", tmp.path)
// The first read boots the Location, as after a server restart.
const response = yield* Effect.promise(() => fetch(url, { headers: server.headers }))
expect(response.status).toBe(200)
const body: unknown = yield* Effect.promise(() => response.json())
if (!isRecord(body) || !Array.isArray(body["data"])) throw new Error("Expected an agent list response")
expect(body["data"].flatMap((agent) => (isRecord(agent) ? [agent["id"]] : []))).toEqual(
expect.arrayContaining(["build", "reviewer"]),
)
}),
)
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}