Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/client/src/promise/generated/types.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions packages/core/src/config/normalize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
179 changes: 176 additions & 3 deletions packages/core/src/session/blob.ts
Original file line number Diff line number Diff line change
@@ -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"]
Expand Down Expand Up @@ -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<string, typeof BlobTable.$inferInsert>
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<SessionStored.File> },
>(db: DatabaseService, input: T): Effect.fn.Return<T> {
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<string>()
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))
29 changes: 16 additions & 13 deletions packages/core/src/session/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})
25 changes: 16 additions & 9 deletions packages/core/src/session/inbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -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,
)
})

/**
Expand Down Expand Up @@ -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* (
Expand Down
Loading
Loading