diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index 8aba08b66962..4279704ae2e8 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2365,6 +2365,7 @@ export type ConfigEntry = portable_shell_scanner?: boolean todo?: boolean background_compaction?: boolean + media_blob?: boolean subagent_depth?: number location_idle_timeout?: string | false policies?: Array<{ diff --git a/packages/core/src/config/normalize.ts b/packages/core/src/config/normalize.ts index e2b4ad4e00b5..fac36c1f3f00 100644 --- a/packages/core/src/config/normalize.ts +++ b/packages/core/src/config/normalize.ts @@ -485,6 +485,15 @@ function normalizeExperimental( ) if (value !== undefined) result.background_compaction = value } + if (own(experimental, "media_blob")) { + const value = decodeEncoded( + ConfigExperimental.Info.fields.media_blob, + experimental.media_blob, + ["experimental", "media_blob"], + diagnostics, + ) + if (value !== undefined) result.media_blob = value + } if (own(experimental, "subagent_depth")) { const value = decodeEncoded( ConfigExperimental.Info.fields.subagent_depth, diff --git a/packages/core/src/session/blob.ts b/packages/core/src/session/blob.ts index 72b4bcc61dac..9208b799d5f4 100644 --- a/packages/core/src/session/blob.ts +++ b/packages/core/src/session/blob.ts @@ -1,12 +1,16 @@ export * as SessionBlob from "./blob.js" -import { inArray } from "drizzle-orm" -import { Effect, Schema } from "effect" +import { createHash } from "node:crypto" +import { and, eq, gte, inArray, notExists, notInArray, type SQL, sql } from "drizzle-orm" +import { Effect, Option, Schema } from "effect" import { map } from "effect/Array" import type { FileAttachment } from "@opencode/schema/prompt" import type { Tool } from "@opencode/schema/tool" +import { Config } from "../config.js" import type { Database } from "../database/database.js" -import { BlobTable, SessionInboxTable, SessionMessageTable } from "./sql.js" +import type { SessionMessage } from "./message.js" +import type { SessionSchema } from "./schema.js" +import { BlobRefTable, BlobTable, SessionInboxTable, SessionMessageTable } from "./sql.js" import { SessionStored } from "./stored.js" type DatabaseService = Database.Interface["db"] @@ -105,3 +109,172 @@ export const hydrateInbox = Effect.fnUntraced(function* (db: DatabaseService, ro return { ...row, payload: { ...payload, files: payload.files.map((file) => inlineFile(file, blobs)) } } }) }) + +/** A blob's hash is the lowercase hex SHA-256 of its raw bytes. */ +export const hashBytes = (raw: Uint8Array) => createHash("sha256").update(raw).digest("hex") + +/** The row a ref keeps its blob alive for: a message at its `seq`, or a pending inbox row at its `enqueued_seq`. */ +export interface Owner { + readonly sessionID: SessionSchema.ID + readonly messageID: SessionMessage.ID + readonly seq: number +} + +/** Blobs taken out of one row, by hash. */ +type Pending = Map +type AssistantPart = SessionMessage.Assistant["content"][number] + +/** Reads `experimental.media_blob` from the Config in scope on every write; without one, media stays inline. */ +const writeEnabled = Effect.gen(function* () { + const config = yield* Effect.serviceOption(Config.Service) + if (Option.isNone(config)) return false + return Config.latest(yield* config.value.entries(), "experimental")?.media_blob === true +}) + +const DATA_URI = /^data:[^,]*;base64,(.*)$/s + +function take(pending: Pending, raw: Buffer, mime: string) { + const hash = hashBytes(raw) + if (!pending.has(hash)) pending.set(hash, { hash, mime, bytes: raw.byteLength, data: raw }) + return SessionStored.ref(hash) +} + +function fileRef(pending: Pending, file: SessionStored.File): SessionStored.File { + if (isFileRef(file)) return file + const { data, ...rest } = file + return { ...rest, uri: take(pending, Buffer.from(data, "base64"), file.mime) } +} + +function toolRef(pending: Pending, item: Tool.Content): Tool.Content { + if (item.type !== "file") return item + const data = DATA_URI.exec(item.uri)?.[1] + return data === undefined ? item : { ...item, uri: take(pending, Buffer.from(data, "base64"), item.mime) } +} + +function toolPartRefs(pending: Pending, part: AssistantPart): AssistantPart { + if (part.type !== "tool" || (part.state.status !== "completed" && part.state.status !== "error")) return part + const content = part.state.content + if (!content) return part + return { ...part, state: { ...part.state, content: map(content, (item) => toolRef(pending, item)) } } +} + +const save = Effect.fnUntraced(function* (db: DatabaseService, pending: Pending) { + if (pending.size === 0) return + yield* db + .insert(BlobTable) + .values([...pending.values()]) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie) +}) + +/** {@link externalize} for a user message or pending inbox user payload. */ +export const externalizePayload = Effect.fnUntraced(function* < + T extends { readonly files?: ReadonlyArray }, +>(db: DatabaseService, input: T): Effect.fn.Return { + if (input.files === undefined || !(yield* writeEnabled)) return input + const pending: Pending = new Map() + const files = input.files.map((file) => fileRef(pending, file)) + if (pending.size === 0) return input + yield* save(db, pending) + return { ...input, files } +}) + +/** + * With `experimental.media_blob` on, moves inline user files and tool `data:` files into `blob` and returns the + * message to store with refs in their place. Existing refs pass through. + */ +export const externalize = Effect.fnUntraced(function* ( + db: DatabaseService, + message: SessionMessage.Info | SessionStored.User, +) { + if (message.type === "user") return yield* externalizePayload(db, message) + if (message.type !== "assistant" || !(yield* writeEnabled)) return message + const pending: Pending = new Map() + const content = message.content.map((part) => toolPartRefs(pending, part)) + if (pending.size === 0) return message + yield* save(db, pending) + return { ...message, content } +}) + +const hashesOf = (data: MessageRow["data"] | InboxRow["payload"]) => { + const hashes = new Set() + collect(data, hashes) + return hashes +} + +/** Records that `owner` references each blob its stored row names, so release keeps them until it lets go. */ +export const recordRefs = Effect.fnUntraced(function* ( + db: DatabaseService, + owner: Owner, + data: MessageRow["data"] | InboxRow["payload"], +) { + const hashes = hashesOf(data) + if (hashes.size === 0) return + // A ref whose blob is already gone keeps nothing alive; reads render it as unavailable. + const found = yield* db + .select({ hash: BlobTable.hash }) + .from(BlobTable) + .where(inArray(BlobTable.hash, [...hashes])) + .all() + .pipe(Effect.orDie) + if (found.length === 0) return + yield* db + .insert(BlobRefTable) + .values( + found.map(({ hash }) => ({ session_id: owner.sessionID, message_id: owner.messageID, hash, seq: owner.seq })), + ) + .onConflictDoUpdate({ + target: [BlobRefTable.session_id, BlobRefTable.message_id, BlobRefTable.hash], + set: { seq: owner.seq }, + }) + .run() + .pipe(Effect.orDie) +}) + +/** Records the refs a rewritten message names and releases the ones it no longer does. */ +export const syncRefs = Effect.fnUntraced(function* (db: DatabaseService, owner: Owner, data: MessageRow["data"]) { + yield* recordRefs(db, owner, data) + const present = [...hashesOf(data)] + const own = [eq(BlobRefTable.session_id, owner.sessionID), eq(BlobRefTable.message_id, owner.messageID)] as const + yield* present.length === 0 ? release(db, ...own) : release(db, ...own, notInArray(BlobRefTable.hash, present)) +}) + +/** Deletes the matching refs, then every blob among theirs that no ref names anymore. */ +const release = Effect.fnUntraced(function* (db: DatabaseService, ...where: readonly [SQL, ...SQL[]]) { + const released = yield* db + .delete(BlobRefTable) + .where(and(...where)) + .returning({ hash: BlobRefTable.hash }) + .all() + .pipe(Effect.orDie) + const hashes = [...new Set(released.map((ref) => ref.hash))] + for (let offset = 0; offset < hashes.length; offset += 500) + yield* db + .delete(BlobTable) + .where( + and( + inArray(BlobTable.hash, hashes.slice(offset, offset + 500)), + notExists( + db + .select({ one: sql`1` }) + .from(BlobRefTable) + .where(eq(BlobRefTable.hash, BlobTable.hash)), + ), + ), + ) + .run() + .pipe(Effect.orDie) +}) + +/** Releases the blobs a removed message or cancelled inbox row referenced. */ +export const releaseMessage = (db: DatabaseService, sessionID: SessionSchema.ID, messageID: SessionMessage.ID) => + release(db, eq(BlobRefTable.session_id, sessionID), eq(BlobRefTable.message_id, messageID)) + +/** Releases the blobs referenced at or after `seq`, for a revert. */ +export const releaseFrom = (db: DatabaseService, sessionID: SessionSchema.ID, seq: number) => + release(db, eq(BlobRefTable.session_id, sessionID), gte(BlobRefTable.seq, seq)) + +/** Releases every blob a deleted session referenced. */ +export const releaseSession = (db: DatabaseService, sessionID: SessionSchema.ID) => + release(db, eq(BlobRefTable.session_id, sessionID)) diff --git a/packages/core/src/session/command.ts b/packages/core/src/session/command.ts index 302f12e40c4e..bf79c2392b31 100644 --- a/packages/core/src/session/command.ts +++ b/packages/core/src/session/command.ts @@ -18,18 +18,21 @@ export const execute = Effect.fn("SessionCommand.execute")(function* (input: { delivery?: SessionInbox.Delivery }) { const instances = yield* Instance.Service - const commands = yield* Plugin.awaitActivation.pipe(Effect.andThen(Command.Service), instances.provide(input.session)) - yield* commands.execute({ - name: input.command, - invocation: { - sessionID: input.session.id, - prompt: { - text: input.text, - files: input.files, - agents: input.agents, - skills: input.skills, + yield* Effect.gen(function* () { + yield* Plugin.awaitActivation + const commands = yield* Command.Service + yield* commands.execute({ + name: input.command, + invocation: { + sessionID: input.session.id, + prompt: { + text: input.text, + files: input.files, + agents: input.agents, + skills: input.skills, + }, + delivery: input.delivery ?? "steer", }, - delivery: input.delivery ?? "steer", - }, - }) + }) + }).pipe(instances.provide(input.session)) }) diff --git a/packages/core/src/session/inbox.ts b/packages/core/src/session/inbox.ts index 36eb12d34af9..9be6743c35e9 100644 --- a/packages/core/src/session/inbox.ts +++ b/packages/core/src/session/inbox.ts @@ -52,7 +52,7 @@ export type Promotable = "input" | "steer" const decodeUser = Schema.decodeUnknownSync(UserPayload) const decodeStoredUser = Schema.decodeUnknownSync(SessionStored.UserPayload) -const encodeUser = Schema.encodeSync(UserPayload) +const encodeStoredUser = Schema.encodeSync(SessionStored.UserPayload) const decodeSynthetic = Schema.decodeUnknownSync(SyntheticPayload) const encodeSynthetic = Schema.encodeSync(SyntheticPayload) const decodeCompaction = Schema.decodeUnknownSync(CompactionPayload) @@ -306,20 +306,21 @@ export const projectAdmitted = Effect.fn("SessionInbox.projectAdmitted")(functio .get() .pipe(Effect.orDie) if (message !== undefined) return yield* Effect.die(new LifecycleConflict({ id: request.id })) + const payload = + request.item.type === "user" + ? encodeStoredUser(yield* SessionBlob.externalizePayload(db, request.item.payload)) + : request.item.type === "synthetic" + ? encodeSynthetic(request.item.payload) + : request.item.type === "compaction" + ? encodeCompaction(request.item.payload) + : encodeMove(request.item.payload) const stored = yield* db .insert(SessionInboxTable) .values({ id: request.id, session_id: request.sessionID, type: request.item.type, - payload: - request.item.type === "user" - ? encodeUser(request.item.payload) - : request.item.type === "synthetic" - ? encodeSynthetic(request.item.payload) - : request.item.type === "compaction" - ? encodeCompaction(request.item.payload) - : encodeMove(request.item.payload), + payload, delivery: request.item.delivery, enqueued_seq: request.enqueuedSeq, time_created: request.timeCreated, @@ -329,6 +330,11 @@ export const projectAdmitted = Effect.fn("SessionInbox.projectAdmitted")(functio .get() .pipe(Effect.orDie) if (!stored) return yield* Effect.die(new LifecycleConflict({ id: request.id })) + yield* SessionBlob.recordRefs( + db, + { sessionID: request.sessionID, messageID: request.id, seq: request.enqueuedSeq }, + payload, + ) }) /** @@ -379,6 +385,7 @@ export const projectCancelled = Effect.fn("SessionInbox.projectCancelled")(funct .get() .pipe(Effect.orDie) if (!deleted) return yield* Effect.die(new LifecycleConflict({ id: input.id })) + yield* SessionBlob.releaseMessage(db, input.sessionID, input.id) }) const projectDelivery = Effect.fn("SessionInbox.projectDelivery")(function* ( diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index e5dba0813ac4..7cce5b808a9b 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -12,6 +12,7 @@ import { SessionMessage } from "./message.js" import { SessionMessageUpdater } from "./message-updater.js" import { SessionInbox } from "./inbox.js" import { InstructionState } from "./instruction-state.js" +import { SessionBlob } from "./blob.js" import { SessionInboxTable, SessionMessageTable, SessionTable } from "./sql.js" import { SessionStored } from "./stored.js" import { InstructionEntry } from "./instruction-entry.js" @@ -236,6 +237,16 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( }), ) yield* db.insert(SessionMessageTable).values(values).run().pipe(Effect.orDie) + yield* Effect.forEach( + values, + (value) => + SessionBlob.recordRefs( + db, + { sessionID: event.data.sessionID, messageID: value.id, seq: value.seq }, + value.data, + ), + { discard: true }, + ) cursor = rows.at(-1)!.seq } @@ -246,21 +257,23 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( function run(db: DatabaseService, event: MessageEvent) { return Effect.gen(function* () { - const updateMessage = (message: SessionMessage.Info) => { - const encoded = encodeMessage(message) - const { id: _, type, ...data } = encoded - return db + const updateMessage = Effect.fnUntraced(function* (message: SessionMessage.Info) { + const stored = yield* SessionBlob.externalize(db, message) + const { id: _, type, ...data } = encodeStored(stored) + const updated = yield* db .update(SessionMessageTable) .set({ type, time_created: DateTime.toEpochMillis(message.time.created), data }) - .where( - and( - eq(SessionMessageTable.id, message.id), - eq(SessionMessageTable.session_id, event.data.sessionID), - ), - ) - .run() + .where(and(eq(SessionMessageTable.id, message.id), eq(SessionMessageTable.session_id, event.data.sessionID))) + .returning({ seq: SessionMessageTable.seq }) + .get() .pipe(Effect.orDie) - } + if (!updated) return + const owner = { sessionID: event.data.sessionID, messageID: message.id, seq: updated.seq } + // Most updates only carry existing refs forward; a content rewrite may also drop some. `externalize` returns + // the same message when it extracted nothing, so streaming updates skip the ref tables entirely. + if (event.type === SessionEvent.MessageContentUpdated.type) yield* SessionBlob.syncRefs(db, owner, data) + else if (stored !== message) yield* SessionBlob.recordRefs(db, owner, data) + }) const appendMessage = (message: SessionMessage.Info) => insertMessage(db, event, message) const adapter: SessionMessageUpdater.Adapter = { getAgent() { @@ -400,13 +413,16 @@ function run(db: DatabaseService, event: MessageEvent) { }) } -function insertMessage( +const encodeStored = (message: SessionMessage.Info | SessionStored.User) => + message.type === "user" ? encodeStoredUser(message) : encodeMessage(message) + +const insertMessage = Effect.fnUntraced(function* ( db: DatabaseService, event: SessionEvent.DurableEvent, message: SessionMessage.Info | SessionStored.User, ) { - const { id: _, type, ...data } = message.type === "user" ? encodeStoredUser(message) : encodeMessage(message) - return db + const { id: _, type, ...data } = encodeStored(yield* SessionBlob.externalize(db, message)) + yield* db .insert(SessionMessageTable) .values({ id: message.id, @@ -418,7 +434,12 @@ function insertMessage( }) .run() .pipe(Effect.orDie) -} + yield* SessionBlob.recordRefs( + db, + { sessionID: event.data.sessionID, messageID: message.id, seq: event.durable.seq }, + data, + ) +}) function projectIdle( db: DatabaseService, @@ -561,7 +582,10 @@ const layer = Layer.effectDiscard( }), ) yield* bus.project(SessionEvent.Deleted, (event) => - db.delete(SessionTable).where(eq(SessionTable.id, event.data.sessionID)).run().pipe(Effect.orDie), + Effect.gen(function* () { + yield* SessionBlob.releaseSession(db, event.data.sessionID) + yield* db.delete(SessionTable).where(eq(SessionTable.id, event.data.sessionID)).run().pipe(Effect.orDie) + }), ) yield* bus.project(SessionEvent.AgentSelected, (event) => Effect.gen(function* () { @@ -815,6 +839,7 @@ const layer = Layer.effectDiscard( .run() .pipe(Effect.orDie) yield* InstructionState.rewind(db, event.data.sessionID, boundary.seq) + yield* SessionBlob.releaseFrom(db, event.data.sessionID, boundary.seq) }), ) yield* bus.subscribe([SessionEvent.Step.Ended, SessionEvent.Step.Failed, SessionEvent.UsageRecorded]).pipe( diff --git a/packages/core/src/session/prompt.ts b/packages/core/src/session/prompt.ts index d721a7454ed1..20246af780de 100644 --- a/packages/core/src/session/prompt.ts +++ b/packages/core/src/session/prompt.ts @@ -10,7 +10,6 @@ import { Effect } from "effect" import path from "path" import { fileURLToPath } from "url" import { Image } from "../image.js" -import { Instance } from "../instance/service.js" import { Mime } from "../mime.js" import { Plugin } from "../plugin/service.js" import { PluginHooks } from "../plugin/hooks.js" @@ -32,60 +31,56 @@ export const prepare = Effect.fn("SessionPrompt.prepare")(function* (request: { input: Input }) { const fs = yield* FSUtil.Service - const instances = yield* Instance.Service - - return yield* Effect.gen(function* () { - yield* Plugin.awaitActivation - const hooks = yield* PluginHooks.Service - const event = yield* hooks.trigger("session", "prompt", { - sessionID: request.session.id, - messageID: request.messageID, - prompt: structuredClone({ - text: request.input.text, - files: request.input.files?.slice(), - agents: request.input.agents?.slice(), - skills: request.input.skills?.slice(), - }), - metadata: structuredClone(request.input.metadata), - delivery: request.input.delivery ?? "steer", - }) - const input = event.prompt - const files = input.files - ? yield* Effect.forEach(input.files, materializeAttachment, { concurrency: 8 }) - : undefined - const requested = input.skills - const selected = yield* Effect.gen(function* () { - if (!requested?.length) return undefined - const skillService = yield* Skill.Service - const prepared = new Map() - return yield* Effect.forEach(requested, (attachment) => - Effect.gen(function* () { - const name = prepared.get(attachment.id) - if (name !== undefined) return { id: attachment.id, name, mention: attachment.mention } - const skill = yield* skillService.get(attachment.id) - if (!skill) return yield* new SkillNotFoundError({ skill: attachment.id }) - prepared.set(skill.id, skill.name) - return { - id: skill.id, - name: skill.name, - text: (yield* Skill.prepare(fs, skill).pipe(Effect.orDie)).output, - mention: attachment.mention, - } - }), - ) - }) - return { - type: "user", - payload: SessionInbox.UserPayload.make({ - text: input.text, - agents: input.agents, - files, - skills: selected?.length ? selected : undefined, - metadata: event.metadata, + yield* Plugin.awaitActivation + const hooks = yield* PluginHooks.Service + const event = yield* hooks.trigger("session", "prompt", { + sessionID: request.session.id, + messageID: request.messageID, + prompt: structuredClone({ + text: request.input.text, + files: request.input.files?.slice(), + agents: request.input.agents?.slice(), + skills: request.input.skills?.slice(), + }), + metadata: structuredClone(request.input.metadata), + delivery: request.input.delivery ?? "steer", + }) + const input = event.prompt + const files = input.files + ? yield* Effect.forEach(input.files, materializeAttachment, { concurrency: 8 }) + : undefined + const requested = input.skills + const selected = yield* Effect.gen(function* () { + if (!requested?.length) return undefined + const skillService = yield* Skill.Service + const prepared = new Map() + return yield* Effect.forEach(requested, (attachment) => + Effect.gen(function* () { + const name = prepared.get(attachment.id) + if (name !== undefined) return { id: attachment.id, name, mention: attachment.mention } + const skill = yield* skillService.get(attachment.id) + if (!skill) return yield* new SkillNotFoundError({ skill: attachment.id }) + prepared.set(skill.id, skill.name) + return { + id: skill.id, + name: skill.name, + text: (yield* Skill.prepare(fs, skill).pipe(Effect.orDie)).output, + mention: attachment.mention, + } }), - delivery: event.delivery, - } satisfies SessionInbox.Item - }).pipe(instances.provide(request.session)) + ) + }) + return { + type: "user", + payload: SessionInbox.UserPayload.make({ + text: input.text, + agents: input.agents, + files, + skills: selected?.length ? selected : undefined, + metadata: event.metadata, + }), + delivery: event.delivery, + } satisfies SessionInbox.Item }) const materializeAttachment = Effect.fn("SessionPrompt.materializeAttachment")(function* ( diff --git a/packages/core/src/session/session.ts b/packages/core/src/session/session.ts index 06c2b241e6dd..d7153134faee 100644 --- a/packages/core/src/session/session.ts +++ b/packages/core/src/session/session.ts @@ -165,19 +165,18 @@ export const make = Effect.fn("Session.make")(function* () { delivery: input.delivery ?? "steer", }) if (existing) return existing - const item = yield* restore( - SessionPrompt.prepare({ session, messageID, input }).pipe( - Effect.provideService(Instance.Service, instances), - Effect.provideService(FSUtil.Service, fs), - ), - ) - // Commit a staged revert only after preparation succeeds, before admitting new work. - if (session.revert) yield* SessionRevert.commit(bus, session) - return yield* admission.admit({ - id: messageID, - sessionID: session.id, - item, - }) + // Preparation, the staged revert commit and admission share one acquisition of the session's location + // services, so projections see its config whoever called prompt. + return yield* Effect.gen(function* () { + const item = yield* restore(SessionPrompt.prepare({ session, messageID, input })) + // Commit a staged revert only after preparation succeeds, before admitting new work. + if (session.revert) yield* SessionRevert.commit(bus, session) + return yield* admission.admit({ + id: messageID, + sessionID: session.id, + item, + }) + }).pipe(instances.provide(session), Effect.provideService(FSUtil.Service, fs)) }).pipe( Effect.catchTag("SessionInbox.LifecycleConflict", () => new PromptConflictError({ sessionID, messageID })), ) diff --git a/packages/core/src/session/stored.ts b/packages/core/src/session/stored.ts index 717a28e2a7a1..f040801d6dcd 100644 --- a/packages/core/src/session/stored.ts +++ b/packages/core/src/session/stored.ts @@ -9,7 +9,7 @@ import { SessionMessage } from "./message.js" /** * Stored rows may reference a `blob` row as `media:` and the lowercase hex SHA-256 of its raw bytes. The blob - * row holds the bytes, size and dimensions; the ref names no server route. + * row holds the bytes and size; the ref names no server route. */ export const Ref = Schema.String.check(Schema.isPattern(/^media:[0-9a-f]{64}$/)) export type Ref = typeof Ref.Type @@ -17,6 +17,9 @@ export type Ref = typeof Ref.Type /** The `blob` hash a {@link Ref} names. */ export const refHash = (ref: Ref) => ref.slice("media:".length) +/** The {@link Ref} naming a `blob` hash. */ +export const ref = (hash: string): Ref => `media:${hash}` + const { data: _, ...attachment } = FileAttachment.fields /** A user file whose bytes live in `blob`. */ diff --git a/packages/core/test/config/normalization.test.ts b/packages/core/test/config/normalization.test.ts index 41a86e261aac..d61e70065f9b 100644 --- a/packages/core/test/config/normalization.test.ts +++ b/packages/core/test/config/normalization.test.ts @@ -526,6 +526,7 @@ describe("ConfigNormalize", () => { portable_shell_scanner: true, todo: true, background_compaction: true, + media_blob: true, subagent_depth: 0, location_idle_timeout: "2 hours", policies: [{ action: "provider.use", resource: "custom", effect: "allow" }], @@ -536,6 +537,7 @@ describe("ConfigNormalize", () => { portable_shell_scanner: true, todo: true, background_compaction: true, + media_blob: true, subagent_depth: 0, location_idle_timeout: "7200000 millis", }, diff --git a/packages/core/test/session-owned.test.ts b/packages/core/test/session-owned.test.ts index 327071b56771..e1322cfb6f4d 100644 --- a/packages/core/test/session-owned.test.ts +++ b/packages/core/test/session-owned.test.ts @@ -751,7 +751,7 @@ describe("SessionPrompt preparation", () => { input, } const items = yield* Effect.forEach([0, 1], () => SessionPrompt.prepare(request)).pipe( - Effect.provideService(Instance.Service, fixture.instances), + fixture.instances.provide(request.session), Effect.satisfiesServicesType(), ) diff --git a/packages/core/test/session-projector.test.ts b/packages/core/test/session-projector.test.ts index dd17856b790e..df8780fd18c1 100644 --- a/packages/core/test/session-projector.test.ts +++ b/packages/core/test/session-projector.test.ts @@ -24,10 +24,15 @@ import { fromRow } from "@opencode/core/session/info" import { SessionInbox } from "@opencode/core/session/inbox" import { SessionStore } from "@opencode/core/session/store" import { SessionStored } from "@opencode/core/session/stored" +import { SessionBlob } from "@opencode/core/session/blob" +import { Config } from "@opencode/core/config" +import { Document, Info } from "@opencode/schema/config" +import { ConfigExperimental } from "@opencode/schema/config/experimental" import { SessionHistory } from "@opencode/core/session/history" import { Shell } from "@opencode/schema/shell" import { InstructionStateTable, + BlobRefTable, BlobTable, SessionInboxTable, SessionMessageTable, @@ -48,6 +53,22 @@ const created = DateTime.makeUnsafe(0) const model = { id: Model.ID.make("model"), providerID: Provider.ID.make("provider") } const previousModel = { ...model, variant: Model.VariantID.make("medium") } const encodeMessage = Schema.encodeSync(SessionMessage.Info) +const mediaBlob = Config.testLayer([ + new Document({ + type: "document", + info: new Info({ experimental: new ConfigExperimental.Info({ media_blob: true }) }), + }), +]) +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", + "base64", +) +const attachment = (name: string, bytes = png, mime = "image/png") => ({ + data: bytes.toString("base64"), + mime, + source: { type: "inline" as const }, + name, +}) const build = Agent.defaultID const assistantRow = ( @@ -1303,4 +1324,239 @@ describe("SessionProjector", () => { ]) }), ) + + it.effect("keeps media inline unless experimental.media_blob is on", () => + Effect.gen(function* () { + const db = yield* seedSession() + const inbox = yield* SessionInbox.Service + const id = SessionMessage.ID.make("msg_media_inline") + yield* inbox.admit({ + id, + sessionID, + item: { type: "user", payload: { text: "inline", files: [attachment("shot.png")] }, delivery: "queue" }, + }) + + const row = yield* db + .select() + .from(SessionInboxTable) + .where(eq(SessionInboxTable.id, id)) + .get() + .pipe(Effect.orDie) + expect(row?.payload).toEqual({ text: "inline", files: [attachment("shot.png")] }) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toEqual([]) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toEqual([]) + }), + ) + + it.effect("stores media once and refs it from inbox, message, and tool rows when experimental.media_blob is on", () => + Effect.gen(function* () { + const db = yield* seedSession() + const bus = yield* Bus.Service + const inbox = yield* SessionInbox.Service + const store = yield* SessionStore.Service + const hash = SessionBlob.hashBytes(png) + const uri = SessionStored.ref(hash) + const id = SessionMessage.ID.make("msg_media_user") + const files = [attachment("shot.png"), attachment("copy.png")] + const refs = [ + { mime: "image/png", source: { type: "inline" }, name: "shot.png", uri }, + { mime: "image/png", source: { type: "inline" }, name: "copy.png", uri }, + ] + + yield* inbox.admit({ id, sessionID, item: { type: "user", payload: { text: "look", files }, delivery: "steer" } }) + const queued = yield* db + .select() + .from(SessionInboxTable) + .where(eq(SessionInboxTable.id, id)) + .get() + .pipe(Effect.orDie) + expect(queued?.payload).toEqual({ text: "look", files: refs }) + expect(yield* inbox.list(sessionID)).toMatchObject([{ id, payload: { text: "look", files } }]) + + const delivered = yield* bus.publish(SessionEvent.InboxDelivered, { sessionID, inboxID: id }) + const message = yield* db + .select() + .from(SessionMessageTable) + .where(eq(SessionMessageTable.id, id)) + .get() + .pipe(Effect.orDie) + expect(message?.data).toMatchObject({ text: "look", files: refs }) + expect((yield* store.message(id))?.message).toMatchObject({ type: "user", files }) + + const assistantMessageID = SessionMessage.ID.make("msg_media_tool") + yield* db.insert(SessionMessageTable).values(assistantRow(assistantMessageID, 0)).run().pipe(Effect.orDie) + yield* bus.publish(SessionEvent.Tool.Input.Started, { sessionID, assistantMessageID, id: "shot", name: "shot" }) + yield* bus.publish(SessionEvent.Tool.Called, { + sessionID, + assistantMessageID, + id: "shot", + input: {}, + executed: true, + }) + yield* bus.publish(SessionEvent.Tool.Success, { + sessionID, + assistantMessageID, + id: "shot", + content: [{ type: "file", uri: `data:image/png;base64,${png.toString("base64")}`, mime: "image/png" }], + executed: true, + }) + const tool = yield* db + .select() + .from(SessionMessageTable) + .where(eq(SessionMessageTable.id, assistantMessageID)) + .get() + .pipe(Effect.orDie) + expect(tool?.data).toMatchObject({ + content: [{ state: { status: "completed", content: [{ type: "file", uri, mime: "image/png" }] } }], + }) + expect((yield* store.message(assistantMessageID))?.message).toMatchObject({ + content: [ + { + state: { + content: [{ type: "file", uri: `data:image/png;base64,${png.toString("base64")}`, mime: "image/png" }], + }, + }, + ], + }) + + expect( + yield* db + .select({ + hash: BlobTable.hash, + mime: BlobTable.mime, + bytes: BlobTable.bytes, + }) + .from(BlobTable) + .all() + .pipe(Effect.orDie), + ).toEqual([{ hash, mime: "image/png", bytes: png.byteLength }]) + expect( + yield* db + .select({ message: BlobRefTable.message_id, hash: BlobRefTable.hash, seq: BlobRefTable.seq }) + .from(BlobRefTable) + .orderBy(asc(BlobRefTable.seq)) + .all() + .pipe(Effect.orDie), + ).toEqual([ + { message: assistantMessageID, hash, seq: 0 }, + { message: id, hash, seq: delivered.durable?.seq }, + ]) + }).pipe(Effect.provide(mediaBlob)), + ) + + it.effect("deletes a cancelled inbox row's blob refs and blobs", () => + Effect.gen(function* () { + const db = yield* seedSession() + const inbox = yield* SessionInbox.Service + const id = SessionMessage.ID.make("msg_media_cancel") + yield* inbox.admit({ + id, + sessionID, + item: { type: "user", payload: { text: "later", files: [attachment("shot.png")] }, delivery: "queue" }, + }) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toHaveLength(1) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toHaveLength(1) + + yield* inbox.cancel({ id, sessionID }) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toEqual([]) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toEqual([]) + }).pipe(Effect.provide(mediaBlob)), + ) + + it.effect("deletes reverted messages' blob refs and the blobs only they referenced", () => + Effect.gen(function* () { + const db = yield* seedSession() + const bus = yield* Bus.Service + const inbox = yield* SessionInbox.Service + const text = Buffer.from("reverted attachment") + const deliver = (id: SessionMessage.ID, files: ReturnType[]) => + Effect.gen(function* () { + yield* inbox.admit({ id, sessionID, item: { type: "user", payload: { text: id, files }, delivery: "steer" } }) + yield* bus.publish(SessionEvent.InboxDelivered, { sessionID, inboxID: id }) + }) + const kept = SessionMessage.ID.make("msg_media_kept") + const reverted = SessionMessage.ID.make("msg_media_reverted") + const shared = SessionMessage.ID.make("msg_media_shared") + yield* deliver(kept, [attachment("shot.png")]) + yield* deliver(reverted, [attachment("notes.txt", text, "text/plain")]) + yield* deliver(shared, [attachment("again.png")]) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toHaveLength(3) + + yield* bus.publish(SessionEvent.RevertEvent.Committed, { sessionID, to: reverted }) + expect( + yield* db + .select({ message: BlobRefTable.message_id, hash: BlobRefTable.hash }) + .from(BlobRefTable) + .all() + .pipe(Effect.orDie), + ).toEqual([{ message: kept, hash: SessionBlob.hashBytes(png) }]) + expect(yield* db.select({ hash: BlobTable.hash }).from(BlobTable).all().pipe(Effect.orDie)).toEqual([ + { hash: SessionBlob.hashBytes(png) }, + ]) + }).pipe(Effect.provide(mediaBlob)), + ) + + it.effect("keeps a blob while a fork references it and deletes it with the last session", () => + Effect.gen(function* () { + const db = yield* seedSession() + const bus = yield* Bus.Service + const inbox = yield* SessionInbox.Service + const id = SessionMessage.ID.make("msg_media_forked") + const childID = Session.ID.make("ses_media_fork") + yield* inbox.admit({ + id, + sessionID, + item: { type: "user", payload: { text: "fork me", files: [attachment("shot.png")] }, delivery: "steer" }, + }) + yield* bus.publish(SessionEvent.InboxDelivered, { sessionID, inboxID: id }) + yield* bus.publish(SessionEvent.Forked, { + sessionID: childID, + parentID: sessionID, + boundary: { type: "through", messageID: id }, + }) + expect( + yield* db.select({ session: BlobRefTable.session_id }).from(BlobRefTable).all().pipe(Effect.orDie), + ).toEqual(expect.arrayContaining([{ session: sessionID }, { session: childID }])) + + yield* bus.publish(SessionEvent.Deleted, { sessionID }) + expect( + yield* db.select({ session: BlobRefTable.session_id }).from(BlobRefTable).all().pipe(Effect.orDie), + ).toEqual([{ session: childID }]) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toHaveLength(1) + + yield* bus.publish(SessionEvent.Deleted, { sessionID: childID }) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toEqual([]) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toEqual([]) + }).pipe(Effect.provide(mediaBlob)), + ) + + it.effect("releases a tool's blob when a content update drops its ref", () => + Effect.gen(function* () { + const db = yield* seedSession() + const bus = yield* Bus.Service + const assistantMessageID = SessionMessage.ID.make("msg_media_rewritten") + yield* db.insert(SessionMessageTable).values(assistantRow(assistantMessageID, 0)).run().pipe(Effect.orDie) + yield* bus.publish(SessionEvent.Tool.Input.Started, { sessionID, assistantMessageID, id: "shot", name: "shot" }) + yield* bus.publish(SessionEvent.Tool.Called, { + sessionID, + assistantMessageID, + id: "shot", + input: {}, + executed: true, + }) + yield* bus.publish(SessionEvent.Tool.Success, { + sessionID, + assistantMessageID, + id: "shot", + content: [{ type: "file", uri: `data:image/png;base64,${png.toString("base64")}`, mime: "image/png" }], + executed: true, + }) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toHaveLength(1) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toHaveLength(1) + + yield* bus.publish(SessionEvent.MessageContentUpdated, { sessionID, messageID: assistantMessageID, content: [] }) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toEqual([]) + expect(yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).toEqual([]) + }).pipe(Effect.provide(mediaBlob)), + ) }) diff --git a/packages/core/test/session-prompt.test.ts b/packages/core/test/session-prompt.test.ts index d6a20188945f..631e5e5cbda2 100644 --- a/packages/core/test/session-prompt.test.ts +++ b/packages/core/test/session-prompt.test.ts @@ -23,7 +23,13 @@ import { SessionMessage } from "@opencode/core/session/message" import { SessionProjector } from "@opencode/core/session/projector" import { SessionExecution } from "@opencode/core/session/execution" import { SessionInbox } from "@opencode/core/session/inbox" -import { SessionInboxTable, SessionMessageTable, SessionTable } from "@opencode/core/session/sql" +import { + BlobRefTable, + BlobTable, + SessionInboxTable, + SessionMessageTable, + SessionTable, +} from "@opencode/core/session/sql" import { SessionStore } from "@opencode/core/session/store" import { LocationServiceMap } from "@opencode/core/location-service-map" import type { LocationServices } from "@opencode/core/location-services" @@ -34,6 +40,10 @@ import { Snapshot } from "@opencode/core/snapshot" import { Skill } from "@opencode/core/skill" import { tmpdirScoped } from "./fixture/tmpdir" import { testEffect } from "./lib/effect" +import { Config } from "@opencode/core/config" +import { Document, Info } from "@opencode/schema/config" +import { ConfigExperimental } from "@opencode/schema/config/experimental" +import { SessionStored } from "@opencode/core/session/stored" const executionCalls: Session.ID[] = [] const interruptCalls: Session.ID[] = [] @@ -62,6 +72,13 @@ const execution = Layer.succeed( awaitIdle: () => Effect.void, }), ) +const mediaDirectory = "/media" +const mediaBlob = Config.testLayer([ + new Document({ + type: "document", + info: new Info({ experimental: new ConfigExperimental.Info({ media_blob: true }) }), + }), +]) const locations = makeGlobalNode({ service: LocationServiceMap.Service, layer: Layer.effect( @@ -69,9 +86,10 @@ const locations = makeGlobalNode({ Effect.gen(function* () { const bus = yield* Bus.Service return yield* LayerMap.make( - (_ref: Location.Ref) => + (ref: Location.Ref) => // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion Layer.mergeAll( + ref.directory === mediaDirectory ? mediaBlob : Layer.empty, LayerNode.compile(LayerNode.group([PluginHooks.node, Skill.node]), { replacements: [Bus.node.replace(Layer.succeed(Bus.Service, bus))], }), @@ -432,6 +450,47 @@ describe("Session.prompt", () => { }), ) + it.effect("stores media refs at admission when the session's config enables media_blob", () => + Effect.gen(function* () { + yield* setup + const { db } = yield* Database.Service + const mediaSessionID = Session.ID.make("ses_prompt_media") + yield* db + .insert(SessionTable) + .values({ + id: mediaSessionID, + project_id: Project.ID.global, + slug: "media", + directory: mediaDirectory, + title: "media", + version: "test", + }) + .run() + .pipe(Effect.orDie) + const bytes = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=" + + const message = yield* (yield* Session.Service).prompt({ + sessionID: mediaSessionID, + text: "Inspect this image", + files: [{ uri: `data:image/png;base64,${bytes}` }], + resume: false, + }) + + const row = yield* db + .select() + .from(SessionInboxTable) + .where(eq(SessionInboxTable.id, message.id)) + .get() + .pipe(Effect.orDie) + const [hash] = (yield* db.select().from(BlobTable).all().pipe(Effect.orDie)).map((blob) => blob.hash) + expect(hash).toBeDefined() + expect(row?.payload).toMatchObject({ files: [{ uri: SessionStored.ref(hash!), mime: "image/png" }] }) + expect(yield* db.select().from(BlobRefTable).all().pipe(Effect.orDie)).toEqual([ + { session_id: mediaSessionID, message_id: message.id, seq: expect.any(Number), hash }, + ]) + }), + ) + it.effect("normalizes large image content before validating persisted Base64", () => Effect.gen(function* () { yield* setup diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 9e362f333b29..e124f4505fb4 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -14778,6 +14778,9 @@ "background_compaction": { "type": "boolean" }, + "media_blob": { + "type": "boolean" + }, "subagent_depth": { "type": "integer", "minimum": 0 diff --git a/packages/schema/src/config/experimental.ts b/packages/schema/src/config/experimental.ts index 4e703eae37c9..633a03e58d46 100644 --- a/packages/schema/src/config/experimental.ts +++ b/packages/schema/src/config/experimental.ts @@ -15,6 +15,10 @@ export class Info extends Schema.Class("ConfigExperimental.Info")({ description: "Enable experimental background compaction: summarize the conversation in the background as it nears the compaction threshold, so automatic compaction does not wait for the summary. Background summaries that are never used still cost tokens. Defaults to false.", }), + media_blob: Schema.Boolean.pipe(optional).annotate({ + description: + "Store new session media once in a deduplicated blob table instead of inline in every message row. Defaults to false.", + }), subagent_depth: NonNegativeInt.pipe(optional).annotate({ description: "Maximum subagent nesting depth. Defaults to 1.", }),