feat(core): tell agents when they are in a fork (#63235)

Co-authored-by: OpenCode Agent <opencode-agent[bot]@users.noreply.github.com>
This commit is contained in:
Sebastian
2026-11-11 08:41:50 +01:00
committed by GitHub
Unverified
parent 070b980c0b
commit e56eff2bc0
9 changed files with 109 additions and 2 deletions
+30
View File
@@ -0,0 +1,30 @@
export * as ForkNoticePlugin from "./fork-notice.js"
import { define } from "@opencode/plugin/effect/plugin"
import { SessionMessage } from "@opencode/schema/session-message"
import { Effect } from "effect"
const notice = `<fork-notice>
This conversation is a fork of another conversation, copied up to the previous message. The original conversation keeps going on its own and may be active right now, as may other forks of it.
- Work started before the fork belongs to the original: background subagents, background shells, schedules, and follow-ups promised there. Their results and notifications go to the original, never here, and you can't continue those subagents. Don't wait for them, redo them, or report their results as yours; if it matters, check what already happened (files, git, PRs, CI).
- Files, repositories, branches and external services are shared with the original. Before changing something the original was working on (its uncommitted changes, branches, worktrees, PRs, deploys, messages), check its current state, and put work that diverges from it on a new branch or worktree.
- Otherwise work normally: new tasks need no extra checks, branches or questions.
- If it's unclear whether this fork or the original should do something, ask.
</fork-notice>`
export const Plugin = define({
id: "opencode.fork-notice",
effect: Effect.fn(function* (ctx) {
yield* ctx.session.hook("fork", ({ sessionID }) =>
ctx.session
.synthetic({
sessionID,
id: SessionMessage.ID.make(`msg_fork_notice_${sessionID}`),
text: notice,
description: "Fork notice",
resume: false,
})
.pipe(Effect.asVoid, Effect.orDie),
)
}),
})
+2
View File
@@ -102,6 +102,7 @@ import { AgentPlugin } from "./agent.js"
import BrowserPlugin from "@opencode/plugin-browser"
import { CommandPlugin } from "./command.js"
import { IdentityPlugin } from "./identity.js"
import { ForkNoticePlugin } from "./fork-notice.js"
import { PlanPlugin } from "./plan.js"
import { GoalPlugin } from "./goal.js"
import { ModelsDevPlugin } from "./models-dev.js"
@@ -251,6 +252,7 @@ const pre = [
WellKnownPlugin.Plugin,
VcsGitPlugin.Plugin,
AgentPlugin.Plugin,
ForkNoticePlugin.Plugin,
PlanPlugin.Plugin,
CommandPlugin.Plugin,
GoalPlugin.Plugin,
+12 -1
View File
@@ -13,6 +13,8 @@ import { SessionMessage } from "./session/message.js"
import { PromptInput } from "@opencode/schema/prompt-input"
import { Bus } from "./bus.js"
import { Instance } from "./instance/service.js"
import { Plugin } from "./plugin/service.js"
import { PluginHooks } from "./plugin/hooks.js"
import { Database } from "./database/database.js"
import { SessionProjector } from "./session/projector.js"
import { SessionMessageTable } from "./session/sql.js"
@@ -379,7 +381,16 @@ const layer = Layer.effect(
...inherited,
})
.pipe(Effect.provideService(SessionBlob.ForkMedia, media))
return yield* result.get(sessionID).pipe(Effect.orDie)
const forked = yield* result.get(sessionID).pipe(Effect.orDie)
yield* Effect.gen(function* () {
yield* Plugin.awaitActivation
const hooks = yield* PluginHooks.Service
yield* hooks.trigger("session", "fork", { sessionID })
}).pipe(
instances.provide(forked),
Effect.catchCause((cause) => Effect.logWarning("fork hook failed", { sessionID, cause })),
)
return forked
}),
get: (sessionID) => sessions.forSession(sessionID).get(),
environment: Effect.fn("Session.environment")(function* (input) {
+25
View File
@@ -673,6 +673,31 @@ describe("Session.create", () => {
}),
)
liveIt.live("queues a fork notice after copied history and before the first prompt", () =>
withTmp((directory) =>
Effect.gen(function* () {
const session = yield* Session.Service
const bus = yield* Bus.Service
const { db } = yield* Database.Service
const parent = yield* session.create({
location: Location.Ref.make({ directory: AbsolutePath.make(directory) }),
})
yield* session.prompt({ sessionID: parent.id, text: "Original", resume: false })
yield* SessionInbox.promote(db, bus, parent.id, "steer")
const fork = yield* session.fork({ sessionID: parent.id })
expect(yield* session.inbox(fork.id)).toMatchObject([{ type: "synthetic", delivery: "steer" }])
yield* session.prompt({ sessionID: fork.id, text: "Continue", resume: false })
yield* SessionInbox.promote(db, bus, fork.id, "steer")
expect(yield* session.context(fork.id)).toMatchObject([
Expected.user("Original"),
{ type: "synthetic", text: expect.stringContaining("<fork-notice>") },
Expected.user("Continue"),
])
expect(yield* session.context(parent.id)).toMatchObject([Expected.user("Original")])
}),
),
)
it.effect("keeps a fork untitled when its parent is untitled", () =>
Effect.gen(function* () {
const session = yield* Session.Service
+1
View File
@@ -196,6 +196,7 @@ export interface SessionIdle {
}
export interface SessionHooks {
readonly fork: { readonly sessionID: Session.ID }
readonly prompt: SessionPrompt
readonly context: SessionContext
readonly compaction: SessionCompaction
+1
View File
@@ -196,6 +196,7 @@ export interface SessionIdle {
}
export interface SessionHooks {
readonly fork: { readonly sessionID: Session.ID }
readonly prompt: SessionPrompt
readonly context: SessionContext
readonly compaction: SessionCompaction
+28 -1
View File
@@ -118,7 +118,10 @@ test("Promise instances are lazy, share by key and Location, and stay isolated b
expect(fork.fork?.sessionID).toBe(sessionID)
const inherited = await first.sessions.prompt({ sessionID: fork.id, text: "Review the fork", resume: false })
expect(inherited.payload.text).toBe(`first:alpha@${directory.path}: Review the fork`)
expect(await first.sessions.inbox.list({ sessionID: fork.id })).toEqual([inherited])
expect(await first.sessions.inbox.list({ sessionID: fork.id })).toEqual([
expect.objectContaining({ type: "synthetic", sessionID: fork.id, id: `msg_fork_notice_${fork.id}` }),
inherited,
])
expect(configured.toSorted()).toEqual(["first:alpha", "first:alpha", "first:beta", "second:alpha"])
expect(setups.toSorted()).toEqual(
@@ -142,6 +145,30 @@ test("Promise instances are lazy, share by key and Location, and stay isolated b
expect(cleanups.toSorted()).toEqual(setups.toSorted())
}, 20_000)
test("a throwing fork hook still returns the saved fork", async () => {
await using directory = await tmpdir("opencode-fork-hook-")
const seen: string[] = []
await using host = await OpenCode.create({
...hostOptions(directory.path),
plugins: [
{
id: "broken-fork-hook",
async setup(ctx) {
await ctx.session.hook("fork", ({ sessionID }) => {
seen.push(sessionID)
throw new Error("fork hook failed")
})
},
},
],
})
const parent = await host.sessions.create({ location: { directory: directory.path } })
await host.sessions.switchAgent({ sessionID: parent.id, agent: "plan" })
const fork = await host.sessions.fork({ sessionID: parent.id })
expect(seen).toEqual([fork.id])
expect(await host.sessions.get({ sessionID: fork.id })).toMatchObject({ id: fork.id, fork: { sessionID: parent.id } })
})
test.each(["configuration", "plugin setup"])(
"Promise instance %s failure admits nothing, preserves healthy instances, and can be retried",
async (failure) => {
@@ -1381,6 +1381,14 @@ so later hooks see changes made by earlier hooks.
Session hooks intercept prompt admission, model calls, native HTTP, and retries.
#### Forks
The `fork` hook runs after OpenCode copies the history and before the fork call returns. `sessionID` identifies the new session.
```ts
await ctx.session.hook("fork", ({ sessionID }) => console.log(sessionID))
```
#### Prompt admission
Intercept incoming user prompts before attachment and skill resolution and durable inbox admission:
@@ -81,6 +81,8 @@ use `.*` to match an ID prefix. A later ID re-enables a plugin.
}
```
To disable the notice added to new forks, add `"-opencode.fork-notice"` to `plugins`.
Two built-in plugins ignore removals so that a repository cannot switch off
[policy](/policies) enforcement: `opencode.config.policy` and
`opencode.provider.opencode`, the Console connection that delivers organization