feat(plugin): expose session instruction entries to plugins (#56550)

This commit is contained in:
Kit Langton
2026-10-20 22:58:50 -07:00
committed by GitHub
Unverified
parent f2beb32aa4
commit 6c74e11e95
9 changed files with 281 additions and 2 deletions
+21
View File
@@ -19,6 +19,7 @@ import { LocationServiceMap } from "../location-service-map.js"
import { Model } from "../model.js"
import { Mcp } from "../mcp/index.js"
import { Session } from "../session.js"
import { InstructionEntry } from "../session/instruction-entry.js"
import { PersistentPty } from "../persistent-pty.js"
import { Provider } from "../provider.js"
import { Reference } from "../reference.js"
@@ -69,6 +70,7 @@ export const make = Effect.fn("PluginHost.make")(function* (
const permission = yield* Permission.Service
const hooks = yield* PluginHooks.Service
const sessions = yield* Session.Service
const instructionEntries = yield* InstructionEntry.Service
const persistentPty = yield* PersistentPty.Service
const locations = yield* LocationServiceMap.Service
const worktrees = yield* Worktree.Service
@@ -587,6 +589,24 @@ export const make = Effect.fn("PluginHost.make")(function* (
.pipe(Effect.map((interrupted) => ({ interrupted }))),
wait: (input) => sessions.wait(input.sessionID),
context: (input) => sessions.context(input.sessionID),
instructions: {
entry: {
list: Effect.fn(function* (input) {
yield* sessions.get(input.sessionID)
return yield* instructionEntries.list(input.sessionID)
}),
put: Effect.fn(function* (input) {
const key = yield* Schema.decodeUnknownEffect(InstructionEntry.Key)(input.key)
yield* sessions.get(input.sessionID)
yield* instructionEntries.put({ ...input, key })
}),
remove: Effect.fn(function* (input) {
const key = yield* Schema.decodeUnknownEffect(InstructionEntry.Key)(input.key)
yield* sessions.get(input.sessionID)
yield* instructionEntries.remove({ ...input, key })
}),
},
},
},
}
return context
@@ -616,6 +636,7 @@ export const requirements = LayerNode.group([
Permission.node,
PluginHooks.node,
Session.node,
InstructionEntry.node,
PersistentPty.node,
LocationServiceMap.node,
])
+2
View File
@@ -24,6 +24,7 @@ import { Plugin } from "@opencode/core/plugin"
import { PluginHooks } from "@opencode/core/plugin/hooks"
import { Provider } from "@opencode/core/provider"
import { Session } from "@opencode/core/session"
import { InstructionEntry } from "@opencode/core/session/instruction-entry"
import { PersistentPty } from "@opencode/core/persistent-pty"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
@@ -97,6 +98,7 @@ export const makePluginTestLayer = (permission = permissionLayer) =>
ManagedPolicy.node,
Mcp.node,
Session.node,
InstructionEntry.node,
PersistentPty.node,
LocationServiceMap.node,
Permission.node,
+7
View File
@@ -185,6 +185,13 @@ export function host(overrides: Overrides = {}): Plugin.Context {
interrupt: overrides.session?.interrupt ?? (() => Effect.die("unused session.interrupt")),
wait: overrides.session?.wait ?? (() => Effect.die("unused session.wait")),
context: overrides.session?.context ?? (() => Effect.die("unused session.context")),
instructions: overrides.session?.instructions ?? {
entry: {
list: () => Effect.die("unused session.instructions.entry.list"),
put: () => Effect.die("unused session.instructions.entry.put"),
remove: () => Effect.die("unused session.instructions.entry.remove"),
},
},
},
}
}
@@ -0,0 +1,196 @@
import { expect } from "bun:test"
import { Bus } from "@opencode/core/bus"
import { Database } from "@opencode/core/database/database"
import { Plugin } from "@opencode/core/plugin"
import { PluginHost } from "@opencode/core/plugin/host"
import { PluginPromise } from "@opencode/core/plugin/promise"
import { Session } from "@opencode/core/session"
import { SessionHistory } from "@opencode/core/session/history"
import { InstructionEntry } from "@opencode/core/session/instruction-entry"
import { InstructionState } from "@opencode/core/session/instruction-state"
import { Effect } from "effect"
import { testEffect } from "../lib/effect"
import { PluginTestLayer } from "./fixture"
const it = testEffect(PluginTestLayer)
const prepareRequest = Effect.fnUntraced(function* (sessionID: Session.ID) {
const { db } = yield* Database.Service
const bus = yield* Bus.Service
const entries = yield* InstructionEntry.Service
const instructions = yield* entries.load(sessionID)
yield* InstructionState.prepare(db, bus, instructions, sessionID)
return yield* SessionHistory.entriesForRunner(db, sessionID, instructions, "local")
})
it.live("Effect plugins can put, list, and remove session instruction entries seen by the next model request", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const sessions = yield* Session.Service
const context = yield* PluginHost.make(plugins)
const created = yield* context.session.create({ title: "Plugin instructions" })
yield* context.session.instructions.entry.put({
sessionID: created.id,
key: "deploy-target",
value: "production",
})
expect(yield* context.session.instructions.entry.list({ sessionID: created.id })).toEqual([
{ key: "deploy-target", value: "production" },
])
expect(yield* sessions.inbox(created.id)).toEqual([])
const first = yield* prepareRequest(created.id)
expect(first.initial).toBe(['<context key="deploy-target">', "production", "</context>"].join("\n"))
expect(first.entries).toEqual([])
yield* context.session.instructions.entry.put({
sessionID: created.id,
key: "deploy-target",
value: { region: "us-east-1" },
})
const second = yield* prepareRequest(created.id)
expect(second.entries.map((entry) => entry.message)).toEqual([
expect.objectContaining({
type: "system",
text: [
'The context under "deploy-target" changed and supersedes the previous value:',
'<context key="deploy-target">',
"{",
' "region": "us-east-1"',
"}",
"</context>",
].join("\n"),
}),
])
yield* context.session.instructions.entry.remove({ sessionID: created.id, key: "deploy-target" })
expect(yield* context.session.instructions.entry.list({ sessionID: created.id })).toEqual([])
const third = yield* prepareRequest(created.id)
expect(third.entries.at(-1)?.message).toMatchObject({
type: "system",
text: 'The context under "deploy-target" no longer applies. Disregard it.',
})
expect(yield* sessions.inbox(created.id)).toEqual([])
const missing = Session.ID.create()
for (const operation of [
context.session.instructions.entry.list({ sessionID: missing }),
context.session.instructions.entry.put({ sessionID: missing, key: "deploy-target", value: "production" }),
context.session.instructions.entry.remove({ sessionID: missing, key: "deploy-target" }),
]) {
expect(yield* operation.pipe(Effect.flip)).toMatchObject({
_tag: "Session.NotFoundError",
sessionID: missing,
})
}
expect(
yield* context.session.instructions.entry
.put({
sessionID: created.id,
key: "oversized",
value: "x".repeat(InstructionEntry.MaxValueBytes),
})
.pipe(Effect.flip),
).toBeInstanceOf(InstructionEntry.ValueTooLargeError)
for (const key of ["Bad Key", "invalid/key"]) {
for (const operation of [
context.session.instructions.entry.put({ sessionID: created.id, key, value: "rejected" }),
context.session.instructions.entry.remove({ sessionID: created.id, key }),
]) {
expect(yield* operation.pipe(Effect.flip)).toMatchObject({ _tag: "SchemaError" })
}
}
yield* context.session.instructions.entry.put({
sessionID: created.id,
key: "recovered",
value: "still works",
})
const fourth = yield* prepareRequest(created.id)
expect(fourth.entries.at(-1)?.message).toMatchObject({
type: "system",
text: ['<context key="recovered">', "still works", "</context>"].join("\n"),
})
}),
)
it.live("Promise plugins can put, list, and remove session instruction entries seen by the next model request", () =>
Effect.gen(function* () {
const plugins = yield* Plugin.Service
const sessions = yield* Session.Service
const context = yield* PluginHost.make(plugins)
const created = yield* context.session.create({ title: "Promise plugin instructions" })
yield* PluginPromise.fromPromise({
id: "test.session-instructions.put",
async setup(ctx) {
expect(
await ctx.session.instructions.entry.put({
sessionID: created.id,
key: "genui.guidelines",
value: "Use GenUI components when appropriate.",
}),
).toBeUndefined()
expect(await ctx.session.instructions.entry.list({ sessionID: created.id })).toEqual([
{ key: "genui.guidelines", value: "Use GenUI components when appropriate." },
])
const missing = Session.ID.create()
await expect(ctx.session.instructions.entry.list({ sessionID: missing })).rejects.toMatchObject({
_tag: "Session.NotFoundError",
sessionID: missing,
})
await expect(
ctx.session.instructions.entry.put({ sessionID: missing, key: "deploy-target", value: "production" }),
).rejects.toMatchObject({ _tag: "Session.NotFoundError", sessionID: missing })
await expect(
ctx.session.instructions.entry.remove({ sessionID: missing, key: "deploy-target" }),
).rejects.toMatchObject({ _tag: "Session.NotFoundError", sessionID: missing })
await expect(
ctx.session.instructions.entry.put({
sessionID: created.id,
key: "invalid/key",
value: "rejected",
}),
).rejects.toMatchObject({ _tag: "SchemaError" })
await expect(
ctx.session.instructions.entry.remove({ sessionID: created.id, key: "invalid/key" }),
).rejects.toMatchObject({ _tag: "SchemaError" })
await expect(
ctx.session.instructions.entry.put({
sessionID: created.id,
key: "oversized",
value: "x".repeat(InstructionEntry.MaxValueBytes),
}),
).rejects.toBeInstanceOf(InstructionEntry.ValueTooLargeError)
},
}).effect(context)
const first = yield* prepareRequest(created.id)
expect(first.initial).toBe(
['<context key="genui.guidelines">', "Use GenUI components when appropriate.", "</context>"].join("\n"),
)
expect(yield* sessions.inbox(created.id)).toEqual([])
yield* PluginPromise.fromPromise({
id: "test.session-instructions.remove",
async setup(ctx) {
expect(
await ctx.session.instructions.entry.remove({
sessionID: created.id,
key: "genui.guidelines",
}),
).toBeUndefined()
expect(await ctx.session.instructions.entry.list({ sessionID: created.id })).toEqual([])
},
}).effect(context)
const second = yield* prepareRequest(created.id)
expect(second.entries.at(-1)?.message).toMatchObject({
type: "system",
text: 'The context under "genui.guidelines" no longer applies. Disregard it.',
})
expect(yield* sessions.inbox(created.id)).toEqual([])
}),
)
+1
View File
@@ -168,6 +168,7 @@ export type SessionDomain = Pick<
| "move"
| "wait"
| "context"
| "instructions"
> & {
readonly hook: ModelHooks<SessionHooks>
}
+16
View File
@@ -609,6 +609,22 @@ export function fromPromise(plugin: Plugin) {
move: adaptApiMethod(SessionEndpoints["session.move"], host.session.move),
wait: adaptApiMethod(SessionEndpoints["session.wait"], host.session.wait),
context: adaptApiMethod(SessionEndpoints["session.context"], host.session.context),
instructions: {
entry: {
list: adaptApiMethod(
SessionEndpoints["session.instructions.entry.list"],
host.session.instructions.entry.list,
),
put: adaptApiMethod(
SessionEndpoints["session.instructions.entry.put"],
host.session.instructions.entry.put,
),
remove: adaptApiMethod(
SessionEndpoints["session.instructions.entry.remove"],
host.session.instructions.entry.remove,
),
},
},
},
shell: {
hook: (name, callback) =>
+1
View File
@@ -168,6 +168,7 @@ export type SessionDomain = Pick<
| "move"
| "wait"
| "context"
| "instructions"
> & {
readonly hook: ModelHooks<SessionHooks>
}
@@ -858,9 +858,24 @@ effect: (ctx) =>
}),
```
Attach, list, or remove keyed session instruction entries with `instructions.entry`. Entries render as `<context key="...">` blocks in the session's instructions, and updates or removals are announced at the next step boundary without queuing a message turn.
```ts
effect: (ctx) =>
Effect.gen(function* () {
const created = yield* ctx.session.create({ title: "Review" }).pipe(Effect.orDie)
yield* ctx.session.instructions.entry
.put({ sessionID: created.id, key: "deploy-target", value: "production" })
.pipe(Effect.orDie)
const entries = yield* ctx.session.instructions.entry.list({ sessionID: created.id }).pipe(Effect.orDie)
yield* ctx.session.instructions.entry.remove({ sessionID: created.id, key: "deploy-target" }).pipe(Effect.orDie)
}),
```
Schemas: [`Session.Info`](/api#schema-Session.Info), [`Model.Ref`](/api#schema-Model.Ref),
[`Session.Inbox.User`](/api#schema-Session.Inbox.User),
[`Session.Inbox.Synthetic`](/api#schema-Session.Inbox.Synthetic).
[`Session.Inbox.Synthetic`](/api#schema-Session.Inbox.Synthetic),
[`InstructionEntry.Info`](/api#schema-InstructionEntry.Info).
```ts
type SessionDomain = Pick<
@@ -881,6 +896,7 @@ type SessionDomain = Pick<
| "move"
| "wait"
| "context"
| "instructions"
>
```
@@ -837,10 +837,19 @@ the next step boundary by default. Pass `delivery: "queue"` to preserve queue or
const compaction = await ctx.session.compact({ sessionID })
```
Attach, list, or remove keyed session instruction entries with `instructions.entry`. Entries render as `<context key="...">` blocks in the session's instructions, and updates or removals are announced at the next step boundary without queuing a message turn.
```ts
await ctx.session.instructions.entry.put({ sessionID, key: "deploy-target", value: "production" })
const entries = await ctx.session.instructions.entry.list({ sessionID })
await ctx.session.instructions.entry.remove({ sessionID, key: "deploy-target" })
```
#### Reference
Schemas: [`Session.Info`](/api#schema-Session.Info), [`Model.Ref`](/api#schema-Model.Ref),
[`Session.Inbox.User`](/api#schema-Session.Inbox.User), [`Session.Inbox.Synthetic`](/api#schema-Session.Inbox.Synthetic)
[`Session.Inbox.User`](/api#schema-Session.Inbox.User), [`Session.Inbox.Synthetic`](/api#schema-Session.Inbox.Synthetic),
[`InstructionEntry.Info`](/api#schema-InstructionEntry.Info)
```ts
interface SessionContext {
@@ -848,6 +857,16 @@ interface SessionContext {
get(input: SessionGetInput, requestOptions?: RequestOptions): Promise<SessionInfo>
remove(input: SessionRemoveInput, requestOptions?: RequestOptions): Promise<void>
context(input: SessionContextInput, requestOptions?: RequestOptions): Promise<readonly SessionMessageInfo[]>
instructions: {
entry: {
list(
input: SessionInstructionsEntryListInput,
requestOptions?: RequestOptions,
): Promise<readonly InstructionEntryInfo[]>
put(input: SessionInstructionsEntryPutInput, requestOptions?: RequestOptions): Promise<void>
remove(input: SessionInstructionsEntryRemoveInput, requestOptions?: RequestOptions): Promise<void>
}
}
switchAgent(input: SessionSwitchAgentInput, requestOptions?: RequestOptions): Promise<void>
switchModel(input: SessionSwitchModelInput, requestOptions?: RequestOptions): Promise<void>
update(input: SessionUpdateInput, requestOptions?: RequestOptions): Promise<void>