diff --git a/packages/core/src/plugin/fork-notice.ts b/packages/core/src/plugin/fork-notice.ts new file mode 100644 index 00000000000..ab317f813a5 --- /dev/null +++ b/packages/core/src/plugin/fork-notice.ts @@ -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 = ` +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. +` + +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), + ) + }), +}) diff --git a/packages/core/src/plugin/internal.ts b/packages/core/src/plugin/internal.ts index aae3f6ccaa4..95b5a1e2583 100644 --- a/packages/core/src/plugin/internal.ts +++ b/packages/core/src/plugin/internal.ts @@ -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, diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 76b2b7b279e..6788a66da5f 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -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) { diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index ad0508e9eab..1701d99de65 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -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("") }, + 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 diff --git a/packages/plugin/src/effect/session.ts b/packages/plugin/src/effect/session.ts index cfa84d44ca5..129a921f1f6 100644 --- a/packages/plugin/src/effect/session.ts +++ b/packages/plugin/src/effect/session.ts @@ -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 diff --git a/packages/plugin/src/promise/session.ts b/packages/plugin/src/promise/session.ts index 5067ee006b1..c1c0523b557 100644 --- a/packages/plugin/src/promise/session.ts +++ b/packages/plugin/src/promise/session.ts @@ -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 diff --git a/packages/sdk/test/instances.test.ts b/packages/sdk/test/instances.test.ts index 87857bd0838..b5439263f25 100644 --- a/packages/sdk/test/instances.test.ts +++ b/packages/sdk/test/instances.test.ts @@ -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) => { diff --git a/services/site/src/docs/content/build/plugins/server.mdx b/services/site/src/docs/content/build/plugins/server.mdx index 665a3c7eecb..a980b878fc6 100644 --- a/services/site/src/docs/content/build/plugins/server.mdx +++ b/services/site/src/docs/content/build/plugins/server.mdx @@ -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: diff --git a/services/site/src/docs/content/plugins.mdx b/services/site/src/docs/content/plugins.mdx index d3c96ff30a3..2c3a2771aaa 100644 --- a/services/site/src/docs/content/plugins.mdx +++ b/services/site/src/docs/content/plugins.mdx @@ -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