fix(core): ask memory's decisions through OpenCode's decision generation, with a configurable decision model

This commit is contained in:
sebastian 2026-11-20 00:03:17 +01:00
parent 2e3b690619
commit 9dfad8075c
13 changed files with 503 additions and 296 deletions

View file

@ -1136,6 +1136,7 @@ export const dict = {
"settings.general.row.consoleMemory.title": "OpenCode Console memory",
"settings.general.row.consoleMemory.description":
"Use your OpenCode Console workspace's shared memory on this server when the workspace offers it",
"settings.general.row.consoleMemory.configured": "This server's config sets console_memory itself; change it there",
"settings.general.row.colorScheme.title": "Color scheme",
"settings.general.row.colorScheme.description": "Choose whether OpenCode follows the system, light, or dark theme",
"settings.general.row.theme.title": "Theme",

View file

@ -102,7 +102,11 @@ export const ServerRowMenuView: Component<{
<Show when={props.shell}>{(shell) => <ShellSubmenu shell={shell()} labels={props.labels} />}</Show>
<Show when={props.memory}>
{(memory) => (
<Menu.CheckboxItem checked={memory().enabled()} onChange={memory().select}>
<Menu.CheckboxItem
checked={memory().enabled()}
disabled={memory().configured()}
onChange={memory().select}
>
{props.labels.memory}
</Menu.CheckboxItem>
)}

View file

@ -150,7 +150,9 @@ export function createServerShellController(server: Accessor<ServerConnection.An
/**
* Whether a server's OpenCode uses the OpenCode Console workspace's shared memory, as its global config says: on unless
* `console_memory` is false. Turning it on removes the setting, so the default applies again.
* `console_memory` is false. Turning it on removes the setting, so the default applies again. While the config sets
* `console_memory` to an object of its own, `configured` says so and the switch leaves it alone: writing true or false
* would replace it.
*/
export function createServerConsoleMemoryController(server: Accessor<ServerConnection.Any>) {
const language = useLanguage()
@ -158,21 +160,20 @@ export function createServerConsoleMemoryController(server: Accessor<ServerConne
const setting = createOptimisticSetting({
source: useServerCtx(server),
initial: true,
initialMeta: undefined,
initialMeta: false,
load: async (context) => {
const entries = await context.sdk.api.config.get().catch(() => [])
const boundary = entries.findIndex((entry) => entry.type === "directory")
const global = boundary === -1 ? entries : entries.slice(0, boundary)
return {
meta: undefined,
value:
global
.flatMap((entry) =>
entry.type === "document" && entry.info.console_memory !== undefined ? [entry.info.console_memory] : [],
)
.at(-1) ?? true,
}
const setting = global
.flatMap((entry) =>
entry.type === "document" && entry.info.console_memory !== undefined ? [entry.info.console_memory] : [],
)
.at(-1)
// Anything but true, false or nothing is the object form.
return { meta: setting !== undefined && setting !== true && setting !== false, value: setting !== false }
},
write: async (value, context) => {
await context.sdk.api.experimental.config.update({ console_memory: value ? null : false })
@ -182,6 +183,7 @@ export function createServerConsoleMemoryController(server: Accessor<ServerConne
return {
enabled: setting.value,
configured: setting.meta,
select: setting.select,
}
}

View file

@ -116,10 +116,18 @@ export const ConsoleMemorySetting: Component<{ controller: ConsoleMemorySettings
return (
<SettingsRow
title={language.t("settings.general.row.consoleMemory.title")}
description={language.t("settings.general.row.consoleMemory.description")}
description={language.t(
props.controller.configured()
? "settings.general.row.consoleMemory.configured"
: "settings.general.row.consoleMemory.description",
)}
>
<div data-action="settings-console-memory">
<Switch checked={props.controller.enabled()} onChange={props.controller.select} />
<Switch
checked={props.controller.enabled()}
disabled={props.controller.configured()}
onChange={props.controller.select}
/>
</div>
</SettingsRow>
)

View file

@ -2571,7 +2571,9 @@ export type ConfigEntry =
plugins?: Array<string | { package: string; options?: { [x: string]: JsonValue } }>
worktree?: ConfigWorktree
warming?: boolean | { prompt?: string; interval?: "auto" | (string & {}); duration?: string }
console_memory?: boolean
console_memory?:
| boolean
| { decisions?: false | string | { providerID: string; model: string; variant?: string } }
providers?: {
[x: string]: {
canonical?: ProviderID

View file

@ -1,13 +1,16 @@
export * as OpencodeMemoryDecide from "./opencode-memory-decide.js"
import { Clock, Effect, Option, Schedule, Schema, Semaphore } from "effect"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"
import type { Context } from "@opencode/plugin/effect/plugin"
import type { DecisionQuestion, DecisionResult } from "@opencode/schema/generate"
import { Model } from "@opencode/schema/model"
import { Provider } from "@opencode/schema/provider"
import { Clock, Effect, Schedule, Semaphore } from "effect"
import { ProviderRequestError } from "../../generate.js"
import type { OpencodeMemoryCapture } from "./opencode-memory-capture.js"
import type { OpencodeMemoryPolicy } from "./opencode-memory-policy.js"
import type { OpencodeWatches } from "./opencode-watches.js"
/** The decision model, pinned: the questions and thresholds below were chosen on it. */
export const MODEL = "jev-1.13"
/** The decision model the questions and thresholds below were chosen on, unless config names another. */
export const MODEL = Model.Ref.make({ providerID: Provider.ID.make("opencode"), id: Model.ID.make("jev-1.13") })
/** The longest a decision may take; past it the caller does what it does without one. */
const DEADLINE = "5 seconds"
@ -22,96 +25,81 @@ export const DURABLE = 0.574
export const APPLIES = 0.64
/** A yes-or-no question, scored by the probability of yes. */
const noul = (instructions: string, yes: string, no: string) => ({
type: "noul",
const predicate = (name: string, instructions: string, yes: string, no: string): DecisionQuestion => ({
type: "predicate",
name,
instructions,
criteria: { true: yes, false: no },
})
const D1 = noul(
const D1 = predicate(
"lasting",
"Does this message state something that should hold for future work in this repository beyond the current task, such as a team rule, convention or decision, or a correction of a standing practice?",
"The message states a lasting team rule, convention or decision, corrects or reverses a standing practice or an earlier rule, or asserts a durable fact about how the team or repository works. It counts even when the same message also asks for a task.",
"Everything in the message is about the current task only: a request for this change (even with words like always, never, must or don't describing the requested behaviour), a temporary constraint, a correction of the agent's current work, a preference for this conversation, a question, or a rule someone else stated that the user asks to check.",
)
const D3 = {
durable: noul(
const D3 = [
predicate(
"durable",
"Would an agent working on a different, later task in this repository need this note, or does it only record this one task?",
"Durable: a team rule, decision or convention (including one the user stated or reversed); how to run, build, lint or test this repository and its environment requirements; a known flaky or broken test and what to do about it; a pitfall or behaviour of existing code that other changes to that area would hit.",
"Task-specific: the requirements or intended behaviour of the function or feature this task changed, how this one fix works or why it was needed, what the change did or its status, measurements or profiling of this task, or something only true today, even when written as a general rule.",
),
fix_record: noul(
predicate(
"fix_record",
"Is this note mainly a record of one specific fix or feature: the bug it fixed, the behaviour it made a function have, or how the change was implemented?",
"The note's core is the behaviour or implementation of a particular change to particular code (what was wrong in a function and what it does now, or what was built), so it mostly restates the task.",
"The note's core is a rule, procedure, environment fact, test-suite fact or pitfall that holds independently of any one change.",
),
}
]
const D4 = noul(
const D4 = predicate(
"applies",
"Is this note specifically about what this task has to change, or about the failure just seen, so that reading it helps the agent do this task correctly?",
"The note's own subject is the code, behaviour, rule or error this task deals with: it names the function, module, behaviour or failure the task is about; or it explains the exact error shown in the failure output and how to get past it (a required setting, command or procedure whose error text matches); or it is a team rule every change of this kind must follow (such as how changes are recorded). What it says agrees with what the task asks for.",
"The note's subject is something else: another function, feature or bug in the same repository or file; general advice on running tests, linting, tooling or the environment that doesn't explain the error shown; or advice that conflicts with the behaviour or results the task explicitly asks for (a note saying to keep behaviour the task asks to change is misleading, not applicable).",
)
const Answers = Schema.Struct({ answers: Schema.Record(Schema.String, Schema.Unknown) })
const Noul = Schema.Struct({ type: Schema.Literal("noul"), noul: Schema.Number })
const Choice = Schema.Struct({
type: Schema.Literal("choice"),
probabilities: Schema.Record(Schema.String, Schema.Number),
})
/** Decisions in flight across this process, as Console's rate limit allows. */
const slots = Semaphore.makeUnsafe(4)
/**
* The plugin's judgements, asked of the decision model through the member's OpenCode Console, with the credential its
* memory requests use. Each answers undefined when it can't be had (no connection, a refusal, a rate limit that
* outlasts the deadline, or the deadline itself), and the caller then does what it did without one.
* The plugin's judgements, asked of a decision model through OpenCode's own decision generation, with the user's
* credentials for its provider: `model` names it, or undefined when config turns decisions off. Each answers undefined
* when it can't be had (no such model, a refusal, a rate limit that outlasts the deadline, or the deadline itself), and
* the caller then does what it did without one.
*/
export const make = (input: {
readonly http: HttpClient.HttpClient
readonly console: Effect.Effect<OpencodeWatches.Console | undefined>
readonly decisions: Context["experimental"]["generate"]["decisions"]
readonly model: Effect.Effect<Model.Ref | undefined>
}) => {
const ask = (state: string, questions: Record<string, unknown>) =>
const ask = (state: string, questions: ReadonlyArray<DecisionQuestion>) =>
Effect.gen(function* () {
const started = yield* Clock.currentTimeMillis
const answer = yield* Effect.gen(function* () {
const console = yield* input.console
if (console === undefined) return undefined
const request = HttpClientRequest.post(
`${new URL(console.server).origin}/inference/systemone/v1/systemone`,
).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.setHeaders(yield* console.headers),
HttpClientRequest.bodyJsonUnsafe({ model: MODEL, state, questions }),
const answers = yield* Effect.gen(function* () {
const model = yield* input.model
if (model === undefined) return undefined
const result = yield* input.decisions({ model, input: [{ type: "text", text: state }], questions }).pipe(
// A provider's rate limit clears within moments: wait, then ask again, within the deadline.
Effect.retry({
while: (cause) => cause instanceof ProviderRequestError && cause.status === 429,
schedule: Schedule.exponential("200 millis"),
}),
)
return yield* HttpClient.withScope(input.http)
.execute(request)
.pipe(
Effect.flatMap((response) =>
response.status === 429 ? Effect.fail(new RateLimited()) : Effect.succeed(response),
),
// Console's decision rate limit clears within moments: wait, then ask again, within the deadline.
Effect.retry({
while: (cause) => cause instanceof RateLimited,
schedule: Schedule.exponential("200 millis"),
}),
Effect.flatMap((response) =>
response.status === 200
? HttpClientResponse.schemaBodyJson(Answers)(response).pipe(Effect.map((body) => body.answers))
: Effect.succeed(undefined),
),
Effect.scoped,
)
return result.answers
}).pipe(
slots.withPermit,
Effect.timeout(DEADLINE),
Effect.catchCause(() => Effect.succeed(undefined)),
)
const ms = (yield* Clock.currentTimeMillis) - started
return { answer, ms }
return { answers, ms }
})
const noulOf = (answers: Record<string, unknown> | undefined, name: string) =>
Option.getOrUndefined(Option.map(Schema.decodeUnknownOption(Noul)(answers?.[name]), (found) => found.noul))
const probability = (answers: DecisionResult["answers"] | undefined, name: string) => {
const answer = answers?.find((item) => item.name === name)
return answer?.type === "predicate" ? answer.probability : undefined
}
const logged = (
question: string,
ms: number,
@ -128,11 +116,11 @@ export const make = (input: {
Effect.gen(function* () {
const result = yield* ask(
`Latest message from a user to an AI coding agent working in their repository:\n\n${message}`,
{ lasting: D1 },
[D1],
)
const probability = noulOf(result.answer, "lasting")
yield* logged("D1.z0", result.ms, probability)
return probability
const p = probability(result.answers, "lasting")
yield* logged("D1.z0", result.ms, p)
return p
}),
/** D2: the given entry a user's message corrects, by its probability, or none; one id at most. */
corrects: (message: string, given: ReadonlyArray<OpencodeMemoryPolicy.Given>) =>
@ -140,30 +128,36 @@ export const make = (input: {
const notes = given.map((entry) => `[${entry.id}] ${entry.title}\n${entry.text}`).join("\n\n")
const result = yield* ask(
`Team notes from shared memory that an AI coding agent was shown:\n\n${notes}\n\nThe user's latest message to the agent:\n\n${message}`,
{
corrects: {
[
{
type: "choice",
name: "corrects",
instructions:
"Which of the team notes, if any, does the user's message correct, saying or implying that what the note states is wrong, outdated or has changed?",
criteria: {
none: "The message corrects none of the notes: it mentions, follows or asks about a note, corrects only the agent's own work, asks for a task, or changes a rule that no note states.",
...Object.fromEntries(
given.map((entry) => [
entry.id,
`The message says or implies that note ${entry.id} ("${entry.title}") is wrong, outdated or has changed.`,
]),
),
},
choices: [
{
value: "none",
description:
"The message corrects none of the notes: it mentions, follows or asks about a note, corrects only the agent's own work, asks for a task, or changes a rule that no note states.",
},
...given.map((entry) => ({
value: entry.id,
description: `The message says or implies that note ${entry.id} ("${entry.title}") is wrong, outdated or has changed.`,
})),
],
},
},
)
const best = Option.getOrUndefined(
Option.map(Schema.decodeUnknownOption(Choice)(result.answer?.corrects), (choice) =>
Object.entries(choice.probabilities)
.filter(([id]) => id !== "none")
.reduce<{ id?: string; p: number }>((top, [id, p]) => (p > top.p ? { id, p } : top), { p: 0 }),
),
],
)
const answer = result.answers?.find((item) => item.name === "corrects")
const best =
answer?.type === "choice"
? answer.probabilities
.filter((item) => item.value !== "none" && typeof item.value === "string")
.reduce<{
id?: string
p: number
}>((top, item) => (item.probability > top.p ? { id: String(item.value), p: item.probability } : top), { p: 0 })
: undefined
yield* logged("D2.z0", result.ms, best?.p, best?.id === undefined ? {} : { entry: best.id })
return best
}),
@ -174,11 +168,11 @@ export const make = (input: {
`Candidate lesson for a team's shared memory, written after an AI coding agent's task in the ${repo} repository:\n\nKind: ${candidate.kind}\nTitle: ${candidate.title}\n\n${candidate.body}`,
D3,
)
const durable = noulOf(result.answer, "durable")
const fix = noulOf(result.answer, "fix_record")
const probability = durable === undefined || fix === undefined ? undefined : durable * (1 - fix)
yield* logged("D3.t2", result.ms, probability)
return probability
const durable = probability(result.answers, "durable")
const fix = probability(result.answers, "fix_record")
const p = durable === undefined || fix === undefined ? undefined : durable * (1 - fix)
yield* logged("D3.t2", result.ms, p)
return p
}),
/** D4: the probability an entry applies to the task at hand, or to the failure just seen. */
applies: (moment: OpencodeMemoryPolicy.Moment, task: string, entry: OpencodeMemoryPolicy.Injected) =>
@ -189,17 +183,13 @@ export const make = (input: {
: ""
const result = yield* ask(
`Task given to an AI coding agent:\n${task}${failure}\n\nNote from the team's shared memory (${entry.kind}): ${entry.title}\n${entry.body.slice(0, 3000)}`,
{ applies: D4 },
[D4],
)
const probability = noulOf(result.answer, "applies")
yield* logged("D4.t3", result.ms, probability, { entry: entry.id })
return probability
const p = probability(result.answers, "applies")
yield* logged("D4.t3", result.ms, p, { entry: entry.id })
return p
}),
}
}
export type Decide = ReturnType<typeof make>
class RateLimited {
readonly _tag = "RateLimited"
}

View file

@ -8,6 +8,8 @@ import { Message, SystemPart, ToolFailure } from "@opencode/ai/effect"
import type { Context } from "@opencode/plugin/effect/plugin"
import { Agent } from "@opencode/schema/agent"
import type { Document } from "@opencode/schema/config"
import { Model } from "@opencode/schema/model"
import { Provider } from "@opencode/schema/provider"
import { Session } from "@opencode/schema/session"
import { SessionMessage } from "@opencode/schema/session-message"
import { Hash } from "@opencode/util/hash"
@ -296,7 +298,23 @@ export const make = Effect.fnUntraced(function* (
const environments = yield* SessionEnvironment.Service
const shells = yield* ShellSelect.Service
const verify = OpencodeMemoryVerify.make({ git, processes, shell: shells.resolve({ priority: "config" }) })
const decide = OpencodeMemoryDecide.make({ http, console: Effect.sync(() => current?.console) })
// The decision model config names under console_memory, the bench's by default; none when config turns decisions off.
const decide = OpencodeMemoryDecide.make({
decisions: ctx.experimental.generate.decisions,
model: config.entries().pipe(
Effect.map((entries) => {
const setting = Config.latest(entries, "console_memory")
const chosen = typeof setting === "object" ? setting.decisions : undefined
if (chosen === false) return undefined
if (chosen === undefined) return OpencodeMemoryDecide.MODEL
return Model.Ref.make({
providerID: Provider.ID.make(chosen.providerID),
id: Model.ID.make(chosen.model),
...(chosen.variant === undefined ? {} : { variant: Model.VariantID.make(chosen.variant) }),
})
}),
),
})
const github = yield* OpencodeMemoryAccess.make(http, processes, yield* OpencodeMemoryAccess.GitHub)
let current: { console: OpencodeWatches.Console; readonly lease: Scope.Closeable } | undefined
const sessions = new Map<string, Tracked>()

View file

@ -1,58 +1,31 @@
import { describe, expect } from "bun:test"
import { Deferred, Effect, Fiber } from "effect"
import { FetchHttpClient, HttpClient } from "effect/http"
import type { DecisionAnswer, DecisionRequest } from "@opencode/schema/generate"
import { Model } from "@opencode/schema/model"
import { Provider } from "@opencode/schema/provider"
import { Deferred, Effect, Fiber, Layer } from "effect"
import { TestClock } from "effect/testing"
import { ModelNotFoundError, ProviderRequestError } from "@opencode/core/generate"
import { OpencodeMemoryDecide } from "@opencode/core/plugin/provider/opencode-memory-decide"
import { testEffect } from "../lib/effect"
import { eventually } from "../lib/eventually"
const it = testEffect(FetchHttpClient.layer)
const it = testEffect(Layer.empty)
type Asked = {
model: string
state: string
questions: Record<string, { type: string; instructions: string; criteria: Record<string, string> }>
/** OpenCode's decision generation, answering each request with `answer`: answers, or an error to fail with. */
const generation = (
answer: (request: DecisionRequest, index: number) => Effect.Effect<ReadonlyArray<DecisionAnswer>, unknown>,
) => {
const asked = new Array<DecisionRequest>()
// Each run is a request, as OpenCode's decision generation makes one per run.
const decisions = (request: DecisionRequest) =>
Effect.suspend(() => {
asked.push(request)
return answer(request, asked.length - 1).pipe(Effect.map((answers) => ({ answers: [...answers] })))
})
return { asked, decisions: decisions as Parameters<typeof OpencodeMemoryDecide.make>[0]["decisions"] }
}
/** Console's decision endpoint, answering each request with `answer`, a status, or a promise it settles later. */
const endpoint = (answer: (asked: Asked, index: number) => unknown) =>
Effect.acquireRelease(
Effect.sync(() => {
const asked = new Array<Asked & { path: string; authorization: string | null }>()
const server = Bun.serve({
port: 0,
fetch: async (request) => {
const body = (await request.json()) as Asked
asked.push({
...body,
path: new URL(request.url).pathname,
authorization: request.headers.get("authorization"),
})
const result = await answer(body, asked.length - 1)
return typeof result === "number"
? Response.json({ error: "no" }, { status: result })
: Response.json({ model: "jev-1.13", answers: result })
},
})
return { server, asked }
}),
(fake) => Effect.promise(() => fake.server.stop(true)),
)
const decider = (origin: string | undefined) =>
Effect.gen(function* () {
const http = yield* HttpClient.HttpClient
return OpencodeMemoryDecide.make({
http,
console: Effect.succeed(
origin === undefined
? undefined
: { key: "ws", server: `${origin}/console`, headers: Effect.succeed({ authorization: "Bearer member" }) },
),
})
})
const noul = (p: number) => ({ type: "noul", noul: p })
const predicate = (name: string, probability: number): DecisionAnswer => ({ type: "predicate", name, probability })
const given = [
{ id: "mem_a", revision: 1, title: "Deploys use wrangler", text: "Run wrangler deploy." },
{ id: "mem_b", revision: 2, title: "Tests", text: "Run bun test." },
@ -65,108 +38,166 @@ const entry = {
revision: 1,
score: 0.4,
}
const limited = new ProviderRequestError({
providerID: "opencode",
reason: "rate_limit",
message: "slow down",
status: 429,
})
describe("OpencodeMemoryDecide", () => {
it.live(
"asks Console's decision endpoint with the member's credential, the pinned model and the bench's questions",
() =>
Effect.gen(function* () {
const fake = yield* endpoint((asked) => {
if (asked.questions.lasting) return { lasting: noul(0.83) }
if (asked.questions.corrects)
return {
corrects: {
type: "choice",
choice: "mem_b",
confidence: 0.9,
probabilities: { none: 0.1, mem_a: 0.2, mem_b: 0.7 },
},
}
if (asked.questions.durable) return { durable: noul(0.8), fix_record: noul(0.25) }
return { applies: noul(0.66) }
})
const decide = yield* decider(fake.server.url.origin)
it.live("asks the configured decision model the bench's questions, through OpenCode's decision generation", () =>
Effect.gen(function* () {
const fake = generation((request) => {
const question = request.questions[0]!
if (question.name === "lasting") return Effect.succeed([predicate("lasting", 0.83)])
if (question.name === "corrects")
return Effect.succeed([
{
type: "choice",
name: "corrects",
choice: "mem_b",
confidence: 0.9,
probabilities: [
{ value: "none", probability: 0.1 },
{ value: "mem_a", probability: 0.2 },
{ value: "mem_b", probability: 0.7 },
],
},
])
if (question.name === "durable")
return Effect.succeed([predicate("durable", 0.8), predicate("fix_record", 0.25)])
return Effect.succeed([predicate("applies", 0.66)])
})
const decide = OpencodeMemoryDecide.make({
decisions: fake.decisions,
model: Effect.succeed(OpencodeMemoryDecide.MODEL),
})
expect(yield* decide.lasting("We squash merges from now on")).toBe(0.83)
expect(fake.asked[0]).toMatchObject({
path: "/inference/systemone/v1/systemone",
authorization: "Bearer member",
model: "jev-1.13",
state:
"Latest message from a user to an AI coding agent working in their repository:\n\nWe squash merges from now on",
})
expect(fake.asked[0]?.questions.lasting).toEqual({
type: "noul",
instructions:
"Does this message state something that should hold for future work in this repository beyond the current task, such as a team rule, convention or decision, or a correction of a standing practice?",
criteria: {
true: "The message states a lasting team rule, convention or decision, corrects or reverses a standing practice or an earlier rule, or asserts a durable fact about how the team or repository works. It counts even when the same message also asks for a task.",
false:
"Everything in the message is about the current task only: a request for this change (even with words like always, never, must or don't describing the requested behaviour), a temporary constraint, a correction of the agent's current work, a preference for this conversation, a question, or a rule someone else stated that the user asks to check.",
expect(yield* decide.lasting("We squash merges from now on")).toBe(0.83)
expect(fake.asked[0]).toEqual({
model: Model.Ref.make({ providerID: Provider.ID.make("opencode"), id: Model.ID.make("jev-1.13") }),
input: [
{
type: "text",
text: "Latest message from a user to an AI coding agent working in their repository:\n\nWe squash merges from now on",
},
})
],
questions: [
{
type: "predicate",
name: "lasting",
instructions:
"Does this message state something that should hold for future work in this repository beyond the current task, such as a team rule, convention or decision, or a correction of a standing practice?",
criteria: {
true: "The message states a lasting team rule, convention or decision, corrects or reverses a standing practice or an earlier rule, or asserts a durable fact about how the team or repository works. It counts even when the same message also asks for a task.",
false:
"Everything in the message is about the current task only: a request for this change (even with words like always, never, must or don't describing the requested behaviour), a temporary constraint, a correction of the agent's current work, a preference for this conversation, a question, or a rule someone else stated that the user asks to check.",
},
},
],
})
// The best entry, never "none", with its probability.
expect(yield* decide.corrects("The tests run with vitest now", given)).toEqual({ id: "mem_b", p: 0.7 })
expect(fake.asked[1]?.state).toBe(
"Team notes from shared memory that an AI coding agent was shown:\n\n[mem_a] Deploys use wrangler\nRun wrangler deploy.\n\n[mem_b] Tests\nRun bun test.\n\nThe user's latest message to the agent:\n\nThe tests run with vitest now",
)
expect(fake.asked[1]?.questions.corrects?.type).toBe("choice")
expect(fake.asked[1]?.questions.corrects?.criteria.mem_b).toBe(
'The message says or implies that note mem_b ("Tests") is wrong, outdated or has changed.',
)
expect(Object.keys(fake.asked[1]?.questions.corrects?.criteria ?? {})).toEqual(["none", "mem_a", "mem_b"])
// The best entry, never "none", with its probability.
expect(yield* decide.corrects("The tests run with vitest now", given)).toEqual({ id: "mem_b", p: 0.7 })
expect(fake.asked[1]?.input).toEqual([
{
type: "text",
text: "Team notes from shared memory that an AI coding agent was shown:\n\n[mem_a] Deploys use wrangler\nRun wrangler deploy.\n\n[mem_b] Tests\nRun bun test.\n\nThe user's latest message to the agent:\n\nThe tests run with vitest now",
},
])
const choice = fake.asked[1]?.questions[0]
expect(choice?.type === "choice" && choice.choices.map((item) => item.value)).toEqual(["none", "mem_a", "mem_b"])
expect(choice?.type === "choice" && choice.choices[2]?.description).toBe(
'The message says or implies that note mem_b ("Tests") is wrong, outdated or has changed.',
)
// Durable, and not mainly a record of one fix.
expect(
yield* decide.durable({ kind: "gotcha", title: "Dates are UTC", body: "Claim: x" }, "github.com/acme/app"),
).toBeCloseTo(0.6, 10)
expect(Object.keys(fake.asked[2]?.questions ?? {})).toEqual(["durable", "fix_record"])
expect(fake.asked[2]?.state).toBe(
"Candidate lesson for a team's shared memory, written after an AI coding agent's task in the github.com/acme/app repository:\n\nKind: gotcha\nTitle: Dates are UTC\n\nClaim: x",
)
// Durable, and not mainly a record of one fix.
expect(
yield* decide.durable({ kind: "gotcha", title: "Dates are UTC", body: "Claim: x" }, "github.com/acme/app"),
).toBeCloseTo(0.6, 10)
expect(fake.asked[2]?.questions.map((question) => question.name)).toEqual(["durable", "fix_record"])
// At a failure, the command and the end of what it printed come with the task.
const output = `${"x".repeat(2500)}\nError: wrangler not found`
expect(
yield* decide.applies(
{ type: "failure", command: "bun run deploy", output, exitCode: 1 },
"Deploy the worker",
entry,
),
).toBe(0.66)
expect(fake.asked[3]?.state).toBe(
`Task given to an AI coding agent:\nDeploy the worker\n\nThe agent ran \`bun run deploy\` and it failed with:\n${output.slice(-2000)}\n\nNote from the team's shared memory (procedure): Deploys use wrangler\nRun wrangler deploy.`,
)
}),
// At a failure, the command and the end of what it printed come with the task.
const output = `${"x".repeat(2500)}\nError: wrangler not found`
expect(
yield* decide.applies(
{ type: "failure", command: "bun run deploy", output, exitCode: 1 },
"Deploy the worker",
entry,
),
).toBe(0.66)
expect(fake.asked[3]?.input).toEqual([
{
type: "text",
text: `Task given to an AI coding agent:\nDeploy the worker\n\nThe agent ran \`bun run deploy\` and it failed with:\n${output.slice(-2000)}\n\nNote from the team's shared memory (procedure): Deploys use wrangler\nRun wrangler deploy.`,
},
])
}),
)
it.live("waits out Console's rate limit within the deadline", () =>
it.live("asks another model when config names one, and none when config turns decisions off", () =>
Effect.gen(function* () {
const fake = yield* endpoint((_, index) => (index < 2 ? 429 : { lasting: noul(0.91) }))
const decide = yield* decider(fake.server.url.origin)
const fake = generation(() => Effect.succeed([predicate("lasting", 0.5)]))
const clef = Model.Ref.make({ providerID: Provider.ID.make("cloudflare-workers-ai"), id: Model.ID.make("clef") })
yield* OpencodeMemoryDecide.make({ decisions: fake.decisions, model: Effect.succeed(clef) }).lasting("hi")
expect(fake.asked.map((request) => request.model)).toEqual([clef])
const off = OpencodeMemoryDecide.make({ decisions: fake.decisions, model: Effect.succeed(undefined) })
expect(yield* off.lasting("hi")).toBeUndefined()
expect(fake.asked).toHaveLength(1)
}),
)
it.live("waits out a rate limit within the deadline", () =>
Effect.gen(function* () {
const fake = generation((_, index) =>
index < 2 ? Effect.fail(limited) : Effect.succeed([predicate("lasting", 0.91)]),
)
const decide = OpencodeMemoryDecide.make({
decisions: fake.decisions,
model: Effect.succeed(OpencodeMemoryDecide.MODEL),
})
expect(yield* decide.lasting("We squash merges")).toBe(0.91)
expect(fake.asked).toHaveLength(3)
}),
)
it.live("answers nothing on a refusal, a malformed answer or without a connection", () =>
it.live("answers nothing for a model that doesn't resolve, a refusal or another failure", () =>
Effect.gen(function* () {
const fake = yield* endpoint((asked) => (asked.state.includes("refused") ? 403 : { other: noul(1) }))
const decide = yield* decider(fake.server.url.origin)
const fake = generation((request) => {
const text = request.input[0]?.type === "text" ? request.input[0].text : ""
if (text.includes("missing"))
return Effect.fail(
new ModelNotFoundError({
providerID: "opencode",
modelID: "jev-1.13",
message: "No decision model opencode/jev-1.13",
}),
)
if (text.includes("refused"))
return Effect.succeed([{ type: "error", name: "lasting", reason: "refusal" } satisfies DecisionAnswer])
return Effect.fail(
new ProviderRequestError({ providerID: "opencode", reason: "provider", message: "down", status: 503 }),
)
})
const decide = OpencodeMemoryDecide.make({
decisions: fake.decisions,
model: Effect.succeed(OpencodeMemoryDecide.MODEL),
})
expect(yield* decide.lasting("missing")).toBeUndefined()
expect(yield* decide.lasting("refused")).toBeUndefined()
expect(yield* decide.lasting("malformed")).toBeUndefined()
expect(yield* decide.corrects("malformed", given)).toBeUndefined()
const offline = yield* decider(undefined)
expect(yield* offline.lasting("anything")).toBeUndefined()
expect(fake.asked).toHaveLength(3)
expect(yield* decide.lasting("down")).toBeUndefined()
expect(yield* decide.corrects("down", given)).toBeUndefined()
}),
)
it.effect("answers nothing once its five seconds are up", () =>
Effect.gen(function* () {
const fake = yield* endpoint(() => new Promise(() => {}))
const decide = yield* decider(fake.server.url.origin)
const fake = generation(() => Effect.never)
const decide = OpencodeMemoryDecide.make({
decisions: fake.decisions,
model: Effect.succeed(OpencodeMemoryDecide.MODEL),
})
const pending = yield* decide.lasting("slow").pipe(Effect.forkChild({ startImmediately: true }))
yield* eventually(
Effect.sync(() => fake.asked.length),
@ -184,14 +215,19 @@ describe("OpencodeMemoryDecide", () => {
const release = yield* Deferred.make<void>()
let open = 0
let most = 0
const fake = yield* endpoint(async () => {
open++
most = Math.max(most, open)
await Effect.runPromise(Deferred.await(release))
open--
return { lasting: noul(0.5) }
const fake = generation(() =>
Effect.gen(function* () {
open++
most = Math.max(most, open)
yield* Deferred.await(release)
open--
return [predicate("lasting", 0.5)]
}),
)
const decide = OpencodeMemoryDecide.make({
decisions: fake.decisions,
model: Effect.succeed(OpencodeMemoryDecide.MODEL),
})
const decide = yield* decider(fake.server.url.origin)
const all = yield* Effect.forEach([1, 2, 3, 4, 5, 6], (n) => decide.lasting(`message ${n}`), {
concurrency: "unbounded",
}).pipe(Effect.forkChild({ startImmediately: true }))
@ -199,7 +235,7 @@ describe("OpencodeMemoryDecide", () => {
Effect.sync(() => fake.asked.length),
(count) => count === 4,
)
yield* Effect.promise(() => Bun.sleep(100))
yield* Effect.promise(() => Bun.sleep(50))
expect(fake.asked).toHaveLength(4)
yield* Deferred.succeed(release, undefined)
expect(yield* Fiber.join(all)).toEqual([0.5, 0.5, 0.5, 0.5, 0.5, 0.5])

View file

@ -6,6 +6,8 @@ import { Message, SystemPart } from "@opencode/ai/effect"
import type { Plugin as PluginContext } from "@opencode/plugin/effect"
import type { SessionHooks } from "@opencode/plugin/effect/session"
import { Document, Event, Info } from "@opencode/schema/config"
import { ConfigConsoleMemory } from "@opencode/schema/config/console-memory"
import type { DecisionAnswer, DecisionRequest } from "@opencode/schema/generate"
import { ConfigMCP } from "@opencode/schema/config/mcp"
import { Model } from "@opencode/schema/model"
import { Deferred, Effect, Exit, Fiber, Layer, Queue, Scope, Stream } from "effect"
@ -34,13 +36,26 @@ import { initGit } from "../fixture/git"
import { advance, drain } from "../lib/clock"
import { eventually, waitUntil } from "../lib/eventually"
import { testEffect } from "../lib/effect"
import { Generate } from "@opencode/core/generate"
import { Generate, ModelNotFoundError, ProviderRequestError } from "@opencode/core/generate"
import { OpencodeMemoryCapture } from "@opencode/core/plugin/provider/opencode-memory-capture"
import { makePluginTestLayer, PluginTestLayer } from "./fixture"
import { makePluginTestLayer } from "./fixture"
const withFlags = (overrides: string) =>
testEffect(PluginTestLayer.pipe(Layer.provide(Layer.succeed(Flag.Overrides, overrides))))
const it = withFlags("console_memory")
/**
* How OpenCode's decision generation answers: by question name, a predicate's probability or a choice's probabilities
* by value, or the status a provider fails with; unset, no decision model resolves. Reset when a test's Console closes.
*/
const judge = {
answer: undefined as
| ((asked: Asked) => Record<string, number | Record<string, number> | undefined> | number)
| undefined,
asked: new Array<Asked>(),
}
/** A decision request, its evidence as one text and its questions by name. */
type Asked = {
readonly model: string
readonly state: string
readonly questions: Record<string, DecisionRequest["questions"][number]>
}
/** What the stand-in model answers a distillation, the prompts it was given, and the model each named. */
const distiller = {
reply: "",
@ -60,7 +75,39 @@ const generating = Layer.succeed(
return distiller.reply
}),
image: () => Effect.die("unused"),
decisions: () => Effect.die("unused"),
decisions: (input) =>
Effect.suspend((): Effect.Effect<{ answers: DecisionAnswer[] }, ModelNotFoundError | ProviderRequestError> => {
const asked: Asked = {
model: `${input.model.providerID}/${input.model.id}`,
state: input.input.map((part) => (part.type === "text" ? part.text : "")).join(""),
questions: Object.fromEntries(input.questions.map((question) => [question.name, question])),
}
judge.asked.push(asked)
if (judge.answer === undefined)
return Effect.fail(
new ModelNotFoundError({ providerID: input.model.providerID, modelID: input.model.id, message: "unknown" }),
)
const answers = judge.answer(asked)
if (typeof answers === "number")
return Effect.fail(
new ProviderRequestError({ providerID: "opencode", reason: "provider", message: "no", status: answers }),
)
return Effect.succeed({
answers: input.questions.map((question): DecisionAnswer => {
const answer = answers[question.name]
if (typeof answer === "number") return { type: "predicate", name: question.name, probability: answer }
if (answer === undefined) return { type: "error", name: question.name, reason: "unanswered" }
const probabilities = Object.entries(answer).map(([value, probability]) => ({ value, probability }))
return {
type: "choice",
name: question.name,
choice: probabilities.toSorted((a, b) => b.probability - a.probability)[0]?.value ?? "none",
confidence: 1,
probabilities,
}
}),
})
}),
video: {
start: () => Effect.die("unused"),
status: () => Effect.die("unused"),
@ -70,6 +117,8 @@ const generating = Layer.succeed(
)
const capturing = (overrides: string) =>
testEffect(makePluginTestLayer(undefined, generating).pipe(Layer.provide(Layer.succeed(Flag.Overrides, overrides))))
const withFlags = capturing
const it = withFlags("console_memory")
const released = withFlags("-console_memory")
type Synthetic = Parameters<PluginContext.Context["session"]["synthetic"]>[0]
@ -114,26 +163,12 @@ const injected = (id: string, score: number, revision = 1) => ({
deliveryID: `mdl_${id}`,
})
/** A decision request as Console's decision endpoint takes it. */
type Decision = {
readonly model: string
readonly state: string
readonly questions: Record<string, { type: string; instructions: string; criteria: Record<string, string> }>
}
/** Console's memory routes and config, in-process, with the request and response shapes and error tags Console uses. */
function fakeConsole() {
const state = {
memory: true,
/** The OpenCode config Console hands out, such as its MCP servers. */
config: {} as Record<string, unknown>,
/**
* How Console's decision endpoint answers a request's questions, or the status it refuses with; unset, it isn't
* there (404), as when the member's Console can't answer decisions.
*/
decide: undefined as ((request: Decision) => Record<string, unknown> | number) | undefined,
/** The decision requests, apart from the memory requests. */
decisions: new Array<Decision & { authorization: string | null }>(),
hits: new Array<ReturnType<typeof hit>>(),
injected: new Array<ReturnType<typeof injected>>(),
/** An entry close enough to refuse a publish without `distinctFrom`. */
@ -201,14 +236,6 @@ function fakeConsole() {
// The list the reachable set is checked against, which the plugin keeps fresh on its own: not logged.
if (url.pathname === "/api/memory/anchors")
return state.stalled ? new Promise<Response>(() => {}) : Response.json({ anchors: state.anchors })
if (url.pathname === "/inference/systemone/v1/systemone") {
const asked = (await request.json()) as Decision
state.decisions.push({ ...asked, authorization: request.headers.get("authorization") })
const answer = state.decide?.(asked) ?? 404
return typeof answer === "number"
? Response.json({ error: "no" }, { status: answer })
: Response.json({ model: "jev-1.13", answers: answer })
}
if (url.pathname === "/api/v2/config")
return Response.json(state.config, { headers: state.memory ? { [OpencodeMemory.header]: "1" } : {} })
const body = (request.method === "GET" ? undefined : await request.json()) as Record<string, unknown> | undefined
@ -325,7 +352,16 @@ function fakeConsole() {
}
const withConsole = <A, E, R>(use: (console: ReturnType<typeof fakeConsole>) => Effect.Effect<A, E, R>) =>
Effect.acquireUseRelease(Effect.sync(fakeConsole), use, (console) => Effect.promise(() => console.server.stop(true)))
Effect.acquireUseRelease(Effect.sync(fakeConsole), use, (console) =>
Effect.promise(() => console.server.stop(true)).pipe(
Effect.andThen(
Effect.sync(() => {
judge.answer = undefined
judge.asked.length = 0
}),
),
),
)
/**
* Signs in to the fake Console and starts the plugin, recording each synthetic message it admits. `servers` are the MCP
@ -431,14 +467,9 @@ const prompt = (sessionID: Session.ID, text: string, metadata?: Record<string, u
})
})
/** A yes-or-no answer, and a choice answer, as Console's decision endpoint gives them. */
const yes = (probability: number) => ({ type: "noul", noul: probability })
const picked = (probabilities: Record<string, number>) => ({
type: "choice",
choice: Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0],
confidence: 1,
probabilities,
})
/** A predicate's probability, and a choice's probabilities by value, as `judge` answers them. */
const yes = (probability: number) => probability
const picked = (probabilities: Record<string, number>) => probabilities
/**
* Waits until the session's last prompt has been judged and recorded: the session's next event waits for it, as the
@ -582,6 +613,35 @@ describe("OpencodePlugin memory", () => {
),
)
it.effect("asks the decision model config names, and none when config turns decisions off", () =>
withConsole((console) =>
Effect.gen(function* () {
const config = yield* Config.Test
const set = (decisions: ConfigConsoleMemory.Settings["decisions"]) =>
config.setEntries([
new Document({
type: "document",
info: new Info({ console_memory: new ConfigConsoleMemory.Settings({ decisions }) }),
}),
])
judge.answer = () => ({ lasting: 0.1 })
yield* set({ providerID: Provider.ID.make("lmstudio"), model: Model.ID.make("clef") })
const { host } = yield* start(console)
const session = yield* host.session.create({})
yield* prompt(session.id, "Deploy the worker")
yield* judged(session.id)
expect(judge.asked.map((item) => item.model)).toEqual(["lmstudio/clef"])
// Off: no decision is asked, and memory reads messages the stricter way.
yield* set(false)
yield* prompt(session.id, "Deploy it again")
yield* judged(session.id)
expect(judge.asked).toHaveLength(1)
expect(yield* memoryTools).toContain("search")
}),
),
)
it.effect("searches with the files the session worked on and reads as the signed-in member", () =>
withConsole((console) =>
Effect.gen(function* () {
@ -986,7 +1046,7 @@ describe("OpencodePlugin memory", () => {
const session = yield* host.session.create({})
console.state.injected = [injected("mem_a", 0.95), injected("mem_b", 0.7)]
// Both apply to the task.
console.state.decide = () => ({ applies: { type: "noul", noul: 0.9 } })
judge.answer = () => ({ applies: 0.9 })
yield* prompt(session.id, " Fix the deploy ")
const first = request(session.id, "Fix the deploy")
@ -1384,7 +1444,7 @@ describe("OpencodePlugin memory", () => {
const instructions = host.session.instructions.entry.list({ sessionID: session.id })
console.state.injected = [injected("mem_deploy", 0.9)]
// Which given entry a message corrects is Console's decision: here, any message that says it's wrong.
console.state.decide = (asked) =>
judge.answer = (asked) =>
asked.questions.corrects
? {
corrects: /wrong|should say/.test(asked.state)
@ -1402,10 +1462,11 @@ describe("OpencodePlugin memory", () => {
yield* judged(session.id)
expect(yield* instructions).toEqual([])
// Asked once, over the entries the session was given.
const asked = console.state.decisions.filter((item) => item.questions.corrects)
const asked = judge.asked.filter((item) => item.questions.corrects)
expect(asked).toHaveLength(1)
expect(asked[0]).toMatchObject({ model: "jev-1.13", authorization: "Bearer secret" })
expect(Object.keys(asked[0]!.questions.corrects!.criteria)).toEqual(["none", "mem_deploy"])
expect(asked[0]?.model).toBe("opencode/jev-1.13")
const choice = asked[0]?.questions.corrects
expect(choice?.type === "choice" && choice.choices.map((item) => item.value)).toEqual(["none", "mem_deploy"])
// The injected entry's body reads "Body of mem_deploy"; the user says otherwise.
yield* prompt(session.id, "No, that body of mem_deploy is wrong, deploy with wrangler instead")
@ -1457,7 +1518,7 @@ describe("OpencodePlugin memory", () => {
injected("mem_e", 0.2),
]
const applies: Record<string, number> = { mem_a: 0.2, mem_b: 0.7, mem_c: 0.9, mem_d: 0.5, mem_e: 0.3 }
console.state.decide = (asked) =>
judge.answer = (asked) =>
asked.questions.applies
? { applies: yes(applies[/Entry (mem_\w)/.exec(asked.state)?.[1] ?? ""] ?? 0) }
: { lasting: yes(0.1) }
@ -1473,10 +1534,10 @@ describe("OpencodePlugin memory", () => {
files: [],
}),
)
expect(console.state.decisions.filter((item) => item.questions.applies)).toHaveLength(5)
expect(judge.asked.filter((item) => item.questions.applies)).toHaveLength(5)
// However many apply, three at most.
console.state.decide = (asked) => (asked.questions.applies ? { applies: yes(0.9) } : { lasting: yes(0.1) })
judge.answer = (asked) => (asked.questions.applies ? { applies: yes(0.9) } : { lasting: yes(0.1) })
const busy = yield* host.session.create({})
yield* prompt(busy.id, "Fix the deploy")
const many = request(busy.id, "Fix the deploy")
@ -1493,7 +1554,7 @@ describe("OpencodePlugin memory", () => {
)
// Without decisions, Console's own bar on the scores: only mem_a reaches it.
console.state.decide = () => 503
judge.answer = () => 503
const other = yield* host.session.create({})
yield* prompt(other.id, "Fix the deploy")
const fallback = request(other.id, "Fix the deploy")
@ -2119,7 +2180,7 @@ describe("OpencodePlugin memory capture", () => {
const rule = "Money parameters carry a Cents suffix in this codebase"
// Wording alone wouldn't make it a rule; the decision does.
expect(OpencodeMemoryCapture.fallback.lasting(rule)).toBe(false)
console.state.decide = (asked) =>
judge.answer = (asked) =>
asked.questions.lasting ? { lasting: yes(asked.state.includes("Cents suffix") ? 0.92 : 0.1) } : 503
distiller.reply = JSON.stringify({
candidates: [
@ -2137,7 +2198,7 @@ describe("OpencodePlugin memory capture", () => {
yield* prompt(session.id, rule)
yield* waitUntil(Effect.sync(() => publishes(console).length === 1))
expect(publishes(console)[0]?.body).toMatchObject({ evidence: [{ kind: "confirmation", ref: rule }] })
expect(console.state.decisions.filter((item) => item.questions.lasting)).toHaveLength(1)
expect(judge.asked.filter((item) => item.questions.lasting)).toHaveLength(1)
}),
),
)
@ -2155,7 +2216,7 @@ describe("OpencodePlugin memory capture", () => {
distiller.reply = JSON.stringify({
candidates: [lesson("How this fix parses dates"), lesson("Tests need TZ=UTC")],
})
console.state.decide = (asked) =>
judge.answer = (asked) =>
asked.questions.durable
? asked.state.includes("Title: How this fix parses dates")
? { durable: yes(0.9), fix_record: yes(0.9) }
@ -2167,9 +2228,7 @@ describe("OpencodePlugin memory capture", () => {
yield* ran(session.id, "shell", { command: "bun test" }, { exitCode: 1, output: " 1 fail" })
yield* ran(session.id, "edit", { path: "src/dates.ts" })
yield* ran(session.id, "shell", { command: "bun test" }, { exitCode: 0, output: " 1 pass" })
yield* waitUntil(
Effect.sync(() => console.state.decisions.filter((item) => item.questions.durable).length === 2),
)
yield* waitUntil(Effect.sync(() => judge.asked.filter((item) => item.questions.durable).length === 2))
yield* waitUntil(Effect.sync(() => publishes(console).length === 1))
yield* drain
expect(publishes(console).map((item) => (item.body as { title: string }).title)).toEqual([

View file

@ -17308,7 +17308,14 @@
]
},
"console_memory": {
"type": "boolean"
"anyOf": [
{
"type": "boolean"
},
{
"$ref": "#/components/schemas/ConfigConsoleMemory.SettingsEncoded"
}
]
},
"providers": {
"type": "object",
@ -17769,6 +17776,33 @@
},
"additionalProperties": false
},
"Config.ModelSelectionEncoded": {
"anyOf": [
{
"type": "string",
"pattern": "^[^/#]+\\/[^#]+(?:#[^#]+)?$"
},
{
"type": "object",
"properties": {
"providerID": {
"type": "string",
"pattern": "^[^/#]+$"
},
"model": {
"type": "string",
"pattern": "^[^#]+$"
},
"variant": {
"type": "string",
"pattern": "^[^#]+$"
}
},
"required": ["providerID", "model"],
"additionalProperties": false
}
]
},
"Config.Patch": {
"type": "object",
"properties": {
@ -17984,6 +18018,23 @@
"required": ["directory"],
"additionalProperties": false
},
"ConfigConsoleMemory.SettingsEncoded": {
"type": "object",
"properties": {
"decisions": {
"anyOf": [
{
"type": "boolean",
"enum": [false]
},
{
"$ref": "#/components/schemas/Config.ModelSelectionEncoded"
}
]
}
},
"additionalProperties": false
},
"ConfigShell.Option": {
"type": "object",
"properties": {

View file

@ -7,6 +7,7 @@ import { AbsolutePath, optional } from "./schema.js"
import { ConfigAgent } from "./config/agent.js"
import { ConfigMedia } from "./config/media.js"
import { ConfigCompaction } from "./config/compaction.js"
import { ConfigConsoleMemory } from "./config/console-memory.js"
import { ConfigCommand } from "./config/command.js"
import { ConfigExperimental } from "./config/experimental.js"
import { ConfigFormatter } from "./config/formatter.js"
@ -112,9 +113,9 @@ export class Info extends Schema.Class<Info>("Config.Info")({
warming: ConfigWarming.Warming.pipe(optional).annotate({
description: "Keep recently active sessions warm with transient model requests (default: false)",
}),
console_memory: Schema.Boolean.pipe(optional).annotate({
console_memory: ConfigConsoleMemory.ConsoleMemory.pipe(optional).annotate({
description:
"Use the OpenCode Console workspace's shared memory when the workspace offers it (default: true). false turns it off for this installation: no memory tools, delivered entries or session capture",
"Use the OpenCode Console workspace's shared memory when the workspace offers it (default: true). false turns it off for this installation: no memory tools, delivered entries or session capture. An object keeps it on and sets how it runs, such as its decision model",
}),
providers: Schema.Record(Schema.String, ConfigProvider.Info).pipe(optional),
experimental: ConfigExperimental.Info.pipe(optional),

View file

@ -0,0 +1,18 @@
export * as ConfigConsoleMemory from "./console-memory.js"
import { Schema } from "effect"
import { optional } from "../schema.js"
import { ConfigModel } from "./model.js"
/** How the OpenCode Console workspace's memory runs here, beyond on or off. */
export class Settings extends Schema.Class<Settings>("ConfigConsoleMemory.Settings")({
decisions: Schema.Union([Schema.Literal(false), ConfigModel.Selection])
.pipe(optional)
.annotate({
description:
'The decision model memory asks which messages state lasting rules, which entries they correct, which lessons last and which entries apply, as "provider/model" (default: opencode/jev-1.13); false answers without one',
}),
}) {}
export const ConsoleMemory = Schema.Union([Schema.Boolean, Settings])
export type ConsoleMemory = typeof ConsoleMemory.Type

View file

@ -430,6 +430,23 @@ While it is off, agents get no memory tools, no entries are delivered to
sessions, and sessions are not captured. The server's settings page has the same
switch, and a change applies without a restart.
Memory asks a decision model which messages state lasting team rules, which
entries a message corrects, which lessons last, and which entries apply to a
task. It uses `opencode/jev-1.13` with your OpenCode sign-in. Name another
decision model from your providers, or set `false` to decide without one.
```jsonc
{
"console_memory": {
"decisions": "opencode/jev-1.13",
},
}
```
Without a decision model, memory takes the stricter reading. Only explicit team
rules count as rules, no correction reminder is shown, and entries are
delivered only above Console's own relevance bar.
### Skills
Add directories or URLs that OpenCode should search for agent skills.