diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 8c1f40b7679..8879a50e3b0 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -67,6 +67,7 @@ import { Job } from "./job.js" import type { Command } from "./command.js" import { SessionEnvironment } from "./session/environment.js" import { InstructionEntry } from "./session/instruction-entry.js" +import { SubagentMetadata } from "./session/subagent-metadata.js" // get project -> project.locations // @@ -93,7 +94,33 @@ type CreateBaseInput = { permissions?: Permission.Ruleset } type CreateInput = CreateBaseInput & - ({ location: Location.Ref; parentID?: never } | { parentID: SessionSchema.ID; location?: never }) + ( + | { location: Location.Ref; parentID?: never } + | { + /** @deprecated Use `Session.spawn`, which also records whether the parent wants a report. */ + parentID: SessionSchema.ID + location?: never + } + ) + +/** Fields shared by both creation paths, published as one durable `SessionEvent.Created`. */ +type CreatedFields = { + parentID?: SessionSchema.ID + location: Location.Ref + title?: string + agent?: Agent.ID + model?: Model.Ref + metadata?: SessionSchema.Metadata + permissions?: Permission.Ruleset +} + +type SpawnInput = { + readonly parent: { readonly id: SessionSchema.ID; readonly notify?: boolean } + readonly agent?: Agent.ID + readonly model?: Model.Ref + readonly title?: string + readonly prompt?: PromptInput.Prompt +} type CompactInput = Parameters[0] & { sessionID: SessionSchema.ID } @@ -131,6 +158,19 @@ export interface Interface { InvalidListCursorError > readonly create: (input: CreateInput) => Effect.Effect + /** + * Starts a child Session under `parent.id`, inheriting its location, metadata and permissions. + * + * `parent.notify` (default true) is written into the child's metadata, so core reports the + * child's result to the parent each time it goes idle. A given prompt is admitted with the + * default resume, so the child starts running in the background; await it with {@link Interface.wait}. + * + * The parent's model is inherited only when the agent is unchanged; otherwise the child keeps + * no model and `SessionRunnerModel.resolve` picks the chosen agent's model. + */ + readonly spawn: ( + input: SpawnInput, + ) => Effect.Effect<{ readonly id: SessionSchema.ID }, NotFoundError | Effect.Error>> readonly fork: ( input: ForkInput, ) => Effect.Effect @@ -284,57 +324,103 @@ const layer = Layer.effect( const isDurableSessionEvent = (item: Bus.LogItem): item is SessionEvent.DurableEvent => Object.hasOwn(SessionEvent.Durable.cases, item.type) + // Both creation paths publish the same durable fact; a concurrent loss of the projection race + // keeps the existing Session identity instead of failing. + const publishCreated = Effect.fnUntraced(function* (sessionID: SessionSchema.ID, fields: CreatedFields) { + const project = yield* projects.resolve(fields.location.directory) + const projected = yield* bus + .publish( + SessionEvent.Created, + { + sessionID, + slug: Slug.create(), + version: app.version, + projectID: project.id, + parentID: fields.parentID, + location: fields.location, + subpath: RelativePath.make( + path.relative(project.directory, fields.location.directory).replaceAll("\\", "/"), + ), + title: fields.title, + agent: fields.agent, + metadata: fields.metadata, + permissions: fields.permissions, + model: fields.model, + }, + { location: fields.location }, + ) + .pipe( + Effect.as({ type: "created" } as const), + Effect.catchDefect((defect) => { + if (!(defect instanceof SessionProjector.SessionAlreadyProjected)) { + return Effect.die(defect) + } + // Concurrent creation lost the projection race. The existing Session identity wins. + return store + .get(sessionID) + .pipe( + Effect.flatMap((session) => + session ? Effect.succeed({ type: "existing", session } as const) : Effect.die(defect), + ), + ) + }), + ) + if (projected.type === "existing") return projected.session + const created = yield* store.get(sessionID) + if (created === undefined) return yield* Effect.die(new NotFoundError({ sessionID })) + // TODO: Restore recorded sessions onto replacement synchronized workspaces in a future API slice. + return created + }) + + const createChild = Effect.fnUntraced(function* (parentID: SessionSchema.ID, input: CreateBaseInput) { + const sessionID = input.id ?? SessionSchema.ID.create() + // A retried create returns the recorded session even if the parent is gone since. + const recorded = yield* store.get(sessionID) + if (recorded) return recorded + const parent = yield* store.get(parentID) + if (parent === undefined) return yield* new NotFoundError({ sessionID: parentID }) + // Children inherit metadata and permissions the way they inherit location, so host policies + // that read them treat the family uniformly. + return yield* publishCreated(sessionID, { + parentID, + location: parent.location, + title: input.title, + agent: input.agent, + model: input.model, + metadata: input.metadata ?? parent.metadata, + permissions: input.permissions ?? parent.permissions, + }) + }) + const result = Service.of({ create: Effect.fn("Session.create")(function* (input) { + if (input.parentID !== undefined) return yield* createChild(input.parentID, input) const sessionID = input.id ?? SessionSchema.ID.create() const recorded = yield* store.get(sessionID) if (recorded) return recorded - const parent = input.parentID ? yield* store.get(input.parentID) : undefined - if (input.parentID && parent === undefined) return yield* new NotFoundError({ sessionID: input.parentID }) - const location = parent?.location ?? (input.location && LocationServiceMap.canonical(input.location)) - if (location === undefined) - return yield* Effect.die(new Error("Session.create requires either location or an existing parentID")) - const project = yield* projects.resolve(location.directory) - const projected = yield* bus - .publish( - SessionEvent.Created, - { - sessionID, - slug: Slug.create(), - version: app.version, - projectID: project.id, - parentID: input.parentID, - location, - subpath: RelativePath.make(path.relative(project.directory, location.directory).replaceAll("\\", "/")), - title: input.title, - agent: input.agent, - // Children inherit metadata and permissions the way they inherit - // location, so host policies that read them treat the family uniformly. - metadata: input.metadata ?? parent?.metadata, - permissions: input.permissions ?? parent?.permissions, - model: input.model, - }, - { location }, - ) - .pipe( - Effect.as({ type: "created" } as const), - Effect.catchDefect((defect) => { - if (!(defect instanceof SessionProjector.SessionAlreadyProjected)) { - return Effect.die(defect) - } - // Concurrent creation lost the projection race. The existing Session identity wins. - return store - .get(sessionID) - .pipe( - Effect.flatMap((session) => - session ? Effect.succeed({ type: "existing", session } as const) : Effect.die(defect), - ), - ) - }), - ) - if (projected.type === "existing") return projected.session - // TODO: Restore recorded sessions onto replacement synchronized workspaces in a future API slice. - return yield* result.get(sessionID).pipe(Effect.orDie) + return yield* publishCreated(sessionID, { + location: LocationServiceMap.canonical(input.location), + title: input.title, + agent: input.agent, + model: input.model, + metadata: input.metadata, + permissions: input.permissions, + }) + }), + spawn: Effect.fn("Session.spawn")(function* (input) { + const parent = yield* result.get(input.parent.id) + const keepsAgent = input.agent === undefined || input.agent === parent.agent + const child = yield* createChild(parent.id, { + title: input.title, + agent: input.agent ?? parent.agent, + // Only an unchanged agent inherits the parent's model; a different agent resolves its own. + model: input.model ?? (keepsAgent ? parent.model : undefined), + // withNotify returns undefined when the inherited preference already matches, which + // leaves createChild to keep the parent's metadata as-is. + metadata: SubagentMetadata.withNotify(parent.metadata, input.parent.notify !== false), + }) + if (input.prompt !== undefined) yield* result.prompt({ ...input.prompt, sessionID: child.id }) + return { id: child.id } }), fork: Effect.fn("Session.fork")(function* (input) { const parent = yield* result.get(input.sessionID) diff --git a/packages/core/test/session-create.test.ts b/packages/core/test/session-create.test.ts index ad0508e9eab..2e7219c5d56 100644 --- a/packages/core/test/session-create.test.ts +++ b/packages/core/test/session-create.test.ts @@ -1309,6 +1309,116 @@ describe("Session.create", () => { ) }) +describe("Session.spawn", () => { + const parentModel = Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }) + + it.effect("starts a child that inherits location, metadata, permissions, agent and model", () => + Effect.gen(function* () { + const session = yield* Session.Service + const metadata = { thread: "C123/1699999999.123" } + const permissions = [{ action: "edit", resource: "/original/**", effect: "deny" as const }] + const parent = yield* session.create({ + location, + metadata, + permissions, + agent: Agent.ID.make("build"), + model: parentModel, + }) + + const spawned = yield* session.spawn({ parent: { id: parent.id }, title: "child" }) + const child = yield* session.get(spawned.id) + + expect(child).toMatchObject({ + parentID: parent.id, + location, + title: "child", + agent: "build", + model: parentModel, + permissions, + }) + // Inheriting the loud default must not add the key, so the metadata stays the parent's own. + expect(child.metadata).toEqual(metadata) + // No prompt was given, so the child waits for work instead of starting a run. + expect(yield* session.inbox(spawned.id)).toEqual([]) + }), + ) + + it.effect("writes the notify preference only when it differs from the inherited one", () => + Effect.gen(function* () { + const session = yield* Session.Service + const loud = yield* session.create({ location, metadata: { thread: "x" } }) + const silent = yield* session.create({ location, metadata: { thread: "x", "subagent.notify": false } }) + + const showing = yield* session.spawn({ parent: { id: loud.id } }) + expect((yield* session.get(showing.id)).metadata).toEqual({ thread: "x" }) + + const muted = yield* session.spawn({ parent: { id: loud.id, notify: false } }) + expect((yield* session.get(muted.id)).metadata).toEqual({ thread: "x", "subagent.notify": false }) + + // Silence is inherited, so an omitted notify has to be written back explicitly. + const revived = yield* session.spawn({ parent: { id: silent.id } }) + expect((yield* session.get(revived.id)).metadata).toEqual({ thread: "x", "subagent.notify": true }) + }), + ) + + it.effect("inherits the model only while the agent stays the same", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location, agent: Agent.ID.make("build"), model: parentModel }) + + const same = yield* session.spawn({ parent: { id: parent.id }, agent: Agent.ID.make("build") }) + expect((yield* session.get(same.id)).model).toMatchObject(parentModel) + + // A different agent leaves the model to SessionRunnerModel.resolve. + const different = yield* session.spawn({ parent: { id: parent.id }, agent: Agent.ID.make("reviewer") }) + expect((yield* session.get(different.id)).agent).toBe(Agent.ID.make("reviewer")) + expect((yield* session.get(different.id)).model).toBeUndefined() + + const explicit = Model.Ref.make({ id: Model.ID.make("explicit"), providerID: Provider.ID.make("test") }) + const overridden = yield* session.spawn({ parent: { id: parent.id }, model: explicit }) + expect((yield* session.get(overridden.id)).model).toMatchObject(explicit) + }), + ) + + it.effect("admits the given prompt to the child", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + + const spawned = yield* session.spawn({ parent: { id: parent.id }, prompt: { text: "do it" } }) + + expect(yield* session.inbox(spawned.id)).toMatchObject([{ type: "user", payload: { text: "do it" } }]) + expect(yield* session.inbox(parent.id)).toEqual([]) + }), + ) + + it.effect("rejects a missing parent", () => + Effect.gen(function* () { + const session = yield* Session.Service + const missing = Session.ID.create() + + expect(yield* Effect.flip(session.spawn({ parent: { id: missing } }))).toEqual( + new Session.NotFoundError({ sessionID: missing }), + ) + expect((yield* session.list({ parentID: missing })).data).toEqual([]) + }), + ) + + it.effect("returns the recorded child when the same creation is retried", () => + Effect.gen(function* () { + const session = yield* Session.Service + const parent = yield* session.create({ location }) + const childID = Session.ID.create() + + const first = yield* session.create({ id: childID, parentID: parent.id, title: "child" }) + const retried = yield* session.create({ id: childID, parentID: parent.id, title: "child" }) + + expect(retried).toEqual(first) + expect((yield* session.list({ parentID: parent.id })).data.map((item) => item.id)).toEqual([childID]) + }), + ) +}) + describe("SessionTransfer", () => { it.effect("exports only settled projected messages", () => Effect.gen(function* () { diff --git a/packages/core/test/subagent-lifetime.test.ts b/packages/core/test/subagent-lifetime.test.ts index bfb66f33c6d..47df81e62ff 100644 --- a/packages/core/test/subagent-lifetime.test.ts +++ b/packages/core/test/subagent-lifetime.test.ts @@ -938,4 +938,92 @@ describe("subagent observer lifetime", () => { expect(notices[1]?.text).not.toContain("first") }), ) + + it.live("a spawned child runs from its prompt and reports to its parent", () => + Effect.gen(function* () { + const dir = yield* tmpdirScoped() + yield* Effect.promise(() => + Bun.write( + `${dir.path}/opencode.json`, + JSON.stringify({ + agents: { reviewer: { mode: "subagent" } }, + permissions: [{ action: "*", resource: "*", effect: "allow" }], + }), + ), + ) + const sessions = yield* Session.Service + const locations = yield* LocationServiceMap.Service + const llm = yield* TestLLM.Test + const parent = yield* sessions.create({ + location: { directory: AbsolutePath.make(dir.path) }, + agent: Agent.ID.make("build"), + model: Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }), + }) + yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe( + Effect.provide(locations.get(parent.location)), + ) + + const spawned = yield* sessions.spawn({ + parent: { id: parent.id }, + agent: Agent.ID.make("reviewer"), + title: "Review fixture", + prompt: { text: "Review the fixture" }, + }) + // The default resume wakes the child, so the spawn alone starts the run. + yield* llm.wait(1).pipe(Effect.timeout("2 seconds")) + yield* sessions.wait(spawned.id) + // The report wakes the parent for one more step. + yield* llm.wait(2).pipe(Effect.timeout("2 seconds")) + yield* sessions.wait(parent.id) + + const notices = yield* reports(parent.id) + expect(notices).toHaveLength(1) + expect(notices[0]).toMatchObject({ metadata: { source: "subagent", childID: spawned.id, state: "completed" } }) + expect(notices[0]?.text).toContain("Review complete") + }), + ) + + it.live("a spawn that asks for silence reports nothing", () => + Effect.gen(function* () { + const dir = yield* tmpdirScoped() + yield* Effect.promise(() => + Bun.write( + `${dir.path}/opencode.json`, + JSON.stringify({ + agents: { reviewer: { mode: "subagent" } }, + permissions: [{ action: "*", resource: "*", effect: "allow" }], + }), + ), + ) + const sessions = yield* Session.Service + const locations = yield* LocationServiceMap.Service + const llm = yield* TestLLM.Test + const parent = yield* sessions.create({ + location: { directory: AbsolutePath.make(dir.path) }, + agent: Agent.ID.make("build"), + model: Model.Ref.make({ id: Model.ID.make("parent"), providerID: Provider.ID.make("test") }), + }) + yield* Plugin.Service.use((plugins) => plugins.awaitActivation).pipe( + Effect.provide(locations.get(parent.location)), + ) + + const spawned = yield* sessions.spawn({ + parent: { id: parent.id, notify: false }, + agent: Agent.ID.make("reviewer"), + prompt: { text: "Review the fixture" }, + }) + expect((yield* sessions.get(spawned.id)).metadata).toEqual({ "subagent.notify": false }) + yield* llm.wait(1).pipe(Effect.timeout("2 seconds")) + yield* sessions.wait(spawned.id) + expect(yield* reports(parent.id)).toEqual([]) + const before = (yield* llm.requests()).length + + // A later prompt on the parent is the only input it ever receives. + yield* sessions.prompt({ sessionID: parent.id, text: "Review the fixture" }) + yield* llm.wait(before + 1).pipe(Effect.timeout("2 seconds")) + yield* sessions.wait(parent.id) + expect(yield* reports(parent.id)).toEqual([]) + expect((yield* sessions.context(parent.id)).filter((message) => message.type === "synthetic")).toEqual([]) + }), + ) })