Skip to content
Draft
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
4 changes: 2 additions & 2 deletions bun.lock

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

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.

2 changes: 1 addition & 1 deletion packages/codemode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"dependencies": {
"acorn": "8.15.0",
"effect": "catalog:",
"psychoscript": "0.11.0"
"psychoscript": "0.14.0"
},
"devDependencies": {
"@tsconfig/bun": "catalog:",
Expand Down
72 changes: 69 additions & 3 deletions packages/codemode/src/codemode/codemode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<R = never> = {
readonly eval: (
code: string,
bindings?: Readonly<Record<string, DataValue>>,
options?: { readonly runId?: string },
) => Effect.Effect<Result, SnapshotError, R>
readonly unload: (names?: ReadonlyArray<string>) => Effect.Effect<UnloadResult, SuspendError>
readonly save: (options?: SuspendOptions) => Effect.Effect<Snapshot, SuspendError>
readonly bindings: () => ReadonlyArray<SessionBinding>
}

/** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
export type Options<Provided extends Record<string, unknown> = {}, Extensions extends ReadonlyArray<Extension> = []> = {
/** Explicit tools exposed to the program as `tools`. */
Expand Down Expand Up @@ -208,6 +237,17 @@ export type Runtime<R = never> = {
* it can't be resumed here.
*/
readonly resume: (state: Snapshot | Uint8Array, options?: RunOptions) => Program<R, SnapshotError>
/** Experimental APIs that may change without compatibility guarantees. */
readonly experimental: {
readonly session: (
bindings?: Readonly<Record<string, DataValue>>,
options?: SessionOptions,
) => Session<R>
readonly restore: (
state: Snapshot | Uint8Array,
options?: RestoreSessionOptions,
) => Effect.Effect<Session<R>, SnapshotError>
}
}

/**
Expand Down Expand Up @@ -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,
),
},
}
}

Expand Down Expand Up @@ -456,10 +511,21 @@ const reported = <R, E>(program: Language.Program<R, E>): Program<R, E> => ({
})

// 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 = <R>(session: Language.Session<R>): Session<R> => ({
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 }
Expand Down
28 changes: 24 additions & 4 deletions packages/codemode/src/codemode/tool-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,11 +612,23 @@ const diagnosed = <A, R>(effect: Effect.Effect<A, unknown, R>) =>
* 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<string>
}

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`
Expand All @@ -631,19 +643,26 @@ export const beforeOnce = <Call, R>(
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<ToolCall> =>
metadata === null ? [] : (metadata as unknown as State).calls.map((call) => ({ name: call.name }))
export const toolCalls = (metadata: Json, runId?: string): Array<ToolCall> => {
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
Expand All @@ -656,14 +675,15 @@ export const globals = <R>(
run: Run,
maxToolCalls: number | undefined,
): { readonly tools: Host.Namespace<R>; readonly search: Host.Fn<R> } => {
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<string, ToolInvocation>()
const root = prepared.root

// 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(
Expand Down
7 changes: 7 additions & 0 deletions packages/codemode/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading
Loading