Skip to content

Commit e56eff2

Browse files
feat(core): tell agents when they are in a fork (#63235)
Co-authored-by: OpenCode Agent <opencode-agent[bot]@users.noreply.github.com>
1 parent 070b980 commit e56eff2

9 files changed

Lines changed: 109 additions & 2 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
export * as ForkNoticePlugin from "./fork-notice.js"
2+
3+
import { define } from "@opencode/plugin/effect/plugin"
4+
import { SessionMessage } from "@opencode/schema/session-message"
5+
import { Effect } from "effect"
6+
7+
const notice = `<fork-notice>
8+
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.
9+
- 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).
10+
- 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.
11+
- Otherwise work normally: new tasks need no extra checks, branches or questions.
12+
- If it's unclear whether this fork or the original should do something, ask.
13+
</fork-notice>`
14+
15+
export const Plugin = define({
16+
id: "opencode.fork-notice",
17+
effect: Effect.fn(function* (ctx) {
18+
yield* ctx.session.hook("fork", ({ sessionID }) =>
19+
ctx.session
20+
.synthetic({
21+
sessionID,
22+
id: SessionMessage.ID.make(`msg_fork_notice_${sessionID}`),
23+
text: notice,
24+
description: "Fork notice",
25+
resume: false,
26+
})
27+
.pipe(Effect.asVoid, Effect.orDie),
28+
)
29+
}),
30+
})

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ import { AgentPlugin } from "./agent.js"
102102
import BrowserPlugin from "@opencode/plugin-browser"
103103
import { CommandPlugin } from "./command.js"
104104
import { IdentityPlugin } from "./identity.js"
105+
import { ForkNoticePlugin } from "./fork-notice.js"
105106
import { PlanPlugin } from "./plan.js"
106107
import { GoalPlugin } from "./goal.js"
107108
import { ModelsDevPlugin } from "./models-dev.js"
@@ -251,6 +252,7 @@ const pre = [
251252
WellKnownPlugin.Plugin,
252253
VcsGitPlugin.Plugin,
253254
AgentPlugin.Plugin,
255+
ForkNoticePlugin.Plugin,
254256
PlanPlugin.Plugin,
255257
CommandPlugin.Plugin,
256258
GoalPlugin.Plugin,

‎packages/core/src/session.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import { SessionMessage } from "./session/message.js"
1313
import { PromptInput } from "@opencode/schema/prompt-input"
1414
import { Bus } from "./bus.js"
1515
import { Instance } from "./instance/service.js"
16+
import { Plugin } from "./plugin/service.js"
17+
import { PluginHooks } from "./plugin/hooks.js"
1618
import { Database } from "./database/database.js"
1719
import { SessionProjector } from "./session/projector.js"
1820
import { SessionMessageTable } from "./session/sql.js"
@@ -379,7 +381,16 @@ const layer = Layer.effect(
379381
...inherited,
380382
})
381383
.pipe(Effect.provideService(SessionBlob.ForkMedia, media))
382-
return yield* result.get(sessionID).pipe(Effect.orDie)
384+
const forked = yield* result.get(sessionID).pipe(Effect.orDie)
385+
yield* Effect.gen(function* () {
386+
yield* Plugin.awaitActivation
387+
const hooks = yield* PluginHooks.Service
388+
yield* hooks.trigger("session", "fork", { sessionID })
389+
}).pipe(
390+
instances.provide(forked),
391+
Effect.catchCause((cause) => Effect.logWarning("fork hook failed", { sessionID, cause })),
392+
)
393+
return forked
383394
}),
384395
get: (sessionID) => sessions.forSession(sessionID).get(),
385396
environment: Effect.fn("Session.environment")(function* (input) {

‎packages/core/test/session-create.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,31 @@ describe("Session.create", () => {
673673
}),
674674
)
675675

676+
liveIt.live("queues a fork notice after copied history and before the first prompt", () =>
677+
withTmp((directory) =>
678+
Effect.gen(function* () {
679+
const session = yield* Session.Service
680+
const bus = yield* Bus.Service
681+
const { db } = yield* Database.Service
682+
const parent = yield* session.create({
683+
location: Location.Ref.make({ directory: AbsolutePath.make(directory) }),
684+
})
685+
yield* session.prompt({ sessionID: parent.id, text: "Original", resume: false })
686+
yield* SessionInbox.promote(db, bus, parent.id, "steer")
687+
const fork = yield* session.fork({ sessionID: parent.id })
688+
expect(yield* session.inbox(fork.id)).toMatchObject([{ type: "synthetic", delivery: "steer" }])
689+
yield* session.prompt({ sessionID: fork.id, text: "Continue", resume: false })
690+
yield* SessionInbox.promote(db, bus, fork.id, "steer")
691+
expect(yield* session.context(fork.id)).toMatchObject([
692+
Expected.user("Original"),
693+
{ type: "synthetic", text: expect.stringContaining("<fork-notice>") },
694+
Expected.user("Continue"),
695+
])
696+
expect(yield* session.context(parent.id)).toMatchObject([Expected.user("Original")])
697+
}),
698+
),
699+
)
700+
676701
it.effect("keeps a fork untitled when its parent is untitled", () =>
677702
Effect.gen(function* () {
678703
const session = yield* Session.Service

‎packages/plugin/src/effect/session.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ export interface SessionIdle {
196196
}
197197

198198
export interface SessionHooks {
199+
readonly fork: { readonly sessionID: Session.ID }
199200
readonly prompt: SessionPrompt
200201
readonly context: SessionContext
201202
readonly compaction: SessionCompaction

‎packages/plugin/src/promise/session.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ export interface SessionIdle {
196196
}
197197

198198
export interface SessionHooks {
199+
readonly fork: { readonly sessionID: Session.ID }
199200
readonly prompt: SessionPrompt
200201
readonly context: SessionContext
201202
readonly compaction: SessionCompaction

‎packages/sdk/test/instances.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,10 @@ test("Promise instances are lazy, share by key and Location, and stay isolated b
118118
expect(fork.fork?.sessionID).toBe(sessionID)
119119
const inherited = await first.sessions.prompt({ sessionID: fork.id, text: "Review the fork", resume: false })
120120
expect(inherited.payload.text).toBe(`first:alpha@${directory.path}: Review the fork`)
121-
expect(await first.sessions.inbox.list({ sessionID: fork.id })).toEqual([inherited])
121+
expect(await first.sessions.inbox.list({ sessionID: fork.id })).toEqual([
122+
expect.objectContaining({ type: "synthetic", sessionID: fork.id, id: `msg_fork_notice_${fork.id}` }),
123+
inherited,
124+
])
122125

123126
expect(configured.toSorted()).toEqual(["first:alpha", "first:alpha", "first:beta", "second:alpha"])
124127
expect(setups.toSorted()).toEqual(
@@ -142,6 +145,30 @@ test("Promise instances are lazy, share by key and Location, and stay isolated b
142145
expect(cleanups.toSorted()).toEqual(setups.toSorted())
143146
}, 20_000)
144147

148+
test("a throwing fork hook still returns the saved fork", async () => {
149+
await using directory = await tmpdir("opencode-fork-hook-")
150+
const seen: string[] = []
151+
await using host = await OpenCode.create({
152+
...hostOptions(directory.path),
153+
plugins: [
154+
{
155+
id: "broken-fork-hook",
156+
async setup(ctx) {
157+
await ctx.session.hook("fork", ({ sessionID }) => {
158+
seen.push(sessionID)
159+
throw new Error("fork hook failed")
160+
})
161+
},
162+
},
163+
],
164+
})
165+
const parent = await host.sessions.create({ location: { directory: directory.path } })
166+
await host.sessions.switchAgent({ sessionID: parent.id, agent: "plan" })
167+
const fork = await host.sessions.fork({ sessionID: parent.id })
168+
expect(seen).toEqual([fork.id])
169+
expect(await host.sessions.get({ sessionID: fork.id })).toMatchObject({ id: fork.id, fork: { sessionID: parent.id } })
170+
})
171+
145172
test.each(["configuration", "plugin setup"])(
146173
"Promise instance %s failure admits nothing, preserves healthy instances, and can be retried",
147174
async (failure) => {

‎services/site/src/docs/content/build/plugins/server.mdx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1381,6 +1381,14 @@ so later hooks see changes made by earlier hooks.
13811381

13821382
Session hooks intercept prompt admission, model calls, native HTTP, and retries.
13831383

1384+
#### Forks
1385+
1386+
The `fork` hook runs after OpenCode copies the history and before the fork call returns. `sessionID` identifies the new session.
1387+
1388+
```ts
1389+
await ctx.session.hook("fork", ({ sessionID }) => console.log(sessionID))
1390+
```
1391+
13841392
#### Prompt admission
13851393

13861394
Intercept incoming user prompts before attachment and skill resolution and durable inbox admission:

‎services/site/src/docs/content/plugins.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ use `.*` to match an ID prefix. A later ID re-enables a plugin.
8181
}
8282
```
8383

84+
To disable the notice added to new forks, add `"-opencode.fork-notice"` to `plugins`.
85+
8486
Two built-in plugins ignore removals so that a repository cannot switch off
8587
[policy](/policies) enforcement: `opencode.config.policy` and
8688
`opencode.provider.opencode`, the Console connection that delivers organization

0 commit comments

Comments
 (0)