diff --git a/bun.lock b/bun.lock index 4570b103204d0..bfac84ff1c971 100644 --- a/bun.lock +++ b/bun.lock @@ -221,7 +221,7 @@ "dependencies": { "acorn": "8.15.0", "effect": "catalog:", - "psychoscript": "0.11.0", + "psychoscript": "0.14.0", }, "devDependencies": { "@tsconfig/bun": "catalog:", @@ -3921,7 +3921,7 @@ "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], - "psychoscript": ["psychoscript@0.11.0", "", { "dependencies": { "acorn": "8.16.0" }, "peerDependencies": { "effect": "^4.1.0" }, "optionalPeers": ["effect"] }, "sha512-xebSMopUdQQPXMruONBdrDczTZNru+Y2MKJecus3/f7INmB1mUzmXl59ydkszV5BebUOzeQYzLMDH/2P5Ygt+A=="], + "psychoscript": ["psychoscript@0.14.0", "", { "dependencies": { "acorn": "8.16.0" }, "peerDependencies": { "effect": "^4.1.0" }, "optionalPeers": ["effect"] }, "sha512-1kS8pvW1cbl1NGtEHLqazwVlQjczc25/sZItXJFg32qSo//rj5wELkxMGeX4kL2biLpjJ2SboPlrmzJosI+Pkw=="], "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index da62d1f3f27a0..96842b9c18930 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2866,6 +2866,7 @@ export type ConfigEntry = console_watches?: boolean model_speeds?: boolean full_codemode?: boolean + codemode_repl?: boolean codemode_agents?: boolean machines?: boolean home_memory?: boolean diff --git a/packages/codemode/package.json b/packages/codemode/package.json index e6b7cc8310785..8ad5a9f2fc00f 100644 --- a/packages/codemode/package.json +++ b/packages/codemode/package.json @@ -29,7 +29,7 @@ "dependencies": { "acorn": "8.15.0", "effect": "catalog:", - "psychoscript": "0.11.0" + "psychoscript": "0.14.0" }, "devDependencies": { "@tsconfig/bun": "catalog:", diff --git a/packages/codemode/src/codemode/codemode.ts b/packages/codemode/src/codemode/codemode.ts index 1c68120076e8b..22262c23059c9 100644 --- a/packages/codemode/src/codemode/codemode.ts +++ b/packages/codemode/src/codemode/codemode.ts @@ -92,6 +92,35 @@ export type SuspendOptions = { readonly maxBytes?: number } +export type SessionStore = Language.SessionStore +export type SessionBinding = Language.SessionBinding +export type SessionBindingKind = Language.SessionBindingKind +export type UnloadResult = Language.UnloadResult + +/** Options for `runtime.experimental.session`. */ +export type SessionOptions = ProgramOptions & { + /** Optional blob store enabling `session.unload()` and lazy loading of unloaded bindings. */ + readonly store?: SessionStore +} + +/** Options for `runtime.experimental.restore`. */ +export type RestoreSessionOptions = RunOptions & { + /** Required when restoring a session that contains unloaded bindings. */ + readonly store?: SessionStore +} + +/** A persistent interpreter session whose top-level bindings survive across sequential `eval` calls. */ +export type Session = { + readonly eval: ( + code: string, + bindings?: Readonly>, + options?: { readonly runId?: string }, + ) => Effect.Effect + readonly unload: (names?: ReadonlyArray) => Effect.Effect + readonly save: (options?: SuspendOptions) => Effect.Effect + readonly bindings: () => ReadonlyArray +} + /** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */ export type Options = {}, Extensions extends ReadonlyArray = []> = { /** Explicit tools exposed to the program as `tools`. */ @@ -208,6 +237,17 @@ export type Runtime = { * it can't be resumed here. */ readonly resume: (state: Snapshot | Uint8Array, options?: RunOptions) => Program + /** Experimental APIs that may change without compatibility guarantees. */ + readonly experimental: { + readonly session: ( + bindings?: Readonly>, + options?: SessionOptions, + ) => Session + readonly restore: ( + state: Snapshot | Uint8Array, + options?: RestoreSessionOptions, + ) => Effect.Effect, SnapshotError> + } } /** @@ -319,6 +359,21 @@ export function make< ), program, resume: (state, runOptions) => reported(runtimeFor(runOptions?.extensions).resume(state)), + experimental: { + session: (bindings, sessionOptions) => + reportedSession( + runtimeFor(sessionOptions?.extensions).experimental.session({ + bindings, + runId: sessionOptions?.runId, + store: sessionOptions?.store, + }), + ), + restore: (state, restoreOptions) => + Effect.map( + runtimeFor(restoreOptions?.extensions).experimental.restore(state, { store: restoreOptions?.store }), + reportedSession, + ), + }, } } @@ -456,10 +511,21 @@ const reported = (program: Language.Program): Program => ({ }) // A run's outcome as Code Mode reports it: the tool calls in place of the run's metadata. -const outcome = (ended: Language.Outcome): Outcome => { - if (ended.ok === "suspended") return ended +const reportedSession = (session: Language.Session): Session => ({ + eval: (code, bindings, evalOptions) => { + const runId = evalOptions?.runId ?? crypto.randomUUID() + return Effect.map(session.eval(code, { bindings, runId }), (ended) => resultOf(ended, runId)).pipe(Effect.scoped) + }, + unload: (names) => session.unload(names), + save: (options) => session.save(options), + bindings: () => session.bindings(), +}) + +const outcome = (ended: Language.Outcome): Outcome => (ended.ok === "suspended" ? ended : resultOf(ended)) + +const resultOf = (ended: Language.Result, runId?: string): Result => { const { metadata, ...result } = ended - const toolCalls = ToolRuntime.toolCalls(metadata) + const toolCalls = ToolRuntime.toolCalls(metadata, runId) if (!result.ok) return { ...result, error: diagnostic(result.error), toolCalls } const { warnings, ...value } = result return { ...value, ...(warnings && { warnings: warnings.map(diagnostic) }), toolCalls } diff --git a/packages/codemode/src/codemode/tool-runtime.ts b/packages/codemode/src/codemode/tool-runtime.ts index 8b285b4a7dfd5..52d794f57dd05 100644 --- a/packages/codemode/src/codemode/tool-runtime.ts +++ b/packages/codemode/src/codemode/tool-runtime.ts @@ -612,11 +612,23 @@ const diagnosed = (effect: Effect.Effect) => * calls whose `before` hook finished, so an idempotent call run again on resume doesn't fire it twice. */ type State = { + runId?: string readonly maxToolCalls: number | null readonly calls: Array<{ readonly name: string; readonly key: string }> before?: Array } +const syncRun = (state: State, runId: string) => { + if (state.runId === undefined) { + state.runId = runId + return + } + if (state.runId === runId) return + state.runId = runId + state.calls.length = 0 + delete state.before +} + /** * Fires a call's `before` once per logical call: skipped when the call's key already finished its `before` in this * run, as an idempotent call run again on resume has. The key is recorded only once `before` succeeds, so a `before` @@ -631,19 +643,26 @@ export const beforeOnce = ( return (call) => Effect.suspend(() => { const state = run.metadata as unknown as State | null + if (state !== null) syncRun(state, run.id) if (state?.before?.includes(key)) return Effect.void return Effect.tap(before(call), () => Effect.sync(() => { const saved = run.metadata as unknown as State | null - if (saved !== null) (saved.before ??= []).push(key) + if (saved === null) return + syncRun(saved, run.id) + ;(saved.before ??= []).push(key) }), ) }) } /** The tool calls a run admitted, from its `run.metadata`. */ -export const toolCalls = (metadata: Json): Array => - metadata === null ? [] : (metadata as unknown as State).calls.map((call) => ({ name: call.name })) +export const toolCalls = (metadata: Json, runId?: string): Array => { + if (metadata === null) return [] + const state = metadata as unknown as State + if (runId !== undefined && state.runId !== undefined && state.runId !== runId) return [] + return state.calls.map((call) => ({ name: call.name })) +} /** * The `tools` and `search` globals of one run, over tools prepared once for the runtime. The run's budget and its @@ -656,7 +675,7 @@ export const globals = ( run: Run, maxToolCalls: number | undefined, ): { readonly tools: Host.Namespace; readonly search: Host.Fn } => { - const state = (run.metadata ??= { maxToolCalls: maxToolCalls ?? null, calls: [] }) as unknown as State + const state = (run.metadata ??= { runId: run.id, maxToolCalls: maxToolCalls ?? null, calls: [] }) as unknown as State const runState = run // The input of each durable call started in this runtime, for `tool.after` once it ends. const invocations = new Map() @@ -664,6 +683,7 @@ export const globals = ( // Counts a call against `maxToolCalls`. An idempotent call run again on resume was counted when it first ran. const admit = (name: string, key: string, idempotent: boolean): void => { + syncRun(state, runState.id) if (idempotent && state.calls.some((call) => call.key === key)) return if (state.maxToolCalls !== null && state.calls.length >= state.maxToolCalls) { throw toolRuntimeError( diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 1a78c1f43de40..befae7eedd367 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -14,11 +14,18 @@ export { type Outcome, type Program, type ProgramOptions, + type RestoreSessionOptions, type RunOptions, type Runtime, + type Session, + type SessionBinding, + type SessionBindingKind, + type SessionOptions, + type SessionStore, type Snapshot, type SnapshotHeader, type Suspended, type SuspendOptions, + type UnloadResult, } from "./codemode/codemode.js" export { ToolError, toolError } from "./codemode/tool-error.js" diff --git a/packages/core/schema.json b/packages/core/schema.json index 4d850911f33a5..cb534938a840c 100644 --- a/packages/core/schema.json +++ b/packages/core/schema.json @@ -1,8 +1,8 @@ { "version": "7", "dialect": "sqlite", - "id": "8053157b-ef92-4aaa-9efa-45e12a91125f", - "prevIds": ["5a81eade-f8b4-4702-8730-c0b0dc7196c7"], + "id": "85eba06c-04cc-45d8-88f4-38446981aa19", + "prevIds": ["8053157b-ef92-4aaa-9efa-45e12a91125f"], "ddl": [ { "name": "account_state", @@ -24,6 +24,18 @@ "name": "blob_v2", "entityType": "tables" }, + { + "name": "codemode_repl_blob_ref", + "entityType": "tables" + }, + { + "name": "codemode_repl_blob", + "entityType": "tables" + }, + { + "name": "codemode_repl_session", + "entityType": "tables" + }, { "name": "credential", "entityType": "tables" @@ -638,6 +650,126 @@ "entityType": "columns", "table": "blob_v2" }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "codemode_repl_blob_ref" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "hash", + "entityType": "columns", + "table": "codemode_repl_blob_ref" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "hash", + "entityType": "columns", + "table": "codemode_repl_blob" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "bytes", + "entityType": "columns", + "table": "codemode_repl_blob" + }, + { + "type": "blob", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "data", + "entityType": "columns", + "table": "codemode_repl_blob" + }, + { + "type": "text", + "notNull": false, + "autoincrement": false, + "default": null, + "generated": null, + "name": "session_id", + "entityType": "columns", + "table": "codemode_repl_session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "mode_key", + "entityType": "columns", + "table": "codemode_repl_session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "visible_seq", + "entityType": "columns", + "table": "codemode_repl_session" + }, + { + "type": "blob", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "root_blob", + "entityType": "columns", + "table": "codemode_repl_session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "bytes", + "entityType": "columns", + "table": "codemode_repl_session" + }, + { + "type": "text", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "binding_names", + "entityType": "columns", + "table": "codemode_repl_session" + }, + { + "type": "integer", + "notNull": true, + "autoincrement": false, + "default": null, + "generated": null, + "name": "time_updated", + "entityType": "columns", + "table": "codemode_repl_session" + }, { "type": "text", "notNull": false, @@ -2239,6 +2371,28 @@ "entityType": "fks", "table": "account_state" }, + { + "columns": ["session_id"], + "tableTo": "session_v2", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_codemode_repl_blob_ref_session_id_session_v2_id_fk", + "entityType": "fks", + "table": "codemode_repl_blob_ref" + }, + { + "columns": ["session_id"], + "tableTo": "session_v2", + "columnsTo": ["id"], + "onUpdate": "NO ACTION", + "onDelete": "CASCADE", + "nameExplicit": false, + "name": "fk_codemode_repl_session_session_id_session_v2_id_fk", + "entityType": "fks", + "table": "codemode_repl_session" + }, { "columns": ["aggregate_id"], "tableTo": "event_sequence", @@ -2389,6 +2543,13 @@ "entityType": "pks", "table": "control_account" }, + { + "columns": ["session_id", "hash"], + "nameExplicit": false, + "name": "codemode_repl_blob_ref_pk", + "entityType": "pks", + "table": "codemode_repl_blob_ref" + }, { "columns": ["project_id", "directory"], "nameExplicit": false, @@ -2459,6 +2620,20 @@ "table": "blob_v2", "entityType": "pks" }, + { + "columns": ["hash"], + "nameExplicit": false, + "name": "codemode_repl_blob_pk", + "table": "codemode_repl_blob", + "entityType": "pks" + }, + { + "columns": ["session_id"], + "nameExplicit": false, + "name": "codemode_repl_session_pk", + "table": "codemode_repl_session", + "entityType": "pks" + }, { "columns": ["id"], "nameExplicit": false, @@ -2638,6 +2813,20 @@ "entityType": "indexes", "table": "blob_v2" }, + { + "columns": [ + { + "value": "hash", + "isExpression": false + } + ], + "isUnique": false, + "where": null, + "origin": "manual", + "name": "codemode_repl_blob_ref_hash_idx", + "entityType": "indexes", + "table": "codemode_repl_blob_ref" + }, { "columns": [ { diff --git a/packages/core/src/codemode/job.ts b/packages/core/src/codemode/job.ts index 9b13077c755c3..291f524ca1c74 100644 --- a/packages/core/src/codemode/job.ts +++ b/packages/core/src/codemode/job.ts @@ -6,6 +6,7 @@ import { extension } from "mime-types" import { Flag } from "../flag.js" import { Job } from "../job.js" import { CodeModeAgents } from "./agents.js" +import { CodeModeRepl } from "./repl.js" import { CodeModeTool } from "./tool.js" import { BackgroundResult } from "../session/background-result.js" import type { Session } from "../session.js" @@ -308,6 +309,7 @@ export const make = Effect.fnUntraced(function* ( } const job = yield* jobs.background(id) if (!job?.notificationID) return yield* Effect.interrupt + CodeModeRepl.markBackground(sessionID, id) // Drain the last progress publication before the tool row becomes terminal. yield* progress.withPermit(Deferred.succeed(detached, undefined)) yield* deliver({ diff --git a/packages/core/src/codemode/repl.ts b/packages/core/src/codemode/repl.ts new file mode 100644 index 0000000000000..590c3fccaa19b --- /dev/null +++ b/packages/core/src/codemode/repl.ts @@ -0,0 +1,656 @@ +export * as CodeModeRepl from "./repl.js" + +import { createHash } from "node:crypto" +import { constants, zstdCompressSync, zstdDecompressSync } from "node:zlib" +import { CodeMode, type Extension } from "@opencode/codemode" +import { and, eq, inArray, notExists, sql } from "drizzle-orm" +import { Effect, Semaphore } from "effect" +import { DatabaseBatch } from "../database/batch.js" +import type { Database } from "../database/database.js" +import type { SessionMessage } from "../session/message.js" +import type { SessionSchema } from "../session/schema.js" +import { SessionMessageTable } from "../session/sql.js" +import { CodeModeReplBlobRefTable, CodeModeReplBlobTable, CodeModeReplSessionTable } from "./sql.js" + +type DB = Database.Interface["db"] + +/** Unload top-level bindings untouched for more than this many cells so live RAM stays bounded. */ +export const UNLOAD_AFTER_CELLS = 5 +/** Maximum number of live session interpreters kept warm in memory across the process. */ +export const MAX_WARM_SESSIONS = 64 +/** Soft byte budget (estimated interpreter baseline plus latest root snapshot size) for warm live interpreters. */ +export const MAX_WARM_BYTES = 256 * 1024 * 1024 + +// Approximate JSC heap per idle interpreter with built-ins initialized (~38 MiB across 64 empty sessions). +const WARM_SESSION_OVERHEAD_BYTES = 600 * 1024 +const RESET_PREFIX = "reset:" +const zstdOptions = { params: { [constants.ZSTD_c_compressionLevel]: 1 } } +const compress = (bytes: Uint8Array) => zstdCompressSync(bytes, zstdOptions) +const decompress = (bytes: Uint8Array) => zstdDecompressSync(bytes) +const sha256 = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex") + +interface PendingBlob { + readonly bytes: number + readonly data: Buffer +} + +interface TrackedStore { + readonly store: CodeMode.SessionStore + readonly pending: Map + committedRefs: Set | undefined +} + +interface WarmEntry { + session: CodeMode.Session + runtime: unknown + modeKey: string + store: TrackedStore + bytes: number + cellCounter: number + epoch: number +} + +interface SessionLock { + readonly semaphore: Semaphore.Semaphore + activeRunID: string | undefined + backgroundRunID: string | undefined + waiters: number + epoch: number +} + +const warm = new Map() +const locks = new Map() + +function lockFor(sessionID: SessionSchema.ID): SessionLock { + const existing = locks.get(sessionID) + if (existing !== undefined) return existing + const created: SessionLock = { + semaphore: Semaphore.makeUnsafe(1), + activeRunID: undefined, + backgroundRunID: undefined, + waiters: 0, + epoch: 0, + } + locks.set(sessionID, created) + return created +} + +function dropLockIfIdle(sessionID: SessionSchema.ID, lock: SessionLock | undefined) { + if (lock === undefined) return + if (lock.activeRunID === undefined && lock.waiters === 0 && !warm.has(sessionID)) locks.delete(sessionID) +} + +function touchWarm(sessionID: SessionSchema.ID, entry: WarmEntry) { + warm.delete(sessionID) + warm.set(sessionID, entry) +} + +function maxLastCell(bindings: ReadonlyArray): number { + let max = 0 + for (const item of bindings) if (item.lastCell > max) max = item.lastCell + return max +} + +/** Drops any live in-memory interpreter for `sessionID` without touching persisted SQLite state. */ +export function forget(sessionID: SessionSchema.ID) { + warm.delete(sessionID) + const lock = locks.get(sessionID) + if (lock === undefined) return + lock.epoch++ + dropLockIfIdle(sessionID, lock) +} + +/** Marks the currently running REPL cell for `sessionID` as moved to background so new cells fail fast. */ +export function markBackground(sessionID: SessionSchema.ID, runID: string) { + const lock = locks.get(sessionID) + if (lock !== undefined && lock.activeRunID === runID) lock.backgroundRunID = runID +} + +/** Returns the background job/run ID holding `sessionID`'s REPL lease, if any. */ +export function backgroundRun(sessionID: SessionSchema.ID): string | undefined { + return locks.get(sessionID)?.backgroundRunID +} + +function resetMessage(reason: string, names: ReadonlyArray): string { + if (names.length === 0) return `[repl reset: ${reason}]` + const shown = names.slice(0, 12).join(", ") + const more = names.length > 12 ? `, +${names.length - 12} more` : "" + return `[repl reset: ${reason}; lost bindings: ${shown}${more}]` +} + +function makeStore(db: DB | undefined, committedRefs: Set | undefined): TrackedStore { + const pending = new Map() + if (db === undefined) { + const memory = new Map() + return { + pending, + committedRefs, + store: { + put: (bytes) => { + const hash = sha256(bytes) + if (!memory.has(hash)) memory.set(hash, compress(bytes)) + return hash + }, + get: (hash) => { + const data = memory.get(hash) + if (data === undefined) throw new Error(`Missing REPL blob ${hash}.`) + return decompress(data) + }, + }, + } + } + // Stage writes in memory and flush them inside saveRow's transaction so cancelled cells never strand orphan blobs. + const tracked: TrackedStore = { + pending, + committedRefs, + store: { + put: (bytes) => { + const hash = sha256(bytes) + if (!pending.has(hash) && !tracked.committedRefs?.has(hash)) { + pending.set(hash, { bytes: bytes.byteLength, data: compress(bytes) }) + } + return hash + }, + get: (hash) => { + const staged = pending.get(hash) + if (staged !== undefined) return decompress(staged.data) + return Effect.runPromise( + db + .select({ data: CodeModeReplBlobTable.data }) + .from(CodeModeReplBlobTable) + .where(eq(CodeModeReplBlobTable.hash, hash)) + .get() + .pipe(Effect.orDie), + ).then((row) => { + if (row === undefined) throw new Error(`Missing REPL blob ${hash}.`) + return decompress(row.data) + }) + }, + }, + } + return tracked +} + +const deleteOrphanBlobs = Effect.fnUntraced(function* (db: DB, candidates: ReadonlyArray) { + const unique = [...new Set(candidates)] + for (const batch of DatabaseBatch.batches(unique, 1)) { + yield* db + .delete(CodeModeReplBlobTable) + .where( + and( + inArray(CodeModeReplBlobTable.hash, batch), + notExists( + db + .select({ one: sql`1` }) + .from(CodeModeReplBlobRefTable) + .where(eq(CodeModeReplBlobRefTable.hash, CodeModeReplBlobTable.hash)), + ), + ), + ) + .run() + .pipe(Effect.orDie) + } +}) + +const deletePersisted = Effect.fnUntraced(function* (db: DB, sessionID: SessionSchema.ID) { + yield* db + .delete(CodeModeReplSessionTable) + .where(eq(CodeModeReplSessionTable.session_id, sessionID)) + .run() + .pipe(Effect.orDie) + const released = yield* db + .delete(CodeModeReplBlobRefTable) + .where(eq(CodeModeReplBlobRefTable.session_id, sessionID)) + .returning({ hash: CodeModeReplBlobRefTable.hash }) + .all() + .pipe(Effect.orDie) + if (released.length > 0) yield* deleteOrphanBlobs(db, released.map((row) => row.hash)) +}) + +const writeResetTombstone = Effect.fnUntraced(function* ( + db: DB, + sessionID: SessionSchema.ID, + reason: string, + names: ReadonlyArray, + visibleSeq: number, +) { + const values = { + session_id: sessionID, + mode_key: `${RESET_PREFIX}${reason}`, + visible_seq: visibleSeq, + root_blob: Buffer.alloc(0), + bytes: 0, + binding_names: names, + time_updated: Date.now(), + } + yield* db + .insert(CodeModeReplSessionTable) + .values(values) + .onConflictDoUpdate({ + target: CodeModeReplSessionTable.session_id, + set: { + mode_key: values.mode_key, + visible_seq: values.visible_seq, + root_blob: values.root_blob, + bytes: 0, + binding_names: values.binding_names, + time_updated: values.time_updated, + }, + }) + .run() + .pipe(Effect.orDie) +}) + +/** Removes persisted REPL state and releases any blob refs owned exclusively by `sessionID`. */ +export const releaseSession = Effect.fnUntraced(function* (db: DB, sessionID: SessionSchema.ID) { + forget(sessionID) + yield* deletePersisted(db, sessionID) +}) + +/** Resets persisted REPL state if its latest cell lives at or after `seq`, leaving a reset notice for the next call. */ +export const releaseFrom = Effect.fnUntraced(function* (db: DB, sessionID: SessionSchema.ID, seq: number) { + forget(sessionID) + const row = yield* db + .select({ + mode_key: CodeModeReplSessionTable.mode_key, + visible_seq: CodeModeReplSessionTable.visible_seq, + binding_names: CodeModeReplSessionTable.binding_names, + }) + .from(CodeModeReplSessionTable) + .where(eq(CodeModeReplSessionTable.session_id, sessionID)) + .get() + .pipe(Effect.orDie) + if (row === undefined || row.visible_seq < seq) return + const nextSeq = Math.max(0, seq - 1) + if (row.mode_key.startsWith(RESET_PREFIX)) { + if (row.binding_names.length === 0) { + yield* deletePersisted(db, sessionID) + return + } + if (nextSeq < row.visible_seq) { + yield* writeResetTombstone(db, sessionID, row.mode_key.slice(RESET_PREFIX.length), row.binding_names, nextSeq) + } + return + } + yield* deletePersisted(db, sessionID) + if (row.binding_names.length === 0) return + yield* writeResetTombstone(db, sessionID, "session reverted", row.binding_names, nextSeq) +}) + +/** Shares the parent's persisted REPL snapshot and blob refs with `targetID`, or records a reset notice if mid-history. */ +export const fork = Effect.fnUntraced(function* ( + db: DB, + sourceID: SessionSchema.ID, + targetID: SessionSchema.ID, + throughSeq: number | undefined, +) { + if (throughSeq === undefined) return + forget(targetID) + const row = yield* db + .select() + .from(CodeModeReplSessionTable) + .where(eq(CodeModeReplSessionTable.session_id, sourceID)) + .get() + .pipe(Effect.orDie) + if (row === undefined) return + if (row.visible_seq > throughSeq) { + if (row.binding_names.length > 0) { + const reason = row.mode_key.startsWith(RESET_PREFIX) + ? row.mode_key.slice(RESET_PREFIX.length) + : "forked before latest REPL state" + yield* writeResetTombstone(db, targetID, reason, row.binding_names, throughSeq) + } + return + } + yield* db + .insert(CodeModeReplSessionTable) + .values({ ...row, session_id: targetID }) + .onConflictDoUpdate({ + target: CodeModeReplSessionTable.session_id, + set: { + mode_key: row.mode_key, + visible_seq: row.visible_seq, + root_blob: row.root_blob, + bytes: row.bytes, + binding_names: row.binding_names, + time_updated: row.time_updated, + }, + }) + .run() + .pipe(Effect.orDie) + if (row.mode_key.startsWith(RESET_PREFIX)) return + const refs = yield* db + .select({ hash: CodeModeReplBlobRefTable.hash }) + .from(CodeModeReplBlobRefTable) + .where(eq(CodeModeReplBlobRefTable.session_id, sourceID)) + .all() + .pipe(Effect.orDie) + for (const batch of DatabaseBatch.batches(refs, 2)) { + yield* db + .insert(CodeModeReplBlobRefTable) + .values(batch.map((ref) => ({ session_id: targetID, hash: ref.hash }))) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie) + } +}) + +const saveRow = Effect.fnUntraced(function* ( + db: DB, + input: { + readonly sessionID: SessionSchema.ID + readonly modeKey: string + readonly visibleSeq: number + readonly raw: Uint8Array + readonly bindings: ReadonlyArray + readonly store: TrackedStore + }, +) { + const compressed = compress(input.raw) + const bindingNames = input.bindings.map((item) => item.name) + const nextKeys = new Set(input.bindings.flatMap((item) => (item.storeKey === undefined ? [] : [item.storeKey]))) + const stagedBlobs: Array<{ readonly hash: string; readonly bytes: number; readonly data: Buffer }> = [] + for (const [hash, blob] of input.store.pending) { + if (nextKeys.has(hash)) stagedBlobs.push({ hash, bytes: blob.bytes, data: blob.data }) + } + const now = Date.now() + yield* db + .transaction( + Effect.fnUntraced(function* (tx) { + for (const batch of DatabaseBatch.batches(stagedBlobs, 3)) { + yield* tx + .insert(CodeModeReplBlobTable) + .values(batch) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie) + } + + yield* tx + .insert(CodeModeReplSessionTable) + .values({ + session_id: input.sessionID, + mode_key: input.modeKey, + visible_seq: input.visibleSeq, + root_blob: compressed, + bytes: input.raw.byteLength, + binding_names: bindingNames, + time_updated: now, + }) + .onConflictDoUpdate({ + target: CodeModeReplSessionTable.session_id, + set: { + mode_key: input.modeKey, + visible_seq: input.visibleSeq, + root_blob: compressed, + bytes: input.raw.byteLength, + binding_names: bindingNames, + time_updated: now, + }, + }) + .run() + .pipe(Effect.orDie) + + const prevKeys = + input.store.committedRefs ?? + new Set( + (yield* tx + .select({ hash: CodeModeReplBlobRefTable.hash }) + .from(CodeModeReplBlobRefTable) + .where(eq(CodeModeReplBlobRefTable.session_id, input.sessionID)) + .all() + .pipe(Effect.orDie)).map((row) => row.hash), + ) + const added = [...nextKeys].filter((hash) => !prevKeys.has(hash)) + const removed = [...prevKeys].filter((hash) => !nextKeys.has(hash)) + + for (const batch of DatabaseBatch.batches(added, 2)) { + yield* tx + .insert(CodeModeReplBlobRefTable) + .values(batch.map((hash) => ({ session_id: input.sessionID, hash }))) + .onConflictDoNothing() + .run() + .pipe(Effect.orDie) + } + for (const batch of DatabaseBatch.batches(removed, 1)) { + yield* tx + .delete(CodeModeReplBlobRefTable) + .where( + and( + eq(CodeModeReplBlobRefTable.session_id, input.sessionID), + inArray(CodeModeReplBlobRefTable.hash, batch), + ), + ) + .run() + .pipe(Effect.orDie) + } + if (removed.length > 0) yield* deleteOrphanBlobs(tx as unknown as DB, removed) + }), + ) + .pipe(Effect.orDie) + input.store.pending.clear() + input.store.committedRefs = nextKeys + return WARM_SESSION_OVERHEAD_BYTES + input.raw.byteLength +}) + +const unloadCold = (entry: WarmEntry) => + Effect.gen(function* () { + const items = entry.session.bindings() + entry.cellCounter = Math.max(entry.cellCounter + 1, maxLastCell(items)) + if (entry.cellCounter <= UNLOAD_AFTER_CELLS) return + const cutoff = entry.cellCounter - UNLOAD_AFTER_CELLS + const stale = items.filter((item) => item.loaded && item.lastCell <= cutoff).map((item) => item.name) + if (stale.length === 0) return + yield* entry.session.unload(stale).pipe(Effect.ignore) + }) + +function evictIfNeeded(keep: SessionSchema.ID) { + let totalBytes = 0 + for (const entry of warm.values()) totalBytes += entry.bytes + for (const [id, entry] of [...warm.entries()]) { + if (warm.size <= MAX_WARM_SESSIONS && totalBytes <= MAX_WARM_BYTES) break + if (id === keep) continue + const lock = locks.get(id) + if (lock !== undefined && (lock.activeRunID !== undefined || lock.waiters > 0)) continue + // Every idle warm entry was already checkpointed at the end of its last cell; drop it without re-saving. + warm.delete(id) + totalBytes -= entry.bytes + dropLockIfIdle(id, lock) + } +} + +/** + * Wraps one REPL cell execution as a `CodeMode.Program` so `CodeModeTool.launch` runs it with the + * existing tool-call progress, permission nesting, file-diff tracking, and job machinery. + */ +export function program(input: { + readonly db: DB | undefined + readonly sessionID: SessionSchema.ID + readonly messageID: SessionMessage.ID | undefined + readonly runID: string + readonly runtime: CodeMode.Runtime + readonly extensions: ReadonlyArray + readonly modeKey: string + readonly code: string + readonly bindings: Readonly> | undefined + readonly onFooter?: (footer: string) => void + readonly onParseError?: (error: CodeMode.Diagnostic) => CodeMode.Diagnostic +}): CodeMode.Program { + return { + run: () => + Effect.suspend(() => { + const lock = lockFor(input.sessionID) + lock.waiters++ + return lock.semaphore + .withPermit( + Effect.gen(function* () { + lock.activeRunID = input.runID + const startEpoch = lock.epoch + let resetNotice: string | undefined + + const acquire = Effect.gen(function* () { + const cached = warm.get(input.sessionID) + if (cached !== undefined && cached.epoch === startEpoch) { + if (cached.runtime === input.runtime && cached.modeKey === input.modeKey) return cached + const priorNames = cached.session.bindings().map((item) => item.name) + if (cached.modeKey === input.modeKey) { + // Tool inventory changed (e.g. MCP added/removed): transfer state onto the new runtime. + yield* cached.session.unload().pipe(Effect.ignore) + const saved = yield* cached.session.save().pipe(Effect.option) + if (saved._tag === "Some") { + const restored = yield* input.runtime.experimental + .restore(saved.value, { extensions: input.extensions, store: cached.store.store }) + .pipe(Effect.option) + if (restored._tag === "Some") { + const next: WarmEntry = { + session: restored.value as unknown as CodeMode.Session, + runtime: input.runtime, + modeKey: input.modeKey, + store: cached.store, + bytes: cached.bytes, + cellCounter: cached.cellCounter, + epoch: startEpoch, + } + touchWarm(input.sessionID, next) + return next + } + } + } + warm.delete(input.sessionID) + if (input.db !== undefined) yield* deletePersisted(input.db, input.sessionID) + resetNotice = resetMessage("runtime configuration changed", priorNames) + } + + if (input.db !== undefined) { + const row = yield* input.db + .select() + .from(CodeModeReplSessionTable) + .where(eq(CodeModeReplSessionTable.session_id, input.sessionID)) + .get() + .pipe(Effect.orDie) + if (row !== undefined) { + if (row.mode_key.startsWith(RESET_PREFIX)) { + yield* deletePersisted(input.db, input.sessionID) + resetNotice = resetMessage(row.mode_key.slice(RESET_PREFIX.length), row.binding_names) + } else { + const tracked = makeStore(input.db, undefined) + const raw = yield* Effect.try(() => decompress(row.root_blob)).pipe(Effect.option) + const restored = + raw._tag === "Some" && row.mode_key === input.modeKey + ? yield* input.runtime.experimental + .restore(raw.value, { extensions: input.extensions, store: tracked.store }) + .pipe(Effect.option) + : { _tag: "None" as const } + if (restored._tag === "Some") { + const session = restored.value as unknown as CodeMode.Session + const next: WarmEntry = { + session, + runtime: input.runtime, + modeKey: input.modeKey, + store: tracked, + bytes: WARM_SESSION_OVERHEAD_BYTES + row.bytes, + cellCounter: maxLastCell(session.bindings()), + epoch: startEpoch, + } + touchWarm(input.sessionID, next) + return next + } + yield* deletePersisted(input.db, input.sessionID) + const reason = + raw._tag !== "Some" + ? "saved state unreadable" + : row.mode_key === input.modeKey + ? "runtime updated" + : "runtime configuration changed" + resetNotice = resetMessage(reason, row.binding_names) + } + } + } + + const tracked = makeStore(input.db, new Set()) + const fresh: WarmEntry = { + session: input.runtime.experimental.session(undefined, { + extensions: input.extensions, + runId: input.runID, + store: tracked.store, + }) as unknown as CodeMode.Session, + runtime: input.runtime, + modeKey: input.modeKey, + store: tracked, + bytes: WARM_SESSION_OVERHEAD_BYTES, + cellCounter: 0, + epoch: startEpoch, + } + touchWarm(input.sessionID, fresh) + return fresh + }) + + const entry = yield* acquire + const typedSession = entry.session as unknown as CodeMode.Session + const rawResult = yield* typedSession.eval(input.code, input.bindings, { runId: input.runID }) + const result: CodeMode.Result = + !rawResult.ok && input.onParseError !== undefined + ? { ...rawResult, error: input.onParseError(rawResult.error) } + : rawResult + + // Only commit if the session wasn't forgotten/reverted/deleted while the cell ran. + if (lock.epoch === startEpoch) { + yield* unloadCold(entry) + const snapshot = yield* entry.session.save().pipe(Effect.option) + if (snapshot._tag === "Some") { + const raw = CodeMode.toBytes(snapshot.value) + if (input.db === undefined) { + entry.bytes = WARM_SESSION_OVERHEAD_BYTES + raw.byteLength + } else { + const message = + input.messageID === undefined + ? undefined + : yield* input.db + .select({ seq: SessionMessageTable.seq }) + .from(SessionMessageTable) + .where( + and( + eq(SessionMessageTable.session_id, input.sessionID), + eq(SessionMessageTable.id, input.messageID), + ), + ) + .get() + .pipe(Effect.orDie) + entry.bytes = yield* saveRow(input.db, { + sessionID: input.sessionID, + modeKey: input.modeKey, + visibleSeq: message?.seq ?? 0, + raw, + bindings: entry.session.bindings(), + store: entry.store, + }) + } + } + touchWarm(input.sessionID, entry) + if (resetNotice !== undefined) input.onFooter?.(resetNotice) + evictIfNeeded(input.sessionID) + } + + return result + }), + ) + .pipe( + Effect.ensuring( + Effect.sync(() => { + lock.waiters-- + if (lock.activeRunID === input.runID) lock.activeRunID = undefined + if (lock.backgroundRunID === input.runID) lock.backgroundRunID = undefined + dropLockIfIdle(input.sessionID, lock) + }), + ), + ) + }), + suspend: () => + Effect.fail( + new CodeMode.SuspendError({ + message: "Session REPL cells cannot suspend mid-run yet; state up to the last completed cell is saved.", + running: [], + }), + ), + } +} \ No newline at end of file diff --git a/packages/core/src/codemode/sql.ts b/packages/core/src/codemode/sql.ts new file mode 100644 index 0000000000000..bcf07e8e64710 --- /dev/null +++ b/packages/core/src/codemode/sql.ts @@ -0,0 +1,43 @@ +import { blob, index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core" +import type { SessionSchema } from "../session/schema.js" +import { SessionTable } from "../session/sql.js" + +/** + * Latest persisted idle Code Mode REPL root snapshot per session. + * Unloaded top-level bindings live in `codemode_repl_blob` and are referenced via `codemode_repl_blob_ref`. + */ +export const CodeModeReplSessionTable = sqliteTable("codemode_repl_session", { + session_id: text() + .$type() + .primaryKey() + .references(() => SessionTable.id, { onDelete: "cascade" }), + mode_key: text().notNull(), + visible_seq: integer().notNull(), + root_blob: blob({ mode: "buffer" }).notNull(), + bytes: integer().notNull(), + binding_names: text({ mode: "json" }).notNull().$type>(), + time_updated: integer().notNull(), +}) + +/** Content-addressed compressed blobs written by the REPL `SessionStore` (SHA-256 hex key of uncompressed bytes). */ +export const CodeModeReplBlobTable = sqliteTable("codemode_repl_blob", { + hash: text().primaryKey(), + bytes: integer().notNull(), + data: blob({ mode: "buffer" }).notNull(), +}) + +/** Reference links between a session's saved REPL snapshot and its unloaded blobs (shared zero-copy across forks). */ +export const CodeModeReplBlobRefTable = sqliteTable( + "codemode_repl_blob_ref", + { + session_id: text() + .$type() + .notNull() + .references(() => SessionTable.id, { onDelete: "cascade" }), + hash: text().notNull(), + }, + (table) => [ + primaryKey({ columns: [table.session_id, table.hash] }), + index("codemode_repl_blob_ref_hash_idx").on(table.hash), + ], +) \ No newline at end of file diff --git a/packages/core/src/codemode/tool.ts b/packages/core/src/codemode/tool.ts index b145f97abc998..cde42fba340b2 100644 --- a/packages/core/src/codemode/tool.ts +++ b/packages/core/src/codemode/tool.ts @@ -45,6 +45,8 @@ import { CodeModeJob } from "./job.js" import type { ServerHandoff } from "./handoff-signal.js" import { CodeModeInputBlocks } from "./input-blocks.js" import { CodeModePath } from "./path.js" +import type { Database } from "../database/database.js" +import { CodeModeRepl } from "./repl.js" import { CodeModeSnapshots } from "./snapshots.js" const ExecuteFile = Schema.Struct({ @@ -143,7 +145,7 @@ export const Parent = Context.Reference("@opencode/CodeModeT * How a request runs Code Mode, decided once by its caller: `full` (`full_codemode`) adds the `path` and `Bun` globals * and the `timeout` and `background` inputs, `agents` (`codemode_agents`) adds agent() and llm(). */ -export type Mode = { readonly full: boolean; readonly agents: boolean } +export type Mode = { readonly full: boolean; readonly agents: boolean; readonly repl?: boolean } export const plain: Mode = { full: false, agents: false } @@ -212,13 +214,15 @@ const executionServices = ( // Invariant model-facing guidance; the changing tool catalog is delivered through Instructions. With `full_codemode`, // the runtime also has Bun's file APIs. -const description = (full: boolean) => +const description = (full: boolean, repl: boolean) => [ full ? "Run JavaScript in a confined Code Mode runtime to work with files and data, script tool calls and HTTP requests, and compose their results." : "Run JavaScript in a confined Code Mode runtime to script tool calls and HTTP requests and compose their results.", "Write plain JavaScript and send it exactly as written: no code fence, and no JSON or other wrapper around it.", - "Each call is a fresh program; nothing carries over from earlier calls.", + repl + ? "This is a persistent JavaScript REPL: top-level variables, functions, and classes persist across calls (and can be redeclared), so keep data you'll reuse in variables instead of re-reading files or re-running commands." + : "Each call is a fresh program; nothing carries over from earlier calls.", full ? "`fetch` is available for HTTP requests, and Bun's file APIs (`Bun.file`, `Bun.write`, `Bun.Glob`) for files, in place of Node's `fs`. Imports and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`." : "`fetch` is available for HTTP requests. Imports, direct filesystem access, and timers are unavailable: there is no `setTimeout` or sleep. All other external access goes through `tools`.", @@ -598,6 +602,8 @@ export const create = ( durable?: Durable, /** The process's handoff signal: while a handoff is in flight, no new full script starts. */ handoff?: ServerHandoff.Interface, + /** Database for persisting session REPL state when `mode.repl` is enabled. */ + db?: Database.Interface["db"], ) => { // Stops the inner durable work a saved run still had in flight, as its own abort would: through the registry runner, // so the tool's cancel runs with the call's ID and span. A failure is dropped, since the run is gone either way. @@ -605,7 +611,13 @@ export const create = ( cancelWork({ state, context, tools: inventory.tools, durable }) // Runs a program, or a saved one resumed with its rows, in a fiber of its own that outlives the call that started it. - const launch = (runID: string, context: ToolContext, run: CodeMode.Program, restored?: RunState) => + const launch = ( + runID: string, + context: ToolContext, + run: CodeMode.Program, + restored?: RunState, + footer?: () => string | undefined, + ) => Effect.gen(function* () { const callIndex = yield* Ref.make(restored?.callIndex ?? 0) const files = yield* Ref.make>( @@ -774,7 +786,9 @@ export const create = ( const collected = (yield* Ref.get(files)) .toSorted((left, right) => left.index - right.index) .flatMap((item) => item.files) - const output = formatResult(executed, toolCalls) + const formatted = formatResult(executed, toolCalls) + const note = footer?.() + const output = note === undefined || note.length === 0 ? formatted : formatted.length === 0 ? note : `${formatted}\n${note}` const value: typeof ExecuteOutput.Type = { output, toolCalls, @@ -896,6 +910,40 @@ export const create = ( // Inside a Code Mode job the run is the job, so a handoff's snapshot is found again by its ID. Another // blocking job (a subagent, say) still gets a fresh run ID. const runID = (yield* CodeModeJob.RunID) ?? `cmr_${Identifier.ascending()}` + if (mode.full && mode.repl === true) { + const busy = CodeModeRepl.backgroundRun(context.sessionID) + if (busy !== undefined && busy !== runID) { + return yield* new ToolError({ + message: `The session REPL is busy running background job ${busy}. Wait for it to finish or cancel it before running another script.`, + }) + } + const blocks = CodeModeInputBlocks.parse(code) + if (!blocks.ok) return { runID, failed: formatResult({ ok: false, error: blocks.error, toolCalls: [] }, []) } + let footer: string | undefined + const selected = runExtensions(mode) + yield* launch( + runID, + context, + CodeModeRepl.program({ + db, + sessionID: context.sessionID, + messageID: context.messageID, + runID, + runtime: runtime(inventory), + extensions: selected, + modeKey: `full:${mode.agents ? "agents" : "plain"}`, + code: blocks.code, + bindings: blocks.inputs && { inputs: blocks.inputs }, + onFooter: (text) => { + footer = text + }, + onParseError: (error) => CodeModeInputBlocks.explain(blocks, error), + }), + undefined, + () => footer, + ) + return { runID } + } const program = prepare(code) if (!program.ok) return { runID, failed: formatResult({ ok: false, error: program.error, toolCalls: [] }, []) } yield* launch( @@ -914,7 +962,7 @@ export const create = ( const created = { name: "execute", - description: description(mode.full), + description: description(mode.full, mode.full && mode.repl === true), input: mode.full ? FullInput : CodeMode.Input, freeform: { type: "text", field: "code" }, output: ExecuteOutput, diff --git a/packages/core/src/database/migration.gen.ts b/packages/core/src/database/migration.gen.ts index 91c6ea920095d..d53b7a91d0b3a 100644 --- a/packages/core/src/database/migration.gen.ts +++ b/packages/core/src/database/migration.gen.ts @@ -69,6 +69,7 @@ import m66 from "./migration/20261201211559_inbox_wake_on_restart.js" import m67 from "./migration/20261202041631_blob_hash.js" import m68 from "./migration/20261202051500_blob_hash_cleanup.js" import m69 from "./migration/20261203211648_session_parent_time_updated.js" +import m70 from "./migration/20261206024613_codemode_repl.js" export const migrations = [ m00, @@ -141,4 +142,5 @@ export const migrations = [ m67, m68, m69, + m70, ] satisfies DatabaseMigration.Migration[] diff --git a/packages/core/src/database/migration/20261206024613_codemode_repl.ts b/packages/core/src/database/migration/20261206024613_codemode_repl.ts new file mode 100644 index 0000000000000..c8539ad42fd8e --- /dev/null +++ b/packages/core/src/database/migration/20261206024613_codemode_repl.ts @@ -0,0 +1,37 @@ +import type { DatabaseMigration } from "../migration.js" + +const migration: DatabaseMigration.Migration = { + id: "20261206024613_codemode_repl", + statements: [ + ` + CREATE TABLE \`codemode_repl_blob_ref\` ( + \`session_id\` text NOT NULL, + \`hash\` text NOT NULL, + CONSTRAINT \`codemode_repl_blob_ref_pk\` PRIMARY KEY(\`session_id\`, \`hash\`), + CONSTRAINT \`fk_codemode_repl_blob_ref_session_id_session_v2_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session_v2\`(\`id\`) ON DELETE CASCADE + ); + `, + ` + CREATE TABLE \`codemode_repl_blob\` ( + \`hash\` text PRIMARY KEY, + \`bytes\` integer NOT NULL, + \`data\` blob NOT NULL + ); + `, + ` + CREATE TABLE \`codemode_repl_session\` ( + \`session_id\` text PRIMARY KEY, + \`mode_key\` text NOT NULL, + \`visible_seq\` integer NOT NULL, + \`root_blob\` blob NOT NULL, + \`bytes\` integer NOT NULL, + \`binding_names\` text NOT NULL, + \`time_updated\` integer NOT NULL, + CONSTRAINT \`fk_codemode_repl_session_session_id_session_v2_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session_v2\`(\`id\`) ON DELETE CASCADE + ); + `, + `CREATE INDEX \`codemode_repl_blob_ref_hash_idx\` ON \`codemode_repl_blob_ref\` (\`hash\`);`, + ], +} + +export default migration diff --git a/packages/core/src/database/schema.gen.ts b/packages/core/src/database/schema.gen.ts index 325f036eee718..1bbf2c9395be8 100644 --- a/packages/core/src/database/schema.gen.ts +++ b/packages/core/src/database/schema.gen.ts @@ -79,6 +79,33 @@ const schema: Omit = { \`time_updated\` integer NOT NULL ); `) + yield* tx.run(` + CREATE TABLE \`codemode_repl_blob_ref\` ( + \`session_id\` text NOT NULL, + \`hash\` text NOT NULL, + CONSTRAINT \`codemode_repl_blob_ref_pk\` PRIMARY KEY(\`session_id\`, \`hash\`), + CONSTRAINT \`fk_codemode_repl_blob_ref_session_id_session_v2_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session_v2\`(\`id\`) ON DELETE CASCADE + ); + `) + yield* tx.run(` + CREATE TABLE \`codemode_repl_blob\` ( + \`hash\` text PRIMARY KEY, + \`bytes\` integer NOT NULL, + \`data\` blob NOT NULL + ); + `) + yield* tx.run(` + CREATE TABLE \`codemode_repl_session\` ( + \`session_id\` text PRIMARY KEY, + \`mode_key\` text NOT NULL, + \`visible_seq\` integer NOT NULL, + \`root_blob\` blob NOT NULL, + \`bytes\` integer NOT NULL, + \`binding_names\` text NOT NULL, + \`time_updated\` integer NOT NULL, + CONSTRAINT \`fk_codemode_repl_session_session_id_session_v2_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session_v2\`(\`id\`) ON DELETE CASCADE + ); + `) yield* tx.run(` CREATE TABLE \`credential\` ( \`id\` text PRIMARY KEY, @@ -350,6 +377,7 @@ const schema: Omit = { yield* tx.run( `CREATE INDEX \`blob_v2_session_idx\` ON \`blob_v2\` (\`session_id\`,\`time_created\`) WHERE "blob_v2"."session_id" is not null;`, ) + yield* tx.run(`CREATE INDEX \`codemode_repl_blob_ref_hash_idx\` ON \`codemode_repl_blob_ref\` (\`hash\`);`) yield* tx.run(`CREATE UNIQUE INDEX \`event_aggregate_seq_idx\` ON \`event\` (\`aggregate_id\`,\`seq\`);`) yield* tx.run(`CREATE INDEX \`event_aggregate_type_seq_idx\` ON \`event\` (\`aggregate_id\`,\`type\`,\`seq\`);`) yield* tx.run(`CREATE INDEX \`job_session_idx\` ON \`job\` (\`session_id\`);`) diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts index 7fc50a27a5dbd..b088edbffdb6a 100644 --- a/packages/core/src/session.ts +++ b/packages/core/src/session.ts @@ -47,6 +47,7 @@ import { } from "./session/error.js" import { Node } from "@opencode/util/effect/app-node" import { LayerNode } from "@opencode/util/effect/layer-node" +import { CodeModeRepl } from "./codemode/repl.js" import { SessionEvent } from "./session/event.js" import { SessionInbox } from "./session/inbox.js" import { InstructionState } from "./session/instruction-state.js" @@ -574,7 +575,12 @@ const layer = Layer.effect( synthetic: (input) => sessions.forSession(input.sessionID).synthetic(input), interrupt: (sessionID, options) => sessions.forSession(sessionID).interrupt(options), revert: { - stage: (input) => sessions.forSession(input.sessionID).revert.stage(input), + stage: (input) => + Effect.gen(function* () { + const backgroundRepl = CodeModeRepl.backgroundRun(input.sessionID) + if (backgroundRepl !== undefined) yield* jobs.cancel(backgroundRepl) + return yield* sessions.forSession(input.sessionID).revert.stage(input) + }), clear: (sessionID) => sessions.forSession(sessionID).revert.clear(), commit: (sessionID) => sessions.forSession(sessionID).revert.commit(), }, diff --git a/packages/core/src/session/context.ts b/packages/core/src/session/context.ts index 27fd0e9bc5af1..526841b277052 100644 --- a/packages/core/src/session/context.ts +++ b/packages/core/src/session/context.ts @@ -170,22 +170,25 @@ const layer = Layer.effect( if (!agent.info) return yield* new AgentNotFoundError({ sessionID: session.id, agent: session.agent ?? agent.id }) // Session permissions narrow discovery the same way they narrow the tool snapshot. const policy = Permission.Policy.fromRules(agent.info.permissions, session.permissions ?? []) - const [selected, hasWebSearch, fullCodeMode, opencodeApi, agentsFlag, agentsImplementation] = yield* Effect.all( - [ - models.select(session, model.available).pipe(Effect.orElseSucceed(() => undefined)), - websearch.available(), - flags.enabled("full_codemode"), - flags.enabled("opencode_api"), - flags.enabled("codemode_agents"), - agentRunner.current, - ], - { concurrency: "unbounded" }, - ) + const [selected, hasWebSearch, fullCodeMode, replFlag, opencodeApi, agentsFlag, agentsImplementation] = + yield* Effect.all( + [ + models.select(session, model.available).pipe(Effect.orElseSucceed(() => undefined)), + websearch.available(), + flags.enabled("full_codemode"), + flags.enabled("codemode_repl"), + flags.enabled("opencode_api"), + flags.enabled("codemode_agents"), + agentRunner.current, + ], + { concurrency: "unbounded" }, + ) // The flag alone isn't enough: the plugin that runs agent() and llm() registers only if it was on at startup. const codeModeAgents = agentsFlag && agentsImplementation !== undefined const fallbackRef = session.model ?? agent.info.model const policyModel = selected?.info ?? (fallbackRef && Model.Info.default(fallbackRef.providerID, fallbackRef.id)) - const mode = { full: fullCodeMode && Tool.codeModeAvailable(policy), agents: codeModeAgents } + const full = fullCodeMode && Tool.codeModeAvailable(policy) + const mode = { full, agents: codeModeAgents, ...(full && replFlag ? { repl: true } : {}) } const tools = yield* registry.snapshot(policy, { mode, services, diff --git a/packages/core/src/session/projector.ts b/packages/core/src/session/projector.ts index a981b7d4c464a..3a3557fe3ec01 100644 --- a/packages/core/src/session/projector.ts +++ b/packages/core/src/session/projector.ts @@ -30,6 +30,7 @@ import { Project } from "@opencode/schema/project" import { AbsolutePath, RelativePath } from "../schema.js" import type { SessionSchema } from "./schema.js" import { SessionHistory } from "./history.js" +import { CodeModeRepl } from "../codemode/repl.js" import { ProjectTable } from "../project/sql.js" type DatabaseService = Database.Interface["db"] @@ -317,6 +318,7 @@ const projectFork = Effect.fn("SessionProjector.projectFork")(function* ( cursor = rows.at(-1)!.seq } if (copiedSeq !== undefined) yield* Bus.reserveSequence(db, event.data.sessionID, copiedSeq) + yield* CodeModeRepl.fork(db, event.data.parentID, event.data.sessionID, copiedSeq) if (event.data.instructions) yield* InstructionState.initialize(db, event.data.sessionID, event.durable.seq, event.data.instructions) }) @@ -1034,6 +1036,7 @@ function projectSession(db: DatabaseService, event: SessionEvent.DurableEvent): case SessionEvent.Deleted.type: return Effect.gen(function* () { yield* SessionBlob.releaseSession(db, event.data.sessionID) + yield* CodeModeRepl.releaseSession(db, event.data.sessionID) yield* db.delete(SessionTable).where(eq(SessionTable.id, event.data.sessionID)).run().pipe(Effect.orDie) }) case SessionEvent.AgentSelected.type: @@ -1167,8 +1170,10 @@ function projectSession(db: DatabaseService, event: SessionEvent.DurableEvent): yield* InstructionState.advanceEpoch(db, event.data.sessionID, event.durable.seq) }) case SessionEvent.RevertEvent.Staged.type: + CodeModeRepl.forget(event.data.sessionID) return setSession(db, event.data.sessionID, { revert: event.data.revert, time_updated: event.created }) case SessionEvent.RevertEvent.Cleared.type: + CodeModeRepl.forget(event.data.sessionID) return setSession(db, event.data.sessionID, { revert: null, time_updated: event.created }) case SessionEvent.RevertEvent.Committed.type: return Effect.gen(function* () { @@ -1207,6 +1212,7 @@ function projectSession(db: DatabaseService, event: SessionEvent.DurableEvent): }) yield* InstructionState.rewind(db, event.data.sessionID, boundary.seq) yield* SessionBlob.releaseFrom(db, event.data.sessionID, boundary.seq) + yield* CodeModeRepl.releaseFrom(db, event.data.sessionID, boundary.seq) }) case SessionEvent.MessageContentUpdated.type: case SessionEvent.Synthetic.type: diff --git a/packages/core/src/session/session.ts b/packages/core/src/session/session.ts index 66ae063bbc869..b3b7932d9d44d 100644 --- a/packages/core/src/session/session.ts +++ b/packages/core/src/session/session.ts @@ -26,6 +26,7 @@ import { SessionExecution } from "./execution.js" import { SessionInbox } from "./inbox.js" import { SessionMessage } from "./message.js" import { SessionPrompt } from "./prompt.js" +import { CodeModeRepl } from "../codemode/repl.js" import { SessionRevert } from "./revert.js" import { SessionShell } from "./shell.js" import { SessionSkill } from "./skill.js" @@ -318,6 +319,7 @@ export const make = Effect.fn("Session.make")(function* () { ) { const session = yield* get(sessionID) if (yield* execution.isActive(sessionID)) return yield* new BusyError({ sessionID }) + CodeModeRepl.forget(sessionID) return yield* SessionRevert.stage({ session, messageID: input.messageID, files: input.files }).pipe( Effect.provideService(Instance.Service, instances), Effect.provideService(Database.Service, database), diff --git a/packages/core/src/tool.ts b/packages/core/src/tool.ts index 5c9b93c2093ed..b80922cd86e9c 100644 --- a/packages/core/src/tool.ts +++ b/packages/core/src/tool.ts @@ -40,6 +40,7 @@ import { ServerHandoff } from "./codemode/handoff-signal.js" import { CodeModeJob } from "./codemode/job.js" import { CodeModeSnapshotFile } from "./codemode/snapshot-file.js" import { CodeModeSnapshots } from "./codemode/snapshots.js" +import { Database } from "./database/database.js" import { CodeModeTool } from "./codemode/tool.js" import { Flag } from "./flag.js" import { Image } from "./image.js" @@ -196,6 +197,7 @@ const layer = Layer.effect( const bus = yield* Bus.Service const snapshots = yield* CodeModeSnapshots.Service const handoff = yield* ServerHandoff.Service + const database = Option.getOrUndefined(yield* Effect.serviceOption(Database.Service)) type NormalizedItem = Tool.Content | "decode" | "size" const normalizeImages = Effect.fnUntraced(function* (content: ReadonlyArray) { @@ -655,7 +657,7 @@ const layer = Layer.effect( const codemode = !codeModeEnabled ? undefined : (() => { - const key = `${mode.full ? "1" : "0"}\0${codemodeEntries.map(([name]) => name).join("\0")}` + const key = `${mode.full ? "1" : "0"}${mode.repl ? "1" : "0"}\0${codemodeEntries.map(([name]) => name).join("\0")}` // Discovery is immutable for a registry revision and visible tool set. Keep executors // fresh, but share the inventory, whose prepared runtime and much larger rendered catalog // are cached by identity, and the execute tool's definition across steps. @@ -679,6 +681,7 @@ const layer = Layer.effect( options?.agents, durableRunner(inventory.tools, reachable), handoff, + database?.db, ) const entry = cached ?? { inventory, diff --git a/packages/core/test/codemode/repl.test.ts b/packages/core/test/codemode/repl.test.ts new file mode 100644 index 0000000000000..9cc81c6d3d8e2 --- /dev/null +++ b/packages/core/test/codemode/repl.test.ts @@ -0,0 +1,315 @@ +import { describe, expect } from "bun:test" +import { CodeMode, Tool } from "@opencode/codemode" +import { Context, Effect, Exit, Layer, Schema } from "effect" +import { CodeModeRepl } from "@opencode/core/codemode/repl" +import { CodeModeReplBlobRefTable, CodeModeReplBlobTable, CodeModeReplSessionTable } from "@opencode/core/codemode/sql" +import { CodeModeTool } from "@opencode/core/codemode/tool" +import { Database } from "@opencode/core/database/database" +import { Project } from "@opencode/core/project" +import { ProjectTable } from "@opencode/core/project/sql" +import { AbsolutePath } from "@opencode/core/schema" +import { Session } from "@opencode/core/session" +import { SessionMessage } from "@opencode/core/session/message" +import { SessionMessageTable, SessionTable } from "@opencode/core/session/sql" +import { eq } from "drizzle-orm" +import { tempGlobalLayer } from "../fixture/global" +import { testEffect } from "../lib/effect" + +const it = testEffect(tempGlobalLayer) +const NOW = Date.parse("2026-12-05T12:00:00Z") + +const setupDb = Effect.gen(function* () { + const ctx = yield* Layer.build(Database.layer()) + const db = Context.get(ctx, Database.Service).db + yield* db + .insert(ProjectTable) + .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] }) + .run() + .pipe(Effect.orDie) + const insertSession = (id: Session.ID) => + db + .insert(SessionTable) + .values({ + id, + project_id: Project.ID.global, + slug: id, + directory: "/project", + version: "test", + time_created: NOW, + time_updated: NOW, + }) + .run() + .pipe(Effect.orDie) + const insertMessage = (sessionID: Session.ID, id: SessionMessage.ID, seq: number) => + db + .insert(SessionMessageTable) + .values({ + id, + session_id: sessionID, + seq, + type: "assistant", + data: {} as never, + time_created: NOW, + time_updated: NOW, + }) + .run() + .pipe(Effect.orDie) + return { db, insertSession, insertMessage } +}) + +const makeToolRuntime = (extra?: Record>) => + CodeMode.make({ + tools: { + ping: Tool.make({ + description: "ping", + input: Schema.Struct({ n: Schema.Number }), + output: Schema.Struct({ out: Schema.Number }), + execute: ({ n }) => Effect.succeed({ out: n + 1 }), + }), + ...extra, + }, + }) + +describe("CodeModeRepl", () => { + it.live("persists bindings across calls, unloads cold vars to SQLite blobs, and lazily restores after forget", () => + Effect.gen(function* () { + const { db, insertSession, insertMessage } = yield* setupDb + const sid = Session.ID.make("ses_repl_1") + const mid1 = SessionMessage.ID.make("msg_1") + yield* insertSession(sid) + yield* insertMessage(sid, mid1, 1) + const rt = makeToolRuntime() + + const run = (runID: string, code: string, messageID = mid1, runtime = rt) => + Effect.gen(function* () { + let footer: string | undefined + const outcome = yield* CodeModeRepl.program({ + db, + sessionID: sid, + messageID, + runID, + runtime, + extensions: [], + modeKey: "full:plain", + code, + bindings: undefined, + onFooter: (text) => { + footer = text + }, + }).run() + expect(outcome.ok).not.toBe("suspended") + return { outcome: outcome as CodeMode.Result, footer } + }) + + // Cell 1 declares a big string + closure using a tool. + const c1 = yield* run("r1", "const old = 'x'.repeat(20000); const fn = async () => old.length + (await tools.ping({ n: 4 })).out; old.length") + expect(c1.outcome).toMatchObject({ ok: true, value: 20000 }) + + // Advance past UNLOAD_AFTER_CELLS so `old` and `fn` spill into codemode_repl_blob. + for (let i = 2; i <= CodeModeRepl.UNLOAD_AFTER_CELLS + 2; i++) { + const res = yield* run(`r${i}`, `const v${i} = ${i}; v${i}`) + expect(res.outcome).toMatchObject({ ok: true, value: i }) + } + + const blobs = yield* db.select().from(CodeModeReplBlobTable).all().pipe(Effect.orDie) + const refs = yield* db + .select() + .from(CodeModeReplBlobRefTable) + .where(eq(CodeModeReplBlobRefTable.session_id, sid)) + .all() + .pipe(Effect.orDie) + expect(blobs.length).toBeGreaterThan(0) + expect(refs.length).toBe(blobs.length) + + // Simulate server restart by dropping warm in-memory interpreter. + CodeModeRepl.forget(sid) + const afterRestart = yield* run("r_after", "await fn()") + expect(afterRestart.outcome).toMatchObject({ ok: true, value: 20005 }) + expect(afterRestart.footer).toBeUndefined() + + // Inventory change (new tool added on a new Runtime) keeps all REPL bindings alive! + const rt2 = makeToolRuntime({ + pong: Tool.make({ + description: "pong", + input: Schema.Struct({}), + output: Schema.Struct({ ok: Schema.Boolean }), + execute: () => Effect.succeed({ ok: true }), + }), + }) + const swapped = yield* run("r_swap", "[old.length, (await tools.pong({})).ok]", mid1, rt2) + expect(swapped.outcome).toMatchObject({ ok: true, value: [20000, true] }) + expect(swapped.footer).toBeUndefined() + + // Fork shares blobs zero-copy and isolates subsequent mutations. + const forkID = Session.ID.make("ses_repl_fork") + yield* insertSession(forkID) + yield* CodeModeRepl.fork(db, sid, forkID, 1) + const blobsBeforeFork = blobs.length + + // Delete parent session; fork still owns the shared blobs! + yield* CodeModeRepl.releaseSession(db, sid) + const forkRow = yield* db + .select() + .from(CodeModeReplSessionTable) + .where(eq(CodeModeReplSessionTable.session_id, forkID)) + .get() + .pipe(Effect.orDie) + expect(forkRow).toBeDefined() + const forkRead = yield* CodeModeRepl.program({ + db, + sessionID: forkID, + messageID: undefined, + runID: "rf1", + runtime: rt2, + extensions: [], + modeKey: "full:plain", + code: "v2 + old.length", + bindings: undefined, + }).run() + expect(forkRead).toMatchObject({ ok: true, value: 20002 }) + expect(blobsBeforeFork).toBeGreaterThan(0) + + // Mid-history fork (before latest visible_seq) records a reset notice with zero copied blobs. + const earlyForkID = Session.ID.make("ses_repl_early_fork") + yield* insertSession(earlyForkID) + yield* CodeModeRepl.fork(db, forkID, earlyForkID, -1) + let earlyFooter: string | undefined + const earlyRead = yield* CodeModeRepl.program({ + db, + sessionID: earlyForkID, + messageID: undefined, + runID: "ref1", + runtime: rt2, + extensions: [], + modeKey: "full:plain", + code: "typeof old", + bindings: undefined, + onFooter: (text) => { + earlyFooter = text + }, + }).run() + expect(earlyRead).toMatchObject({ ok: true, value: "undefined" }) + expect(earlyFooter).toContain("[repl reset: forked before latest REPL state") + expect(earlyFooter).toContain("old") + + // Revert past visible_seq deletes unreferenced blobs AND reports a reset notice on the next call. + yield* CodeModeRepl.releaseFrom(db, forkID, 0) + const remainingBlobs = yield* db.select().from(CodeModeReplBlobTable).all().pipe(Effect.orDie) + expect(remainingBlobs).toHaveLength(0) + let revertFooter: string | undefined + const afterRevert = yield* CodeModeRepl.program({ + db, + sessionID: forkID, + messageID: undefined, + runID: "rf_after_revert", + runtime: rt2, + extensions: [], + modeKey: "full:plain", + code: "typeof old", + bindings: undefined, + onFooter: (text) => { + revertFooter = text + }, + }).run() + expect(afterRevert).toMatchObject({ ok: true, value: "undefined" }) + expect(revertFooter).toContain("[repl reset: session reverted") + expect(revertFooter).toContain("old") + yield* CodeModeRepl.releaseSession(db, forkID) + yield* CodeModeRepl.releaseSession(db, earlyForkID) + }).pipe(Effect.scoped), + ) + + it.live("resets cleanly with a notice when modeKey changes and preserves per-cell inputs scoping", () => + Effect.gen(function* () { + const { db, insertSession } = yield* setupDb + const sid = Session.ID.make("ses_repl_2") + yield* insertSession(sid) + const rt = makeToolRuntime() + + const r1 = yield* CodeModeRepl.program({ + db, + sessionID: sid, + messageID: undefined, + runID: "a1", + runtime: rt, + extensions: [], + modeKey: "full:plain", + code: "const keep = inputs.text; keep", + bindings: { inputs: { text: "hello" } }, + }).run() + expect(r1).toMatchObject({ ok: true, value: "hello" }) + + // Next cell sees `keep`, NOT `inputs`. + const r2 = yield* CodeModeRepl.program({ + db, + sessionID: sid, + messageID: undefined, + runID: "a2", + runtime: rt, + extensions: [], + modeKey: "full:plain", + code: "[keep, typeof inputs]", + bindings: undefined, + }).run() + expect(r2).toMatchObject({ ok: true, value: ["hello", "undefined"] }) + + // Mode key change resets cleanly and saves the new cell's binding. + let footer: string | undefined + const r3 = yield* CodeModeRepl.program({ + db, + sessionID: sid, + messageID: undefined, + runID: "a3", + runtime: rt, + extensions: [], + modeKey: "full:agents", + code: "const fresh = 7; [typeof keep, fresh]", + bindings: undefined, + onFooter: (text) => { + footer = text + }, + }).run() + expect(r3).toMatchObject({ ok: true, value: ["undefined", 7] }) + expect(footer).toContain("[repl reset:") + expect(footer).toContain("keep") + + CodeModeRepl.forget(sid) + const r4 = yield* CodeModeRepl.program({ + db, + sessionID: sid, + messageID: undefined, + runID: "a4", + runtime: rt, + extensions: [], + modeKey: "full:agents", + code: "fresh", + bindings: undefined, + }).run() + expect(r4).toMatchObject({ ok: true, value: 7 }) + + yield* CodeModeRepl.releaseSession(db, sid) + }).pipe(Effect.scoped), + ) + + it.live("keeps CodeModeTool.create stateless when repl flag is false and rejects mid-run suspend when true", () => + Effect.gen(function* () { + const sid = Session.ID.make("ses_repl_3") + const rt = makeToolRuntime() + const prog = CodeModeRepl.program({ + db: undefined, + sessionID: sid, + messageID: undefined, + runID: "s1", + runtime: rt, + extensions: [], + modeKey: "full:plain", + code: "1", + bindings: undefined, + }) + const suspended = yield* Effect.exit(prog.suspend()) + expect(Exit.isFailure(suspended)).toBe(true) + expect(CodeModeTool.plain.repl).toBeUndefined() + CodeModeRepl.forget(sid) + }), + ) +}) \ No newline at end of file diff --git a/packages/schema/src/config/flag.ts b/packages/schema/src/config/flag.ts index c9b2bdc2539b1..d8588532c8f83 100644 --- a/packages/schema/src/config/flag.ts +++ b/packages/schema/src/config/flag.ts @@ -16,6 +16,8 @@ export const registry = { model_speeds: "Offer a model's faster and slower service tiers (fast, flex…) as speeds of that model: one entry in the model picker with a speed selector, instead of a separate entry per tier such as gpt-5.5-fast.", full_codemode: "Enable the full Code Mode work in progress.", + codemode_repl: + "Keep Code Mode top-level declarations alive across execute calls within a session, persisted to SQLite with lazy unloading of cold bindings. Requires full_codemode; opt in explicitly.", codemode_agents: "Let Code Mode scripts start subagents with agent() and make single model calls with llm(), each optionally returning a value checked against a schema, so one script can fan work out, verify it and combine the results.", machines: "Let a tool path name a machine, as in gpu:/work/train.py, and act on that machine's files and processes.", @@ -41,7 +43,7 @@ export type Key = keyof typeof registry /** Flags the server reports to clients at `GET /api/experimental/flag`, so they can adapt their UI. */ export const ui: readonly Key[] = ["full_codemode"] -export const optInOnly: ReadonlySet = new Set(["todo"]) +export const optInOnly: ReadonlySet = new Set(["todo", "codemode_repl"]) /** Flags that stay off outside local and dev builds, whatever `OPENCODE_FLAGS` or config say. */ export const localOnly: ReadonlySet = new Set(["opencode_api", "google_ai_plan"])