| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208 |
- import { describe, expect } from "bun:test"
- import {
- LLMClient,
- LLMError,
- LLMEvent,
- Model,
- Tool,
- TransportReason,
- type LLMClientShape,
- type LLMRequest,
- } from "@opencode-ai/llm"
- import * as OpenAIChat from "@opencode-ai/llm/protocols/openai-chat"
- import { Database } from "@opencode-ai/core/database/database"
- import { EventV2 } from "@opencode-ai/core/event"
- import { PermissionV2 } from "@opencode-ai/core/permission"
- import { EventTable } from "@opencode-ai/core/event/sql"
- import { Project } from "@opencode-ai/core/project"
- import { ProjectTable } from "@opencode-ai/core/project/sql"
- import { QuestionV2 } from "@opencode-ai/core/question"
- import { AbsolutePath } from "@opencode-ai/core/schema"
- import { SessionV2 } from "@opencode-ai/core/session"
- import { SessionEvent } from "@opencode-ai/core/session/event"
- import { SessionInput } from "@opencode-ai/core/session/input"
- import { SessionMessage } from "@opencode-ai/core/session/message"
- import { Prompt } from "@opencode-ai/core/session/prompt"
- import { SessionProjector } from "@opencode-ai/core/session/projector"
- import { SessionExecution } from "@opencode-ai/core/session/execution"
- import { SessionRunCoordinator } from "@opencode-ai/core/session/run-coordinator"
- import { SessionRunner } from "@opencode-ai/core/session/runner"
- import * as SessionRunnerLLM from "@opencode-ai/core/session/runner/llm"
- import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
- import { ToolRegistry } from "@opencode-ai/core/tool/registry"
- import { ApplicationTools } from "@opencode-ai/core/tool/application-tools"
- import { NativeTool } from "@opencode-ai/core/tool/native"
- import { SessionInputTable, SessionMessageTable, SessionTable } from "@opencode-ai/core/session/sql"
- import { SessionStore } from "@opencode-ai/core/session/store"
- import { ModelV2 } from "@opencode-ai/core/model"
- import { ProviderV2 } from "@opencode-ai/core/provider"
- import { Cause, DateTime, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect"
- import { asc, eq } from "drizzle-orm"
- import { testEffect } from "./lib/effect"
- const database = Database.layerFromPath(":memory:")
- const events = EventV2.layer.pipe(Layer.provide(database))
- const questions = QuestionV2.layer.pipe(Layer.provide(events))
- const projector = SessionProjector.layer.pipe(Layer.provide(events), Layer.provide(database))
- const store = SessionStore.layer.pipe(Layer.provide(database))
- const requests: LLMRequest[] = []
- let response: LLMEvent[] = []
- let responses: LLMEvent[][] | undefined
- let responseStream: Stream.Stream<LLMEvent, LLMError> | undefined
- let streamGate: Deferred.Deferred<void> | undefined
- let streamStarted: Deferred.Deferred<void> | undefined
- let streamFailure: LLMError | undefined
- let toolExecutionGate: Deferred.Deferred<void> | undefined
- let toolExecutionsStarted: Deferred.Deferred<void> | undefined
- let activeToolExecutions = 0
- let maxActiveToolExecutions = 0
- const client = Layer.succeed(
- LLMClient.Service,
- LLMClient.Service.of({
- prepare: () => Effect.die("unused"),
- stream: ((request: LLMRequest) => {
- requests.push(request)
- if (responseStream) {
- const stream = responseStream
- responseStream = undefined
- return stream
- }
- const events = streamFailure
- ? Stream.fail(streamFailure)
- : Stream.fromIterable(responses === undefined ? response : (responses.shift() ?? []))
- if (!streamGate) return events
- return Stream.unwrap(
- (streamStarted ? Deferred.succeed(streamStarted, undefined) : Effect.void).pipe(
- Effect.andThen(Deferred.await(streamGate)),
- Effect.as(events),
- ),
- )
- }) as unknown as LLMClientShape["stream"],
- generate: () => Effect.die("unused"),
- }),
- )
- const model = Model.make({ id: "fake-model", provider: "fake", route: OpenAIChat.route })
- const authorizations: ToolRegistry.AuthorizeInput[] = []
- const executions: string[] = []
- const permission = Layer.succeed(
- PermissionV2.Service,
- PermissionV2.Service.of({
- assert: () => Effect.die("unused"),
- ask: () => Effect.die("unused"),
- reply: () => Effect.die("unused"),
- get: () => Effect.die("unused"),
- forSession: () => Effect.die("unused"),
- list: () => Effect.die("unused"),
- }),
- )
- const applications = ApplicationTools.layer
- const registry = ToolRegistry.layer.pipe(Layer.provide(permission), Layer.provide(applications))
- const echo = Layer.effectDiscard(
- ToolRegistry.Service.use((registry) =>
- registry.contribute((editor) => {
- ;(editor.set("echo", {
- authorize: (input) =>
- Effect.sync(() => {
- authorizations.push(input)
- }),
- tool: Tool.make({
- description: "Echo text",
- parameters: Schema.Struct({ text: Schema.String }),
- success: Schema.Struct({ text: Schema.String }),
- toModelOutput: ({ output }) => [{ type: "text", text: output.text }],
- execute: ({ text }) =>
- Effect.gen(function* () {
- executions.push(text)
- activeToolExecutions++
- maxActiveToolExecutions = Math.max(maxActiveToolExecutions, activeToolExecutions)
- if (activeToolExecutions === 5 && toolExecutionsStarted) {
- yield* Deferred.succeed(toolExecutionsStarted, undefined)
- }
- if (toolExecutionGate) yield* Deferred.await(toolExecutionGate)
- return { text }
- }).pipe(Effect.ensuring(Effect.sync(() => activeToolExecutions--))),
- }),
- }),
- editor.set("defect", {
- tool: Tool.make({
- description: "Fail unexpectedly",
- parameters: Schema.Struct({}),
- success: Schema.Struct({}),
- execute: () => Effect.die("unexpected tool defect"),
- }),
- }))
- }),
- ),
- ).pipe(Layer.provide(registry))
- const models = SessionRunnerModel.layerWith(() => Effect.succeed(model))
- const runner = SessionRunnerLLM.layer.pipe(
- Layer.provide(database),
- Layer.provide(store),
- Layer.provide(events),
- Layer.provide(client),
- Layer.provide(registry),
- Layer.provide(models),
- )
- const coordinator = SessionRunCoordinator.layer.pipe(Layer.provide(runner))
- const execution = Layer.effect(
- SessionExecution.Service,
- SessionRunCoordinator.Service.pipe(
- Effect.map((coordinator) => SessionExecution.Service.of({ resume: coordinator.run, wake: coordinator.wake })),
- ),
- ).pipe(Layer.provide(coordinator))
- const sessions = SessionV2.layer.pipe(
- Layer.provide(events),
- Layer.provide(database),
- Layer.provide(store),
- Layer.provide(Project.defaultLayer),
- Layer.provide(execution),
- )
- const it = testEffect(
- Layer.mergeAll(
- database,
- events,
- questions,
- projector,
- store,
- client,
- permission,
- applications,
- registry,
- echo,
- models,
- runner,
- coordinator,
- execution,
- sessions,
- ),
- )
- const sessionID = SessionV2.ID.make("ses_runner_test")
- const otherSessionID = SessionV2.ID.make("ses_runner_other")
- const insertSession = (id: SessionV2.ID) =>
- Effect.gen(function* () {
- const { db } = yield* Database.Service
- yield* db
- .insert(SessionTable)
- .values({
- id,
- project_id: Project.ID.global,
- slug: id,
- directory: "/project",
- title: "test",
- version: "test",
- })
- .onConflictDoNothing()
- .run()
- .pipe(Effect.orDie)
- })
- const setup = Effect.gen(function* () {
- const { db } = yield* Database.Service
- response = []
- responses = undefined
- streamFailure = undefined
- responseStream = undefined
- streamGate = undefined
- streamStarted = undefined
- toolExecutionGate = undefined
- toolExecutionsStarted = undefined
- activeToolExecutions = 0
- maxActiveToolExecutions = 0
- yield* db
- .insert(ProjectTable)
- .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
- .onConflictDoNothing()
- .run()
- .pipe(Effect.orDie)
- yield* insertSession(sessionID)
- })
- const providerUnavailable = () =>
- new LLMError({
- module: "test",
- method: "stream",
- reason: new TransportReason({ message: "Provider unavailable" }),
- })
- const userTexts = (request: LLMRequest) =>
- request.messages.flatMap((message) =>
- message.role === "user"
- ? message.content.flatMap((content) => (content.type === "text" ? [content.text] : []))
- : [],
- )
- const replaySessionProjection = (id: SessionV2.ID) =>
- Effect.gen(function* () {
- const { db } = yield* Database.Service
- const events = yield* EventV2.Service
- const recorded = yield* db
- .select()
- .from(EventTable)
- .where(eq(EventTable.aggregate_id, id))
- .orderBy(asc(EventTable.seq))
- .all()
- .pipe(Effect.orDie)
- yield* events.remove(id)
- yield* db.delete(SessionInputTable).where(eq(SessionInputTable.session_id, id)).run().pipe(Effect.orDie)
- yield* db.delete(SessionMessageTable).where(eq(SessionMessageTable.session_id, id)).run().pipe(Effect.orDie)
- yield* events.replayAll(
- recorded.map((event) => ({
- id: event.id,
- aggregateID: event.aggregate_id,
- seq: event.seq,
- type: event.type,
- data: event.data,
- })),
- )
- })
- type FragmentKind = "text" | "reasoning" | "tool input"
- type FragmentFixture = {
- readonly delta: EventV2.Definition
- readonly completeEvents: LLMEvent[]
- readonly partialEvents: LLMEvent[]
- readonly expectedAssistant: unknown
- readonly expectedContent: unknown
- }
- const fragmentKinds: readonly FragmentKind[] = ["text", "reasoning", "tool input"]
- const fragmentID = (kind: FragmentKind, suffix: string) => `${kind === "tool input" ? "call" : kind}-${suffix}`
- const fragmentFixture = (kind: FragmentKind, id: string, chunks: readonly string[]): FragmentFixture => {
- const text = chunks.join("")
- switch (kind) {
- case "text": {
- const partialEvents = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.textStart({ id }),
- ...chunks.map((text) => LLMEvent.textDelta({ id, text })),
- ]
- const expectedContent = { type: "text", id, text }
- return {
- delta: SessionEvent.Text.Delta,
- partialEvents,
- completeEvents: [
- ...partialEvents,
- LLMEvent.textEnd({ id }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- expectedAssistant: { type: "assistant", finish: "stop", content: [expectedContent] },
- expectedContent,
- }
- }
- case "reasoning": {
- const partialEvents = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.reasoningStart({ id }),
- ...chunks.map((text) => LLMEvent.reasoningDelta({ id, text })),
- ]
- const expectedContent = { type: "reasoning", id, text }
- return {
- delta: SessionEvent.Reasoning.Delta,
- partialEvents,
- completeEvents: [
- ...partialEvents,
- LLMEvent.reasoningEnd({ id }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- expectedAssistant: { type: "assistant", finish: "stop", content: [expectedContent] },
- expectedContent,
- }
- }
- case "tool input": {
- const partialEvents = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolInputStart({ id, name: "echo" }),
- ...chunks.map((text) => LLMEvent.toolInputDelta({ id, name: "echo", text })),
- ]
- const expectedContent = { type: "tool", id, state: { status: "pending", input: text } }
- return {
- delta: SessionEvent.Tool.Input.Delta,
- partialEvents,
- completeEvents: [...partialEvents, LLMEvent.toolInputEnd({ id, name: "echo" })],
- expectedAssistant: { type: "assistant", content: [expectedContent] },
- expectedContent,
- }
- }
- }
- }
- const verifyEphemeralDeltas = (kind: FragmentKind) =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const prompt = `Stream ${kind}`
- const chunks = Array.from({ length: 32 }, (_, index) => `${index},`)
- const fixture = fragmentFixture(kind, fragmentID(kind, "many"), chunks)
- const expectedContext = [{ type: "user", text: prompt }, fixture.expectedAssistant]
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: prompt }), resume: false })
- const events = yield* EventV2.Service
- const live = yield* events.subscribe(fixture.delta).pipe(Stream.take(32), Stream.runCollect, Effect.forkScoped)
- yield* Effect.yieldNow
- response = fixture.completeEvents
- yield* session.resume(sessionID)
- const { db } = yield* Database.Service
- const deltas = yield* db
- .select({ type: EventTable.type })
- .from(EventTable)
- .where(eq(EventTable.type, EventV2.versionedType(fixture.delta.type, 1)))
- .all()
- .pipe(Effect.orDie)
- expect(Array.from(yield* Fiber.join(live))).toHaveLength(32)
- expect(deltas).toHaveLength(0)
- expect(yield* session.context(sessionID)).toMatchObject(expectedContext)
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject(expectedContext)
- })
- const verifyPartialFlushOnFailure = (kind: FragmentKind) =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const prompt = `Fail after ${kind}`
- const fixture = fragmentFixture(kind, fragmentID(kind, "partial"), ["Partial"])
- const failure = providerUnavailable()
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: prompt }), resume: false })
- responseStream = Stream.concat(Stream.fromIterable(fixture.partialEvents), Stream.fail(failure))
- expect(yield* session.resume(sessionID).pipe(Effect.flip)).toBe(failure)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: prompt },
- {
- type: "assistant",
- finish: "error",
- error: { type: "unknown", message: "Provider unavailable" },
- content: [fixture.expectedContent],
- },
- ])
- })
- const verifyPartialFlushOnInterruption = (kind: FragmentKind) =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const prompt = `Interrupt after ${kind}`
- const fixture = fragmentFixture(kind, fragmentID(kind, "interrupted"), ["Partial"])
- const streamed = yield* Deferred.make<void>()
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: prompt }), resume: false })
- responseStream = Stream.concat(
- Stream.fromIterable(fixture.partialEvents),
- Stream.fromEffect(Deferred.succeed(streamed, undefined)).pipe(Stream.flatMap(() => Stream.never)),
- )
- const runner = yield* SessionRunner.Service
- const fiber = yield* runner.run({ sessionID, force: true }).pipe(Effect.forkChild)
- yield* Deferred.await(streamed)
- yield* Fiber.interrupt(fiber)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: prompt },
- {
- type: "assistant",
- content: [
- kind === "tool input"
- ? { type: "tool", id: fragmentID(kind, "interrupted"), state: { status: "error" } }
- : fixture.expectedContent,
- ],
- },
- ])
- })
- describe("SessionRunnerLLM", () => {
- it.effect("advertises and executes a globally attached application tool", () =>
- Effect.gen(function* () {
- yield* setup
- const applicationTools = yield* ApplicationTools.Service
- const session = yield* SessionV2.Service
- const contexts: NativeTool.Context[] = []
- yield* applicationTools.attach({
- application_context: NativeTool.make({
- description: "Read application context",
- parameters: Schema.Struct({ query: Schema.String }),
- success: Schema.Struct({ answer: Schema.String }),
- execute: ({ query }, context) =>
- Effect.sync(() => {
- contexts.push(context)
- return { answer: query.toUpperCase() }
- }),
- }),
- })
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Use application context" }), resume: false })
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-application", name: "application_context", input: { query: "hello" } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [],
- ]
- yield* session.resume(sessionID)
- expect(requests[0]?.tools.map((tool) => tool.name)).toContain("application_context")
- expect(contexts).toEqual([{ sessionID, id: "call-application", name: "application_context" }])
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Use application context" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-application",
- state: { status: "completed", structured: { answer: "HELLO" } },
- },
- ],
- },
- ])
- }),
- )
- it.effect("starts a real runner turn after default prompt recording", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- requests.length = 0
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = []
- const message = yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Run automatically" }) })
- expect(requests).toHaveLength(1)
- expect(yield* session.messages({ sessionID })).toMatchObject([
- { id: message.id, type: "user", text: "Run automatically" },
- ])
- }),
- )
- it.effect("streams one request with registry definitions from chronological V2 user history", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "First" }), resume: false })
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Second" }), resume: false })
- requests.length = 0
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = []
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(requests[0]?.model).toBe(model)
- expect(requests[0]?.tools.map((tool) => tool.name)).toEqual(["echo", "defect"])
- expect(requests[0]?.messages.map((message) => ({ role: message.role, content: message.content }))).toEqual([
- { role: "user", content: [{ type: "text", text: "First" }] },
- { role: "user", content: [{ type: "text", text: "Second" }] },
- ])
- expect(yield* session.messages({ sessionID })).toHaveLength(2)
- }),
- )
- it.effect("projects reasoning and tool events without executing or continuing tools", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Use tools" }), resume: false })
- requests.length = 0
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.reasoningStart({ id: "reasoning-1" }),
- LLMEvent.reasoningDelta({ id: "reasoning-1", text: "Think" }),
- LLMEvent.reasoningEnd({ id: "reasoning-1" }),
- LLMEvent.toolInputStart({ id: "call-error", name: "write" }),
- LLMEvent.toolInputDelta({ id: "call-error", name: "write", text: '{"path":"README.md"}' }),
- LLMEvent.toolInputEnd({ id: "call-error", name: "write" }),
- LLMEvent.toolCall({ id: "call-error", name: "write", input: { path: "README.md" }, providerExecuted: true }),
- LLMEvent.toolError({ id: "call-error", name: "write", message: "Denied" }),
- LLMEvent.toolResult({ id: "call-error", name: "write", result: { type: "error", value: "Denied" } }),
- LLMEvent.toolCall({
- id: "call-provider",
- name: "web_search",
- input: { query: "hello" },
- providerExecuted: true,
- providerMetadata: { fake: { source: "provider" } },
- }),
- LLMEvent.toolResult({
- id: "call-provider",
- name: "web_search",
- result: {
- type: "content",
- value: [
- { type: "text", text: "Hello" },
- { type: "media", mediaType: "image/png", data: "data:image/png;base64,aGVsbG8=", filename: "hello.png" },
- ],
- },
- providerExecuted: true,
- providerMetadata: { fake: { source: "provider" } },
- }),
- LLMEvent.stepFinish({
- index: 0,
- reason: "tool-calls",
- usage: {
- inputTokens: 10,
- nonCachedInputTokens: 8,
- outputTokens: 4,
- reasoningTokens: 1,
- cacheReadInputTokens: 2,
- },
- }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(requests[0]?.tools.map((tool) => tool.name)).toEqual(["echo", "defect"])
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Use tools" },
- {
- type: "assistant",
- finish: "tool-calls",
- tokens: { input: 8, output: 3, reasoning: 1, cache: { read: 2, write: 0 } },
- content: [
- { type: "reasoning", id: "reasoning-1", text: "Think" },
- {
- type: "tool",
- id: "call-error",
- name: "write",
- state: {
- status: "error",
- input: { path: "README.md" },
- error: { type: "unknown", message: "Denied" },
- },
- },
- {
- type: "tool",
- id: "call-provider",
- name: "web_search",
- provider: { executed: true, metadata: { fake: { source: "provider" } } },
- state: {
- status: "completed",
- input: { query: "hello" },
- structured: {},
- content: [
- { type: "text", text: "Hello" },
- { type: "file", mime: "image/png", source: { type: "data", data: "aGVsbG8=" }, name: "hello.png" },
- ],
- },
- },
- ],
- },
- ])
- }),
- )
- it.effect("continues with reloaded history after durably settling one local tool call", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Echo this" }), resume: false })
- requests.length = 0
- authorizations.length = 0
- executions.length = 0
- streamGate = undefined
- streamStarted = undefined
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-echo", name: "echo", input: { text: "hello" } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.textStart({ id: "text-final" }),
- LLMEvent.textDelta({ id: "text-final", text: "Done" }),
- LLMEvent.textEnd({ id: "text-final" }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(2)
- expect(requests[1]?.messages.map((message) => message.role)).toEqual(["user", "assistant", "tool"])
- expect(authorizations).toMatchObject([{ sessionID, call: { id: "call-echo", name: "echo" } }])
- expect(executions).toEqual(["hello"])
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Echo this" },
- {
- type: "assistant",
- finish: "tool-calls",
- content: [
- {
- type: "tool",
- id: "call-echo",
- name: "echo",
- state: {
- status: "completed",
- input: { text: "hello" },
- structured: { text: "hello" },
- content: [{ type: "text", text: "hello" }],
- },
- },
- ],
- },
- { type: "assistant", finish: "stop", content: [{ type: "text", id: "text-final", text: "Done" }] },
- ])
- }),
- )
- it.effect("restores durable reasoning provider metadata in a second-turn request", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Think first" }), resume: false })
- requests.length = 0
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.reasoningStart({ id: "reasoning-anthropic" }),
- LLMEvent.reasoningDelta({ id: "reasoning-anthropic", text: "Signed thought" }),
- LLMEvent.reasoningEnd({ id: "reasoning-anthropic", providerMetadata: { anthropic: { signature: "sig_1" } } }),
- LLMEvent.reasoningStart({
- id: "reasoning-openai",
- providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: null } },
- }),
- LLMEvent.reasoningDelta({ id: "reasoning-openai", text: "Encrypted thought" }),
- LLMEvent.reasoningEnd({
- id: "reasoning-openai",
- providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
- }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ]
- yield* session.resume(sessionID)
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Think first" },
- {
- type: "assistant",
- content: [
- { type: "reasoning", text: "Signed thought", providerMetadata: { anthropic: { signature: "sig_1" } } },
- {
- type: "reasoning",
- text: "Encrypted thought",
- providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
- },
- ],
- },
- ])
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Continue" }), resume: false })
- response = []
- yield* session.resume(sessionID)
- expect(requests[1]?.messages[1]?.content).toEqual([
- { type: "reasoning", text: "Signed thought", providerMetadata: { anthropic: { signature: "sig_1" } } },
- {
- type: "reasoning",
- text: "Encrypted thought",
- providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
- },
- ])
- }),
- )
- it.effect("replays durable provider-executed tool results inline in a second-turn request", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Search first" }), resume: false })
- requests.length = 0
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({
- id: "hosted-search",
- name: "web_search",
- input: { query: "Effect" },
- providerExecuted: true,
- providerMetadata: { openai: { itemId: "hosted-search" } },
- }),
- LLMEvent.toolResult({
- id: "hosted-search",
- name: "web_search",
- result: { type: "json", value: [{ title: "Effect" }] },
- providerExecuted: true,
- providerMetadata: { anthropic: { blockType: "web_search_tool_result" } },
- }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ]
- yield* session.resume(sessionID)
- yield* replaySessionProjection(sessionID)
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Continue" }), resume: false })
- response = []
- yield* session.resume(sessionID)
- expect(requests[1]?.messages.map((message) => message.role)).toEqual(["user", "assistant", "user"])
- expect(requests[1]?.messages[1]?.content).toMatchObject([
- {
- type: "tool-call",
- id: "hosted-search",
- name: "web_search",
- input: { query: "Effect" },
- providerExecuted: true,
- providerMetadata: { openai: { itemId: "hosted-search" } },
- },
- {
- type: "tool-result",
- id: "hosted-search",
- name: "web_search",
- result: { type: "json", value: [{ title: "Effect" }] },
- providerExecuted: true,
- providerMetadata: { anthropic: { blockType: "web_search_tool_result" } },
- },
- ])
- }),
- )
- it.effect("starts recorded local tools eagerly and awaits settlement before continuing", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Echo five times" }), resume: false })
- requests.length = 0
- executions.length = 0
- toolExecutionGate = yield* Deferred.make<void>()
- toolExecutionsStarted = yield* Deferred.make<void>()
- const providerGate = yield* Deferred.make<void>()
- response = []
- responses = undefined
- const initial = Stream.fromIterable([
- LLMEvent.stepStart({ index: 0 }),
- ...Array.from({ length: 5 }, (_, index) =>
- LLMEvent.toolCall({ id: `call-echo-${index}`, name: "echo", input: { text: `${index}` } }),
- ),
- ])
- const final = Stream.fromIterable([
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ])
- streamGate = undefined
- responseStream = Stream.concat(
- initial,
- Stream.fromEffect(Deferred.await(providerGate)).pipe(Stream.flatMap(() => final)),
- )
- const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(toolExecutionsStarted)
- expect(executions).toHaveLength(5)
- expect(maxActiveToolExecutions).toBe(5)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Echo five times" },
- {
- type: "assistant",
- content: Array.from({ length: 5 }, (_, index) => ({
- type: "tool",
- id: `call-echo-${index}`,
- state: { status: "running", input: { text: `${index}` } },
- })),
- },
- ])
- yield* Deferred.succeed(providerGate, undefined)
- yield* Effect.yieldNow
- expect(requests).toHaveLength(1)
- yield* Deferred.succeed(toolExecutionGate, undefined)
- yield* Fiber.join(run)
- toolExecutionGate = undefined
- toolExecutionsStarted = undefined
- expect(executions).toHaveLength(5)
- expect(maxActiveToolExecutions).toBe(5)
- expect(requests).toHaveLength(2)
- }),
- )
- it.effect("settles repeated provider-local tool call IDs against their owning assistant messages", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Echo twice" }), resume: false })
- requests.length = 0
- executions.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "tool_0", name: "echo", input: { text: "first" } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "tool_0", name: "echo", input: { text: "second" } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [],
- ]
- yield* session.resume(sessionID)
- expect(executions).toEqual(["first", "second"])
- expect(requests).toHaveLength(3)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Echo twice" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "tool_0",
- state: { status: "completed", structured: { text: "first" }, content: [{ type: "text", text: "first" }] },
- },
- ],
- },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "tool_0",
- state: {
- status: "completed",
- structured: { text: "second" },
- content: [{ type: "text", text: "second" }],
- },
- },
- ],
- },
- ])
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Echo twice" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "tool_0",
- state: { status: "completed", structured: { text: "first" }, content: [{ type: "text", text: "first" }] },
- },
- ],
- },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "tool_0",
- state: {
- status: "completed",
- structured: { text: "second" },
- content: [{ type: "text", text: "second" }],
- },
- },
- ],
- },
- ])
- }),
- )
- it.effect("joins concurrent resume calls into one active provider run", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Run once" }), resume: false })
- requests.length = 0
- responses = undefined
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.textStart({ id: "text-once" }),
- LLMEvent.textDelta({ id: "text-once", text: "Once" }),
- LLMEvent.textEnd({ id: "text-once" }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ]
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- const second = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Effect.yieldNow
- expect(requests).toHaveLength(1)
- yield* Deferred.succeed(streamGate, undefined)
- yield* Fiber.join(first)
- yield* Fiber.join(second)
- streamGate = undefined
- streamStarted = undefined
- expect(requests).toHaveLength(1)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Run once" },
- { type: "assistant", finish: "stop", content: [{ type: "text", id: "text-once", text: "Once" }] },
- ])
- }),
- )
- it.effect("steers an active provider turn with newly recorded prompts", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start working" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Change direction" }) })
- yield* Deferred.succeed(streamGate, undefined)
- yield* Fiber.join(first)
- streamGate = undefined
- streamStarted = undefined
- yield* Effect.yieldNow
- expect(requests).toHaveLength(2)
- expect(userTexts(requests[0]!)).toEqual(["Start working"])
- expect(userTexts(requests[1]!)).toEqual(["Start working", "Change direction"])
- expect((yield* session.context(sessionID)).map((message) => message.type)).toEqual([
- "user",
- "assistant",
- "user",
- "assistant",
- ])
- }),
- )
- it.effect("starts queued input after the active activity settles", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start working" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-echo", name: "echo", input: { text: "hello" } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Wait until the next activity" }),
- delivery: "queue",
- })
- yield* Deferred.succeed(streamGate, undefined)
- yield* Fiber.join(first)
- streamGate = undefined
- streamStarted = undefined
- expect(requests).toHaveLength(3)
- expect(userTexts(requests[0]!)).toEqual(["Start working"])
- expect(userTexts(requests[1]!)).toEqual(["Start working"])
- expect(userTexts(requests[2]!)).toEqual(["Start working", "Wait until the next activity"])
- }),
- )
- it.effect("runs queued active inputs as separate FIFO activities", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start working" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Queue first" }), delivery: "queue" })
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Queue second" }), delivery: "queue" })
- yield* Deferred.succeed(streamGate, undefined)
- yield* Fiber.join(first)
- streamGate = undefined
- streamStarted = undefined
- expect(requests).toHaveLength(3)
- expect(userTexts(requests[0]!)).toEqual(["Start working"])
- expect(userTexts(requests[1]!)).toEqual(["Start working", "Queue first"])
- expect(userTexts(requests[2]!)).toEqual(["Start working", "Queue first", "Queue second"])
- }),
- )
- it.effect("opens queued input after idle steering activity settles", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start steering activity" }), resume: false })
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Queue later activity" }),
- delivery: "queue",
- resume: false,
- })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(2)
- expect(userTexts(requests[0]!)).toEqual(["Start steering activity"])
- expect(userTexts(requests[1]!)).toEqual(["Start steering activity", "Queue later activity"])
- }),
- )
- it.effect("coalesces steers into the active queued activity before starting the next queued activity", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start working" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- const firstGate = yield* Deferred.make<void>()
- const secondGate = yield* Deferred.make<void>()
- streamGate = firstGate
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- while (requests.length < 1) yield* Effect.yieldNow
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Queue first" }), delivery: "queue" })
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Queue second" }), delivery: "queue" })
- streamGate = secondGate
- yield* Deferred.succeed(firstGate, undefined)
- while (requests.length < 2) yield* Effect.yieldNow
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Steer first queued activity" }) })
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Also steer first queued activity" }) })
- yield* Deferred.succeed(secondGate, undefined)
- yield* Fiber.join(first)
- streamGate = undefined
- expect(requests).toHaveLength(4)
- expect(userTexts(requests[0]!)).toEqual(["Start working"])
- expect(userTexts(requests[1]!)).toEqual(["Start working", "Queue first"])
- expect(userTexts(requests[2]!)).toEqual([
- "Start working",
- "Queue first",
- "Steer first queued activity",
- "Also steer first queued activity",
- ])
- expect(userTexts(requests[3]!)).toEqual([
- "Start working",
- "Queue first",
- "Steer first queued activity",
- "Also steer first queued activity",
- "Queue second",
- ])
- }),
- )
- it.effect("coalesces multiple active steering prompts into one continuation turn", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start working" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "First steer" }) })
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Second steer" }) })
- yield* Deferred.succeed(streamGate, undefined)
- yield* Fiber.join(first)
- streamGate = undefined
- streamStarted = undefined
- yield* Effect.yieldNow
- expect(requests).toHaveLength(2)
- expect(userTexts(requests[1]!)).toEqual(["Start working", "First steer", "Second steer"])
- yield* (yield* SessionRunCoordinator.Service).wake(sessionID)
- yield* Effect.yieldNow
- expect(requests).toHaveLength(2)
- }),
- )
- it.effect("runs steering input accepted while the active provider turn fails", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Start working" }), resume: false })
- requests.length = 0
- responses = undefined
- response = []
- streamFailure = providerUnavailable()
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Recover with this" }) })
- yield* Deferred.succeed(streamGate, undefined)
- expect(yield* Fiber.join(first).pipe(Effect.flip)).toBe(streamFailure)
- streamFailure = undefined
- streamGate = undefined
- streamStarted = undefined
- yield* Effect.yieldNow
- expect(requests).toHaveLength(2)
- expect(userTexts(requests[1]!)).toEqual(["Start working", "Recover with this"])
- }),
- )
- it.effect("durably fails local tools left running by a prior process before continuing", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const events = yield* EventV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Recover interrupted tool" }), resume: false })
- yield* SessionInput.promoteSteers((yield* Database.Service).db, events, sessionID, Number.MAX_SAFE_INTEGER)
- const assistantMessageID = SessionMessage.ID.create()
- yield* events.publish(SessionEvent.Step.Started, {
- sessionID,
- assistantMessageID,
- timestamp: yield* DateTime.now,
- agent: "build",
- model: { id: ModelV2.ID.make("fake-model"), providerID: ProviderV2.ID.make("fake") },
- })
- yield* events.publish(SessionEvent.Tool.Input.Started, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-interrupted",
- name: "echo",
- })
- yield* events.publish(SessionEvent.Tool.Input.Ended, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-interrupted",
- text: '{"text":"stale"}',
- })
- yield* events.publish(SessionEvent.Tool.Called, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-interrupted",
- tool: "echo",
- input: { text: "stale" },
- provider: { executed: false },
- })
- requests.length = 0
- response = []
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(requests[0]?.messages.map((message) => message.role)).toEqual(["user", "assistant", "tool"])
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Recover interrupted tool" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-interrupted",
- state: { status: "error", error: { type: "unknown", message: "Tool execution interrupted" } },
- },
- ],
- },
- ])
- }),
- )
- it.effect("durably fails hosted tools left running by a prior process before continuing inline", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const events = yield* EventV2.Service
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Recover interrupted hosted tool" }),
- resume: false,
- })
- yield* SessionInput.promoteSteers((yield* Database.Service).db, events, sessionID, Number.MAX_SAFE_INTEGER)
- const assistantMessageID = SessionMessage.ID.create()
- yield* events.publish(SessionEvent.Step.Started, {
- sessionID,
- assistantMessageID,
- timestamp: yield* DateTime.now,
- agent: "build",
- model: { id: ModelV2.ID.make("fake-model"), providerID: ProviderV2.ID.make("fake") },
- })
- yield* events.publish(SessionEvent.Tool.Input.Started, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-hosted-interrupted",
- name: "web_search",
- })
- yield* events.publish(SessionEvent.Tool.Input.Ended, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-hosted-interrupted",
- text: '{"query":"stale"}',
- })
- yield* events.publish(SessionEvent.Tool.Called, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-hosted-interrupted",
- tool: "web_search",
- input: { query: "stale" },
- provider: { executed: true, metadata: { openai: { itemId: "call-hosted-interrupted" } } },
- })
- requests.length = 0
- response = []
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(requests[0]?.messages.map((message) => message.role)).toEqual(["user", "assistant"])
- expect(requests[0]?.messages[1]?.content).toMatchObject([
- {
- type: "tool-call",
- id: "call-hosted-interrupted",
- providerExecuted: true,
- providerMetadata: { openai: { itemId: "call-hosted-interrupted" } },
- },
- { type: "tool-result", id: "call-hosted-interrupted", providerExecuted: true, result: { type: "error" } },
- ])
- }),
- )
- it.effect("durably fails pending tool input left by a prior process before continuing", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const events = yield* EventV2.Service
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Recover interrupted tool input" }),
- resume: false,
- })
- yield* SessionInput.promoteSteers((yield* Database.Service).db, events, sessionID, Number.MAX_SAFE_INTEGER)
- const assistantMessageID = SessionMessage.ID.create()
- yield* events.publish(SessionEvent.Step.Started, {
- sessionID,
- assistantMessageID,
- timestamp: yield* DateTime.now,
- agent: "build",
- model: { id: ModelV2.ID.make("fake-model"), providerID: ProviderV2.ID.make("fake") },
- })
- yield* events.publish(SessionEvent.Tool.Input.Started, {
- sessionID,
- timestamp: yield* DateTime.now,
- assistantMessageID,
- callID: "call-pending-interrupted",
- name: "echo",
- })
- requests.length = 0
- response = []
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(requests[0]?.messages.map((message) => message.role)).toEqual(["user", "assistant", "tool"])
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Recover interrupted tool input" },
- { type: "assistant", content: [{ type: "tool", id: "call-pending-interrupted", state: { status: "error" } }] },
- ])
- }),
- )
- it.effect("starts the first queued activity when woken while idle", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Wait for fresh activity" }),
- delivery: "queue",
- resume: false,
- })
- requests.length = 0
- yield* (yield* SessionRunCoordinator.Service).wake(sessionID)
- yield* Effect.yieldNow
- expect(requests).toHaveLength(1)
- expect(userTexts(requests[0]!)).toEqual(["Wait for fresh activity"])
- }),
- )
- it.effect("does not spend one activity step budget across queued activities", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const queued = Array.from({ length: 26 }, (_, index) => `Queued activity ${index + 1}`)
- for (const text of queued) {
- yield* session.prompt({ sessionID, prompt: new Prompt({ text }), delivery: "queue", resume: false })
- }
- requests.length = 0
- responses = queued.map(() => [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ])
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(queued.length)
- expect(userTexts(requests.at(-1)!)).toEqual(queued)
- }),
- )
- it.effect("retries inbox input after prompt projection rolls back", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const events = yield* EventV2.Service
- const defect = new Error("fail after prompt promotion")
- let fail = true
- yield* events.project(SessionEvent.PromptLifecycle.Promoted, () => (fail ? Effect.die(defect) : Effect.void))
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Recover promoted input" }), resume: false })
- expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe(defect)
- fail = false
- requests.length = 0
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ]
- yield* (yield* SessionRunCoordinator.Service).wake(sessionID)
- while (requests.length === 0) yield* Effect.yieldNow
- expect(userTexts(requests[0]!)).toEqual(["Recover promoted input"])
- }),
- )
- it.effect("does not strand a committed promotion when a post-commit listener defects", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const events = yield* EventV2.Service
- yield* events.listen((event) =>
- event.type === SessionEvent.PromptLifecycle.Promoted.type
- ? Effect.die("fail after prompt promotion commits")
- : Effect.void,
- )
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Run committed promotion" }),
- resume: false,
- })
- requests.length = 0
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(userTexts(requests[0]!)).toEqual(["Run committed promotion"])
- }),
- )
- it.effect("runs different sessions concurrently", () =>
- Effect.gen(function* () {
- yield* setup
- yield* insertSession(otherSessionID)
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Run first" }), resume: false })
- yield* session.prompt({ sessionID: otherSessionID, prompt: new Prompt({ text: "Run second" }), resume: false })
- requests.length = 0
- responses = undefined
- response = []
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- const second = yield* session.resume(otherSessionID).pipe(Effect.forkChild)
- yield* Effect.yieldNow
- expect(requests).toHaveLength(2)
- yield* Deferred.succeed(streamGate, undefined)
- yield* Fiber.join(first)
- yield* Fiber.join(second)
- streamGate = undefined
- streamStarted = undefined
- }),
- )
- it.effect("fans out one failed run and allows a later retry", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Retry after failure" }), resume: false })
- requests.length = 0
- responses = undefined
- response = []
- streamFailure = providerUnavailable()
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- const second = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Effect.yieldNow
- expect(requests).toHaveLength(1)
- yield* Deferred.succeed(streamGate, undefined)
- const [firstExit, secondExit] = yield* Effect.all([Fiber.await(first), Fiber.await(second)])
- expect(secondExit).toEqual(firstExit)
- streamFailure = undefined
- streamGate = undefined
- streamStarted = undefined
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(2)
- }),
- )
- it.effect("durably settles local tool failures before continuing", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Call missing" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-missing", name: "missing", input: {} }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.textStart({ id: "text-after-error" }),
- LLMEvent.textDelta({ id: "text-after-error", text: "Recovered" }),
- LLMEvent.textEnd({ id: "text-after-error" }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- streamGate = undefined
- streamStarted = undefined
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(2)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Call missing" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-missing",
- state: { status: "error", error: { message: "Unknown tool: missing" } },
- },
- ],
- },
- { type: "assistant", finish: "stop", content: [{ type: "text", id: "text-after-error", text: "Recovered" }] },
- ])
- }),
- )
- it.effect("durably settles unexpected local tool defects before continuing", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Call defect" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-defect", name: "defect", input: {} }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [],
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(2)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Call defect" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-defect",
- state: { status: "error", error: { message: "unexpected tool defect" } },
- },
- ],
- },
- ])
- }),
- )
- it.effect("interrupts runner continuation when a question is dismissed", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const registry = yield* ToolRegistry.Service
- const questions = yield* QuestionV2.Service
- const transform = yield* registry.transform()
- yield* transform((editor) =>
- editor.set("question", {
- tool: Tool.make({
- description: "Ask the user",
- parameters: Schema.Struct({}),
- success: Schema.Struct({}),
- }),
- execute: ({ sessionID }) => questions.ask({ sessionID, questions: [] }).pipe(Effect.as({}), Effect.orDie),
- }),
- )
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Ask then stop" }), resume: false })
- requests.length = 0
- responses = [
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-question", name: "question", input: {} }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ],
- [],
- ]
- const run = yield* session.resume(sessionID).pipe(Effect.exit, Effect.forkChild)
- let pending = yield* questions.list()
- while (pending.length === 0) {
- yield* Effect.yieldNow
- pending = yield* questions.list()
- }
- yield* questions.reject(pending[0]!.id)
- const exit = yield* Fiber.join(run)
- expect(exit._tag).toBe("Failure")
- if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
- expect(requests).toHaveLength(1)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Ask then stop" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-question",
- state: { status: "error", error: { type: "unknown", message: "Tool execution interrupted" } },
- },
- ],
- },
- ])
- }),
- )
- it.effect("awaits started local tools before surfacing provider stream failure", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Settle before failing" }), resume: false })
- const failure = providerUnavailable()
- toolExecutionGate = yield* Deferred.make<void>()
- responseStream = Stream.concat(
- Stream.fromIterable([
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-before-failure", name: "echo", input: { text: "settle" } }),
- ]),
- Stream.fail(failure),
- )
- const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
- while (executions.length === 0) yield* Effect.yieldNow
- yield* Effect.yieldNow
- yield* Deferred.succeed(toolExecutionGate, undefined)
- expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
- toolExecutionGate = undefined
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Settle before failing" },
- {
- type: "assistant",
- content: [
- { type: "tool", id: "call-before-failure", state: { status: "completed", structured: { text: "settle" } } },
- ],
- },
- ])
- }),
- )
- it.effect("durably fails blocked local tools when a provider turn is interrupted", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Interrupt blocked tool" }), resume: false })
- executions.length = 0
- toolExecutionGate = yield* Deferred.make<void>()
- responseStream = Stream.concat(
- Stream.fromIterable([
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-before-interrupt", name: "echo", input: { text: "blocked" } }),
- ]),
- Stream.never,
- )
- const runner = yield* SessionRunner.Service
- const run = yield* runner.run({ sessionID, force: true }).pipe(Effect.forkChild)
- while (executions.length === 0) yield* Effect.yieldNow
- yield* Fiber.interrupt(run)
- toolExecutionGate = undefined
- expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Interrupt blocked tool" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-before-interrupt",
- state: { status: "error", error: { type: "unknown", message: "Tool execution interrupted" } },
- },
- ],
- },
- ])
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Interrupt blocked tool" },
- { type: "assistant", content: [{ type: "tool", id: "call-before-interrupt", state: { status: "error" } }] },
- ])
- requests.length = 0
- responseStream = undefined
- response = []
- yield* session.resume(sessionID)
- expect(requests[0]?.messages.map((message) => message.role)).toEqual(["user", "assistant", "tool"])
- }),
- )
- it.effect("durably fails blocked local tools when interrupted while awaiting settlement", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Interrupt tool settlement" }), resume: false })
- executions.length = 0
- toolExecutionGate = yield* Deferred.make<void>()
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-await-interrupt", name: "echo", input: { text: "blocked" } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ]
- const runner = yield* SessionRunner.Service
- const run = yield* runner.run({ sessionID, force: true }).pipe(Effect.forkChild)
- while (executions.length === 0) yield* Effect.yieldNow
- yield* Fiber.interrupt(run)
- toolExecutionGate = undefined
- expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Interrupt tool settlement" },
- {
- type: "assistant",
- content: [
- {
- type: "tool",
- id: "call-await-interrupt",
- state: { status: "error", error: { type: "unknown", message: "Tool execution interrupted" } },
- },
- ],
- },
- ])
- }),
- )
- it.effect("fails after the bounded number of local tool continuation steps", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Loop forever" }), resume: false })
- requests.length = 0
- authorizations.length = 0
- executions.length = 0
- streamGate = undefined
- streamStarted = undefined
- responses = Array.from({ length: 25 }, (_, index) => [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: `call-echo-${index}`, name: "echo", input: { text: `${index}` } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ])
- const failure = yield* session.resume(sessionID).pipe(Effect.flip)
- expect(failure).toMatchObject({ _tag: "SessionRunner.StepLimitExceededError", sessionID, limit: 25 })
- expect(requests).toHaveLength(25)
- expect(executions).toHaveLength(25)
- }),
- )
- it.effect("does not restart a capped tool loop for a coalesced stale wake", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- const coordinator = yield* SessionRunCoordinator.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Loop forever" }), resume: false })
- requests.length = 0
- responses = Array.from({ length: 25 }, (_, index) => [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: `call-capped-${index}`, name: "echo", input: { text: `${index}` } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ])
- streamGate = yield* Deferred.make<void>()
- streamStarted = yield* Deferred.make<void>()
- const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
- yield* Deferred.await(streamStarted)
- yield* coordinator.wake(sessionID)
- yield* Deferred.succeed(streamGate, undefined)
- expect(yield* Fiber.join(run).pipe(Effect.flip)).toMatchObject({ _tag: "SessionRunner.StepLimitExceededError" })
- streamGate = undefined
- streamStarted = undefined
- yield* Effect.yieldNow
- expect(requests).toHaveLength(25)
- }),
- )
- it.effect("accepts a terminal response on the final bounded provider turn", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Finish at the limit" }), resume: false })
- requests.length = 0
- responses = [
- ...Array.from({ length: 24 }, (_, index) => [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: `call-terminal-${index}`, name: "echo", input: { text: `${index}` } }),
- LLMEvent.stepFinish({ index: 0, reason: "tool-calls" }),
- LLMEvent.finish({ reason: "tool-calls" }),
- ]),
- [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ],
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(25)
- }),
- )
- it.effect("projects provider errors as terminal assistant step failures", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Fail durably" }), resume: false })
- requests.length = 0
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = [LLMEvent.stepStart({ index: 0 }), LLMEvent.providerError({ message: "Provider unavailable" })]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Fail durably" },
- { type: "assistant", finish: "error", error: { type: "unknown", message: "Provider unavailable" } },
- ])
- }),
- )
- it.effect("projects provider errors emitted before assistant step start", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Fail before step" }), resume: false })
- requests.length = 0
- response = [LLMEvent.providerError({ message: "Provider unavailable" })]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Fail before step" },
- { type: "assistant", finish: "error", error: { type: "unknown", message: "Provider unavailable" } },
- ])
- }),
- )
- it.effect("projects raw provider stream failures as terminal assistant step failures", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Fail raw stream durably" }), resume: false })
- const failure = providerUnavailable()
- responseStream = Stream.fail(failure)
- expect(yield* session.resume(sessionID).pipe(Effect.flip)).toBe(failure)
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Fail raw stream durably" },
- { type: "assistant", finish: "error", error: { type: "unknown", message: "Provider unavailable" } },
- ])
- }),
- )
- it.effect("does not continue automatically after a provider error follows a local tool call", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Do not continue failed provider" }),
- resume: false,
- })
- requests.length = 0
- const executionCount = executions.length
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({ id: "call-before-provider-error", name: "echo", input: { text: "settled" } }),
- LLMEvent.providerError({ message: "Provider unavailable" }),
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(executions.slice(executionCount)).toEqual(["settled"])
- }),
- )
- it.effect("durably fails a hosted tool when its provider errors before returning a result", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Fail hosted tool durably" }), resume: false })
- requests.length = 0
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({
- id: "call-hosted-provider-error",
- name: "web_search",
- input: { query: "effect" },
- providerExecuted: true,
- }),
- LLMEvent.providerError({ message: "Provider unavailable" }),
- ]
- yield* session.resume(sessionID)
- expect(requests).toHaveLength(1)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Fail hosted tool durably" },
- {
- type: "assistant",
- content: [{ type: "tool", id: "call-hosted-provider-error", state: { status: "error" } }],
- },
- ])
- }),
- )
- it.effect("durably fails a hosted tool left unresolved at normal provider EOF", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Fail hosted tool at EOF" }), resume: false })
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({
- id: "call-hosted-eof",
- name: "web_search",
- input: { query: "effect" },
- providerExecuted: true,
- }),
- ]
- yield* session.resume(sessionID)
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Fail hosted tool at EOF" },
- { type: "assistant", content: [{ type: "tool", id: "call-hosted-eof", state: { status: "error" } }] },
- ])
- }),
- )
- it.effect("durably fails a hosted tool left unresolved by a raw provider stream failure", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({
- sessionID,
- prompt: new Prompt({ text: "Fail hosted tool on raw failure" }),
- resume: false,
- })
- const failure = providerUnavailable()
- responseStream = Stream.concat(
- Stream.fromIterable([
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolCall({
- id: "call-hosted-raw-failure",
- name: "web_search",
- input: { query: "effect" },
- providerExecuted: true,
- }),
- ]),
- Stream.fail(failure),
- )
- expect(yield* session.resume(sessionID).pipe(Effect.flip)).toBe(failure)
- yield* replaySessionProjection(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Fail hosted tool on raw failure" },
- {
- type: "assistant",
- finish: "error",
- error: { type: "unknown", message: "Provider unavailable" },
- content: [{ type: "tool", id: "call-hosted-raw-failure", state: { status: "error" } }],
- },
- ])
- }),
- )
- it.effect("keeps interleaved assistant text blocks separate", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Two blocks" }), resume: false })
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.textStart({ id: "text-1" }),
- LLMEvent.textStart({ id: "text-2" }),
- LLMEvent.textDelta({ id: "text-1", text: "First" }),
- LLMEvent.textDelta({ id: "text-2", text: "Second" }),
- LLMEvent.textEnd({ id: "text-1" }),
- LLMEvent.textEnd({ id: "text-2" }),
- LLMEvent.stepFinish({ index: 0, reason: "stop" }),
- LLMEvent.finish({ reason: "stop" }),
- ]
- yield* session.resume(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Two blocks" },
- {
- type: "assistant",
- content: [
- { type: "text", id: "text-1", text: "First" },
- { type: "text", id: "text-2", text: "Second" },
- ],
- },
- ])
- }),
- )
- for (const kind of fragmentKinds) {
- it.effect(`broadcasts provider ${kind} deltas without storing projection rewrites`, () =>
- verifyEphemeralDeltas(kind),
- )
- it.effect(`durably closes partial ${kind} when the provider stream fails`, () => verifyPartialFlushOnFailure(kind))
- it.effect(`durably closes partial ${kind} when the provider stream is interrupted`, () =>
- verifyPartialFlushOnInterruption(kind),
- )
- }
- it.effect("rejects duplicate streamed text starts", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = [LLMEvent.textStart({ id: "text-1" }), LLMEvent.textStart({ id: "text-1" })]
- expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe(
- "Duplicate text start: text-1",
- )
- }),
- )
- it.effect("transitions streamed raw tool input to parsed called input", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- yield* session.prompt({ sessionID, prompt: new Prompt({ text: "Call provider tool" }), resume: false })
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = [
- LLMEvent.stepStart({ index: 0 }),
- LLMEvent.toolInputStart({ id: "call-parsed", name: "web_search" }),
- LLMEvent.toolInputDelta({ id: "call-parsed", name: "web_search", text: '{"query":"hello"}' }),
- LLMEvent.toolInputEnd({ id: "call-parsed", name: "web_search" }),
- LLMEvent.toolCall({ id: "call-parsed", name: "web_search", input: { query: "hello" }, providerExecuted: true }),
- ]
- yield* session.resume(sessionID)
- expect(yield* session.context(sessionID)).toMatchObject([
- { type: "user", text: "Call provider tool" },
- {
- type: "assistant",
- content: [{ type: "tool", id: "call-parsed", state: { status: "error", input: { query: "hello" } } }],
- },
- ])
- }),
- )
- it.effect("rejects malformed streamed tool input ordering", () =>
- Effect.gen(function* () {
- yield* setup
- const session = yield* SessionV2.Service
- responses = undefined
- streamGate = undefined
- streamStarted = undefined
- response = [LLMEvent.toolInputDelta({ id: "call-1", name: "read", text: "{}" })]
- expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe(
- "Tool input delta before start: call-1",
- )
- }),
- )
- })
|