session-runner.test.ts 182 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992
  1. import { describe, expect, test } from "bun:test"
  2. import {
  3. AIError,
  4. LLMEvent,
  5. LLMRequest,
  6. Message,
  7. LanguageModel,
  8. SystemPart,
  9. ToolFailure,
  10. TransportReason,
  11. InvalidProviderOutputReason,
  12. InvalidRequestReason,
  13. RateLimitReason,
  14. } from "@opencode-ai/ai"
  15. import * as OpenAIChat from "@opencode-ai/ai/protocols/openai-chat"
  16. import { TestLLM } from "@opencode-ai/ai/testing"
  17. import { Catalog } from "@opencode-ai/core/catalog"
  18. import { Database } from "@opencode-ai/core/database/database"
  19. import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
  20. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  21. import { LayerNodePlatform } from "@opencode-ai/core/effect/app-node-platform"
  22. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  23. import { Bus } from "@opencode-ai/core/bus"
  24. import { Event } from "@opencode-ai/schema/event"
  25. import { App } from "@opencode-ai/core/app"
  26. import { Permission } from "@opencode-ai/core/permission"
  27. import { EventTable } from "@opencode-ai/core/event/sql"
  28. import { Project } from "@opencode-ai/core/project"
  29. import { ProjectTable } from "@opencode-ai/core/project/sql"
  30. import { Form } from "@opencode-ai/core/form"
  31. import { AbsolutePath } from "@opencode-ai/core/schema"
  32. import { Session } from "@opencode-ai/core/session"
  33. import { Snapshot } from "@opencode-ai/core/snapshot"
  34. import { SessionEvent } from "@opencode-ai/core/session/event"
  35. import { SessionPending } from "@opencode-ai/core/session/pending"
  36. import { SessionMessage } from "@opencode-ai/core/session/message"
  37. import { Money } from "@opencode-ai/schema/money"
  38. import { SessionProjector } from "@opencode-ai/core/session/projector"
  39. import { SessionExecution } from "@opencode-ai/core/session/execution"
  40. import { SessionRunCoordinator } from "@opencode-ai/core/session/run-coordinator"
  41. import { SessionRunner } from "@opencode-ai/core/session/runner"
  42. import * as SessionRunnerLLM from "@opencode-ai/core/session/runner/llm"
  43. import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
  44. import { PromptCacheDiagnostics } from "@opencode-ai/core/session/prompt-cache-diagnostics"
  45. import { SessionUsage } from "@opencode-ai/core/session/usage"
  46. import { PluginSupervisor } from "@opencode-ai/core/plugin/supervisor"
  47. import { PluginHooks } from "@opencode-ai/core/plugin/hooks"
  48. import { SystemPromptPlugin } from "@opencode-ai/core/plugin/system-prompt"
  49. import { QuestionTool } from "@opencode-ai/core/tool/plugin/question"
  50. import { Agent } from "@opencode-ai/core/agent"
  51. import { Config } from "@opencode-ai/core/config"
  52. import { Document, Info } from "@opencode-ai/schema/config"
  53. import { ConfigCompaction } from "@opencode-ai/schema/config/compaction"
  54. import { Tool } from "@opencode-ai/core/tool"
  55. import type { Info as ToolInfo } from "@opencode-ai/schema/tool"
  56. import {
  57. InstructionStateTable,
  58. SessionPendingTable,
  59. SessionMessageTable,
  60. SessionTable,
  61. } from "@opencode-ai/core/session/sql"
  62. import { InstructionEntry } from "@opencode-ai/core/session/instruction-entry"
  63. import { SessionStore } from "@opencode-ai/core/session/store"
  64. import { Instructions } from "@opencode-ai/core/instructions"
  65. import { InstructionBuiltIns } from "@opencode-ai/core/instructions/builtins"
  66. import { InstructionDiscovery } from "@opencode-ai/core/instruction-discovery"
  67. import { SkillInstructions } from "@opencode-ai/core/skill/instructions"
  68. import { ReferenceInstructions } from "@opencode-ai/core/reference/instructions"
  69. import { McpInstructions } from "@opencode-ai/core/mcp/instructions"
  70. import { ID } from "@opencode-ai/core/model"
  71. import { Location } from "@opencode-ai/core/location"
  72. import { Provider } from "@opencode-ai/core/provider"
  73. import { Cause, DateTime, Deferred, Effect, Exit, Fiber, Layer, Schema, Scope, Stream } from "effect"
  74. import { TestClock } from "effect/testing"
  75. import { asc, eq } from "drizzle-orm"
  76. import { testEffect } from "./lib/effect"
  77. import { agentHost, catalogHost, host } from "./plugin/host"
  78. import PROMPT_DEFAULT from "../src/session/runner/prompt/base.txt"
  79. import { CodeModeInstructions } from "@opencode-ai/core/codemode/instructions"
  80. let requests: LLMRequest[] = []
  81. const emptyCodeMode = `\n\n${CodeModeInstructions.render({ total: 0, shown: 0, namespaces: [] })}`
  82. type ToolBarrier = {
  83. readonly count: number
  84. readonly started: Deferred.Deferred<void>
  85. readonly release: Deferred.Deferred<void>
  86. active: number
  87. maxActive: number
  88. }
  89. let toolBarrier: ToolBarrier | undefined
  90. const releaseTools = (barrier: ToolBarrier) =>
  91. Effect.sync(() => {
  92. if (toolBarrier === barrier) toolBarrier = undefined
  93. }).pipe(Effect.andThen(Deferred.succeed(barrier.release, undefined)), Effect.asVoid)
  94. const blockTools = (count = 1) =>
  95. Effect.acquireRelease(
  96. Effect.all({ started: Deferred.make<void>(), release: Deferred.make<void>() }).pipe(
  97. Effect.map((deferreds) => {
  98. const barrier = { count, ...deferreds, active: 0, maxActive: 0 }
  99. toolBarrier = barrier
  100. return barrier
  101. }),
  102. ),
  103. releaseTools,
  104. ).pipe(
  105. Effect.map((barrier) => ({
  106. started: Deferred.await(barrier.started),
  107. release: releaseTools(barrier),
  108. maxActive: Effect.sync(() => barrier.maxActive),
  109. })),
  110. )
  111. const awaitToolBarrier = Effect.suspend(() => {
  112. const barrier = toolBarrier
  113. if (!barrier) return Effect.void
  114. barrier.active++
  115. barrier.maxActive = Math.max(barrier.maxActive, barrier.active)
  116. return (barrier.active === barrier.count ? Deferred.succeed(barrier.started, undefined) : Effect.void).pipe(
  117. Effect.andThen(Deferred.await(barrier.release)),
  118. Effect.ensuring(Effect.sync(() => barrier.active--)),
  119. )
  120. })
  121. const testLLM = TestLLM.layer({
  122. fallback: [],
  123. transformRequest: (request) =>
  124. LLMRequest.update(request, {
  125. system: request.system.map((part) => ({
  126. ...part,
  127. text: part.text.replace(emptyCodeMode, ""),
  128. })),
  129. tools: request.tools.filter((tool) => tool.name !== "execute"),
  130. }),
  131. })
  132. const client = TestLLM.clientLayer
  133. const model = LanguageModel.make({ id: "fake-model", provider: "fake", route: OpenAIChat.route })
  134. const defaultSystem = PROMPT_DEFAULT
  135. const replacementModel = LanguageModel.make({ id: "replacement", provider: "fake", route: OpenAIChat.route })
  136. const compactModel = LanguageModel.make({
  137. id: "compact",
  138. provider: "fake",
  139. route: OpenAIChat.route.with({ limits: { context: 4_000, output: 50 } }),
  140. })
  141. const fullOutputModel = LanguageModel.make({
  142. id: "full-output",
  143. provider: "fake",
  144. route: OpenAIChat.route.with({ limits: { context: 262_144, output: 262_144 } }),
  145. })
  146. const undersizedContextModel = LanguageModel.make({
  147. id: "undersized-context",
  148. provider: "fake",
  149. route: OpenAIChat.route.with({ limits: { context: 1, output: 1_000 } }),
  150. })
  151. const recoveryModel = LanguageModel.make({
  152. id: "recovery",
  153. provider: "fake",
  154. route: OpenAIChat.route.with({ limits: { context: 20_000, output: 1_000 } }),
  155. })
  156. test("calculates step cost using the matching context tier", () => {
  157. expect(
  158. SessionUsage.calculateCost(
  159. [
  160. {
  161. input: Money.USDPerMillionTokens.make(1),
  162. output: Money.USDPerMillionTokens.make(2),
  163. cache: {
  164. read: Money.USDPerMillionTokens.make(0.1),
  165. write: Money.USDPerMillionTokens.make(0.5),
  166. },
  167. },
  168. {
  169. tier: { type: "context", size: 100 },
  170. input: Money.USDPerMillionTokens.make(3),
  171. output: Money.USDPerMillionTokens.make(4),
  172. cache: {
  173. read: Money.USDPerMillionTokens.make(0.2),
  174. write: Money.USDPerMillionTokens.make(0.6),
  175. },
  176. },
  177. ],
  178. { input: 80, output: 10, reasoning: 2, cache: { read: 20, write: 1 } },
  179. ),
  180. ).toBeCloseTo(0.0002926)
  181. })
  182. test("does not apply an ineligible tier without base pricing", () => {
  183. expect(
  184. SessionUsage.calculateCost(
  185. [
  186. {
  187. tier: { type: "context", size: 100 },
  188. input: Money.USDPerMillionTokens.make(3),
  189. output: Money.USDPerMillionTokens.make(4),
  190. cache: {
  191. read: Money.USDPerMillionTokens.make(0.2),
  192. write: Money.USDPerMillionTokens.make(0.6),
  193. },
  194. },
  195. ],
  196. { input: 80, output: 10, reasoning: 2, cache: { read: 20, write: 0 } },
  197. ),
  198. ).toBe(Money.USD.zero)
  199. })
  200. const authorizations: Tool.Context[] = []
  201. const executions: string[] = []
  202. const permissionFail = {
  203. name: "permission_fail",
  204. description: "Reject a permission",
  205. input: Schema.Struct({}),
  206. output: Schema.Struct({}),
  207. execute: () =>
  208. new ToolFailure({
  209. message: "Permission denied: edit",
  210. error: new Permission.BlockedError({
  211. rules: [],
  212. permission: "edit",
  213. resources: ["src/index.ts"],
  214. }),
  215. }),
  216. }
  217. const permission = Layer.succeed(
  218. Permission.Service,
  219. Permission.Service.of({
  220. assert: () => Effect.die("unused"),
  221. ask: () => Effect.die("unused"),
  222. reply: () => Effect.die("unused"),
  223. get: () => Effect.die("unused"),
  224. forSession: () => Effect.die("unused"),
  225. list: () => Effect.die("unused"),
  226. }),
  227. )
  228. const transformTools = (registry: Tool.Interface, tools: Readonly<Record<string, ToolInfo>>, options?: Tool.Options) =>
  229. registry.transform((draft) =>
  230. Object.entries(tools).forEach(([name, tool]) => draft.add({ ...tool, name, options: options ?? tool.options })),
  231. )
  232. const echo = Layer.effectDiscard(
  233. Tool.Service.use((registry) =>
  234. transformTools(
  235. registry,
  236. {
  237. echo: {
  238. name: "echo",
  239. description: "Echo text",
  240. input: Schema.Struct({ text: Schema.String }),
  241. output: Schema.Struct({ text: Schema.String }),
  242. execute: ({ text }, context) =>
  243. Effect.gen(function* () {
  244. authorizations.push(context)
  245. executions.push(text)
  246. yield* awaitToolBarrier
  247. return { output: { text }, content: text }
  248. }),
  249. },
  250. defect: {
  251. name: "defect",
  252. description: "Fail unexpectedly",
  253. input: Schema.Struct({}),
  254. output: Schema.Struct({}),
  255. execute: () => awaitToolBarrier.pipe(Effect.andThen(Effect.die("unexpected tool defect"))),
  256. },
  257. storefail: {
  258. name: "storefail",
  259. description: "Produce output that cannot be persisted",
  260. input: Schema.Struct({}),
  261. output: Schema.Struct({}),
  262. execute: () => Effect.succeed({ output: {} }),
  263. },
  264. },
  265. { codemode: false },
  266. ),
  267. ),
  268. )
  269. const echoNode = makeLocationNode({ name: "test/session-runner-tools", layer: echo, deps: [Tool.node] })
  270. let modelResolveHook = Effect.void
  271. let currentModel = model
  272. const models = Layer.mock(SessionRunnerModel.Service)({
  273. resolve: (session) =>
  274. modelResolveHook.pipe(
  275. Effect.as(
  276. SessionRunnerModel.resolved(session.model?.id === "replacement" ? replacementModel : currentModel, {
  277. capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
  278. cost: [],
  279. variant: session.model?.variant,
  280. }),
  281. ),
  282. ),
  283. })
  284. const systemContextKey = Instructions.Key.make("test/context")
  285. let systemBaseline = "Initial context"
  286. let systemRemoved = false
  287. let systemUnavailable = false
  288. let systemLoadHook = Effect.void
  289. const skillBaselines = new Map<Agent.ID, string>()
  290. const systemContext = Layer.mock(InstructionBuiltIns.Service, {
  291. load: () =>
  292. Effect.sync(() =>
  293. Instructions.make({
  294. key: systemContextKey,
  295. codec: Schema.toCodecJson(Schema.String),
  296. read: systemLoadHook.pipe(
  297. Effect.andThen(
  298. Effect.sync(() =>
  299. systemUnavailable ? Instructions.unavailable : systemRemoved ? Instructions.removed : systemBaseline,
  300. ),
  301. ),
  302. ),
  303. render: {
  304. initial: String,
  305. changed: (_previous, current) => current,
  306. removed: () => "System context source removed: test/context",
  307. },
  308. }),
  309. ),
  310. })
  311. const instructionContext = Layer.mock(InstructionDiscovery.Service, { load: () => Effect.succeed(Instructions.empty) })
  312. const skillInstructions = Layer.mock(SkillInstructions.Service, {
  313. load: (agent) =>
  314. Effect.succeed(
  315. skillBaselines.has(agent.id)
  316. ? Instructions.make({
  317. key: Instructions.Key.make("test/skill-guidance"),
  318. codec: Schema.toCodecJson(Schema.String),
  319. read: Effect.succeed(skillBaselines.get(agent.id)!),
  320. render: {
  321. initial: String,
  322. changed: (_previous, current) => current,
  323. removed: () => "Skill guidance removed",
  324. },
  325. })
  326. : Instructions.empty,
  327. ),
  328. })
  329. const referenceInstructions = Layer.mock(ReferenceInstructions.Service, {
  330. load: () => Effect.succeed(Instructions.empty),
  331. })
  332. const mcpInstructions = Layer.mock(McpInstructions.Service, { load: () => Effect.succeed(Instructions.empty) })
  333. const config = Config.testLayer([
  334. new Document({
  335. type: "document",
  336. info: new Info({
  337. compaction: new ConfigCompaction.Info({
  338. buffer: 3_000,
  339. keep: new ConfigCompaction.Keep({ tokens: 1_000 }),
  340. }),
  341. }),
  342. }),
  343. ])
  344. let pluginFlushHook = Effect.void
  345. const pluginSupervisor = Layer.succeed(
  346. PluginSupervisor.Service,
  347. PluginSupervisor.Service.of({
  348. flush: Effect.suspend(() => pluginFlushHook),
  349. }),
  350. )
  351. const promptCatalog = Layer.mock(Catalog.Service, {
  352. provider: {
  353. get: () => Effect.succeed(undefined),
  354. all: () => Effect.succeed([]),
  355. available: () => Effect.succeed([]),
  356. },
  357. model: {
  358. get: () => Effect.succeed(undefined),
  359. all: () => Effect.succeed([]),
  360. available: () => Effect.succeed([]),
  361. default: () => Effect.succeed(undefined),
  362. small: () => Effect.succeed(undefined),
  363. },
  364. })
  365. const runnerLayer = AppNodeBuilder.build(SessionRunnerLLM.node, [
  366. [Snapshot.node, Snapshot.noopLayer],
  367. [LayerNodePlatform.llmClient, client],
  368. [SessionRunnerModel.node, models],
  369. [InstructionBuiltIns.node, systemContext],
  370. [InstructionDiscovery.node, instructionContext],
  371. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  372. [SkillInstructions.node, skillInstructions],
  373. [ReferenceInstructions.node, referenceInstructions],
  374. [Permission.node, permission],
  375. [Config.node, config],
  376. [McpInstructions.node, mcpInstructions],
  377. [PluginSupervisor.node, pluginSupervisor],
  378. ])
  379. const execution = Layer.effect(
  380. SessionExecution.Service,
  381. Effect.gen(function* () {
  382. const sessionRunner = yield* SessionRunner.Service
  383. const coordinator = yield* SessionRunCoordinator.make<Session.ID, SessionRunner.RunError>({
  384. drain: (sessionID, force) => sessionRunner.drain({ sessionID, force }),
  385. })
  386. return SessionExecution.Service.of({
  387. active: coordinator.active,
  388. resume: coordinator.run,
  389. wake: coordinator.wake,
  390. interrupt: coordinator.interrupt,
  391. awaitIdle: coordinator.awaitIdle,
  392. })
  393. }),
  394. ).pipe(Layer.provide(runnerLayer))
  395. const it = testEffect(
  396. AppNodeBuilder.build(
  397. LayerNode.group([
  398. Database.node,
  399. Bus.node,
  400. Form.node,
  401. SessionProjector.node,
  402. SessionStore.node,
  403. Agent.node,
  404. Catalog.node,
  405. Tool.node,
  406. Tool.node,
  407. PluginHooks.node,
  408. PluginHooks.node,
  409. echoNode,
  410. SessionRunnerModel.node,
  411. InstructionBuiltIns.node,
  412. InstructionDiscovery.node,
  413. InstructionEntry.node,
  414. SkillInstructions.node,
  415. ReferenceInstructions.node,
  416. Config.node,
  417. Snapshot.node,
  418. SessionRunnerLLM.node,
  419. SessionExecution.node,
  420. Session.node,
  421. ]),
  422. [
  423. [Bus.node, Bus.configured({ persist: true })],
  424. [LayerNodePlatform.llmClient, client],
  425. [Permission.node, permission],
  426. [Catalog.node, promptCatalog],
  427. [SessionRunnerModel.node, models],
  428. [InstructionBuiltIns.node, systemContext],
  429. [InstructionDiscovery.node, instructionContext],
  430. [Location.node, Location.boundNode({ directory: AbsolutePath.make("/project") })],
  431. [SkillInstructions.node, skillInstructions],
  432. [ReferenceInstructions.node, referenceInstructions],
  433. [Snapshot.node, Snapshot.noopLayer],
  434. [SessionExecution.node, execution],
  435. [Config.node, config],
  436. [PluginSupervisor.node, pluginSupervisor],
  437. ],
  438. ).pipe(Layer.provideMerge(testLLM)),
  439. )
  440. const sessionID = Session.ID.make("ses_runner_test")
  441. const otherSessionID = Session.ID.make("ses_runner_other")
  442. const admit = (session: Session.Interface, text: string) => session.prompt({ sessionID, text, resume: false })
  443. const runPrompt = Effect.fnUntraced(function* (session: Session.Interface, text: string) {
  444. const message = yield* admit(session, text)
  445. yield* session.resume(sessionID)
  446. return message
  447. })
  448. const insertSession = (id: Session.ID) =>
  449. Effect.gen(function* () {
  450. const { db } = yield* Database.Service
  451. yield* db
  452. .insert(SessionTable)
  453. .values({
  454. id,
  455. project_id: Project.ID.global,
  456. slug: id,
  457. directory: "/project",
  458. title: "test",
  459. version: "test",
  460. })
  461. .onConflictDoNothing()
  462. .run()
  463. .pipe(Effect.orDie)
  464. })
  465. const setup = Effect.gen(function* () {
  466. const { db } = yield* Database.Service
  467. const agents = yield* Agent.Service
  468. const catalog = yield* Catalog.Service
  469. const hooks = yield* PluginHooks.Service
  470. const pluginHost = host({
  471. agent: agentHost(agents),
  472. catalog: catalogHost(catalog),
  473. session: { hook: (name, callback) => hooks.register("session", name, callback) },
  474. })
  475. yield* Effect.forEach(SystemPromptPlugin.Plugins, (plugin) => plugin.effect(pluginHost), {
  476. discard: true,
  477. })
  478. requests = (yield* TestLLM.Service).requests
  479. authorizations.length = 0
  480. executions.length = 0
  481. systemBaseline = "Initial context"
  482. systemRemoved = false
  483. systemUnavailable = false
  484. systemLoadHook = Effect.void
  485. modelResolveHook = Effect.void
  486. pluginFlushHook = Effect.void
  487. currentModel = model
  488. skillBaselines.clear()
  489. toolBarrier = undefined
  490. yield* agents.transform((draft) =>
  491. draft.update(Agent.ID.make("build"), (agent) => {
  492. agent.mode = "primary"
  493. }),
  494. )
  495. yield* db
  496. .insert(ProjectTable)
  497. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  498. .onConflictDoNothing()
  499. .run()
  500. .pipe(Effect.orDie)
  501. yield* insertSession(sessionID)
  502. return yield* Session.Service
  503. })
  504. const providerUnavailable = () =>
  505. new AIError({
  506. module: "test",
  507. method: "stream",
  508. reason: new TransportReason({ message: "Provider unavailable" }),
  509. })
  510. const incompleteStream = () =>
  511. new AIError({
  512. module: "test",
  513. method: "stream",
  514. reason: new InvalidProviderOutputReason({
  515. classification: "incomplete-stream",
  516. message: "The provider response ended unexpectedly.",
  517. }),
  518. })
  519. const INCOMPLETE_STREAM_CONTINUATION =
  520. "The previous response was interrupted. Continue from where you left off without repeating completed content."
  521. const invalidRequest = () =>
  522. new AIError({
  523. module: "test",
  524. method: "stream",
  525. reason: new InvalidRequestReason({ message: "Invalid request" }),
  526. })
  527. const rateLimited = (retryAfterMs?: number) =>
  528. new AIError({
  529. module: "test",
  530. method: "stream",
  531. reason: new RateLimitReason({ message: "Rate limited", retryAfterMs }),
  532. })
  533. const setupOverflowRecovery = Effect.gen(function* () {
  534. const session = yield* setup
  535. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-earlier"))
  536. yield* runPrompt(session, "Earlier question ".repeat(700))
  537. currentModel = recoveryModel
  538. requests.length = 0
  539. return session
  540. })
  541. const messageTexts = (request: LLMRequest, role: "user" | "system") =>
  542. request.messages.flatMap((message) =>
  543. message.role === role ? message.content.flatMap((content) => (content.type === "text" ? [content.text] : [])) : [],
  544. )
  545. const userTexts = (request: LLMRequest) => messageTexts(request, "user")
  546. const systemTexts = (request: LLMRequest) => messageTexts(request, "system")
  547. const messageRoles = (request: LLMRequest | undefined) => request?.messages.map((message) => message.role)
  548. const recordedEventTypes = (id: Session.ID) =>
  549. Effect.gen(function* () {
  550. const { db } = yield* Database.Service
  551. return yield* db
  552. .select({ type: EventTable.type })
  553. .from(EventTable)
  554. .where(eq(EventTable.aggregate_id, id))
  555. .orderBy(asc(EventTable.seq))
  556. .all()
  557. .pipe(
  558. Effect.orDie,
  559. Effect.map((rows) => rows.map((row) => row.type)),
  560. )
  561. })
  562. const recordedStepSettlementEvents = (id: Session.ID, assistantMessageID: SessionMessage.ID) =>
  563. Effect.gen(function* () {
  564. const { db } = yield* Database.Service
  565. const settlementTypes = new Set([
  566. "session.step.started.1",
  567. "session.tool.called.1",
  568. "session.tool.success.2",
  569. "session.tool.failed.2",
  570. "session.step.ended.1",
  571. "session.step.failed.1",
  572. ])
  573. return (yield* db
  574. .select({ type: EventTable.type, data: EventTable.data })
  575. .from(EventTable)
  576. .where(eq(EventTable.aggregate_id, id))
  577. .orderBy(asc(EventTable.seq))
  578. .all()
  579. .pipe(Effect.orDie)).filter(
  580. (event) => settlementTypes.has(event.type) && event.data.assistantMessageID === assistantMessageID,
  581. )
  582. })
  583. const recordedStepSettlementTypes = (id: Session.ID, assistantMessageID: SessionMessage.ID) =>
  584. recordedStepSettlementEvents(id, assistantMessageID).pipe(Effect.map((events) => events.map((event) => event.type)))
  585. const hostedCall = (id: string, query: string) =>
  586. LLMEvent.toolCall({ id, name: "web_search", input: { query }, providerExecuted: true })
  587. const requireAssistant = (messages: readonly SessionMessage.Info[]) => {
  588. const assistant = messages.find((message) => message.type === "assistant")
  589. if (!assistant) throw new Error("Assistant message missing")
  590. return assistant
  591. }
  592. const replaySessionProjection = (id: Session.ID) =>
  593. Effect.gen(function* () {
  594. const { db } = yield* Database.Service
  595. const bus = yield* Bus.Service
  596. const recorded = yield* db
  597. .select()
  598. .from(EventTable)
  599. .where(eq(EventTable.aggregate_id, id))
  600. .orderBy(asc(EventTable.seq))
  601. .all()
  602. .pipe(Effect.orDie)
  603. yield* bus.remove(id)
  604. yield* db.delete(InstructionStateTable).where(eq(InstructionStateTable.session_id, id)).run().pipe(Effect.orDie)
  605. yield* db.delete(SessionPendingTable).where(eq(SessionPendingTable.session_id, id)).run().pipe(Effect.orDie)
  606. yield* db.delete(SessionMessageTable).where(eq(SessionMessageTable.session_id, id)).run().pipe(Effect.orDie)
  607. yield* bus.replayAll(
  608. recorded.map((event) => ({
  609. id: event.id,
  610. created: DateTime.makeUnsafe(event.created),
  611. aggregateID: event.aggregate_id,
  612. seq: event.seq,
  613. type: event.type,
  614. data: event.data,
  615. })),
  616. )
  617. })
  618. type FragmentKind = "text" | "reasoning" | "tool input"
  619. type FragmentFixture = {
  620. readonly delta: Event.Definition
  621. readonly completeEvents: LLMEvent[]
  622. readonly partialEvents: LLMEvent[]
  623. readonly expectedAssistant: unknown
  624. readonly expectedContent: unknown
  625. }
  626. const fragmentKinds: readonly FragmentKind[] = ["text", "reasoning", "tool input"]
  627. const fragmentID = (kind: FragmentKind, suffix: string) => `${kind === "tool input" ? "call" : kind}-${suffix}`
  628. const fragmentFixture = (kind: FragmentKind, id: string, chunks: readonly string[]): FragmentFixture => {
  629. const text = chunks.join("")
  630. switch (kind) {
  631. case "text": {
  632. const partialEvents = [
  633. LLMEvent.stepStart({ index: 0 }),
  634. LLMEvent.textStart({ id }),
  635. ...chunks.map((text) => LLMEvent.textDelta({ id, text })),
  636. ]
  637. const expectedContent = { type: "text", text }
  638. return {
  639. delta: SessionEvent.Text.Delta,
  640. partialEvents,
  641. completeEvents: [
  642. ...partialEvents,
  643. LLMEvent.textEnd({ id }),
  644. LLMEvent.stepFinish({ index: 0, reason: { normalized: "stop" } }),
  645. LLMEvent.finish({ reason: { normalized: "stop" } }),
  646. ],
  647. expectedAssistant: { type: "assistant", finish: "stop", content: [expectedContent] },
  648. expectedContent,
  649. }
  650. }
  651. case "reasoning": {
  652. const partialEvents = [
  653. LLMEvent.stepStart({ index: 0 }),
  654. LLMEvent.reasoningStart({ id }),
  655. ...chunks.map((text) => LLMEvent.reasoningDelta({ id, text })),
  656. ]
  657. const expectedContent = { type: "reasoning", text }
  658. return {
  659. delta: SessionEvent.Reasoning.Delta,
  660. partialEvents,
  661. completeEvents: [
  662. ...partialEvents,
  663. LLMEvent.reasoningEnd({ id }),
  664. LLMEvent.stepFinish({ index: 0, reason: { normalized: "stop" } }),
  665. LLMEvent.finish({ reason: { normalized: "stop" } }),
  666. ],
  667. expectedAssistant: { type: "assistant", finish: "stop", content: [expectedContent] },
  668. expectedContent,
  669. }
  670. }
  671. case "tool input": {
  672. const partialEvents = [
  673. LLMEvent.stepStart({ index: 0 }),
  674. LLMEvent.toolInputStart({ id, name: "echo" }),
  675. ...chunks.map((text) => LLMEvent.toolInputDelta({ id, name: "echo", text })),
  676. ]
  677. const expectedContent = { type: "tool", id, state: { status: "streaming", input: text } }
  678. return {
  679. delta: SessionEvent.Tool.Input.Delta,
  680. partialEvents,
  681. completeEvents: [...partialEvents, LLMEvent.toolInputEnd({ id, name: "echo" })],
  682. expectedAssistant: { type: "assistant", content: [expectedContent] },
  683. expectedContent,
  684. }
  685. }
  686. }
  687. }
  688. const verifyEphemeralDeltas = (kind: FragmentKind) =>
  689. Effect.gen(function* () {
  690. const session = yield* setup
  691. const prompt = `Stream ${kind}`
  692. const chunks = Array.from({ length: 32 }, (_, index) => `${index},`)
  693. const fixture = fragmentFixture(kind, fragmentID(kind, "many"), chunks)
  694. const expectedContext = [{ type: "user", text: prompt }, fixture.expectedAssistant]
  695. yield* admit(session, prompt)
  696. const bus = yield* Bus.Service
  697. const live = yield* bus.subscribe(fixture.delta).pipe(Stream.take(32), Stream.runCollect, Effect.forkScoped)
  698. yield* Effect.yieldNow
  699. yield* TestLLM.push(fixture.completeEvents)
  700. yield* session.resume(sessionID)
  701. const { db } = yield* Database.Service
  702. const deltas = yield* db
  703. .select({ type: EventTable.type })
  704. .from(EventTable)
  705. .where(eq(EventTable.type, Bus.versionedType(fixture.delta.type, 1)))
  706. .all()
  707. .pipe(Effect.orDie)
  708. expect(Array.from(yield* Fiber.join(live))).toHaveLength(32)
  709. expect(deltas).toHaveLength(0)
  710. expect(yield* session.context(sessionID)).toMatchObject(expectedContext)
  711. yield* replaySessionProjection(sessionID)
  712. expect(yield* session.context(sessionID)).toMatchObject(expectedContext)
  713. })
  714. const verifyPartialFlushOnFailure = (kind: FragmentKind) =>
  715. Effect.gen(function* () {
  716. const session = yield* setup
  717. const prompt = `Fail after ${kind}`
  718. const fixture = fragmentFixture(kind, fragmentID(kind, "partial"), ["Partial"])
  719. const failure = providerUnavailable()
  720. yield* admit(session, prompt)
  721. yield* TestLLM.push(TestLLM.failAfter(failure, ...fixture.partialEvents))
  722. expect(yield* session.resume(sessionID).pipe(Effect.flip)).toBe(failure)
  723. expect(yield* session.context(sessionID)).toMatchObject([
  724. { type: "user", text: prompt },
  725. {
  726. type: "assistant",
  727. finish: "error",
  728. error: { type: "provider.transport", message: "Provider unavailable" },
  729. content: [
  730. kind === "tool input"
  731. ? {
  732. type: "tool",
  733. id: fragmentID(kind, "partial"),
  734. state: {
  735. status: "error",
  736. error: { type: "provider.transport", message: "Provider unavailable" },
  737. },
  738. }
  739. : fixture.expectedContent,
  740. ],
  741. },
  742. ])
  743. expect(requests).toHaveLength(1)
  744. })
  745. const verifyPartialFlushOnInterruption = (kind: FragmentKind) =>
  746. Effect.gen(function* () {
  747. const session = yield* setup
  748. const prompt = `Interrupt after ${kind}`
  749. const fixture = fragmentFixture(kind, fragmentID(kind, "interrupted"), ["Partial"])
  750. const streamed = yield* Deferred.make<void>()
  751. yield* admit(session, prompt)
  752. yield* TestLLM.push(
  753. Stream.concat(
  754. Stream.fromIterable(fixture.partialEvents),
  755. Stream.fromEffect(Deferred.succeed(streamed, undefined)).pipe(Stream.flatMap(() => Stream.never)),
  756. ),
  757. )
  758. const runner = yield* SessionRunner.Service
  759. const fiber = yield* runner.drain({ sessionID, force: true }).pipe(Effect.forkChild)
  760. yield* Deferred.await(streamed)
  761. yield* Fiber.interrupt(fiber)
  762. expect(yield* session.context(sessionID)).toMatchObject([
  763. { type: "user", text: prompt },
  764. {
  765. type: "assistant",
  766. finish: "error",
  767. error: { type: "aborted", message: "Step interrupted" },
  768. content: [
  769. kind === "tool input"
  770. ? { type: "tool", id: fragmentID(kind, "interrupted"), state: { status: "error" } }
  771. : fixture.expectedContent,
  772. ],
  773. },
  774. ])
  775. })
  776. describe("SessionRunnerLLM", () => {
  777. it.effect("retries title generation from the first prompt after execution and title failures", () =>
  778. Effect.gen(function* () {
  779. const session = yield* setup
  780. const agents = yield* Agent.Service
  781. const { db } = yield* Database.Service
  782. yield* db.update(SessionTable).set({ title: null }).where(eq(SessionTable.id, sessionID)).run().pipe(Effect.orDie)
  783. yield* agents.transform((draft) =>
  784. draft.update(Agent.ID.make("title"), (agent) => {
  785. agent.mode = "primary"
  786. agent.hidden = true
  787. agent.system = "Generate a title."
  788. }),
  789. )
  790. yield* admit(session, "First prompt")
  791. yield* TestLLM.push(Stream.fail(invalidRequest()))
  792. expect((yield* session.resume(sessionID).pipe(Effect.exit))._tag).toBe("Failure")
  793. yield* admit(session, "Second prompt")
  794. const titleFailed = yield* Deferred.make<void>()
  795. yield* TestLLM.push(
  796. TestLLM.text("Recovered", "text-recovered"),
  797. Stream.make(LLMEvent.providerError({ message: "Title provider unavailable" })).pipe(
  798. Stream.ensuring(Deferred.succeed(titleFailed, undefined)),
  799. ),
  800. )
  801. yield* session.resume(sessionID)
  802. yield* Deferred.await(titleFailed)
  803. yield* Effect.yieldNow
  804. expect((yield* session.get(sessionID)).title).toBeUndefined()
  805. const bus = yield* Bus.Service
  806. const renamed = yield* bus.subscribe(SessionEvent.Renamed).pipe(
  807. Stream.filter((event) => event.data.sessionID === sessionID),
  808. Stream.take(1),
  809. Stream.runCollect,
  810. Effect.forkScoped({ startImmediately: true }),
  811. )
  812. yield* admit(session, "Third prompt")
  813. yield* TestLLM.push(
  814. TestLLM.text("Recovered again", "text-recovered-again"),
  815. TestLLM.text("Generated title", "text-title"),
  816. )
  817. yield* session.resume(sessionID)
  818. yield* Fiber.join(renamed)
  819. expect(requests).toHaveLength(5)
  820. expect(requests[2]?.messages).toContainEqual(Message.user("First prompt"))
  821. expect(requests[4]?.messages).toContainEqual(Message.user("First prompt"))
  822. expect((yield* session.get(sessionID)).title).toBe("Generated title")
  823. }),
  824. )
  825. it.effect("applies session context hooks without exposing unavailable tools", () =>
  826. Effect.gen(function* () {
  827. const session = yield* setup
  828. const hooks = yield* PluginHooks.Service
  829. yield* hooks.register("session", "context", (event) =>
  830. Effect.sync(() => {
  831. event.system = [SystemPart.make("Hooked system")]
  832. event.messages = [Message.user("Hooked message")]
  833. delete event.tools.echo
  834. event.tools.unregistered = { description: "Unavailable", input: { type: "object" } }
  835. }),
  836. )
  837. yield* admit(session, "Original message")
  838. yield* TestLLM.push(TestLLM.tool("call-removed", "echo", { text: "blocked" }))
  839. yield* session.resume(sessionID)
  840. // A hook-removed call fails independently and continues while step allowance remains.
  841. expect(requests).toHaveLength(2)
  842. expect(requests[0]?.system.map((part) => part.text)).toEqual(["Hooked system"])
  843. expect(requests[0]?.messages).toEqual([Message.user("Hooked message")])
  844. expect(requests[0]?.tools.map((tool) => tool.name)).not.toContain("echo")
  845. expect(requests[0]?.tools.map((tool) => tool.name)).not.toContain("unregistered")
  846. expect(executions).toEqual([])
  847. expect(yield* session.context(sessionID)).toMatchObject([
  848. { type: "user", text: "Original message" },
  849. {
  850. type: "assistant",
  851. content: [
  852. {
  853. type: "tool",
  854. id: "call-removed",
  855. state: { status: "error", error: { type: "tool.execution" } },
  856. },
  857. ],
  858. },
  859. ])
  860. }),
  861. )
  862. it.effect("executes a tool renamed by a session context hook", () =>
  863. Effect.gen(function* () {
  864. const session = yield* setup
  865. const hooks = yield* PluginHooks.Service
  866. yield* hooks.register("session", "context", (event) =>
  867. Effect.sync(() => {
  868. event.tools.renamed_echo = event.tools.echo!
  869. delete event.tools.echo
  870. }),
  871. )
  872. yield* admit(session, "Use the renamed tool")
  873. yield* TestLLM.push(TestLLM.tool("call-renamed", "renamed_echo", { text: "renamed" }), [])
  874. yield* session.resume(sessionID)
  875. expect(requests[0]?.tools.map((tool) => tool.name)).toContain("renamed_echo")
  876. expect(requests[0]?.tools.map((tool) => tool.name)).not.toContain("echo")
  877. expect(executions).toEqual(["renamed"])
  878. }),
  879. )
  880. it.effect("advertises and executes a location registered tool", () =>
  881. Effect.gen(function* () {
  882. const session = yield* setup
  883. const registry = yield* Tool.Service
  884. const contexts: Tool.Context[] = []
  885. yield* transformTools(
  886. registry,
  887. {
  888. location_context: {
  889. name: "location_context",
  890. description: "Read application context",
  891. input: Schema.Struct({ query: Schema.String }),
  892. output: Schema.Struct({ answer: Schema.String }),
  893. execute: ({ query }, context) =>
  894. Effect.gen(function* () {
  895. contexts.push(context)
  896. yield* context.progress({ phase: "reading" })
  897. return { output: { answer: query.toUpperCase() } }
  898. }),
  899. },
  900. },
  901. { codemode: false },
  902. )
  903. yield* admit(session, "Use application context")
  904. yield* TestLLM.push(TestLLM.tool("call-location", "location_context", { query: "hello" }), [])
  905. const bus = yield* Bus.Service
  906. const progressFiber = yield* bus.subscribe(SessionEvent.Tool.Progress).pipe(
  907. Stream.filter((event) => event.data.sessionID === sessionID && event.data.id === "call-location"),
  908. Stream.take(1),
  909. Stream.runCollect,
  910. Effect.forkScoped({ startImmediately: true }),
  911. )
  912. yield* session.resume(sessionID)
  913. expect(requests[0]?.tools.map((tool) => tool.name)).toContain("location_context")
  914. expect(contexts).toEqual([
  915. {
  916. sessionID,
  917. agent: Agent.ID.make("build"),
  918. messageID: expect.stringMatching(/^msg_/),
  919. id: Tool.CallID.make("call-location"),
  920. progress: expect.any(Function),
  921. },
  922. ])
  923. expect(Array.from(yield* Fiber.join(progressFiber))[0]?.data.metadata).toEqual({ phase: "reading" })
  924. expect(yield* session.context(sessionID)).toMatchObject([
  925. { type: "user", text: "Use application context" },
  926. {
  927. type: "assistant",
  928. content: [
  929. {
  930. type: "tool",
  931. id: "call-location",
  932. state: { status: "completed", content: [{ type: "text", text: '{"answer":"HELLO"}' }] },
  933. },
  934. ],
  935. },
  936. ])
  937. }),
  938. )
  939. it.effect("executes the tool advertised before a registry reload", () =>
  940. Effect.gen(function* () {
  941. const session = yield* setup
  942. const registry = yield* Tool.Service
  943. const scope = yield* Scope.make()
  944. const executions: string[] = []
  945. yield* transformTools(
  946. registry,
  947. {
  948. reloaded: {
  949. name: "reloaded",
  950. description: "Record the advertised tool",
  951. input: Schema.Struct({}),
  952. output: Schema.Struct({ value: Schema.String }),
  953. execute: () =>
  954. Effect.sync(() => executions.push("advertised")).pipe(Effect.as({ output: { value: "advertised" } })),
  955. },
  956. },
  957. { codemode: false },
  958. ).pipe(Scope.provide(scope))
  959. yield* admit(session, "Use the reloaded tool")
  960. yield* TestLLM.push(TestLLM.tool("call-reloaded", "reloaded", {}), [])
  961. const stream = yield* TestLLM.gate
  962. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  963. yield* stream.started
  964. yield* Scope.close(scope, Exit.void)
  965. yield* transformTools(
  966. registry,
  967. {
  968. reloaded: {
  969. name: "reloaded",
  970. description: "Record the replacement tool",
  971. input: Schema.Struct({}),
  972. output: Schema.Struct({ value: Schema.String }),
  973. execute: () =>
  974. Effect.sync(() => executions.push("replacement")).pipe(Effect.as({ output: { value: "replacement" } })),
  975. },
  976. },
  977. { codemode: false },
  978. )
  979. yield* stream.release
  980. yield* Fiber.join(run)
  981. expect(executions).toEqual(["advertised"])
  982. expect(yield* session.context(sessionID)).toMatchObject([
  983. { type: "user", text: "Use the reloaded tool" },
  984. {
  985. type: "assistant",
  986. content: [
  987. {
  988. type: "tool",
  989. id: "call-reloaded",
  990. state: { status: "completed", content: [{ type: "text", text: '{"value":"advertised"}' }] },
  991. },
  992. ],
  993. },
  994. ])
  995. }),
  996. )
  997. it.effect("starts a real runner step after default prompt recording", () =>
  998. Effect.gen(function* () {
  999. const session = yield* setup
  1000. const message = yield* session.prompt({
  1001. sessionID,
  1002. text: "Run automatically",
  1003. })
  1004. yield* session.wait(sessionID)
  1005. expect(requests).toHaveLength(1)
  1006. expect(yield* session.messages({ sessionID })).toMatchObject([
  1007. { id: message.id, type: "user", text: "Run automatically" },
  1008. ])
  1009. }),
  1010. )
  1011. it.effect("runs a follow-up when synthetic input arrives during an active continuation", () =>
  1012. Effect.gen(function* () {
  1013. const session = yield* setup
  1014. const secondStarted = yield* Deferred.make<void>()
  1015. const releaseSecond = yield* Deferred.make<void>()
  1016. yield* TestLLM.push(
  1017. Stream.fromIterable(TestLLM.tool("call-echo", "echo", { text: "background started" })),
  1018. Stream.unwrap(
  1019. Deferred.succeed(secondStarted, undefined).pipe(
  1020. Effect.andThen(Deferred.await(releaseSecond)),
  1021. Effect.as(Stream.fromIterable(TestLLM.stop())),
  1022. ),
  1023. ),
  1024. Stream.fromIterable(TestLLM.text("Handled completion", "text-completion")),
  1025. )
  1026. yield* admit(session, "Start background work")
  1027. const running = yield* session.resume(sessionID).pipe(Effect.forkChild({ startImmediately: true }))
  1028. yield* Deferred.await(secondStarted)
  1029. yield* session.synthetic({ sessionID, text: "Background work completed" })
  1030. yield* Deferred.succeed(releaseSecond, undefined)
  1031. yield* Fiber.join(running)
  1032. expect(requests).toHaveLength(3)
  1033. expect(userTexts(requests[2])).toContain("Background work completed")
  1034. }),
  1035. )
  1036. it.effect("streams one request with registry definitions from chronological user history", () =>
  1037. Effect.gen(function* () {
  1038. const session = yield* setup
  1039. yield* admit(session, "First")
  1040. yield* runPrompt(session, "Second")
  1041. expect(requests).toHaveLength(1)
  1042. expect(requests[0]?.model).toBe(model)
  1043. expect(requests[0]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail"])
  1044. expect(requests[0]?.messages.map((message) => ({ role: message.role, content: message.content }))).toEqual([
  1045. { role: "user", content: [{ type: "text", text: "First" }] },
  1046. { role: "user", content: [{ type: "text", text: "Second" }] },
  1047. ])
  1048. expect(yield* session.messages({ sessionID })).toHaveLength(2)
  1049. }),
  1050. )
  1051. it.effect("marks the initial instruction sync as baseline metadata", () =>
  1052. Effect.gen(function* () {
  1053. const session = yield* setup
  1054. const bus = yield* Bus.Service
  1055. const instructionEvents: Event.Payload[] = []
  1056. const unsubscribe = yield* bus.listen((event) =>
  1057. Effect.sync(() => {
  1058. if (event.type === "session.instructions.updated") instructionEvents.push(event)
  1059. }),
  1060. )
  1061. yield* runPrompt(session, "First")
  1062. systemBaseline = "Changed context"
  1063. yield* runPrompt(session, "Second")
  1064. yield* unsubscribe
  1065. expect(instructionEvents).toHaveLength(2)
  1066. expect(instructionEvents[0]?.metadata).toEqual({ instructions: { initial: true } })
  1067. expect(instructionEvents[1]?.metadata).toBeUndefined()
  1068. }),
  1069. )
  1070. it.effect("retries the first request after system context becomes available", () =>
  1071. Effect.gen(function* () {
  1072. const session = yield* setup
  1073. const { db } = yield* Database.Service
  1074. const messageID = SessionMessage.ID.create()
  1075. systemUnavailable = true
  1076. yield* session.prompt({
  1077. id: messageID,
  1078. sessionID,
  1079. text: "First",
  1080. resume: false,
  1081. })
  1082. const exit = yield* session.resume(sessionID).pipe(Effect.exit)
  1083. expect(Exit.isFailure(exit)).toBe(true)
  1084. if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(Instructions.InitializationBlocked)
  1085. expect(requests).toHaveLength(0)
  1086. expect(yield* SessionPending.has(db, sessionID, "steer")).toBe(true)
  1087. expect(
  1088. yield* db.select().from(InstructionStateTable).where(eq(InstructionStateTable.session_id, sessionID)).get(),
  1089. ).toBeUndefined()
  1090. systemUnavailable = false
  1091. yield* session.prompt({ id: messageID, sessionID, text: "First" })
  1092. yield* session.wait(sessionID)
  1093. expect(requests).toHaveLength(1)
  1094. expect(messageRoles(requests[0])).toEqual(["user"])
  1095. }),
  1096. )
  1097. it.effect("interrupts a source Location runner after a Session moves", () =>
  1098. Effect.gen(function* () {
  1099. const session = yield* setup
  1100. const bus = yield* Bus.Service
  1101. const { db } = yield* Database.Service
  1102. yield* runPrompt(session, "First")
  1103. yield* bus.publish(SessionEvent.Moved, {
  1104. sessionID,
  1105. location: Location.Ref.make({ directory: AbsolutePath.make("/moved") }),
  1106. })
  1107. expect(
  1108. yield* db.select().from(InstructionStateTable).where(eq(InstructionStateTable.session_id, sessionID)).get(),
  1109. ).toBeUndefined()
  1110. yield* admit(session, "Second")
  1111. const exit = yield* session.resume(sessionID).pipe(Effect.exit)
  1112. expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBe(true)
  1113. expect(requests).toHaveLength(1)
  1114. expect(yield* SessionPending.has(db, sessionID, "steer")).toBe(true)
  1115. }),
  1116. )
  1117. it.effect("seeds a fork with the parent's newest instruction values", () =>
  1118. Effect.gen(function* () {
  1119. const session = yield* setup
  1120. yield* runPrompt(session, "First")
  1121. systemBaseline = "Changed context"
  1122. const second = yield* runPrompt(session, "Second")
  1123. systemBaseline = "Latest context"
  1124. yield* runPrompt(session, "Third")
  1125. const forked = yield* session.fork({ sessionID, boundary: { type: "before", messageID: second.id } })
  1126. expect(
  1127. yield* (yield* Database.Service).db
  1128. .select()
  1129. .from(InstructionStateTable)
  1130. .where(eq(InstructionStateTable.session_id, forked.id))
  1131. .get(),
  1132. ).toMatchObject({
  1133. initial_values: { "test/context": Instructions.hash("Latest context") },
  1134. current_values: { "test/context": Instructions.hash("Latest context") },
  1135. })
  1136. yield* session.prompt({ sessionID: forked.id, text: "Forked", resume: false })
  1137. yield* session.resume(forked.id)
  1138. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([defaultSystem, "Latest context"])
  1139. // Copied history keeps the frozen chronological update; no new update is emitted.
  1140. expect(systemTexts(requests.at(-1)!)).toContain("Changed context")
  1141. expect(systemTexts(requests.at(-1)!)).not.toContain("Latest context")
  1142. const { db } = yield* Database.Service
  1143. const bus = yield* Bus.Service
  1144. const recorded = yield* db
  1145. .select()
  1146. .from(EventTable)
  1147. .where(eq(EventTable.aggregate_id, forked.id))
  1148. .orderBy(asc(EventTable.seq))
  1149. .all()
  1150. yield* bus.remove(forked.id)
  1151. yield* db.delete(SessionTable).where(eq(SessionTable.id, forked.id)).run()
  1152. yield* bus.replayAll(
  1153. recorded.map((event) => ({
  1154. id: event.id,
  1155. created: DateTime.makeUnsafe(event.created),
  1156. aggregateID: event.aggregate_id,
  1157. seq: event.seq,
  1158. type: event.type,
  1159. data: event.data,
  1160. })),
  1161. )
  1162. expect(
  1163. yield* db.select().from(InstructionStateTable).where(eq(InstructionStateTable.session_id, forked.id)).get(),
  1164. ).toMatchObject({ current_values: { "test/context": Instructions.hash("Latest context") } })
  1165. }),
  1166. )
  1167. it.effect("keeps nested forks self-contained", () =>
  1168. Effect.gen(function* () {
  1169. const session = yield* setup
  1170. yield* runPrompt(session, "First")
  1171. systemBaseline = "Changed context"
  1172. const second = yield* runPrompt(session, "Second")
  1173. const child = yield* session.fork({ sessionID, boundary: { type: "before", messageID: second.id } })
  1174. const inheritedFirst = (yield* session.messages({ sessionID: child.id })).find(
  1175. (message) => message.type === "user" && message.text === "First",
  1176. )
  1177. if (!inheritedFirst) return yield* Effect.die(new Error("Nested fork boundary message not found"))
  1178. const grandchild = yield* session.fork({
  1179. sessionID: child.id,
  1180. boundary: { type: "before", messageID: inheritedFirst.id },
  1181. })
  1182. expect(
  1183. yield* (yield* Database.Service).db
  1184. .select()
  1185. .from(InstructionStateTable)
  1186. .where(eq(InstructionStateTable.session_id, grandchild.id))
  1187. .get(),
  1188. ).toMatchObject({
  1189. initial_values: { "test/context": Instructions.hash("Changed context") },
  1190. current_values: { "test/context": Instructions.hash("Changed context") },
  1191. })
  1192. return undefined
  1193. }),
  1194. )
  1195. it.effect("re-establishes a fresh baseline when instruction state is missing", () =>
  1196. Effect.gen(function* () {
  1197. const session = yield* setup
  1198. const { db } = yield* Database.Service
  1199. yield* runPrompt(session, "First")
  1200. yield* db.delete(InstructionStateTable).where(eq(InstructionStateTable.session_id, sessionID)).run()
  1201. yield* admit(session, "Second")
  1202. requests.length = 0
  1203. yield* session.resume(sessionID)
  1204. expect(requests).toHaveLength(1)
  1205. expect(requests[0]?.system.map((part) => part.text)).toEqual([defaultSystem, "Initial context"])
  1206. expect(messageRoles(requests[0])).toEqual(["user", "user"])
  1207. // The projected row is authoritative: a missing row admits a fresh baseline
  1208. // instead of rebuilding from durable events.
  1209. expect(
  1210. yield* db
  1211. .select({ data: EventTable.data })
  1212. .from(EventTable)
  1213. .where(eq(EventTable.type, "session.instructions.updated.2"))
  1214. .all(),
  1215. ).toHaveLength(2)
  1216. expect(yield* db.select().from(InstructionStateTable).get()).toMatchObject({
  1217. initial_values: { "test/context": Instructions.hash("Initial context") },
  1218. current_values: { "test/context": Instructions.hash("Initial context") },
  1219. })
  1220. }),
  1221. )
  1222. it.effect("keeps the initial instructions stable and derives a chronological update from values", () =>
  1223. Effect.gen(function* () {
  1224. const session = yield* setup
  1225. yield* runPrompt(session, "First")
  1226. systemBaseline = "Changed context"
  1227. yield* runPrompt(session, "Second")
  1228. expect(
  1229. PromptCacheDiagnostics.compare(
  1230. PromptCacheDiagnostics.snapshot(requests[0]),
  1231. PromptCacheDiagnostics.snapshot(requests[1]),
  1232. ),
  1233. ).toEqual({ status: "append-only", previousMessages: 1, currentMessages: 3 })
  1234. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1235. [defaultSystem, "Initial context"],
  1236. [defaultSystem, "Initial context"],
  1237. ])
  1238. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1239. expect(requests[1]?.messages.at(1)?.content).toEqual([{ type: "text", text: "Changed context" }])
  1240. // The chronological update is a durable client-visible system message.
  1241. const messages = yield* session.messages({ sessionID })
  1242. expect(messages).toHaveLength(3)
  1243. expect(messages[1]).toMatchObject({ type: "system", text: "Changed context" })
  1244. const { db } = yield* Database.Service
  1245. const updates = yield* db
  1246. .select({ data: EventTable.data })
  1247. .from(EventTable)
  1248. .where(eq(EventTable.type, "session.instructions.updated.2"))
  1249. .orderBy(asc(EventTable.seq))
  1250. .all()
  1251. .pipe(Effect.orDie)
  1252. expect(updates).toHaveLength(2)
  1253. expect(updates[0]?.data).toMatchObject({
  1254. sessionID,
  1255. delta: { "test/context": Instructions.hash("Initial context") },
  1256. })
  1257. expect(updates[1]?.data).toEqual({
  1258. sessionID,
  1259. delta: { "test/context": Instructions.hash("Changed context") },
  1260. text: "Changed context",
  1261. })
  1262. yield* replaySessionProjection(sessionID)
  1263. expect(yield* session.messages({ sessionID })).toHaveLength(3)
  1264. }),
  1265. )
  1266. it.effect("uses the selected model family prompt when the agent does not override it", () =>
  1267. Effect.gen(function* () {
  1268. const session = yield* setup
  1269. currentModel = LanguageModel.make({ id: "gpt-5", provider: "openai", route: OpenAIChat.route })
  1270. yield* admit(session, "First")
  1271. yield* TestLLM.push(TestLLM.text("Done", "text-provider-prompt"))
  1272. yield* session.resume(sessionID)
  1273. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([
  1274. expect.stringContaining("You are OpenCode, You and the user share the same workspace"),
  1275. "Initial context",
  1276. ])
  1277. }),
  1278. )
  1279. it.effect("uses the selected model family prompt when the agent system override is empty", () =>
  1280. Effect.gen(function* () {
  1281. const session = yield* setup
  1282. currentModel = LanguageModel.make({ id: "gpt-5", provider: "openai", route: OpenAIChat.route })
  1283. const agent = yield* Agent.Service
  1284. yield* agent.transform((editor) =>
  1285. editor.update(Agent.ID.make("build"), (agent) => {
  1286. agent.system = ""
  1287. agent.mode = "primary"
  1288. }),
  1289. )
  1290. yield* admit(session, "First")
  1291. yield* TestLLM.push(TestLLM.text("Done", "text-empty-agent-system"))
  1292. yield* session.resume(sessionID)
  1293. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([
  1294. expect.stringContaining("You are OpenCode, You and the user share the same workspace"),
  1295. "Initial context",
  1296. ])
  1297. }),
  1298. )
  1299. it.effect("includes the effective default agent system before durable context", () =>
  1300. Effect.gen(function* () {
  1301. const session = yield* setup
  1302. const agent = yield* Agent.Service
  1303. yield* agent.transform((editor) =>
  1304. editor.update(Agent.ID.make("build"), (agent) => {
  1305. agent.system = "Build agent instructions"
  1306. agent.mode = "primary"
  1307. }),
  1308. )
  1309. yield* admit(session, "First")
  1310. yield* TestLLM.push(TestLLM.text("Done", "text-build"))
  1311. yield* session.resume(sessionID)
  1312. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Build agent instructions", "Initial context"])
  1313. }),
  1314. )
  1315. it.effect("uses the configured default agent system for omitted-agent sessions", () =>
  1316. Effect.gen(function* () {
  1317. const session = yield* setup
  1318. const agent = yield* Agent.Service
  1319. yield* agent.transform((editor) => {
  1320. editor.update(Agent.ID.make("build"), (agent) => {
  1321. agent.system = "Build agent instructions"
  1322. agent.mode = "primary"
  1323. })
  1324. editor.update(Agent.ID.make("reviewer"), (agent) => {
  1325. agent.system = "Reviewer instructions"
  1326. agent.mode = "primary"
  1327. })
  1328. editor.default(Agent.ID.make("reviewer"))
  1329. })
  1330. yield* admit(session, "First")
  1331. yield* TestLLM.push(TestLLM.text("Done", "text-reviewer"))
  1332. yield* session.resume(sessionID)
  1333. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Reviewer instructions", "Initial context"])
  1334. expect((yield* session.messages({ sessionID }))[0]).toMatchObject({ type: "assistant", agent: "reviewer" })
  1335. }),
  1336. )
  1337. it.effect("uses only the agent prompt and initial instructions as system parts", () =>
  1338. Effect.gen(function* () {
  1339. const session = yield* setup
  1340. const agent = yield* Agent.Service
  1341. yield* agent.transform((editor) =>
  1342. editor.update(Agent.ID.make("build"), (agent) => {
  1343. agent.system = "Build agent instructions"
  1344. agent.mode = "primary"
  1345. }),
  1346. )
  1347. yield* admit(session, "First")
  1348. yield* TestLLM.push(TestLLM.text("Done", "text-no-system"))
  1349. yield* session.resume(sessionID)
  1350. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Build agent instructions", "Initial context"])
  1351. }),
  1352. )
  1353. it.effect("uses an explicitly selected non-build agent system", () =>
  1354. Effect.gen(function* () {
  1355. const session = yield* setup
  1356. const { db } = yield* Database.Service
  1357. const agent = yield* Agent.Service
  1358. yield* agent.transform((editor) =>
  1359. editor.update(Agent.ID.make("reviewer"), (agent) => {
  1360. agent.system = "Reviewer instructions"
  1361. agent.mode = "primary"
  1362. }),
  1363. )
  1364. yield* db
  1365. .update(SessionTable)
  1366. .set({ agent: "reviewer" })
  1367. .where(eq(SessionTable.id, sessionID))
  1368. .run()
  1369. .pipe(Effect.orDie)
  1370. yield* admit(session, "First")
  1371. yield* TestLLM.push(TestLLM.text("Done", "text-selected"))
  1372. yield* session.resume(sessionID)
  1373. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Reviewer instructions", "Initial context"])
  1374. expect((yield* session.messages({ sessionID }))[0]).toMatchObject({ type: "assistant", agent: "reviewer" })
  1375. }),
  1376. )
  1377. it.effect("fails before the model request when the selected agent is unavailable", () =>
  1378. Effect.gen(function* () {
  1379. yield* setup
  1380. const { db } = yield* Database.Service
  1381. yield* db
  1382. .update(SessionTable)
  1383. .set({ agent: "explore" })
  1384. .where(eq(SessionTable.id, sessionID))
  1385. .run()
  1386. .pipe(Effect.orDie)
  1387. const session = yield* Session.Service
  1388. yield* session.prompt({ sessionID, text: "Inspect files", resume: false })
  1389. requests.length = 0
  1390. yield* TestLLM.push([])
  1391. const failure = yield* session.resume(sessionID).pipe(Effect.flip)
  1392. expect(failure).toMatchObject({
  1393. _tag: "Session.AgentNotFoundError",
  1394. sessionID,
  1395. agent: "explore",
  1396. })
  1397. expect(requests).toHaveLength(0)
  1398. }),
  1399. )
  1400. it.effect("waits for initial plugin readiness before constructing the model request", () =>
  1401. Effect.gen(function* () {
  1402. yield* setup
  1403. const release = yield* Deferred.make<void>()
  1404. pluginFlushHook = Deferred.await(release)
  1405. const session = yield* Session.Service
  1406. yield* session.prompt({ sessionID, text: "Wait for plugins", resume: false })
  1407. requests.length = 0
  1408. yield* TestLLM.push([])
  1409. const running = yield* session.resume(sessionID).pipe(Effect.forkChild({ startImmediately: true }))
  1410. yield* Effect.yieldNow
  1411. expect(requests).toHaveLength(0)
  1412. expect(running.pollUnsafe()).toBeUndefined()
  1413. yield* Deferred.succeed(release, undefined)
  1414. yield* Fiber.join(running)
  1415. expect(requests).toHaveLength(1)
  1416. }),
  1417. )
  1418. it.effect("updates selected-agent skill instructions after an agent switch", () =>
  1419. Effect.gen(function* () {
  1420. const session = yield* setup
  1421. const bus = yield* Bus.Service
  1422. const agents = yield* Agent.Service
  1423. yield* agents.transform((draft) =>
  1424. draft.update(Agent.ID.make("reviewer"), (agent) => {
  1425. agent.mode = "primary"
  1426. }),
  1427. )
  1428. skillBaselines.set(Agent.ID.make("build"), "Build skills")
  1429. yield* runPrompt(session, "First")
  1430. skillBaselines.set(Agent.ID.make("reviewer"), "Reviewer skills")
  1431. yield* bus.publish(SessionEvent.AgentSelected, {
  1432. sessionID,
  1433. agent: Agent.ID.make("reviewer"),
  1434. })
  1435. yield* runPrompt(session, "Second")
  1436. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1437. [defaultSystem, "Initial context\n\nBuild skills"],
  1438. [defaultSystem, "Initial context\n\nBuild skills"],
  1439. ])
  1440. expect(systemTexts(requests[1])).toContainEqual(expect.stringContaining("Reviewer skills"))
  1441. }),
  1442. )
  1443. it.effect("keeps the sampled agent when selection changes during observation", () =>
  1444. Effect.gen(function* () {
  1445. const session = yield* setup
  1446. const bus = yield* Bus.Service
  1447. skillBaselines.set(Agent.ID.make("build"), "Build skills")
  1448. skillBaselines.set(Agent.ID.make("reviewer"), "Reviewer skills")
  1449. let switched = false
  1450. systemLoadHook = Effect.suspend(() => {
  1451. if (switched) return Effect.void
  1452. switched = true
  1453. return bus
  1454. .publish(SessionEvent.AgentSelected, {
  1455. sessionID,
  1456. agent: Agent.ID.make("reviewer"),
  1457. })
  1458. .pipe(Effect.asVoid)
  1459. })
  1460. yield* runPrompt(session, "First")
  1461. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1462. [defaultSystem, "Initial context\n\nBuild skills"],
  1463. ])
  1464. }),
  1465. )
  1466. it.effect("keeps the sampled model when selection changes during model resolution", () =>
  1467. Effect.gen(function* () {
  1468. const session = yield* setup
  1469. const bus = yield* Bus.Service
  1470. let switched = false
  1471. modelResolveHook = Effect.suspend(() => {
  1472. if (switched) return Effect.void
  1473. switched = true
  1474. return bus
  1475. .publish(SessionEvent.ModelSelected, {
  1476. sessionID,
  1477. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  1478. })
  1479. .pipe(Effect.asVoid)
  1480. })
  1481. yield* runPrompt(session, "First")
  1482. expect(requests.map((request) => request.model)).toEqual([model])
  1483. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1484. [defaultSystem, "Initial context"],
  1485. ])
  1486. }),
  1487. )
  1488. it.effect("admits removed context as a chronological System message", () =>
  1489. Effect.gen(function* () {
  1490. const session = yield* setup
  1491. yield* runPrompt(session, "First")
  1492. systemRemoved = true
  1493. yield* runPrompt(session, "Second")
  1494. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1495. expect(requests[1]?.messages.at(1)?.content).toEqual([
  1496. { type: "text", text: "System context source removed: test/context" },
  1497. ])
  1498. expect(yield* session.messages({ sessionID })).toHaveLength(3)
  1499. }),
  1500. )
  1501. it.effect("renders API context entries through add, change, and removal", () =>
  1502. Effect.gen(function* () {
  1503. const session = yield* setup
  1504. const contextEntries = yield* InstructionEntry.Service
  1505. yield* contextEntries.put({ sessionID, key: "deploy-target", value: "production" })
  1506. yield* runPrompt(session, "First")
  1507. // String values render verbatim inside the initial tagged block.
  1508. expect(requests[0]?.system.map((part) => part.text)).toEqual([
  1509. defaultSystem,
  1510. ["Initial context", "", '<context key="deploy-target">', "production", "</context>"].join("\n"),
  1511. ])
  1512. // Non-string JSON pretty-prints; the change narrates as a System update.
  1513. yield* contextEntries.put({ sessionID, key: "deploy-target", value: { region: "us-east-1" } })
  1514. yield* runPrompt(session, "Second")
  1515. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1516. expect(requests[1]?.messages.at(1)?.content).toEqual([
  1517. {
  1518. type: "text",
  1519. text: [
  1520. 'The context under "deploy-target" changed and supersedes the previous value:',
  1521. '<context key="deploy-target">',
  1522. "{",
  1523. ' "region": "us-east-1"',
  1524. "}",
  1525. "</context>",
  1526. ].join("\n"),
  1527. },
  1528. ])
  1529. expect(yield* contextEntries.list(sessionID)).toEqual([{ key: "deploy-target", value: { region: "us-east-1" } }])
  1530. // Deleting the row announces removal through the stored removal text.
  1531. yield* contextEntries.remove({ sessionID, key: "deploy-target" })
  1532. yield* runPrompt(session, "Third")
  1533. expect(messageRoles(requests[2])).toEqual(["user", "system", "user", "system", "user"])
  1534. expect(requests[2]?.messages.at(-2)?.content).toEqual([
  1535. { type: "text", text: 'The context under "deploy-target" no longer applies. Disregard it.' },
  1536. ])
  1537. expect(yield* contextEntries.list(sessionID)).toEqual([])
  1538. }),
  1539. )
  1540. it.effect("retains JSON null API entries as values", () =>
  1541. Effect.gen(function* () {
  1542. const session = yield* setup
  1543. const entries = yield* InstructionEntry.Service
  1544. yield* entries.put({ sessionID, key: "nullable", value: "present" })
  1545. yield* runPrompt(session, "First")
  1546. yield* entries.put({ sessionID, key: "nullable", value: null })
  1547. yield* runPrompt(session, "Second")
  1548. expect(requests[1]?.messages.at(1)?.content).toEqual([
  1549. {
  1550. type: "text",
  1551. text: [
  1552. 'The context under "nullable" changed and supersedes the previous value:',
  1553. '<context key="nullable">',
  1554. "null",
  1555. "</context>",
  1556. ].join("\n"),
  1557. },
  1558. ])
  1559. expect(yield* entries.list(sessionID)).toEqual([{ key: "nullable", value: null }])
  1560. }),
  1561. )
  1562. it.effect("rejects API instruction entries larger than 8KB", () =>
  1563. Effect.gen(function* () {
  1564. yield* setup
  1565. const entries = yield* InstructionEntry.Service
  1566. const exit = yield* entries
  1567. .put({ sessionID, key: "oversized", value: "x".repeat(InstructionEntry.MaxValueBytes) })
  1568. .pipe(Effect.exit)
  1569. expect(Exit.isFailure(exit)).toBe(true)
  1570. if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(InstructionEntry.ValueTooLargeError)
  1571. expect(yield* entries.list(sessionID)).toEqual([])
  1572. }),
  1573. )
  1574. it.effect("keeps initial instructions and chronological updates after a model switch", () =>
  1575. Effect.gen(function* () {
  1576. const session = yield* setup
  1577. const bus = yield* Bus.Service
  1578. yield* runPrompt(session, "First")
  1579. systemBaseline = "Changed context"
  1580. yield* runPrompt(session, "Second")
  1581. yield* bus.publish(SessionEvent.ModelSelected, {
  1582. sessionID,
  1583. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  1584. })
  1585. systemBaseline = "Replacement context"
  1586. yield* runPrompt(session, "Third")
  1587. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1588. [defaultSystem, "Initial context"],
  1589. [defaultSystem, "Initial context"],
  1590. [defaultSystem, "Initial context"],
  1591. ])
  1592. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1593. expect(requests[2]?.messages.filter((message) => message.role === "system")).toHaveLength(2)
  1594. expect((yield* session.context(sessionID)).map((message) => message.type)).toEqual([
  1595. "user",
  1596. "system",
  1597. "user",
  1598. "model-switched",
  1599. "system",
  1600. "user",
  1601. ])
  1602. yield* replaySessionProjection(sessionID)
  1603. expect(yield* session.messages({ sessionID })).toHaveLength(6)
  1604. yield* runPrompt(session, "Fourth")
  1605. }),
  1606. )
  1607. it.effect("preserves instruction values while a source is temporarily unavailable", () =>
  1608. Effect.gen(function* () {
  1609. const session = yield* setup
  1610. const bus = yield* Bus.Service
  1611. yield* runPrompt(session, "First")
  1612. yield* bus.publish(SessionEvent.ModelSelected, {
  1613. sessionID,
  1614. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  1615. })
  1616. systemUnavailable = true
  1617. yield* runPrompt(session, "Second")
  1618. systemUnavailable = false
  1619. systemBaseline = "Replacement context"
  1620. yield* runPrompt(session, "Third")
  1621. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1622. [defaultSystem, "Initial context"],
  1623. [defaultSystem, "Initial context"],
  1624. [defaultSystem, "Initial context"],
  1625. ])
  1626. }),
  1627. )
  1628. it.effect("moves the epoch at compaction and narrates later changes", () =>
  1629. Effect.gen(function* () {
  1630. const session = yield* setup
  1631. const bus = yield* Bus.Service
  1632. yield* runPrompt(session, "First")
  1633. yield* bus.publish(SessionEvent.Compaction.Started, {
  1634. sessionID,
  1635. reason: "manual",
  1636. recent: "",
  1637. })
  1638. yield* bus.publish(SessionEvent.Compaction.Ended, {
  1639. sessionID,
  1640. reason: "manual",
  1641. text: "summary",
  1642. recent: "",
  1643. })
  1644. systemBaseline = "Replacement context"
  1645. yield* runPrompt(session, "Second")
  1646. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1647. [defaultSystem, "Initial context"],
  1648. [defaultSystem, "Initial context"],
  1649. ])
  1650. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1651. expect(requests[1]?.messages.at(1)?.content).toEqual([{ type: "text", text: "Replacement context" }])
  1652. yield* replaySessionProjection(sessionID)
  1653. yield* runPrompt(session, "Third")
  1654. }),
  1655. )
  1656. it.effect("runs one durable compaction barrier after tool settlement and before later inputs", () =>
  1657. Effect.gen(function* () {
  1658. const session = yield* setup
  1659. currentModel = recoveryModel
  1660. const stream = yield* TestLLM.gate
  1661. yield* TestLLM.push(
  1662. TestLLM.tool("call-active", "echo", { text: "active" }),
  1663. [LLMEvent.textDelta({ id: "summary", text: "durable summary" })],
  1664. TestLLM.text("Steer complete", "text-steer"),
  1665. TestLLM.text("Queue complete", "text-queue"),
  1666. )
  1667. yield* admit(session, "Active work")
  1668. const active = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1669. yield* stream.started
  1670. const first = yield* session.compact({ sessionID })
  1671. const second = yield* session.compact({ sessionID })
  1672. expect(second.id).toBe(first.id)
  1673. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toMatchObject({
  1674. id: first.id,
  1675. })
  1676. expect((yield* session.messages({ sessionID })).find((message) => message.id === first.id)).toBeUndefined()
  1677. yield* admit(session, "Steer after compaction")
  1678. yield* session.synthetic({ sessionID, text: "Completion after compaction", resume: false })
  1679. yield* session.prompt({
  1680. sessionID,
  1681. text: "Queue after compaction",
  1682. delivery: "queue",
  1683. resume: false,
  1684. })
  1685. expect(yield* SessionPending.has((yield* Database.Service).db, sessionID, "steer")).toBe(false)
  1686. yield* stream.release
  1687. yield* Fiber.join(active)
  1688. expect(requests).toHaveLength(4)
  1689. expect(userTexts(requests[1])[0]).toContain("Create a new anchored summary")
  1690. expect(userTexts(requests[2])).toContain("Steer after compaction")
  1691. expect(userTexts(requests[2])).toContain("Completion after compaction")
  1692. expect(userTexts(requests[3])).toContain("Queue after compaction")
  1693. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1694. expect((yield* session.messages({ sessionID })).find((message) => message.id === first.id)).toMatchObject({
  1695. type: "compaction",
  1696. status: "completed",
  1697. summary: "durable summary",
  1698. })
  1699. }),
  1700. )
  1701. it.effect("releases queued prompts when durable compaction fails", () =>
  1702. Effect.gen(function* () {
  1703. const session = yield* setup
  1704. currentModel = recoveryModel
  1705. const stream = yield* TestLLM.gate
  1706. yield* TestLLM.push(
  1707. TestLLM.text("Active complete", "text-active-failure"),
  1708. [],
  1709. TestLLM.text("Continued", "text-after-failure"),
  1710. )
  1711. yield* admit(session, "Active work")
  1712. const active = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1713. yield* stream.started
  1714. const compaction = yield* session.compact({ sessionID })
  1715. yield* session.prompt({
  1716. sessionID,
  1717. text: "Continue after failure",
  1718. delivery: "queue",
  1719. resume: false,
  1720. })
  1721. yield* stream.release
  1722. yield* Fiber.join(active)
  1723. expect(requests).toHaveLength(3)
  1724. expect(userTexts(requests[2])).toContain("Continue after failure")
  1725. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1726. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1727. type: "compaction",
  1728. status: "failed",
  1729. })
  1730. expect(
  1731. (yield* recordedEventTypes(sessionID)).filter(
  1732. (type) => type === Bus.versionedType(SessionEvent.Compaction.Failed.type, 1),
  1733. ),
  1734. ).toHaveLength(1)
  1735. }),
  1736. )
  1737. it.effect("explains when manual compaction has no history", () =>
  1738. Effect.gen(function* () {
  1739. yield* setup
  1740. const session = yield* Session.Service
  1741. const compaction = yield* session.compact({ sessionID })
  1742. modelResolveHook = Effect.die("model resolution should not run")
  1743. yield* session.resume(sessionID)
  1744. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1745. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1746. type: "compaction",
  1747. status: "failed",
  1748. reason: "manual",
  1749. error: { type: "compaction.unavailable", message: "Nothing to compact yet" },
  1750. })
  1751. expect(
  1752. (yield* recordedEventTypes(sessionID)).filter(
  1753. (type) => type === Bus.versionedType(SessionEvent.Compaction.Failed.type, 1),
  1754. ),
  1755. ).toHaveLength(1)
  1756. }),
  1757. )
  1758. it.effect("manually compacts when the model has no context limit", () =>
  1759. Effect.gen(function* () {
  1760. const session = yield* setup
  1761. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-unknown-history"))
  1762. yield* runPrompt(session, "Earlier question")
  1763. requests.length = 0
  1764. yield* TestLLM.push(TestLLM.text("Manual summary", "text-manual-unknown-summary"))
  1765. const compaction = yield* session.compact({ sessionID })
  1766. yield* session.resume(sessionID)
  1767. expect(requests).toHaveLength(1)
  1768. expect(userTexts(requests[0])[0]).toContain("Earlier question")
  1769. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1770. type: "compaction",
  1771. status: "completed",
  1772. summary: "Manual summary",
  1773. })
  1774. }),
  1775. )
  1776. it.effect("preserves provider errors from manual compaction", () =>
  1777. Effect.gen(function* () {
  1778. const session = yield* setup
  1779. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-provider-history"))
  1780. yield* runPrompt(session, "Earlier question")
  1781. yield* TestLLM.push([LLMEvent.providerError({ message: "summary unavailable" })])
  1782. const compaction = yield* session.compact({ sessionID })
  1783. yield* session.resume(sessionID)
  1784. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1785. type: "compaction",
  1786. status: "failed",
  1787. error: { type: "provider.error", message: "summary unavailable" },
  1788. })
  1789. }),
  1790. )
  1791. it.effect("preserves typed provider failures from manual compaction", () =>
  1792. Effect.gen(function* () {
  1793. const session = yield* setup
  1794. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-failure-history"))
  1795. yield* runPrompt(session, "Earlier question")
  1796. yield* TestLLM.push(Stream.fail(providerUnavailable()))
  1797. const compaction = yield* session.compact({ sessionID })
  1798. yield* session.resume(sessionID)
  1799. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1800. type: "compaction",
  1801. status: "failed",
  1802. error: { type: "provider.transport", message: "Provider unavailable" },
  1803. })
  1804. }),
  1805. )
  1806. it.effect("records cancelled manual compaction without surfacing an internal failure", () =>
  1807. Effect.gen(function* () {
  1808. const session = yield* setup
  1809. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-interrupt-history"))
  1810. yield* runPrompt(session, "Earlier question")
  1811. const streamed = yield* Deferred.make<void>()
  1812. const partial = fragmentFixture("text", "text-manual-interrupt-summary", ["Partial summary"])
  1813. yield* TestLLM.push(
  1814. Stream.concat(
  1815. Stream.fromIterable(partial.partialEvents),
  1816. Stream.fromEffect(Deferred.succeed(streamed, undefined)).pipe(Stream.flatMap(() => Stream.never)),
  1817. ),
  1818. )
  1819. const compaction = yield* session.compact({ sessionID })
  1820. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1821. yield* Deferred.await(streamed)
  1822. yield* session.interrupt(sessionID)
  1823. yield* Fiber.await(run)
  1824. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1825. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1826. type: "compaction",
  1827. status: "failed",
  1828. reason: "manual",
  1829. error: { type: "aborted", message: "Compaction cancelled" },
  1830. })
  1831. }),
  1832. )
  1833. it.effect("settles an admitted manual compaction when pre-start resolution throws", () =>
  1834. Effect.gen(function* () {
  1835. const session = yield* setup
  1836. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-resolution-history"))
  1837. yield* runPrompt(session, "Earlier question")
  1838. const compaction = yield* session.compact({ sessionID })
  1839. modelResolveHook = Effect.die("model resolution failed")
  1840. expect(yield* Effect.exit(session.resume(sessionID))).toMatchObject({ _tag: "Failure" })
  1841. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1842. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1843. type: "compaction",
  1844. status: "failed",
  1845. reason: "manual",
  1846. })
  1847. expect(
  1848. (yield* recordedEventTypes(sessionID)).filter(
  1849. (type) => type === Bus.versionedType(SessionEvent.Compaction.Failed.type, 1),
  1850. ),
  1851. ).toHaveLength(1)
  1852. }),
  1853. )
  1854. it.effect("automatically compacts into a completed summary and retained recent turn", () =>
  1855. Effect.gen(function* () {
  1856. const session = yield* setup
  1857. yield* TestLLM.push(TestLLM.textWithUsage("Earlier answer", "text-first", 3_950))
  1858. yield* runPrompt(session, "Earlier question ".repeat(180))
  1859. currentModel = compactModel
  1860. requests.length = 0
  1861. yield* TestLLM.push(
  1862. TestLLM.text("## Objective\n- Preserve the task", "text-summary"),
  1863. TestLLM.textWithUsage("Continued", "text-final", 3_950),
  1864. )
  1865. yield* runPrompt(session, "Recent exact request ".repeat(180))
  1866. expect(requests).toHaveLength(2)
  1867. expect(userTexts(requests[0])[0]).toContain("## Objective")
  1868. expect(userTexts(requests[1])).toHaveLength(1)
  1869. expect(userTexts(requests[1])[0]).toContain("<summary>\n## Objective\n- Preserve the task\n</summary>")
  1870. expect(userTexts(requests[1])[0]).toContain(`[User]: ${"Recent exact request ".repeat(180)}`)
  1871. const context = yield* (yield* SessionStore.Service).context(sessionID)
  1872. expect(context.map((message) => message.type)).toEqual(["compaction", "assistant"])
  1873. expect(context[0]).toMatchObject({
  1874. type: "compaction",
  1875. summary: "## Objective\n- Preserve the task",
  1876. })
  1877. requests.length = 0
  1878. executions.length = 0
  1879. yield* TestLLM.push(
  1880. TestLLM.text("## Objective\n- Preserve the updated task", "text-summary-2"),
  1881. TestLLM.text("Continued again", "text-final-2"),
  1882. )
  1883. yield* runPrompt(session, "Newest exact request ".repeat(180))
  1884. expect(requests).toHaveLength(2)
  1885. expect(userTexts(requests[0])[0]).toContain(
  1886. "<previous-summary>\n## Objective\n- Preserve the task\n</previous-summary>",
  1887. )
  1888. expect(userTexts(requests[0])[0]).toContain("Recent exact request")
  1889. expect((yield* (yield* SessionStore.Service).context(sessionID))[0]).toMatchObject({
  1890. type: "compaction",
  1891. summary: "## Objective\n- Preserve the updated task",
  1892. })
  1893. }),
  1894. )
  1895. it.effect("does not compact immediately when the advertised output limit fills the context", () =>
  1896. Effect.gen(function* () {
  1897. const session = yield* setup
  1898. currentModel = fullOutputModel
  1899. yield* TestLLM.push(TestLLM.textWithUsage("Earlier answer", "text-full-output-first", 9_500))
  1900. yield* runPrompt(session, "Earlier question")
  1901. requests.length = 0
  1902. yield* TestLLM.push(TestLLM.text("Continued", "text-full-output-final"))
  1903. yield* runPrompt(session, "Continue")
  1904. expect(requests).toHaveLength(1)
  1905. expect(userTexts(requests[0])).toContain("Continue")
  1906. expect(yield* session.context(sessionID)).not.toContainEqual(expect.objectContaining({ type: "compaction" }))
  1907. }),
  1908. )
  1909. it.effect("stops after required automatic compaction fails", () =>
  1910. Effect.gen(function* () {
  1911. const session = yield* setup
  1912. yield* TestLLM.push(TestLLM.textWithUsage("Earlier answer", "text-before-failed-compaction", 3_950))
  1913. yield* runPrompt(session, "Earlier question ".repeat(180))
  1914. currentModel = compactModel
  1915. requests.length = 0
  1916. yield* TestLLM.push(
  1917. [LLMEvent.providerError({ message: "Unsupported parameter: max_output_tokens" })],
  1918. TestLLM.text("Must not run", "text-after-failed-compaction"),
  1919. )
  1920. yield* admit(session, "Recent exact request ".repeat(180))
  1921. expect(yield* Effect.exit(session.resume(sessionID))).toMatchObject({ _tag: "Failure" })
  1922. expect(requests).toHaveLength(1)
  1923. expect(requests[0]?.generation).toBeUndefined()
  1924. expect(yield* session.context(sessionID)).toContainEqual(
  1925. expect.objectContaining({
  1926. type: "compaction",
  1927. status: "failed",
  1928. reason: "auto",
  1929. error: expect.objectContaining({ message: "Unsupported parameter: max_output_tokens" }),
  1930. }),
  1931. )
  1932. }),
  1933. )
  1934. it.effect("forces one compaction and retries after provider context overflow", () =>
  1935. Effect.gen(function* () {
  1936. const session = yield* setupOverflowRecovery
  1937. yield* TestLLM.push(
  1938. [
  1939. LLMEvent.stepStart({ index: 0 }),
  1940. LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" }),
  1941. ],
  1942. TestLLM.text("## Objective\n- Recover overflow", "text-summary"),
  1943. TestLLM.text("Recovered", "text-final"),
  1944. )
  1945. yield* runPrompt(session, "Continue")
  1946. expect(requests).toHaveLength(3)
  1947. expect(userTexts(requests[1])[0]).toContain("## Objective")
  1948. expect(userTexts(requests[2])[0]).toContain("<summary>\n## Objective\n- Recover overflow\n</summary>")
  1949. expect(yield* session.context(sessionID)).toMatchObject([
  1950. { type: "compaction", summary: "## Objective\n- Recover overflow" },
  1951. { type: "assistant", finish: "stop" },
  1952. ])
  1953. yield* replaySessionProjection(sessionID)
  1954. expect(yield* session.context(sessionID)).toMatchObject([
  1955. { type: "compaction" },
  1956. { type: "assistant", finish: "stop" },
  1957. ])
  1958. }),
  1959. )
  1960. it.effect("recovers from provider context overflow without a configured context limit", () =>
  1961. Effect.gen(function* () {
  1962. const session = yield* setupOverflowRecovery
  1963. currentModel = model
  1964. yield* TestLLM.push(
  1965. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  1966. TestLLM.text("## Objective\n- Recover unknown limit", "text-summary-unknown-limit"),
  1967. TestLLM.text("Recovered", "text-final-unknown-limit"),
  1968. )
  1969. yield* runPrompt(session, "Continue")
  1970. expect(requests).toHaveLength(3)
  1971. expect(yield* session.context(sessionID)).toMatchObject([
  1972. { type: "compaction", summary: "## Objective\n- Recover unknown limit" },
  1973. { type: "assistant", finish: "stop" },
  1974. ])
  1975. }),
  1976. )
  1977. it.effect("recovers from provider context overflow despite an undersized configured context limit", () =>
  1978. Effect.gen(function* () {
  1979. const session = yield* setupOverflowRecovery
  1980. currentModel = undersizedContextModel
  1981. yield* TestLLM.push(
  1982. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  1983. TestLLM.text("## Objective\n- Recover undersized limit", "text-summary-undersized-limit"),
  1984. TestLLM.text("Recovered", "text-final-undersized-limit"),
  1985. )
  1986. yield* runPrompt(session, "Continue")
  1987. expect(requests).toHaveLength(3)
  1988. expect(yield* session.context(sessionID)).toMatchObject([
  1989. { type: "compaction", summary: "## Objective\n- Recover undersized limit" },
  1990. { type: "assistant", finish: "stop" },
  1991. ])
  1992. }),
  1993. )
  1994. it.effect("persists a second context overflow after one recovery", () =>
  1995. Effect.gen(function* () {
  1996. const session = yield* setupOverflowRecovery
  1997. const overflow = () => [
  1998. LLMEvent.stepStart({ index: 0 }),
  1999. LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" }),
  2000. ]
  2001. yield* TestLLM.push(overflow(), TestLLM.text("## Objective\n- Recover once", "text-summary"), overflow())
  2002. yield* admit(session, "Continue")
  2003. expect((yield* session.resume(sessionID).pipe(Effect.flip)).message).toBe("prompt too long")
  2004. expect(requests).toHaveLength(3)
  2005. expect(yield* session.context(sessionID)).toMatchObject([
  2006. { type: "compaction" },
  2007. { type: "assistant", finish: "error", error: { message: "prompt too long" } },
  2008. ])
  2009. }),
  2010. )
  2011. it.effect("recovers once from a raw context overflow failure", () =>
  2012. Effect.gen(function* () {
  2013. const session = yield* setupOverflowRecovery
  2014. yield* TestLLM.push(
  2015. Stream.fail(
  2016. new AIError({
  2017. module: "test",
  2018. method: "stream",
  2019. reason: new InvalidRequestReason({
  2020. message: "prompt too long",
  2021. classification: "context-overflow",
  2022. }),
  2023. }),
  2024. ),
  2025. )
  2026. yield* TestLLM.push(
  2027. TestLLM.text("## Objective\n- Recover raw overflow", "text-summary"),
  2028. TestLLM.text("Recovered", "text-final"),
  2029. )
  2030. yield* runPrompt(session, "Continue")
  2031. expect(requests).toHaveLength(3)
  2032. expect(yield* session.context(sessionID)).toMatchObject([
  2033. { type: "compaction", summary: "## Objective\n- Recover raw overflow" },
  2034. { type: "assistant", finish: "stop" },
  2035. ])
  2036. }),
  2037. )
  2038. it.effect("publishes the original overflow when recovery summarization fails", () =>
  2039. Effect.gen(function* () {
  2040. const session = yield* setupOverflowRecovery
  2041. yield* TestLLM.push(
  2042. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  2043. [LLMEvent.providerError({ message: "summary unavailable" })],
  2044. )
  2045. yield* admit(session, "Continue")
  2046. expect((yield* session.resume(sessionID).pipe(Effect.flip)).message).toBe("prompt too long")
  2047. expect(requests).toHaveLength(2)
  2048. const context = yield* session.context(sessionID)
  2049. expect(context).toContainEqual(
  2050. expect.objectContaining({
  2051. type: "compaction",
  2052. status: "failed",
  2053. reason: "auto",
  2054. error: { type: "provider.error", message: "summary unavailable" },
  2055. }),
  2056. )
  2057. expect(context.slice(-3)).toMatchObject([
  2058. { type: "user", text: "Continue" },
  2059. { type: "compaction", status: "failed", reason: "auto" },
  2060. { type: "assistant", finish: "error", error: { message: "prompt too long" } },
  2061. ])
  2062. }),
  2063. )
  2064. it.effect("interrupts overflow recovery while the summary provider is running", () =>
  2065. Effect.gen(function* () {
  2066. const session = yield* setupOverflowRecovery
  2067. yield* TestLLM.push(
  2068. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  2069. TestLLM.text("## Objective\n- Interrupted", "text-summary"),
  2070. )
  2071. const first = yield* TestLLM.gate
  2072. yield* admit(session, "Continue")
  2073. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2074. yield* first.started
  2075. const summary = yield* TestLLM.gate
  2076. yield* first.release
  2077. yield* summary.started
  2078. yield* session.interrupt(sessionID)
  2079. const exit = yield* Fiber.await(run)
  2080. expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBeTrue()
  2081. expect(yield* session.context(sessionID)).toContainEqual(
  2082. expect.objectContaining({
  2083. type: "compaction",
  2084. status: "failed",
  2085. reason: "auto",
  2086. error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
  2087. }),
  2088. )
  2089. }),
  2090. )
  2091. it.effect("uses epoch values after compaction while a source is unavailable", () =>
  2092. Effect.gen(function* () {
  2093. const session = yield* setup
  2094. const bus = yield* Bus.Service
  2095. yield* runPrompt(session, "First")
  2096. systemBaseline = "Changed context"
  2097. yield* runPrompt(session, "Second")
  2098. yield* bus.publish(SessionEvent.Compaction.Started, {
  2099. sessionID,
  2100. reason: "manual",
  2101. recent: "",
  2102. })
  2103. yield* bus.publish(SessionEvent.Compaction.Ended, {
  2104. sessionID,
  2105. reason: "manual",
  2106. text: "summary",
  2107. recent: "",
  2108. })
  2109. systemUnavailable = true
  2110. yield* runPrompt(session, "Third")
  2111. // Compaction already moved current values into the new epoch before the unavailable read.
  2112. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([defaultSystem, "Changed context"])
  2113. expect(systemTexts(requests.at(-1)!)).not.toContain("Changed context")
  2114. }),
  2115. )
  2116. it.effect("projects reasoning and tool events without executing or continuing tools", () =>
  2117. Effect.gen(function* () {
  2118. const session = yield* setup
  2119. yield* admit(session, "Use tools")
  2120. yield* TestLLM.push(
  2121. TestLLM.complete(
  2122. {
  2123. reason: { normalized: "tool-calls" },
  2124. usage: {
  2125. inputTokens: 10,
  2126. nonCachedInputTokens: 8,
  2127. outputTokens: 4,
  2128. reasoningTokens: 1,
  2129. cacheReadInputTokens: 2,
  2130. },
  2131. },
  2132. LLMEvent.reasoningStart({ id: "reasoning-1" }),
  2133. LLMEvent.reasoningDelta({ id: "reasoning-1", text: "Think" }),
  2134. LLMEvent.reasoningEnd({ id: "reasoning-1" }),
  2135. LLMEvent.toolInputStart({ id: "call-error", name: "write" }),
  2136. LLMEvent.toolInputDelta({ id: "call-error", name: "write", text: '{"path":"README.md"}' }),
  2137. LLMEvent.toolInputEnd({ id: "call-error", name: "write" }),
  2138. LLMEvent.toolCall({ id: "call-error", name: "write", input: { path: "README.md" }, providerExecuted: true }),
  2139. LLMEvent.toolError({ id: "call-error", name: "write", message: "Denied" }),
  2140. LLMEvent.toolResult({ id: "call-error", name: "write", result: { type: "error", value: "Denied" } }),
  2141. LLMEvent.toolCall({
  2142. id: "call-provider",
  2143. name: "web_search",
  2144. input: { query: "hello" },
  2145. providerExecuted: true,
  2146. providerMetadata: { openai: { source: "provider" } },
  2147. }),
  2148. LLMEvent.toolResult({
  2149. id: "call-provider",
  2150. name: "web_search",
  2151. result: {
  2152. type: "content",
  2153. value: [
  2154. { type: "text", text: "Hello" },
  2155. { type: "file", uri: "data:image/png;base64,aGVsbG8=", mime: "image/png", name: "hello.png" },
  2156. ],
  2157. },
  2158. providerExecuted: true,
  2159. providerMetadata: { openai: { source: "provider" } },
  2160. }),
  2161. ),
  2162. )
  2163. yield* session.resume(sessionID)
  2164. expect(requests).toHaveLength(1)
  2165. expect(requests[0]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail"])
  2166. expect(yield* session.context(sessionID)).toMatchObject([
  2167. { type: "user", text: "Use tools" },
  2168. {
  2169. type: "assistant",
  2170. finish: "tool-calls",
  2171. cost: 0,
  2172. tokens: { input: 8, output: 3, reasoning: 1, cache: { read: 2, write: 0 } },
  2173. content: [
  2174. { type: "reasoning", text: "Think" },
  2175. {
  2176. type: "tool",
  2177. id: "call-error",
  2178. name: "write",
  2179. state: {
  2180. status: "error",
  2181. input: { path: "README.md" },
  2182. error: { type: "tool.execution", message: "Denied" },
  2183. },
  2184. },
  2185. {
  2186. type: "tool",
  2187. id: "call-provider",
  2188. name: "web_search",
  2189. executed: true,
  2190. providerState: { source: "provider" },
  2191. providerResultState: { source: "provider" },
  2192. state: {
  2193. status: "completed",
  2194. input: { query: "hello" },
  2195. content: [
  2196. { type: "text", text: "Hello" },
  2197. { type: "file", mime: "image/png", uri: "data:image/png;base64,aGVsbG8=", name: "hello.png" },
  2198. ],
  2199. },
  2200. },
  2201. ],
  2202. },
  2203. ])
  2204. }),
  2205. )
  2206. it.effect("continues with reloaded history after durably settling one local tool call", () =>
  2207. Effect.gen(function* () {
  2208. const session = yield* setup
  2209. yield* admit(session, "Echo this")
  2210. yield* TestLLM.push(TestLLM.tool("call-echo", "echo", { text: "hello" }), TestLLM.text("Done", "text-final"))
  2211. yield* session.resume(sessionID)
  2212. expect(requests).toHaveLength(2)
  2213. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "tool"])
  2214. expect(authorizations).toMatchObject([{ sessionID, id: "call-echo" }])
  2215. expect(executions).toEqual(["hello"])
  2216. const context = yield* session.context(sessionID)
  2217. expect(context).toMatchObject([
  2218. { type: "user", text: "Echo this" },
  2219. {
  2220. type: "assistant",
  2221. finish: "tool-calls",
  2222. content: [
  2223. {
  2224. type: "tool",
  2225. id: "call-echo",
  2226. name: "echo",
  2227. state: {
  2228. status: "completed",
  2229. input: { text: "hello" },
  2230. content: [{ type: "text", text: "hello" }],
  2231. },
  2232. },
  2233. ],
  2234. },
  2235. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Done" }] },
  2236. ])
  2237. const assistant = requireAssistant(context)
  2238. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  2239. "session.step.started.1",
  2240. "session.tool.called.1",
  2241. "session.tool.success.2",
  2242. "session.step.ended.1",
  2243. ])
  2244. }),
  2245. )
  2246. it.effect("reloads a model switch before a tool-driven continuation step", () =>
  2247. Effect.gen(function* () {
  2248. const session = yield* setup
  2249. const bus = yield* Bus.Service
  2250. yield* admit(session, "Echo this")
  2251. yield* TestLLM.push(TestLLM.tool("call-echo", "echo", { text: "hello" }), TestLLM.stop())
  2252. const tools = yield* blockTools()
  2253. const run = yield* Effect.forkChild(session.resume(sessionID))
  2254. yield* tools.started
  2255. yield* bus.publish(SessionEvent.ModelSelected, {
  2256. sessionID,
  2257. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  2258. })
  2259. systemBaseline = "Replacement context"
  2260. yield* tools.release
  2261. yield* Fiber.join(run)
  2262. expect(requests.map((request) => request.model)).toEqual([model, replacementModel])
  2263. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  2264. [defaultSystem, "Initial context"],
  2265. [defaultSystem, "Initial context"],
  2266. ])
  2267. expect(systemTexts(requests[1])).toContain("Replacement context")
  2268. }),
  2269. )
  2270. it.effect("restores durable reasoning provider metadata in the next request", () =>
  2271. Effect.gen(function* () {
  2272. const session = yield* setup
  2273. yield* admit(session, "Think first")
  2274. yield* TestLLM.push(
  2275. TestLLM.stop(
  2276. LLMEvent.reasoningStart({ id: "reasoning-anthropic" }),
  2277. LLMEvent.reasoningDelta({ id: "reasoning-anthropic", text: "Signed thought" }),
  2278. LLMEvent.reasoningEnd({
  2279. id: "reasoning-anthropic",
  2280. providerMetadata: { openai: { signature: "sig_1" }, anthropic: { ignored: true } },
  2281. }),
  2282. LLMEvent.reasoningStart({
  2283. id: "reasoning-openai",
  2284. providerMetadata: {
  2285. openai: { itemId: "rs_1", reasoningEncryptedContent: null },
  2286. anthropic: { ignored: true },
  2287. },
  2288. }),
  2289. LLMEvent.reasoningDelta({ id: "reasoning-openai", text: "Encrypted thought" }),
  2290. LLMEvent.reasoningEnd({
  2291. id: "reasoning-openai",
  2292. providerMetadata: {
  2293. openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" },
  2294. anthropic: { ignored: true },
  2295. },
  2296. }),
  2297. ),
  2298. )
  2299. yield* session.resume(sessionID)
  2300. yield* replaySessionProjection(sessionID)
  2301. expect(yield* session.context(sessionID)).toMatchObject([
  2302. { type: "user", text: "Think first" },
  2303. {
  2304. type: "assistant",
  2305. content: [
  2306. {
  2307. type: "reasoning",
  2308. text: "Signed thought",
  2309. state: { signature: "sig_1" },
  2310. },
  2311. {
  2312. type: "reasoning",
  2313. text: "Encrypted thought",
  2314. state: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" },
  2315. },
  2316. ],
  2317. },
  2318. ])
  2319. yield* admit(session, "Continue")
  2320. yield* TestLLM.push([])
  2321. yield* session.resume(sessionID)
  2322. expect(requests[1]?.messages[1]?.content).toEqual([
  2323. {
  2324. type: "reasoning",
  2325. text: "Signed thought",
  2326. providerMetadata: { openai: { signature: "sig_1" } },
  2327. },
  2328. {
  2329. type: "reasoning",
  2330. text: "Encrypted thought",
  2331. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
  2332. },
  2333. ])
  2334. }),
  2335. )
  2336. it.effect("restores durable text provider metadata in the next request", () =>
  2337. Effect.gen(function* () {
  2338. const session = yield* setup
  2339. yield* admit(session, "Check first")
  2340. yield* TestLLM.push(
  2341. TestLLM.stop(
  2342. LLMEvent.textStart({ id: "commentary", providerMetadata: { openai: { phase: "commentary" } } }),
  2343. LLMEvent.textDelta({ id: "commentary", text: "Checking." }),
  2344. LLMEvent.textEnd({
  2345. id: "commentary",
  2346. providerMetadata: { openai: { phase: "commentary" }, anthropic: { ignored: true } },
  2347. }),
  2348. ),
  2349. )
  2350. yield* session.resume(sessionID)
  2351. yield* replaySessionProjection(sessionID)
  2352. expect(yield* session.context(sessionID)).toMatchObject([
  2353. { type: "user", text: "Check first" },
  2354. {
  2355. type: "assistant",
  2356. content: [{ type: "text", text: "Checking.", state: { phase: "commentary" } }],
  2357. },
  2358. ])
  2359. yield* admit(session, "Continue")
  2360. yield* TestLLM.push([])
  2361. yield* session.resume(sessionID)
  2362. expect(requests[1]?.messages[1]?.content).toEqual([
  2363. {
  2364. type: "text",
  2365. text: "Checking.",
  2366. providerMetadata: { openai: { phase: "commentary" } },
  2367. },
  2368. ])
  2369. }),
  2370. )
  2371. it.effect("replays durable provider-executed tool results inline in the next request", () =>
  2372. Effect.gen(function* () {
  2373. const session = yield* setup
  2374. yield* admit(session, "Search first")
  2375. yield* TestLLM.push(
  2376. TestLLM.stop(
  2377. LLMEvent.toolCall({
  2378. id: "hosted-search",
  2379. name: "web_search",
  2380. input: { query: "Effect" },
  2381. providerExecuted: true,
  2382. providerMetadata: { openai: { itemId: "hosted-search" }, fake: { ignored: true } },
  2383. }),
  2384. LLMEvent.toolResult({
  2385. id: "hosted-search",
  2386. name: "web_search",
  2387. result: { type: "json", value: [{ title: "Effect" }] },
  2388. providerExecuted: true,
  2389. providerMetadata: { openai: { blockType: "web_search_tool_result" }, anthropic: { ignored: true } },
  2390. }),
  2391. ),
  2392. )
  2393. yield* session.resume(sessionID)
  2394. yield* replaySessionProjection(sessionID)
  2395. yield* admit(session, "Continue")
  2396. yield* TestLLM.push([])
  2397. yield* session.resume(sessionID)
  2398. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "user"])
  2399. expect(requests[1]?.messages[1]?.content).toMatchObject([
  2400. {
  2401. type: "tool-call",
  2402. id: "hosted-search",
  2403. name: "web_search",
  2404. input: { query: "Effect" },
  2405. providerExecuted: true,
  2406. providerMetadata: { openai: { itemId: "hosted-search" } },
  2407. },
  2408. {
  2409. type: "tool-result",
  2410. id: "hosted-search",
  2411. name: "web_search",
  2412. // The generic replay result derives from canonical stored content.
  2413. result: { type: "text", value: '[{"title":"Effect"}]' },
  2414. providerExecuted: true,
  2415. providerMetadata: { openai: { blockType: "web_search_tool_result" } },
  2416. },
  2417. ])
  2418. }),
  2419. )
  2420. it.effect("starts recorded local tools eagerly and awaits settlement before continuing", () =>
  2421. Effect.gen(function* () {
  2422. const session = yield* setup
  2423. yield* admit(session, "Echo five times")
  2424. const tools = yield* blockTools(5)
  2425. const providerGate = yield* Deferred.make<void>()
  2426. const initial = Stream.fromIterable([
  2427. LLMEvent.stepStart({ index: 0 }),
  2428. ...Array.from({ length: 5 }, (_, index) =>
  2429. LLMEvent.toolCall({ id: `call-echo-${index}`, name: "echo", input: { text: `${index}` } }),
  2430. ),
  2431. ])
  2432. const final = Stream.fromIterable([
  2433. LLMEvent.stepFinish({ index: 0, reason: { normalized: "tool-calls" } }),
  2434. LLMEvent.finish({ reason: { normalized: "tool-calls" } }),
  2435. ])
  2436. yield* TestLLM.push(
  2437. Stream.concat(initial, Stream.fromEffect(Deferred.await(providerGate)).pipe(Stream.flatMap(() => final))),
  2438. )
  2439. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2440. yield* tools.started
  2441. expect(executions).toHaveLength(5)
  2442. expect(yield* tools.maxActive).toBe(5)
  2443. expect(yield* session.context(sessionID)).toMatchObject([
  2444. { type: "user", text: "Echo five times" },
  2445. {
  2446. type: "assistant",
  2447. content: Array.from({ length: 5 }, (_, index) => ({
  2448. type: "tool",
  2449. id: `call-echo-${index}`,
  2450. state: { status: "running", input: { text: `${index}` } },
  2451. })),
  2452. },
  2453. ])
  2454. yield* Deferred.succeed(providerGate, undefined)
  2455. yield* Effect.yieldNow
  2456. expect(requests).toHaveLength(1)
  2457. yield* tools.release
  2458. yield* Fiber.join(run)
  2459. expect(executions).toHaveLength(5)
  2460. expect(yield* tools.maxActive).toBe(5)
  2461. expect(requests).toHaveLength(2)
  2462. }),
  2463. )
  2464. it.effect("settles repeated provider-local tool call IDs against their owning assistant messages", () =>
  2465. Effect.gen(function* () {
  2466. const session = yield* setup
  2467. yield* admit(session, "Echo twice")
  2468. yield* TestLLM.push(
  2469. TestLLM.tool("tool_0", "echo", { text: "first" }),
  2470. TestLLM.tool("tool_0", "echo", { text: "second" }),
  2471. [],
  2472. )
  2473. yield* session.resume(sessionID)
  2474. const expected = [
  2475. { type: "user", text: "Echo twice" },
  2476. {
  2477. type: "assistant",
  2478. content: [
  2479. {
  2480. type: "tool",
  2481. id: "tool_0",
  2482. state: { status: "completed", content: [{ type: "text", text: "first" }] },
  2483. },
  2484. ],
  2485. },
  2486. {
  2487. type: "assistant",
  2488. content: [
  2489. {
  2490. type: "tool",
  2491. id: "tool_0",
  2492. state: { status: "completed", content: [{ type: "text", text: "second" }] },
  2493. },
  2494. ],
  2495. },
  2496. ]
  2497. expect(executions).toEqual(["first", "second"])
  2498. expect(requests).toHaveLength(3)
  2499. expect(yield* session.context(sessionID)).toMatchObject(expected)
  2500. yield* replaySessionProjection(sessionID)
  2501. expect(yield* session.context(sessionID)).toMatchObject(expected)
  2502. }),
  2503. )
  2504. it.effect("joins concurrent resume calls into one active provider run", () =>
  2505. Effect.gen(function* () {
  2506. const session = yield* setup
  2507. yield* admit(session, "Run once")
  2508. yield* TestLLM.push(TestLLM.text("Once", "text-once"))
  2509. const stream = yield* TestLLM.gate
  2510. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2511. yield* stream.started
  2512. const second = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2513. yield* Effect.yieldNow
  2514. expect(requests).toHaveLength(1)
  2515. yield* stream.release
  2516. yield* Fiber.join(first)
  2517. yield* Fiber.join(second)
  2518. expect(requests).toHaveLength(1)
  2519. expect(yield* session.context(sessionID)).toMatchObject([
  2520. { type: "user", text: "Run once" },
  2521. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Once" }] },
  2522. ])
  2523. }),
  2524. )
  2525. it.effect("steers an active step with newly recorded prompts", () =>
  2526. Effect.gen(function* () {
  2527. const session = yield* setup
  2528. yield* admit(session, "Start working")
  2529. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop())
  2530. const stream = yield* TestLLM.gate
  2531. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2532. yield* stream.started
  2533. yield* session.prompt({ sessionID, text: "Change direction" })
  2534. yield* stream.release
  2535. yield* Fiber.join(first)
  2536. yield* Effect.yieldNow
  2537. expect(requests).toHaveLength(2)
  2538. expect(userTexts(requests[0])).toEqual(["Start working"])
  2539. expect(userTexts(requests[1])).toEqual(["Start working", "Change direction"])
  2540. expect((yield* session.context(sessionID)).map((message) => message.type)).toEqual([
  2541. "user",
  2542. "assistant",
  2543. "user",
  2544. "assistant",
  2545. ])
  2546. }),
  2547. )
  2548. it.effect("promotes queued input after continuation ends", () =>
  2549. Effect.gen(function* () {
  2550. const session = yield* setup
  2551. yield* admit(session, "Start working")
  2552. yield* TestLLM.push(TestLLM.tool("call-echo", "echo", { text: "hello" }), TestLLM.stop(), TestLLM.stop())
  2553. const stream = yield* TestLLM.gate
  2554. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2555. yield* stream.started
  2556. yield* session.prompt({
  2557. sessionID,
  2558. text: "Wait until continuation ends",
  2559. delivery: "queue",
  2560. })
  2561. yield* stream.release
  2562. yield* Fiber.join(first)
  2563. expect(requests).toHaveLength(3)
  2564. expect(userTexts(requests[0])).toEqual(["Start working"])
  2565. expect(userTexts(requests[1])).toEqual(["Start working"])
  2566. expect(userTexts(requests[2])).toEqual(["Start working", "Wait until continuation ends"])
  2567. }),
  2568. )
  2569. it.effect("preserves durable queued input for a later wake after interruption", () =>
  2570. Effect.gen(function* () {
  2571. const session = yield* setup
  2572. const { db } = yield* Database.Service
  2573. yield* admit(session, "Interrupt current work")
  2574. yield* TestLLM.push([], TestLLM.stop())
  2575. const stream = yield* TestLLM.gate
  2576. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2577. yield* stream.started
  2578. yield* session.prompt({
  2579. sessionID,
  2580. text: "Run after interrupt",
  2581. delivery: "queue",
  2582. })
  2583. yield* session.interrupt(sessionID)
  2584. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  2585. expect(requests).toHaveLength(1)
  2586. expect(yield* SessionPending.has(db, sessionID, "queue")).toBe(true)
  2587. const resumed = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2588. yield* stream.started
  2589. yield* stream.release
  2590. yield* Fiber.join(resumed)
  2591. expect(requests).toHaveLength(2)
  2592. expect(userTexts(requests[0])).toEqual(["Interrupt current work"])
  2593. expect(userTexts(requests[1])).toEqual(["Interrupt current work", "Run after interrupt"])
  2594. }),
  2595. )
  2596. it.effect("preserves durable steering input for a later resume after interruption", () =>
  2597. Effect.gen(function* () {
  2598. const session = yield* setup
  2599. const { db } = yield* Database.Service
  2600. yield* admit(session, "Interrupt current work")
  2601. yield* TestLLM.push([], TestLLM.stop())
  2602. const stream = yield* TestLLM.gate
  2603. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2604. yield* stream.started
  2605. yield* session.prompt({
  2606. sessionID,
  2607. text: "Steer after interrupt",
  2608. })
  2609. yield* session.interrupt(sessionID)
  2610. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  2611. expect(requests).toHaveLength(1)
  2612. expect(yield* SessionPending.has(db, sessionID, "steer")).toBe(true)
  2613. const resumed = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2614. yield* stream.started
  2615. yield* stream.release
  2616. yield* Fiber.join(resumed)
  2617. expect(requests).toHaveLength(2)
  2618. expect(userTexts(requests[0])).toEqual(["Interrupt current work"])
  2619. expect(userTexts(requests[1])).toEqual(["Interrupt current work", "Steer after interrupt"])
  2620. }),
  2621. )
  2622. it.effect("promotes queued inputs one at a time in FIFO order", () =>
  2623. Effect.gen(function* () {
  2624. const session = yield* setup
  2625. yield* admit(session, "Start working")
  2626. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop(), TestLLM.stop())
  2627. const stream = yield* TestLLM.gate
  2628. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2629. yield* stream.started
  2630. yield* session.prompt({ sessionID, text: "Queue first", delivery: "queue" })
  2631. yield* session.prompt({ sessionID, text: "Queue second", delivery: "queue" })
  2632. yield* stream.release
  2633. yield* Fiber.join(first)
  2634. expect(requests).toHaveLength(3)
  2635. expect(userTexts(requests[0])).toEqual(["Start working"])
  2636. expect(userTexts(requests[1])).toEqual(["Start working", "Queue first"])
  2637. expect(userTexts(requests[2])).toEqual(["Start working", "Queue first", "Queue second"])
  2638. }),
  2639. )
  2640. it.effect("promotes queued input after steering continuation ends", () =>
  2641. Effect.gen(function* () {
  2642. const session = yield* setup
  2643. yield* admit(session, "Start steering")
  2644. yield* session.prompt({
  2645. sessionID,
  2646. text: "Queue for later",
  2647. delivery: "queue",
  2648. resume: false,
  2649. })
  2650. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop())
  2651. yield* session.resume(sessionID)
  2652. expect(requests).toHaveLength(2)
  2653. expect(userTexts(requests[0])).toEqual(["Start steering"])
  2654. expect(userTexts(requests[1])).toEqual(["Start steering", "Queue for later"])
  2655. }),
  2656. )
  2657. it.effect("promotes steers before the next queued input", () =>
  2658. Effect.gen(function* () {
  2659. const session = yield* setup
  2660. yield* admit(session, "Start working")
  2661. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop(), TestLLM.stop(), TestLLM.stop())
  2662. const firstStream = yield* TestLLM.gate
  2663. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2664. yield* firstStream.started
  2665. yield* session.prompt({ sessionID, text: "Queue first", delivery: "queue" })
  2666. yield* session.prompt({ sessionID, text: "Queue second", delivery: "queue" })
  2667. const secondStream = yield* TestLLM.gate
  2668. yield* firstStream.release
  2669. yield* secondStream.started
  2670. yield* session.prompt({ sessionID, text: "Steer before next queued input" })
  2671. yield* session.prompt({
  2672. sessionID,
  2673. text: "Also steer before next queued input",
  2674. })
  2675. yield* session.synthetic({ sessionID, text: "Background completion before next queued input" })
  2676. yield* secondStream.release
  2677. yield* Fiber.join(first)
  2678. expect(requests).toHaveLength(4)
  2679. expect(userTexts(requests[0])).toEqual(["Start working"])
  2680. expect(userTexts(requests[1])).toEqual(["Start working", "Queue first"])
  2681. expect(userTexts(requests[2])).toEqual([
  2682. "Start working",
  2683. "Queue first",
  2684. "Steer before next queued input",
  2685. "Also steer before next queued input",
  2686. "Background completion before next queued input",
  2687. ])
  2688. expect(userTexts(requests[3])).toEqual([
  2689. "Start working",
  2690. "Queue first",
  2691. "Steer before next queued input",
  2692. "Also steer before next queued input",
  2693. "Background completion before next queued input",
  2694. "Queue second",
  2695. ])
  2696. }),
  2697. )
  2698. it.effect("coalesces multiple active steering prompts into one continuation step", () =>
  2699. Effect.gen(function* () {
  2700. const session = yield* setup
  2701. yield* admit(session, "Start working")
  2702. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop())
  2703. const stream = yield* TestLLM.gate
  2704. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2705. yield* stream.started
  2706. yield* session.prompt({ sessionID, text: "First steer" })
  2707. yield* session.prompt({ sessionID, text: "Second steer" })
  2708. yield* stream.release
  2709. yield* Fiber.join(first)
  2710. yield* Effect.yieldNow
  2711. expect(requests).toHaveLength(2)
  2712. expect(userTexts(requests[1])).toEqual(["Start working", "First steer", "Second steer"])
  2713. yield* (yield* SessionExecution.Service).wake(sessionID)
  2714. yield* Effect.yieldNow
  2715. expect(requests).toHaveLength(2)
  2716. }),
  2717. )
  2718. it.effect("runs steering input accepted while the active step fails", () =>
  2719. Effect.gen(function* () {
  2720. const session = yield* setup
  2721. yield* admit(session, "Start working")
  2722. const failure = invalidRequest()
  2723. yield* TestLLM.push(Stream.fail(failure))
  2724. const stream = yield* TestLLM.gate
  2725. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2726. yield* stream.started
  2727. yield* session.prompt({ sessionID, text: "Recover with this" })
  2728. yield* stream.release
  2729. expect(yield* Fiber.join(first).pipe(Effect.flip)).toBe(failure)
  2730. yield* TestLLM.push([])
  2731. yield* session.wait(sessionID)
  2732. expect(requests).toHaveLength(2)
  2733. expect(userTexts(requests[1])).toEqual(["Start working", "Recover with this"])
  2734. }),
  2735. )
  2736. it.effect("durably fails local tools left running by a prior process before continuing", () =>
  2737. Effect.gen(function* () {
  2738. const session = yield* setup
  2739. const bus = yield* Bus.Service
  2740. yield* admit(session, "Recover interrupted tool")
  2741. yield* SessionPending.promote((yield* Database.Service).db, bus, sessionID, "steer")
  2742. const assistantMessageID = SessionMessage.ID.create()
  2743. yield* bus.publish(SessionEvent.Step.Started, {
  2744. sessionID,
  2745. assistantMessageID,
  2746. agent: Agent.ID.make("build"),
  2747. model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") },
  2748. })
  2749. yield* bus.publish(SessionEvent.Tool.Input.Started, {
  2750. sessionID,
  2751. assistantMessageID,
  2752. id: "call-interrupted",
  2753. name: "echo",
  2754. })
  2755. yield* bus.publish(SessionEvent.Tool.Input.Ended, {
  2756. sessionID,
  2757. assistantMessageID,
  2758. id: "call-interrupted",
  2759. text: '{"text":"stale"}',
  2760. })
  2761. yield* bus.publish(SessionEvent.Tool.Called, {
  2762. sessionID,
  2763. assistantMessageID,
  2764. id: "call-interrupted",
  2765. input: { text: "stale" },
  2766. executed: false,
  2767. })
  2768. requests.length = 0
  2769. yield* TestLLM.push([])
  2770. yield* session.resume(sessionID)
  2771. expect(requests).toHaveLength(1)
  2772. expect(messageRoles(requests[0])).toEqual(["user", "assistant", "tool"])
  2773. expect(yield* session.context(sessionID)).toMatchObject([
  2774. { type: "user", text: "Recover interrupted tool" },
  2775. {
  2776. type: "assistant",
  2777. content: [
  2778. {
  2779. type: "tool",
  2780. id: "call-interrupted",
  2781. state: {
  2782. status: "error",
  2783. error: { type: "aborted", message: "Tool execution interrupted: echo" },
  2784. },
  2785. },
  2786. ],
  2787. },
  2788. ])
  2789. }),
  2790. )
  2791. it.effect("durably fails hosted tools left running by a prior process before continuing inline", () =>
  2792. Effect.gen(function* () {
  2793. const session = yield* setup
  2794. const bus = yield* Bus.Service
  2795. yield* admit(session, "Recover interrupted hosted tool")
  2796. yield* SessionPending.promote((yield* Database.Service).db, bus, sessionID, "steer")
  2797. const assistantMessageID = SessionMessage.ID.create()
  2798. yield* bus.publish(SessionEvent.Step.Started, {
  2799. sessionID,
  2800. assistantMessageID,
  2801. agent: Agent.ID.make("build"),
  2802. model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") },
  2803. })
  2804. yield* bus.publish(SessionEvent.Tool.Input.Started, {
  2805. sessionID,
  2806. assistantMessageID,
  2807. id: "call-hosted-interrupted",
  2808. name: "web_search",
  2809. })
  2810. yield* bus.publish(SessionEvent.Tool.Input.Ended, {
  2811. sessionID,
  2812. assistantMessageID,
  2813. id: "call-hosted-interrupted",
  2814. text: '{"query":"stale"}',
  2815. })
  2816. yield* bus.publish(SessionEvent.Tool.Called, {
  2817. sessionID,
  2818. assistantMessageID,
  2819. id: "call-hosted-interrupted",
  2820. input: { query: "stale" },
  2821. executed: true,
  2822. state: { itemId: "call-hosted-interrupted" },
  2823. })
  2824. requests.length = 0
  2825. yield* TestLLM.push([])
  2826. yield* session.resume(sessionID)
  2827. expect(requests).toHaveLength(1)
  2828. expect(messageRoles(requests[0])).toEqual(["user", "assistant"])
  2829. expect(requests[0]?.messages[1]?.content).toMatchObject([
  2830. {
  2831. type: "tool-call",
  2832. id: "call-hosted-interrupted",
  2833. providerExecuted: true,
  2834. providerMetadata: { openai: { itemId: "call-hosted-interrupted" } },
  2835. },
  2836. { type: "tool-result", id: "call-hosted-interrupted", providerExecuted: true, result: { type: "error" } },
  2837. ])
  2838. }),
  2839. )
  2840. it.effect("durably fails pending tool input left by a prior process before continuing", () =>
  2841. Effect.gen(function* () {
  2842. const session = yield* setup
  2843. const bus = yield* Bus.Service
  2844. yield* admit(session, "Recover interrupted tool input")
  2845. yield* SessionPending.promote((yield* Database.Service).db, bus, sessionID, "steer")
  2846. const assistantMessageID = SessionMessage.ID.create()
  2847. yield* bus.publish(SessionEvent.Step.Started, {
  2848. sessionID,
  2849. assistantMessageID,
  2850. agent: Agent.ID.make("build"),
  2851. model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") },
  2852. })
  2853. yield* bus.publish(SessionEvent.Tool.Input.Started, {
  2854. sessionID,
  2855. assistantMessageID,
  2856. id: "call-pending-interrupted",
  2857. name: "echo",
  2858. })
  2859. requests.length = 0
  2860. yield* TestLLM.push([])
  2861. yield* session.resume(sessionID)
  2862. expect(requests).toHaveLength(1)
  2863. expect(messageRoles(requests[0])).toEqual(["user", "assistant", "tool"])
  2864. expect(yield* session.context(sessionID)).toMatchObject([
  2865. { type: "user", text: "Recover interrupted tool input" },
  2866. { type: "assistant", content: [{ type: "tool", id: "call-pending-interrupted", state: { status: "error" } }] },
  2867. ])
  2868. }),
  2869. )
  2870. it.effect("promotes the first queued input when woken while idle", () =>
  2871. Effect.gen(function* () {
  2872. const session = yield* setup
  2873. yield* session.prompt({
  2874. sessionID,
  2875. text: "Wait in queue",
  2876. delivery: "queue",
  2877. resume: false,
  2878. })
  2879. const stream = yield* TestLLM.gate
  2880. yield* (yield* SessionExecution.Service).wake(sessionID)
  2881. yield* stream.started
  2882. yield* stream.release
  2883. expect(requests).toHaveLength(1)
  2884. expect(userTexts(requests[0])).toEqual(["Wait in queue"])
  2885. }),
  2886. )
  2887. it.effect("retries inbox input after prompt projection rolls back", () =>
  2888. Effect.gen(function* () {
  2889. const session = yield* setup
  2890. const bus = yield* Bus.Service
  2891. const defect = new Error("fail after prompt promotion")
  2892. let fail = true
  2893. yield* bus.project(SessionEvent.InputPromoted, () => (fail ? Effect.die(defect) : Effect.void))
  2894. yield* admit(session, "Recover promoted input")
  2895. expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe(defect)
  2896. fail = false
  2897. requests.length = 0
  2898. yield* TestLLM.push(TestLLM.stop())
  2899. const stream = yield* TestLLM.gate
  2900. yield* (yield* SessionExecution.Service).wake(sessionID)
  2901. yield* stream.started
  2902. yield* stream.release
  2903. expect(userTexts(requests[0])).toEqual(["Recover promoted input"])
  2904. }),
  2905. )
  2906. it.effect("does not strand a committed promotion when a post-commit listener defects", () =>
  2907. Effect.gen(function* () {
  2908. const session = yield* setup
  2909. const bus = yield* Bus.Service
  2910. yield* bus.listen((event) =>
  2911. event.type === SessionEvent.InputPromoted.type
  2912. ? Effect.die("fail after prompt promotion commits")
  2913. : Effect.void,
  2914. )
  2915. yield* runPrompt(session, "Run committed promotion")
  2916. expect(requests).toHaveLength(1)
  2917. expect(userTexts(requests[0])).toEqual(["Run committed promotion"])
  2918. }),
  2919. )
  2920. it.effect("adds session correlation headers to model requests", () =>
  2921. Effect.gen(function* () {
  2922. const session = yield* setup
  2923. yield* runPrompt(session, "Run correlated request")
  2924. expect(requests[0]?.http?.headers).toEqual({
  2925. "x-session-affinity": sessionID,
  2926. "X-Session-Id": sessionID,
  2927. "User-Agent": App.useragent(App.make()),
  2928. "x-opencode-project": Project.ID.global,
  2929. "x-opencode-session": sessionID,
  2930. "x-opencode-client": "opencode",
  2931. })
  2932. }),
  2933. )
  2934. it.effect("adds the parent session header to child model requests", () =>
  2935. Effect.gen(function* () {
  2936. const session = yield* setup
  2937. const parentID = Session.ID.make("ses_runner_parent")
  2938. const { db } = yield* Database.Service
  2939. yield* db
  2940. .update(SessionTable)
  2941. .set({ parent_id: parentID })
  2942. .where(eq(SessionTable.id, sessionID))
  2943. .run()
  2944. .pipe(Effect.orDie)
  2945. yield* runPrompt(session, "Run child request")
  2946. expect(requests[0]?.http?.headers?.["x-parent-session-id"]).toBe(parentID)
  2947. }),
  2948. )
  2949. it.effect("runs different sessions concurrently", () =>
  2950. Effect.gen(function* () {
  2951. const session = yield* setup
  2952. yield* insertSession(otherSessionID)
  2953. yield* admit(session, "Run first")
  2954. yield* session.prompt({
  2955. sessionID: otherSessionID,
  2956. text: "Run second",
  2957. resume: false,
  2958. })
  2959. const stream = yield* TestLLM.gate
  2960. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2961. yield* stream.started
  2962. const second = yield* session.resume(otherSessionID).pipe(Effect.forkChild)
  2963. yield* stream.started
  2964. expect(requests).toHaveLength(2)
  2965. expect(requests.map((request) => request.promptCacheKey)).toEqual([sessionID, otherSessionID])
  2966. yield* stream.release
  2967. yield* Fiber.join(first)
  2968. yield* Fiber.join(second)
  2969. }),
  2970. )
  2971. it.effect("bounds 64-character session prompt cache keys", () =>
  2972. Effect.gen(function* () {
  2973. const session = yield* setup
  2974. const longSessionID = Session.ID.make(`ses_${"a".repeat(64)}`)
  2975. const otherLongSessionID = Session.ID.make(`ses_${"b".repeat(64)}`)
  2976. yield* insertSession(longSessionID)
  2977. yield* insertSession(otherLongSessionID)
  2978. yield* session.prompt({
  2979. sessionID: longSessionID,
  2980. text: "Run long session",
  2981. resume: false,
  2982. })
  2983. yield* session.prompt({
  2984. sessionID: otherLongSessionID,
  2985. text: "Run other long session",
  2986. resume: false,
  2987. })
  2988. yield* session.resume(longSessionID)
  2989. yield* session.resume(otherLongSessionID)
  2990. const keys = requests.map((request) => request.promptCacheKey)
  2991. expect(keys).toEqual([longSessionID.slice(4), otherLongSessionID.slice(4)])
  2992. expect(keys.every((key) => typeof key === "string" && key.length === 64)).toBe(true)
  2993. expect(keys[0]).not.toBe(keys[1])
  2994. }),
  2995. )
  2996. it.effect("fans out one failed run and allows a later retry", () =>
  2997. Effect.gen(function* () {
  2998. const session = yield* setup
  2999. yield* admit(session, "Retry after failure")
  3000. yield* TestLLM.push(Stream.fail(invalidRequest()))
  3001. const stream = yield* TestLLM.gate
  3002. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3003. yield* stream.started
  3004. const second = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3005. yield* Effect.yieldNow
  3006. expect(requests).toHaveLength(1)
  3007. yield* stream.release
  3008. const [firstExit, secondExit] = yield* Effect.all([Fiber.await(first), Fiber.await(second)])
  3009. expect(secondExit).toEqual(firstExit)
  3010. yield* TestLLM.push([])
  3011. yield* session.resume(sessionID)
  3012. expect(requests).toHaveLength(2)
  3013. }),
  3014. )
  3015. it.effect("durably settles local tool failures before continuing", () =>
  3016. Effect.gen(function* () {
  3017. const session = yield* setup
  3018. yield* admit(session, "Call missing")
  3019. yield* TestLLM.push(TestLLM.tool("call-missing", "missing", {}), TestLLM.text("Recovered", "text-after-error"))
  3020. yield* session.resume(sessionID)
  3021. expect(requests).toHaveLength(2)
  3022. expect(yield* session.context(sessionID)).toMatchObject([
  3023. { type: "user", text: "Call missing" },
  3024. {
  3025. type: "assistant",
  3026. content: [
  3027. {
  3028. type: "tool",
  3029. id: "call-missing",
  3030. state: {
  3031. status: "error",
  3032. error: { type: "tool.execution", message: "Unknown tool: missing" },
  3033. },
  3034. },
  3035. ],
  3036. },
  3037. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3038. ])
  3039. }),
  3040. )
  3041. it.effect("returns unexpected local tool defects to the model and continues", () =>
  3042. Effect.gen(function* () {
  3043. const session = yield* setup
  3044. yield* admit(session, "Call defect")
  3045. yield* TestLLM.push(TestLLM.tool("call-defect", "defect", {}), TestLLM.text("Recovered", "text-after-defect"))
  3046. yield* session.resume(sessionID)
  3047. expect(requests).toHaveLength(2)
  3048. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "tool"])
  3049. const context = yield* session.context(sessionID)
  3050. expect(context).toMatchObject([
  3051. { type: "user", text: "Call defect" },
  3052. {
  3053. type: "assistant",
  3054. content: [
  3055. {
  3056. type: "tool",
  3057. id: "call-defect",
  3058. state: {
  3059. status: "error",
  3060. error: { type: "unknown", message: "unexpected tool defect" },
  3061. },
  3062. },
  3063. ],
  3064. },
  3065. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3066. ])
  3067. const assistant = requireAssistant(context)
  3068. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  3069. "session.step.started.1",
  3070. "session.tool.called.1",
  3071. "session.tool.failed.2",
  3072. "session.step.ended.1",
  3073. ])
  3074. }),
  3075. )
  3076. it.effect("returns tool-wrapped policy blocks to the model and continues", () =>
  3077. Effect.gen(function* () {
  3078. const session = yield* setup
  3079. const registry = yield* Tool.Service
  3080. yield* transformTools(
  3081. registry,
  3082. {
  3083. blocked: {
  3084. name: "blocked",
  3085. description: "Fail because policy blocked execution",
  3086. input: Schema.Struct({}),
  3087. output: Schema.Struct({}),
  3088. execute: () =>
  3089. Effect.fail(new Permission.BlockedError({ rules: [], permission: "blocked", resources: ["*"] })).pipe(
  3090. Effect.mapError(() => new Tool.Error({ message: "Permission blocked" })),
  3091. ),
  3092. },
  3093. },
  3094. { codemode: false },
  3095. )
  3096. yield* admit(session, "Call blocked")
  3097. yield* TestLLM.push(TestLLM.tool("call-blocked", "blocked", {}), TestLLM.stop())
  3098. yield* session.resume(sessionID)
  3099. expect(requests).toHaveLength(2)
  3100. expect(yield* session.context(sessionID)).toMatchObject([
  3101. { type: "user", text: "Call blocked" },
  3102. {
  3103. type: "assistant",
  3104. content: [
  3105. { type: "tool", id: "call-blocked", state: { status: "error", error: { message: "Permission blocked" } } },
  3106. ],
  3107. },
  3108. { type: "assistant", finish: "stop" },
  3109. ])
  3110. }),
  3111. )
  3112. it.effect("interrupts runner continuation when permission approval is declined", () =>
  3113. Effect.gen(function* () {
  3114. const session = yield* setup
  3115. const registry = yield* Tool.Service
  3116. yield* transformTools(
  3117. registry,
  3118. {
  3119. declined: {
  3120. name: "declined",
  3121. description: "Fail because the user declined approval",
  3122. input: Schema.Struct({}),
  3123. output: Schema.Struct({}),
  3124. execute: () => Effect.die(new Permission.DeclinedError()),
  3125. },
  3126. },
  3127. { codemode: false },
  3128. )
  3129. yield* admit(session, "Call declined")
  3130. yield* TestLLM.push(TestLLM.tool("call-declined", "declined", {}))
  3131. const exit = yield* session.resume(sessionID).pipe(Effect.exit)
  3132. expect(exit._tag).toBe("Failure")
  3133. if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
  3134. expect(requests).toHaveLength(1)
  3135. expect(yield* session.context(sessionID)).toMatchObject([
  3136. { type: "user", text: "Call declined" },
  3137. {
  3138. type: "assistant",
  3139. content: [
  3140. {
  3141. type: "tool",
  3142. id: "call-declined",
  3143. state: { status: "error", error: { type: "aborted", message: "The user declined this tool call" } },
  3144. },
  3145. ],
  3146. },
  3147. ])
  3148. }),
  3149. )
  3150. it.effect("returns permission corrections to the model and continues", () =>
  3151. Effect.gen(function* () {
  3152. const session = yield* setup
  3153. const registry = yield* Tool.Service
  3154. yield* transformTools(
  3155. registry,
  3156. {
  3157. corrected: {
  3158. name: "corrected",
  3159. description: "Fail with user correction feedback",
  3160. input: Schema.Struct({}),
  3161. output: Schema.Struct({}),
  3162. execute: () =>
  3163. Effect.fail(new Permission.CorrectedError({ feedback: "Use another tool" })).pipe(
  3164. Effect.mapError(() => new Tool.Error({ message: "Use another tool" })),
  3165. ),
  3166. },
  3167. },
  3168. { codemode: false },
  3169. )
  3170. yield* admit(session, "Call corrected")
  3171. yield* TestLLM.push(TestLLM.tool("call-corrected", "corrected", {}), TestLLM.stop())
  3172. yield* session.resume(sessionID)
  3173. expect(requests).toHaveLength(2)
  3174. expect(yield* session.context(sessionID)).toMatchObject([
  3175. { type: "user", text: "Call corrected" },
  3176. {
  3177. type: "assistant",
  3178. content: [
  3179. { type: "tool", id: "call-corrected", state: { status: "error", error: { message: "Use another tool" } } },
  3180. ],
  3181. },
  3182. { type: "assistant", finish: "stop" },
  3183. ])
  3184. }),
  3185. )
  3186. it.effect("returns configured permission denials to the model and continues", () =>
  3187. Effect.gen(function* () {
  3188. const session = yield* setup
  3189. const registry = yield* Tool.Service
  3190. yield* transformTools(registry, { permissionfail: permissionFail }, { codemode: false })
  3191. yield* admit(session, "Reject permission")
  3192. yield* TestLLM.push(TestLLM.tool("call-permission", "permissionfail", {}), [
  3193. LLMEvent.stepStart({ index: 0 }),
  3194. LLMEvent.stepFinish({ index: 0, reason: { normalized: "stop" } }),
  3195. ])
  3196. yield* session.resume(sessionID)
  3197. expect(requests).toHaveLength(2)
  3198. expect(yield* session.context(sessionID)).toMatchObject([
  3199. { type: "user" },
  3200. {
  3201. type: "assistant",
  3202. content: [
  3203. {
  3204. type: "tool",
  3205. id: "call-permission",
  3206. state: {
  3207. status: "error",
  3208. error: {
  3209. type: "permission.rejected",
  3210. message: "Permission denied: edit",
  3211. },
  3212. },
  3213. },
  3214. ],
  3215. },
  3216. { type: "assistant", finish: "stop" },
  3217. ])
  3218. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.step.failed.1")
  3219. }),
  3220. )
  3221. it.effect("interrupts runner continuation when a question is cancelled", () =>
  3222. Effect.gen(function* () {
  3223. const session = yield* setup
  3224. const registry = yield* Tool.Service
  3225. yield* transformTools(
  3226. registry,
  3227. {
  3228. question: {
  3229. name: "question",
  3230. description: "Ask the user",
  3231. input: Schema.Struct({}),
  3232. output: Schema.Struct({}),
  3233. execute: () => Effect.die(new QuestionTool.CancelledError()),
  3234. },
  3235. },
  3236. { codemode: false },
  3237. )
  3238. yield* admit(session, "Ask then stop")
  3239. yield* TestLLM.push(TestLLM.tool("call-question", "question", {}), [])
  3240. const run = yield* session.resume(sessionID).pipe(Effect.exit, Effect.forkChild)
  3241. const exit = yield* Fiber.join(run)
  3242. expect(exit._tag).toBe("Failure")
  3243. if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
  3244. expect(requests).toHaveLength(1)
  3245. expect(yield* session.context(sessionID)).toMatchObject([
  3246. { type: "user", text: "Ask then stop" },
  3247. {
  3248. type: "assistant",
  3249. content: [
  3250. {
  3251. type: "tool",
  3252. id: "call-question",
  3253. state: { status: "error", error: { type: "aborted", message: "The user dismissed this question" } },
  3254. },
  3255. ],
  3256. },
  3257. ])
  3258. }),
  3259. )
  3260. it.effect("awaits started local tools before surfacing provider stream failure", () =>
  3261. Effect.gen(function* () {
  3262. const session = yield* setup
  3263. yield* admit(session, "Settle before failing")
  3264. const failure = providerUnavailable()
  3265. const tools = yield* blockTools()
  3266. yield* TestLLM.push(
  3267. TestLLM.failAfter(
  3268. failure,
  3269. LLMEvent.stepStart({ index: 0 }),
  3270. LLMEvent.toolCall({ id: "call-before-failure", name: "echo", input: { text: "settle" } }),
  3271. ),
  3272. )
  3273. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3274. yield* tools.started
  3275. yield* tools.release
  3276. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  3277. const context = yield* session.context(sessionID)
  3278. expect(context).toMatchObject([
  3279. { type: "user", text: "Settle before failing" },
  3280. {
  3281. type: "assistant",
  3282. content: [
  3283. {
  3284. type: "tool",
  3285. id: "call-before-failure",
  3286. state: { status: "completed", content: [{ type: "text", text: "settle" }] },
  3287. },
  3288. ],
  3289. },
  3290. ])
  3291. const assistant = requireAssistant(context)
  3292. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  3293. "session.step.started.1",
  3294. "session.tool.called.1",
  3295. "session.tool.success.2",
  3296. "session.step.failed.1",
  3297. ])
  3298. }),
  3299. )
  3300. it.effect("durably fails blocked local tools when a step is interrupted", () =>
  3301. Effect.gen(function* () {
  3302. const session = yield* setup
  3303. yield* admit(session, "Interrupt blocked tool")
  3304. const tools = yield* blockTools()
  3305. yield* TestLLM.push(
  3306. TestLLM.hangAfter(
  3307. LLMEvent.stepStart({ index: 0 }),
  3308. LLMEvent.toolCall({ id: "call-before-interrupt", name: "echo", input: { text: "blocked" } }),
  3309. ),
  3310. )
  3311. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3312. yield* tools.started
  3313. yield* session.interrupt(sessionID)
  3314. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  3315. yield* session.interrupt(sessionID)
  3316. const context = yield* session.context(sessionID)
  3317. expect(context).toMatchObject([
  3318. { type: "user", text: "Interrupt blocked tool" },
  3319. {
  3320. type: "assistant",
  3321. content: [
  3322. {
  3323. type: "tool",
  3324. id: "call-before-interrupt",
  3325. state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } },
  3326. },
  3327. ],
  3328. },
  3329. ])
  3330. const assistant = requireAssistant(context)
  3331. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  3332. "session.step.started.1",
  3333. "session.tool.called.1",
  3334. "session.tool.failed.2",
  3335. "session.step.failed.1",
  3336. ])
  3337. yield* replaySessionProjection(sessionID)
  3338. expect(yield* session.context(sessionID)).toMatchObject([
  3339. { type: "user", text: "Interrupt blocked tool" },
  3340. { type: "assistant", content: [{ type: "tool", id: "call-before-interrupt", state: { status: "error" } }] },
  3341. ])
  3342. requests.length = 0
  3343. yield* TestLLM.push([])
  3344. yield* session.resume(sessionID)
  3345. expect(messageRoles(requests[0])).toEqual(["user", "assistant", "tool"])
  3346. }),
  3347. )
  3348. it.effect("interrupts a blocked step without local tool execution", () =>
  3349. Effect.gen(function* () {
  3350. const session = yield* setup
  3351. yield* admit(session, "Interrupt provider")
  3352. const stream = yield* TestLLM.gate
  3353. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3354. yield* stream.started
  3355. yield* session.interrupt(sessionID)
  3356. const exit = yield* Fiber.await(run)
  3357. expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBeTrue()
  3358. expect(requests).toHaveLength(1)
  3359. expect(yield* session.context(sessionID)).toMatchObject([
  3360. { type: "user", text: "Interrupt provider" },
  3361. { type: "assistant", finish: "error", error: { type: "aborted", message: "Step interrupted" } },
  3362. ])
  3363. expect(yield* recordedEventTypes(sessionID)).toContain("session.step.failed.1")
  3364. yield* session.interrupt(sessionID)
  3365. }),
  3366. )
  3367. it.effect("durably fails blocked local tools when interrupted while awaiting settlement", () =>
  3368. Effect.gen(function* () {
  3369. const session = yield* setup
  3370. yield* admit(session, "Interrupt tool settlement")
  3371. const tools = yield* blockTools()
  3372. yield* TestLLM.push(TestLLM.tool("call-await-interrupt", "echo", { text: "blocked" }))
  3373. const runner = yield* SessionRunner.Service
  3374. const run = yield* runner.drain({ sessionID, force: true }).pipe(Effect.forkChild)
  3375. yield* tools.started
  3376. yield* Fiber.interrupt(run)
  3377. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  3378. expect(yield* session.context(sessionID)).toMatchObject([
  3379. { type: "user", text: "Interrupt tool settlement" },
  3380. {
  3381. type: "assistant",
  3382. finish: "error",
  3383. error: { type: "aborted", message: "Step interrupted" },
  3384. content: [
  3385. {
  3386. type: "tool",
  3387. id: "call-await-interrupt",
  3388. state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } },
  3389. },
  3390. ],
  3391. },
  3392. ])
  3393. const eventTypes = yield* recordedEventTypes(sessionID)
  3394. expect(eventTypes).toContain("session.step.failed.1")
  3395. expect(eventTypes).not.toContain("session.step.ended.1")
  3396. }),
  3397. )
  3398. it.effect("forces a text response on an agent's configured final step", () =>
  3399. Effect.gen(function* () {
  3400. const session = yield* setup
  3401. const agents = yield* Agent.Service
  3402. yield* agents.transform((editor) =>
  3403. editor.update(Agent.ID.make("build"), (agent) => {
  3404. agent.steps = 2
  3405. }),
  3406. )
  3407. yield* admit(session, "Finish at the limit")
  3408. yield* TestLLM.push(
  3409. TestLLM.tool("call-terminal", "echo", { text: "done" }),
  3410. TestLLM.tool("call-forbidden", "echo", { text: "forbidden" }),
  3411. )
  3412. yield* session.resume(sessionID)
  3413. expect(requests).toHaveLength(2)
  3414. expect(requests[0]?.toolChoice).toBeUndefined()
  3415. expect(requests[1]?.toolChoice).toMatchObject({ type: "none" })
  3416. // Protocols with native "none" keep these definitions for prompt caching.
  3417. expect(requests[1]?.tools.map((tool) => tool.name)).toContain("echo")
  3418. expect(requests[1]?.messages.at(-1)).toMatchObject({
  3419. role: "assistant",
  3420. content: [{ type: "text", text: expect.stringContaining("MAXIMUM STEPS REACHED") }],
  3421. })
  3422. expect(executions).toEqual(["done"])
  3423. expect(yield* session.context(sessionID)).toMatchObject([
  3424. { type: "user", text: "Finish at the limit" },
  3425. { type: "assistant", content: [{ type: "tool", id: "call-terminal", state: { status: "completed" } }] },
  3426. { type: "assistant", content: [{ type: "tool", id: "call-forbidden", state: { status: "error" } }] },
  3427. ])
  3428. }),
  3429. )
  3430. it.effect("resets the configured step allowance when steering input promotes", () =>
  3431. Effect.gen(function* () {
  3432. const session = yield* setup
  3433. const agents = yield* Agent.Service
  3434. yield* agents.transform((editor) =>
  3435. editor.update(Agent.ID.make("build"), (agent) => {
  3436. agent.steps = 2
  3437. }),
  3438. )
  3439. yield* admit(session, "Start work")
  3440. yield* TestLLM.push(
  3441. TestLLM.tool("call-before-steer", "echo", { text: "before" }),
  3442. TestLLM.tool("call-after-steer", "echo", { text: "after" }),
  3443. TestLLM.stop(),
  3444. )
  3445. const stream = yield* TestLLM.gate
  3446. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3447. yield* stream.started
  3448. yield* session.prompt({ sessionID, text: "Change direction" })
  3449. yield* stream.release
  3450. yield* Fiber.join(run)
  3451. expect(requests).toHaveLength(3)
  3452. expect(requests[1]?.toolChoice).toBeUndefined()
  3453. expect(requests[1]?.tools).not.toEqual([])
  3454. expect(requests[2]?.toolChoice).toMatchObject({ type: "none" })
  3455. expect(executions).toEqual(["before", "after"])
  3456. }),
  3457. )
  3458. it.effect("projects provider errors as terminal assistant step failures", () =>
  3459. Effect.gen(function* () {
  3460. const session = yield* setup
  3461. yield* TestLLM.push([
  3462. LLMEvent.stepStart({ index: 0 }),
  3463. LLMEvent.providerError({ message: "Provider unavailable" }),
  3464. ])
  3465. expect((yield* runPrompt(session, "Fail durably").pipe(Effect.flip)).message).toBe("Provider unavailable")
  3466. expect(requests).toHaveLength(1)
  3467. expect(yield* session.context(sessionID)).toMatchObject([
  3468. { type: "user", text: "Fail durably" },
  3469. { type: "assistant", finish: "error", error: { type: "provider.unknown", message: "Provider unavailable" } },
  3470. ])
  3471. }),
  3472. )
  3473. it.effect("projects provider errors emitted before assistant step start", () =>
  3474. Effect.gen(function* () {
  3475. const session = yield* setup
  3476. yield* TestLLM.push([LLMEvent.providerError({ message: "Provider unavailable" })])
  3477. expect((yield* runPrompt(session, "Fail before step").pipe(Effect.flip)).message).toBe("Provider unavailable")
  3478. expect(requests).toHaveLength(1)
  3479. expect(yield* session.context(sessionID)).toMatchObject([
  3480. { type: "user", text: "Fail before step" },
  3481. { type: "assistant", finish: "error", error: { type: "provider.unknown", message: "Provider unavailable" } },
  3482. ])
  3483. }),
  3484. )
  3485. it.effect("projects content-filter finishes as visible terminal failures", () =>
  3486. Effect.gen(function* () {
  3487. const session = yield* setup
  3488. yield* TestLLM.push(
  3489. TestLLM.complete(
  3490. {
  3491. reason: { normalized: "content-filter" },
  3492. usage: { nonCachedInputTokens: 8, outputTokens: 3, reasoningTokens: 1 },
  3493. },
  3494. LLMEvent.textStart({ id: "partial" }),
  3495. LLMEvent.textDelta({ id: "partial", text: "Partial" }),
  3496. ),
  3497. )
  3498. expect((yield* runPrompt(session, "Blocked response").pipe(Effect.flip)).message).toBe(
  3499. "Provider blocked the response",
  3500. )
  3501. expect(yield* session.context(sessionID)).toMatchObject([
  3502. { type: "user" },
  3503. {
  3504. type: "assistant",
  3505. finish: "error",
  3506. error: { type: "provider.content-filter" },
  3507. cost: 0,
  3508. tokens: { input: 8, output: 2, reasoning: 1, cache: { read: 0, write: 0 } },
  3509. content: [{ type: "text", text: "Partial" }],
  3510. },
  3511. ])
  3512. expect(yield* session.get(sessionID)).toMatchObject({
  3513. cost: 0,
  3514. tokens: { input: 8, output: 2, reasoning: 1, cache: { read: 0, write: 0 } },
  3515. })
  3516. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.step.ended.1")
  3517. }),
  3518. )
  3519. it.effect("settles a local tool before one content-filter step failure", () =>
  3520. Effect.gen(function* () {
  3521. const session = yield* setup
  3522. yield* admit(session, "Tool before blocked response")
  3523. const tools = yield* blockTools()
  3524. yield* TestLLM.push(
  3525. TestLLM.complete(
  3526. { reason: { normalized: "content-filter" } },
  3527. LLMEvent.toolCall({ id: "call-before-content-filter", name: "echo", input: { text: "settled" } }),
  3528. ),
  3529. )
  3530. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3531. yield* tools.started
  3532. yield* tools.release
  3533. expect((yield* Fiber.join(run).pipe(Effect.flip)).message).toBe("Provider blocked the response")
  3534. const assistant = requireAssistant(yield* session.context(sessionID))
  3535. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  3536. expect(bus.map((event) => event.type)).toEqual([
  3537. "session.step.started.1",
  3538. "session.tool.called.1",
  3539. "session.tool.success.2",
  3540. "session.step.failed.1",
  3541. ])
  3542. expect(
  3543. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  3544. ).toHaveLength(1)
  3545. }),
  3546. )
  3547. it.effect("does not recover context overflow after durable assistant output", () =>
  3548. Effect.gen(function* () {
  3549. const session = yield* setup
  3550. yield* TestLLM.push([
  3551. LLMEvent.stepStart({ index: 0 }),
  3552. LLMEvent.textStart({ id: "text-partial" }),
  3553. LLMEvent.textDelta({ id: "text-partial", text: "Partial" }),
  3554. LLMEvent.textEnd({ id: "text-partial" }),
  3555. LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" }),
  3556. ])
  3557. expect((yield* runPrompt(session, "Fail after output").pipe(Effect.flip)).message).toBe("prompt too long")
  3558. expect(requests).toHaveLength(1)
  3559. expect(yield* session.context(sessionID)).toMatchObject([
  3560. { type: "user", text: "Fail after output" },
  3561. {
  3562. type: "assistant",
  3563. finish: "error",
  3564. error: { message: "prompt too long" },
  3565. content: [{ type: "text", text: "Partial" }],
  3566. },
  3567. ])
  3568. }),
  3569. )
  3570. it.effect("projects raw provider stream failures as terminal assistant step failures", () =>
  3571. Effect.gen(function* () {
  3572. const session = yield* setup
  3573. const failure = invalidRequest()
  3574. yield* TestLLM.push(Stream.fail(failure))
  3575. expect(yield* runPrompt(session, "Fail raw stream durably").pipe(Effect.flip)).toBe(failure)
  3576. yield* replaySessionProjection(sessionID)
  3577. expect(yield* session.context(sessionID)).toMatchObject([
  3578. { type: "user", text: "Fail raw stream durably" },
  3579. { type: "assistant", finish: "error", error: { type: "provider.invalid-request", message: "Invalid request" } },
  3580. ])
  3581. }),
  3582. )
  3583. it.effect("retries eligible pre-output failures after exponential backoff", () =>
  3584. Effect.gen(function* () {
  3585. const session = yield* setup
  3586. yield* admit(session, "Retry transport")
  3587. yield* TestLLM.push(Stream.fail(providerUnavailable()))
  3588. yield* TestLLM.push(TestLLM.text("Recovered", "retry-success"))
  3589. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3590. yield* TestLLM.wait(1)
  3591. yield* TestClock.adjust("1999 millis")
  3592. expect(requests).toHaveLength(1)
  3593. yield* TestClock.adjust("1 millis")
  3594. yield* Fiber.join(run)
  3595. expect(requests).toHaveLength(2)
  3596. const eventTypes = yield* recordedEventTypes(sessionID)
  3597. expect(eventTypes).toContain("session.retry.scheduled.1")
  3598. expect(eventTypes.filter((type) => type === "session.step.started.1")).toHaveLength(2)
  3599. expect(yield* session.context(sessionID)).toMatchObject([
  3600. { type: "user" },
  3601. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3602. ])
  3603. yield* replaySessionProjection(sessionID)
  3604. expect((yield* session.context(sessionID)).filter((message) => message.type === "assistant")).toHaveLength(1)
  3605. }),
  3606. )
  3607. it.effect("retries an incomplete stream before output", () =>
  3608. Effect.gen(function* () {
  3609. const session = yield* setup
  3610. yield* admit(session, "Retry incomplete stream")
  3611. yield* TestLLM.push(Stream.fail(incompleteStream()))
  3612. yield* TestLLM.push(TestLLM.text("Recovered", "incomplete-stream-success"))
  3613. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3614. yield* TestLLM.wait(1)
  3615. yield* TestClock.adjust("2 seconds")
  3616. yield* Fiber.join(run)
  3617. expect(requests).toHaveLength(2)
  3618. expect(yield* session.context(sessionID)).toMatchObject([
  3619. { type: "user" },
  3620. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3621. ])
  3622. }),
  3623. )
  3624. it.effect("uses a larger provider retry-after delay", () =>
  3625. Effect.gen(function* () {
  3626. const session = yield* setup
  3627. yield* admit(session, "Retry rate limit")
  3628. yield* TestLLM.push(Stream.fail(rateLimited(5_000)))
  3629. yield* TestLLM.push(TestLLM.text("Recovered", "retry-after-success"))
  3630. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3631. yield* TestLLM.wait(1)
  3632. yield* TestClock.adjust("4999 millis")
  3633. expect(requests).toHaveLength(1)
  3634. yield* TestClock.adjust("1 millis")
  3635. yield* Fiber.join(run)
  3636. expect(requests).toHaveLength(2)
  3637. }),
  3638. )
  3639. it.effect("continues an incomplete stream after observable text", () =>
  3640. Effect.gen(function* () {
  3641. const session = yield* setup
  3642. const failure = incompleteStream()
  3643. yield* admit(session, "Continue partial output")
  3644. yield* TestLLM.push(
  3645. TestLLM.failAfter(
  3646. failure,
  3647. LLMEvent.stepStart({ index: 0 }),
  3648. LLMEvent.textStart({ id: "partial-rate-limit" }),
  3649. LLMEvent.textDelta({ id: "partial-rate-limit", text: "Partial" }),
  3650. ),
  3651. )
  3652. yield* TestLLM.push(TestLLM.text(" continuation", "continued-text"))
  3653. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3654. yield* TestLLM.wait(1)
  3655. yield* TestClock.adjust("2 seconds")
  3656. yield* Fiber.join(run)
  3657. expect(requests).toHaveLength(2)
  3658. expect(requests[1]?.messages.at(-2)).toMatchObject({
  3659. role: "assistant",
  3660. content: [{ type: "text", text: "Partial" }],
  3661. })
  3662. expect(requests[1]?.messages.at(-1)).toMatchObject({
  3663. role: "user",
  3664. content: [
  3665. {
  3666. type: "text",
  3667. text: INCOMPLETE_STREAM_CONTINUATION,
  3668. },
  3669. ],
  3670. })
  3671. const context = yield* session.context(sessionID)
  3672. expect(context).toMatchObject([
  3673. { type: "user", text: "Continue partial output" },
  3674. {
  3675. type: "assistant",
  3676. finish: "error",
  3677. error: { type: "provider.invalid-output" },
  3678. content: [{ type: "text", text: "Partial" }],
  3679. },
  3680. {
  3681. type: "synthetic",
  3682. text: INCOMPLETE_STREAM_CONTINUATION,
  3683. },
  3684. { type: "assistant", finish: "stop", content: [{ type: "text", text: " continuation" }] },
  3685. ])
  3686. const assistants = context.filter((message) => message.type === "assistant")
  3687. expect(new Set(assistants.map((message) => message.id)).size).toBe(2)
  3688. expect(context.find((message) => message.type === "synthetic")?.description).toBeUndefined()
  3689. expect(yield* recordedEventTypes(sessionID)).toContain("session.retry.scheduled.1")
  3690. yield* replaySessionProjection(sessionID)
  3691. expect(yield* session.context(sessionID)).toMatchObject(context)
  3692. }),
  3693. )
  3694. it.effect("lowers interrupted reasoning before continuing an incomplete stream", () =>
  3695. Effect.gen(function* () {
  3696. const session = yield* setup
  3697. yield* admit(session, "Continue interrupted reasoning")
  3698. yield* TestLLM.push(
  3699. TestLLM.failAfter(
  3700. incompleteStream(),
  3701. LLMEvent.stepStart({ index: 0 }),
  3702. LLMEvent.reasoningStart({ id: "partial-reasoning" }),
  3703. LLMEvent.reasoningDelta({ id: "partial-reasoning", text: "Partial thought" }),
  3704. ),
  3705. )
  3706. yield* TestLLM.push(TestLLM.text("Recovered", "reasoning-recovery"))
  3707. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3708. yield* TestLLM.wait(1)
  3709. yield* TestClock.adjust("2 seconds")
  3710. yield* Fiber.join(run)
  3711. expect(requests[1]?.messages.at(-2)).toMatchObject({
  3712. role: "assistant",
  3713. content: [{ type: "text", text: "Partial thought" }],
  3714. })
  3715. expect(requests[1]?.messages.at(-1)).toMatchObject({
  3716. role: "user",
  3717. content: [
  3718. {
  3719. type: "text",
  3720. text: INCOMPLETE_STREAM_CONTINUATION,
  3721. },
  3722. ],
  3723. })
  3724. expect(yield* session.context(sessionID)).toMatchObject([
  3725. { type: "user" },
  3726. { type: "assistant", finish: "error", content: [{ type: "reasoning", text: "Partial thought" }] },
  3727. { type: "synthetic" },
  3728. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3729. ])
  3730. }),
  3731. )
  3732. it.effect("continues an incomplete stream after settling a local tool", () =>
  3733. Effect.gen(function* () {
  3734. const session = yield* setup
  3735. yield* admit(session, "Continue after tool")
  3736. yield* TestLLM.push(
  3737. TestLLM.failAfter(
  3738. incompleteStream(),
  3739. LLMEvent.stepStart({ index: 0 }),
  3740. LLMEvent.toolCall({ id: "call-before-close", name: "echo", input: { text: "settled" } }),
  3741. ),
  3742. )
  3743. yield* TestLLM.push(TestLLM.text("Recovered", "tool-recovery"))
  3744. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3745. yield* TestLLM.wait(1)
  3746. while (!(yield* recordedEventTypes(sessionID)).includes("session.retry.scheduled.1")) yield* Effect.yieldNow
  3747. yield* TestClock.adjust("2 seconds")
  3748. yield* Fiber.join(run)
  3749. expect(executions).toEqual(["settled"])
  3750. expect(requests[1]?.messages.slice(-3)).toMatchObject([
  3751. {
  3752. role: "assistant",
  3753. content: [{ type: "tool-call", id: "call-before-close", name: "echo", input: { text: "settled" } }],
  3754. },
  3755. { role: "tool", content: [{ type: "tool-result", id: "call-before-close" }] },
  3756. {
  3757. role: "user",
  3758. content: [
  3759. {
  3760. type: "text",
  3761. text: INCOMPLETE_STREAM_CONTINUATION,
  3762. },
  3763. ],
  3764. },
  3765. ])
  3766. }),
  3767. )
  3768. it.effect("continues an incomplete stream after settling a local tool defect", () =>
  3769. Effect.gen(function* () {
  3770. const session = yield* setup
  3771. yield* admit(session, "Continue after tool defect")
  3772. yield* TestLLM.push(
  3773. TestLLM.failAfter(
  3774. incompleteStream(),
  3775. LLMEvent.stepStart({ index: 0 }),
  3776. LLMEvent.toolCall({ id: "call-defect-before-close", name: "defect", input: {} }),
  3777. ),
  3778. )
  3779. yield* TestLLM.push(TestLLM.text("Recovered", "tool-defect-recovery"))
  3780. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3781. yield* TestLLM.wait(1)
  3782. while (!(yield* recordedEventTypes(sessionID)).includes("session.retry.scheduled.1")) yield* Effect.yieldNow
  3783. yield* TestClock.adjust("2 seconds")
  3784. yield* Fiber.join(run)
  3785. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "tool", "user"])
  3786. expect(yield* session.context(sessionID)).toMatchObject([
  3787. { type: "user" },
  3788. {
  3789. type: "assistant",
  3790. content: [
  3791. {
  3792. type: "tool",
  3793. id: "call-defect-before-close",
  3794. state: { status: "error", error: { type: "unknown", message: "unexpected tool defect" } },
  3795. },
  3796. ],
  3797. },
  3798. { type: "synthetic", text: INCOMPLETE_STREAM_CONTINUATION },
  3799. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3800. ])
  3801. }),
  3802. )
  3803. it.effect("stops incomplete stream continuations after five total attempts", () =>
  3804. Effect.gen(function* () {
  3805. const session = yield* setup
  3806. yield* admit(session, "Exhaust partial continuations")
  3807. const failure = incompleteStream()
  3808. yield* TestLLM.always(
  3809. TestLLM.failAfter(
  3810. failure,
  3811. LLMEvent.stepStart({ index: 0 }),
  3812. LLMEvent.textStart({ id: "partial-exhaustion" }),
  3813. LLMEvent.textDelta({ id: "partial-exhaustion", text: "Partial" }),
  3814. ),
  3815. )
  3816. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3817. yield* TestLLM.wait(1)
  3818. for (const [index, delay] of [2_000, 4_000, 8_000, 16_000].entries()) {
  3819. yield* TestClock.adjust(delay)
  3820. yield* TestLLM.wait(index + 2)
  3821. }
  3822. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  3823. expect(requests).toHaveLength(5)
  3824. const context = yield* session.context(sessionID)
  3825. expect(context.filter((message) => message.type === "assistant")).toHaveLength(5)
  3826. expect(context.filter((message) => message.type === "synthetic")).toHaveLength(4)
  3827. }),
  3828. )
  3829. it.effect("stops after five total retry attempts", () =>
  3830. Effect.gen(function* () {
  3831. const session = yield* setup
  3832. yield* admit(session, "Exhaust retries")
  3833. const failure = providerUnavailable()
  3834. yield* TestLLM.always(Stream.fail(failure))
  3835. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3836. yield* TestLLM.wait(1)
  3837. for (const [index, delay] of [2_000, 4_000, 8_000, 16_000].entries()) {
  3838. yield* TestClock.adjust(delay)
  3839. yield* TestLLM.wait(index + 2)
  3840. }
  3841. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  3842. expect(requests).toHaveLength(5)
  3843. const database = (yield* Database.Service).db
  3844. const retries = yield* database
  3845. .select({ data: EventTable.data })
  3846. .from(EventTable)
  3847. .where(eq(EventTable.type, "session.retry.scheduled.1"))
  3848. .orderBy(asc(EventTable.seq))
  3849. .all()
  3850. .pipe(Effect.orDie)
  3851. expect(retries.map((event) => event.data)).toMatchObject([
  3852. { attempt: 2, at: 2_000 },
  3853. { attempt: 3, at: 6_000 },
  3854. { attempt: 4, at: 14_000 },
  3855. { attempt: 5, at: 30_000 },
  3856. ])
  3857. expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.step.started.1")).toHaveLength(5)
  3858. const assistant = requireAssistant(yield* session.context(sessionID))
  3859. expect(yield* recordedStepSettlementEvents(sessionID, assistant.id)).toMatchObject([
  3860. { type: "session.step.started.1" },
  3861. { type: "session.step.started.1" },
  3862. { type: "session.step.started.1" },
  3863. { type: "session.step.started.1" },
  3864. { type: "session.step.started.1" },
  3865. { type: "session.step.failed.1" },
  3866. ])
  3867. }),
  3868. )
  3869. it.effect("retries a model call without consuming the logical agent step", () =>
  3870. Effect.gen(function* () {
  3871. const session = yield* setup
  3872. const agents = yield* Agent.Service
  3873. yield* agents.transform((editor) =>
  3874. editor.update(Agent.ID.make("build"), (agent) => {
  3875. agent.steps = 2
  3876. }),
  3877. )
  3878. yield* admit(session, "Retry without consuming a step")
  3879. const failure = providerUnavailable()
  3880. yield* TestLLM.push(Stream.fail(failure))
  3881. yield* TestLLM.push(TestLLM.tool("call-after-retry", "echo", { text: "recovered" }), TestLLM.stop())
  3882. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3883. yield* TestLLM.wait(1)
  3884. yield* TestClock.adjust("2 seconds")
  3885. yield* Fiber.join(run)
  3886. expect(requests).toHaveLength(3)
  3887. expect(requests[0]?.toolChoice).toBeUndefined()
  3888. expect(requests[0]?.tools.map((tool) => tool.name)).toContain("echo")
  3889. expect(requests[1]?.toolChoice).toBeUndefined()
  3890. expect(requests[1]?.tools.map((tool) => tool.name)).toContain("echo")
  3891. expect(requests[1]?.messages.at(-1)).not.toMatchObject({
  3892. role: "assistant",
  3893. content: [{ type: "text", text: expect.stringContaining("MAXIMUM STEPS REACHED") }],
  3894. })
  3895. expect(requests[2]?.toolChoice).toMatchObject({ type: "none" })
  3896. // The final step keeps tool definitions to preserve provider prompt caching.
  3897. expect(requests[2]?.tools.map((tool) => tool.name)).toContain("echo")
  3898. expect(requests[2]?.messages.at(-1)).toMatchObject({
  3899. role: "assistant",
  3900. content: [{ type: "text", text: expect.stringContaining("MAXIMUM STEPS REACHED") }],
  3901. })
  3902. expect(executions).toEqual(["recovered"])
  3903. const eventTypes = yield* recordedEventTypes(sessionID)
  3904. expect(eventTypes.filter((type) => type === "session.step.started.1")).toHaveLength(3)
  3905. expect(eventTypes.filter((type) => type === "session.retry.scheduled.1")).toHaveLength(1)
  3906. expect((yield* session.context(sessionID)).filter((message) => message.type === "assistant")).toHaveLength(2)
  3907. }),
  3908. )
  3909. it.effect("does not retry non-eligible provider failures", () =>
  3910. Effect.gen(function* () {
  3911. const session = yield* setup
  3912. const failure = invalidRequest()
  3913. yield* TestLLM.push(Stream.fail(failure))
  3914. expect(yield* runPrompt(session, "Do not retry").pipe(Effect.flip)).toBe(failure)
  3915. expect(requests).toHaveLength(1)
  3916. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.retry.scheduled.1")
  3917. }),
  3918. )
  3919. it.effect("settles malformed streamed tool input before the provider failure", () =>
  3920. Effect.gen(function* () {
  3921. const session = yield* setup
  3922. const failure = new AIError({
  3923. module: "test",
  3924. method: "stream",
  3925. reason: new InvalidProviderOutputReason({ message: "Invalid JSON input for tool call echo" }),
  3926. })
  3927. yield* TestLLM.push(
  3928. TestLLM.failAfter(
  3929. failure,
  3930. LLMEvent.stepStart({ index: 0 }),
  3931. LLMEvent.toolInputStart({ id: "call-malformed", name: "echo" }),
  3932. LLMEvent.toolInputDelta({ id: "call-malformed", name: "echo", text: '{"text":"partial' }),
  3933. ),
  3934. )
  3935. expect(yield* runPrompt(session, "Call a malformed tool").pipe(Effect.flip)).toBe(failure)
  3936. const assistant = requireAssistant(yield* session.context(sessionID))
  3937. yield* TestLLM.push(TestLLM.stop())
  3938. yield* runPrompt(session, "Continue")
  3939. expect(yield* recordedStepSettlementEvents(sessionID, assistant.id)).toMatchObject([
  3940. { type: "session.step.started.1" },
  3941. {
  3942. type: "session.tool.failed.2",
  3943. data: {
  3944. id: "call-malformed",
  3945. error: { type: "provider.invalid-output", message: "Invalid JSON input for tool call echo" },
  3946. },
  3947. },
  3948. {
  3949. type: "session.step.failed.1",
  3950. data: { error: { type: "provider.invalid-output", message: "Invalid JSON input for tool call echo" } },
  3951. },
  3952. ])
  3953. }),
  3954. )
  3955. it.effect("continues after malformed local tool input without exposing raw arguments", () =>
  3956. Effect.gen(function* () {
  3957. const session = yield* setup
  3958. const marker = "raw-malformed-marker"
  3959. const raw = `{"text":"${marker}`
  3960. yield* TestLLM.push(
  3961. TestLLM.toolCalls(
  3962. LLMEvent.toolInputStart({ id: "call-malformed", name: "echo" }),
  3963. LLMEvent.toolInputDelta({ id: "call-malformed", name: "echo", text: raw }),
  3964. LLMEvent.toolInputEnd({ id: "call-malformed", name: "echo" }),
  3965. LLMEvent.toolInputError({
  3966. id: "call-malformed",
  3967. name: "echo",
  3968. raw,
  3969. }),
  3970. ),
  3971. TestLLM.stop(),
  3972. )
  3973. yield* runPrompt(session, "Recover malformed tool input")
  3974. expect(requests).toHaveLength(2)
  3975. expect(executions).toEqual([])
  3976. expect(JSON.stringify(requests[1])).not.toContain(marker)
  3977. expect(requests[1]?.messages).toEqual(
  3978. expect.arrayContaining([
  3979. expect.objectContaining({
  3980. role: "assistant",
  3981. content: expect.arrayContaining([
  3982. expect.objectContaining({ type: "tool-call", id: "call-malformed", name: "echo", input: {} }),
  3983. ]),
  3984. }),
  3985. expect.objectContaining({
  3986. role: "tool",
  3987. content: expect.arrayContaining([
  3988. expect.objectContaining({
  3989. type: "tool-result",
  3990. id: "call-malformed",
  3991. result: expect.objectContaining({
  3992. type: "error",
  3993. value: expect.objectContaining({
  3994. error: expect.objectContaining({
  3995. message: "Tool call arguments were malformed JSON and were not executed. Retry with valid JSON.",
  3996. }),
  3997. }),
  3998. }),
  3999. }),
  4000. ]),
  4001. }),
  4002. ]),
  4003. )
  4004. const context = yield* session.context(sessionID)
  4005. const failed = context.find(
  4006. (message): message is SessionMessage.Assistant =>
  4007. message.type === "assistant" && message.content.some((item) => item.type === "tool"),
  4008. )
  4009. expect(failed).toMatchObject({
  4010. content: [
  4011. {
  4012. type: "tool",
  4013. id: "call-malformed",
  4014. executed: false,
  4015. state: {
  4016. status: "error",
  4017. input: {},
  4018. error: {
  4019. type: "tool.input-json",
  4020. message: "Tool call arguments were malformed JSON and were not executed. Retry with valid JSON.",
  4021. },
  4022. },
  4023. },
  4024. ],
  4025. })
  4026. if (!failed) throw new Error("Malformed tool assistant missing")
  4027. expect(failed.error).toBeUndefined()
  4028. expect(yield* recordedStepSettlementTypes(sessionID, failed.id)).toEqual([
  4029. "session.step.started.1",
  4030. "session.tool.failed.2",
  4031. "session.step.ended.1",
  4032. ])
  4033. const database = (yield* Database.Service).db
  4034. const durable = yield* database
  4035. .select({ type: EventTable.type, data: EventTable.data })
  4036. .from(EventTable)
  4037. .where(eq(EventTable.aggregate_id, sessionID))
  4038. .all()
  4039. .pipe(Effect.orDie)
  4040. expect(durable.find((event) => event.type === "session.tool.input.ended.1")?.data).toMatchObject({
  4041. id: "call-malformed",
  4042. text: raw,
  4043. })
  4044. }),
  4045. )
  4046. it.effect("settles a valid sibling before recovering malformed tool input", () =>
  4047. Effect.gen(function* () {
  4048. const session = yield* setup
  4049. yield* admit(session, "Run parallel tools")
  4050. const tools = yield* blockTools()
  4051. yield* TestLLM.push(
  4052. TestLLM.toolCalls(
  4053. LLMEvent.toolCall({ id: "call-valid", name: "echo", input: { text: "valid" } }),
  4054. LLMEvent.toolInputError({
  4055. id: "call-malformed",
  4056. name: "echo",
  4057. raw: '{"text":"partial',
  4058. }),
  4059. ),
  4060. TestLLM.stop(),
  4061. )
  4062. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  4063. yield* tools.started
  4064. expect(requests).toHaveLength(1)
  4065. yield* tools.release
  4066. yield* Fiber.join(run)
  4067. expect(requests).toHaveLength(2)
  4068. expect(executions).toEqual(["valid"])
  4069. const request = requests[1]
  4070. if (!request) throw new Error("Malformed recovery request missing")
  4071. expect(request.messages.flatMap((message) => (message.role === "tool" ? message.content : []))).toEqual(
  4072. expect.arrayContaining([
  4073. expect.objectContaining({ id: "call-valid", type: "tool-result" }),
  4074. expect.objectContaining({ id: "call-malformed", type: "tool-result" }),
  4075. ]),
  4076. )
  4077. }),
  4078. )
  4079. it.effect("does not recover malformed input after sibling execution is interrupted", () =>
  4080. Effect.gen(function* () {
  4081. const session = yield* setup
  4082. yield* admit(session, "Interrupt malformed recovery")
  4083. const tools = yield* blockTools()
  4084. yield* TestLLM.push(
  4085. TestLLM.toolCalls(
  4086. LLMEvent.toolCall({ id: "call-valid", name: "echo", input: { text: "blocked" } }),
  4087. LLMEvent.toolInputError({
  4088. id: "call-malformed",
  4089. name: "echo",
  4090. raw: '{"text":"partial',
  4091. }),
  4092. ),
  4093. )
  4094. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  4095. yield* tools.started
  4096. while (
  4097. !(yield* session.context(sessionID)).some(
  4098. (message) =>
  4099. message.type === "assistant" &&
  4100. message.content.some((item) => item.type === "tool" && item.id === "call-malformed"),
  4101. )
  4102. )
  4103. yield* Effect.yieldNow
  4104. yield* session.interrupt(sessionID)
  4105. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  4106. expect(requests).toHaveLength(1)
  4107. expect(yield* session.context(sessionID)).toMatchObject([
  4108. { type: "user", text: "Interrupt malformed recovery" },
  4109. {
  4110. type: "assistant",
  4111. error: { type: "aborted", message: "Step interrupted" },
  4112. content: [
  4113. { type: "tool", id: "call-valid", state: { status: "error", error: { type: "aborted" } } },
  4114. { type: "tool", id: "call-malformed", state: { status: "error" } },
  4115. ],
  4116. },
  4117. ])
  4118. }),
  4119. )
  4120. it.effect("records malformed provider-executed input as executed", () =>
  4121. Effect.gen(function* () {
  4122. const session = yield* setup
  4123. const failure = new AIError({
  4124. module: "test",
  4125. method: "stream",
  4126. reason: new InvalidProviderOutputReason({ message: "Invalid hosted tool input" }),
  4127. })
  4128. yield* TestLLM.push(
  4129. TestLLM.failAfter(
  4130. failure,
  4131. LLMEvent.stepStart({ index: 0 }),
  4132. LLMEvent.toolInputStart({ id: "call-hosted", name: "web_search", providerExecuted: true }),
  4133. LLMEvent.toolInputDelta({ id: "call-hosted", name: "web_search", text: '{"query":"partial' }),
  4134. ),
  4135. )
  4136. expect(yield* runPrompt(session, "Fail malformed hosted input").pipe(Effect.flip)).toBe(failure)
  4137. expect(requireAssistant(yield* session.context(sessionID))).toMatchObject({
  4138. error: { type: "provider.invalid-output", message: "Invalid hosted tool input" },
  4139. content: [
  4140. {
  4141. type: "tool",
  4142. id: "call-hosted",
  4143. executed: true,
  4144. state: { status: "error", error: { type: "provider.invalid-output" } },
  4145. },
  4146. ],
  4147. })
  4148. }),
  4149. )
  4150. it.effect("records a provider failure after malformed input", () =>
  4151. Effect.gen(function* () {
  4152. const session = yield* setup
  4153. const failure = new AIError({
  4154. module: "test",
  4155. method: "stream",
  4156. reason: new InvalidProviderOutputReason({ message: "Provider failed after malformed input" }),
  4157. })
  4158. yield* TestLLM.push(
  4159. TestLLM.failAfter(
  4160. failure,
  4161. LLMEvent.stepStart({ index: 0 }),
  4162. LLMEvent.toolInputError({
  4163. id: "call-malformed",
  4164. name: "echo",
  4165. raw: '{"text":"partial',
  4166. }),
  4167. ),
  4168. )
  4169. expect(yield* runPrompt(session, "Fail after malformed input").pipe(Effect.flip)).toBe(failure)
  4170. expect(requireAssistant(yield* session.context(sessionID))).toMatchObject({
  4171. error: { type: "provider.invalid-output", message: "Provider failed after malformed input" },
  4172. content: [
  4173. {
  4174. type: "tool",
  4175. id: "call-malformed",
  4176. executed: false,
  4177. state: { status: "error", error: { type: "tool.input-json" } },
  4178. },
  4179. ],
  4180. })
  4181. expect(requests).toHaveLength(1)
  4182. }),
  4183. )
  4184. it.effect("continues after repeated malformed tool input", () =>
  4185. Effect.gen(function* () {
  4186. const session = yield* setup
  4187. const malformed = (id: string) =>
  4188. TestLLM.toolCalls(
  4189. LLMEvent.toolInputError({
  4190. id,
  4191. name: "echo",
  4192. raw: '{"text":"partial',
  4193. }),
  4194. )
  4195. yield* TestLLM.push(
  4196. malformed("call-first"),
  4197. TestLLM.tool("call-valid-between", "echo", { text: "valid" }),
  4198. malformed("call-second"),
  4199. TestLLM.stop(),
  4200. )
  4201. yield* runPrompt(session, "Keep producing malformed tools")
  4202. expect(requests).toHaveLength(4)
  4203. expect(executions).toEqual(["valid"])
  4204. expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.step.failed.1")).toHaveLength(0)
  4205. }),
  4206. )
  4207. it.effect("does not continue malformed tool input past the agent step limit", () =>
  4208. Effect.gen(function* () {
  4209. const session = yield* setup
  4210. const agents = yield* Agent.Service
  4211. yield* agents.transform((editor) =>
  4212. editor.update(Agent.ID.make("build"), (agent) => {
  4213. agent.steps = 2
  4214. }),
  4215. )
  4216. const malformed = (id: string) =>
  4217. TestLLM.toolCalls(
  4218. LLMEvent.toolInputError({
  4219. id,
  4220. name: "echo",
  4221. raw: '{"text":"partial',
  4222. }),
  4223. )
  4224. yield* TestLLM.push(malformed("call-first"), malformed("call-at-limit"))
  4225. yield* runPrompt(session, "Stop malformed tools at the step limit")
  4226. expect(requests).toHaveLength(2)
  4227. expect(requests[0]?.toolChoice).toBeUndefined()
  4228. expect(requests[1]?.toolChoice).toMatchObject({ type: "none" })
  4229. expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.tool.failed.2")).toHaveLength(2)
  4230. }),
  4231. )
  4232. it.effect("does not continue automatically after a provider error follows a local tool call", () =>
  4233. Effect.gen(function* () {
  4234. const session = yield* setup
  4235. yield* admit(session, "Do not continue failed provider")
  4236. const tools = yield* blockTools()
  4237. yield* TestLLM.push([
  4238. LLMEvent.stepStart({ index: 0 }),
  4239. LLMEvent.toolCall({ id: "call-before-provider-error", name: "echo", input: { text: "settled" } }),
  4240. LLMEvent.providerError({ message: "Provider unavailable" }),
  4241. ])
  4242. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  4243. yield* tools.started
  4244. yield* tools.release
  4245. expect((yield* Fiber.join(run).pipe(Effect.flip)).message).toBe("Provider unavailable")
  4246. expect(requests).toHaveLength(1)
  4247. expect(executions).toEqual(["settled"])
  4248. const context = yield* session.context(sessionID)
  4249. const assistant = requireAssistant(context)
  4250. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  4251. "session.step.started.1",
  4252. "session.tool.called.1",
  4253. "session.tool.success.2",
  4254. "session.step.failed.1",
  4255. ])
  4256. }),
  4257. )
  4258. it.effect("durably fails a hosted tool when its provider errors before returning a result", () =>
  4259. Effect.gen(function* () {
  4260. const session = yield* setup
  4261. yield* TestLLM.push([
  4262. LLMEvent.stepStart({ index: 0 }),
  4263. hostedCall("call-hosted-provider-error", "effect"),
  4264. LLMEvent.providerError({ message: "Provider unavailable" }),
  4265. ])
  4266. expect((yield* runPrompt(session, "Fail hosted tool durably").pipe(Effect.flip)).message).toBe(
  4267. "Provider unavailable",
  4268. )
  4269. expect(requests).toHaveLength(1)
  4270. const context = yield* session.context(sessionID)
  4271. expect(context).toMatchObject([
  4272. { type: "user", text: "Fail hosted tool durably" },
  4273. {
  4274. type: "assistant",
  4275. content: [{ type: "tool", id: "call-hosted-provider-error", state: { status: "error" } }],
  4276. },
  4277. ])
  4278. const assistant = requireAssistant(context)
  4279. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  4280. "session.step.started.1",
  4281. "session.tool.called.1",
  4282. "session.tool.failed.2",
  4283. "session.step.failed.1",
  4284. ])
  4285. }),
  4286. )
  4287. it.effect("preserves a tool defect before provider failure settlement", () =>
  4288. Effect.gen(function* () {
  4289. const session = yield* setup
  4290. yield* TestLLM.push([
  4291. LLMEvent.stepStart({ index: 0 }),
  4292. LLMEvent.toolCall({ id: "call-defect-provider-error", name: "defect", input: {} }),
  4293. LLMEvent.providerError({ message: "Provider unavailable" }),
  4294. ])
  4295. expect((yield* runPrompt(session, "Defect while provider fails").pipe(Effect.flip)).message).toBe(
  4296. "Provider unavailable",
  4297. )
  4298. const context = yield* session.context(sessionID)
  4299. const assistant = requireAssistant(context)
  4300. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4301. expect(bus.map((event) => event.type)).toEqual([
  4302. "session.step.started.1",
  4303. "session.tool.called.1",
  4304. "session.tool.failed.2",
  4305. "session.step.failed.1",
  4306. ])
  4307. expect(bus[2]?.data.error).toMatchObject({ type: "unknown", message: "unexpected tool defect" })
  4308. }),
  4309. )
  4310. it.effect("preserves the provider failure when tool output persistence also fails", () =>
  4311. Effect.gen(function* () {
  4312. const session = yield* setup
  4313. yield* admit(session, "Storage fails while provider fails")
  4314. yield* TestLLM.push([
  4315. LLMEvent.stepStart({ index: 0 }),
  4316. LLMEvent.toolCall({ id: "call-store-provider-error", name: "storefail", input: {} }),
  4317. LLMEvent.providerError({ message: "Provider unavailable" }),
  4318. ])
  4319. expect(yield* session.resume(sessionID).pipe(Effect.exit)).toMatchObject({
  4320. _tag: "Failure",
  4321. })
  4322. expect(requireAssistant(yield* session.context(sessionID))).toMatchObject({
  4323. error: { type: "provider.unknown", message: "Provider unavailable" },
  4324. })
  4325. }),
  4326. )
  4327. it.effect("durably fails a hosted tool left unresolved at normal provider EOF", () =>
  4328. Effect.gen(function* () {
  4329. const session = yield* setup
  4330. yield* TestLLM.push([LLMEvent.stepStart({ index: 0 }), hostedCall("call-hosted-eof", "effect")])
  4331. expect((yield* runPrompt(session, "Fail hosted tool at EOF").pipe(Effect.flip)).message).toBe(
  4332. "Provider did not return a tool result",
  4333. )
  4334. const assistant = requireAssistant(yield* session.context(sessionID))
  4335. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4336. expect(bus.map((event) => event.type)).toEqual([
  4337. "session.step.started.1",
  4338. "session.tool.called.1",
  4339. "session.tool.failed.2",
  4340. "session.step.failed.1",
  4341. ])
  4342. expect(
  4343. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4344. ).toHaveLength(1)
  4345. yield* replaySessionProjection(sessionID)
  4346. expect(yield* session.context(sessionID)).toMatchObject([
  4347. { type: "user", text: "Fail hosted tool at EOF" },
  4348. {
  4349. type: "assistant",
  4350. finish: "error",
  4351. error: { type: "tool.result-missing" },
  4352. content: [{ type: "tool", id: "call-hosted-eof", state: { status: "error" } }],
  4353. },
  4354. ])
  4355. }),
  4356. )
  4357. it.effect("fails an unresolved hosted tool before one clean step end", () =>
  4358. Effect.gen(function* () {
  4359. const session = yield* setup
  4360. yield* TestLLM.push(TestLLM.stop(hostedCall("call-hosted-clean-end", "effect")))
  4361. yield* runPrompt(session, "Settle hosted tool before ending")
  4362. const assistant = requireAssistant(yield* session.context(sessionID))
  4363. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4364. expect(bus.map((event) => event.type)).toEqual([
  4365. "session.step.started.1",
  4366. "session.tool.called.1",
  4367. "session.tool.failed.2",
  4368. "session.step.ended.1",
  4369. ])
  4370. expect(
  4371. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4372. ).toHaveLength(1)
  4373. }),
  4374. )
  4375. it.effect("settles unresolved local and hosted tools before one raw provider failure", () =>
  4376. Effect.gen(function* () {
  4377. const session = yield* setup
  4378. yield* admit(session, "Fail unresolved tools")
  4379. const failure = invalidRequest()
  4380. const providerFailed = yield* Deferred.make<void>()
  4381. const tools = yield* blockTools()
  4382. yield* TestLLM.push(
  4383. Stream.concat(
  4384. Stream.fromIterable([
  4385. LLMEvent.stepStart({ index: 0 }),
  4386. LLMEvent.toolCall({ id: "call-local-raw-failure", name: "defect", input: {} }),
  4387. hostedCall("call-hosted-raw-failure-pair", "effect"),
  4388. ]),
  4389. Stream.fromEffect(Deferred.succeed(providerFailed, undefined)).pipe(
  4390. Stream.flatMap(() => Stream.fail(failure)),
  4391. ),
  4392. ),
  4393. )
  4394. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  4395. yield* Deferred.await(providerFailed)
  4396. yield* tools.release
  4397. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  4398. const assistant = requireAssistant(yield* session.context(sessionID))
  4399. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4400. expect(bus.map((event) => ({ type: event.type, id: event.data.id }))).toEqual([
  4401. { type: "session.step.started.1", id: undefined },
  4402. { type: "session.tool.called.1", id: "call-local-raw-failure" },
  4403. { type: "session.tool.called.1", id: "call-hosted-raw-failure-pair" },
  4404. { type: "session.tool.failed.2", id: "call-local-raw-failure" },
  4405. { type: "session.tool.failed.2", id: "call-hosted-raw-failure-pair" },
  4406. { type: "session.step.failed.1", id: undefined },
  4407. ])
  4408. expect(
  4409. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4410. ).toHaveLength(1)
  4411. }),
  4412. )
  4413. it.effect("durably fails a hosted tool left unresolved by a raw provider stream failure", () =>
  4414. Effect.gen(function* () {
  4415. const session = yield* setup
  4416. const failure = providerUnavailable()
  4417. yield* TestLLM.push(
  4418. Stream.concat(
  4419. Stream.fromIterable([LLMEvent.stepStart({ index: 0 }), hostedCall("call-hosted-raw-failure", "effect")]),
  4420. Stream.fail(failure),
  4421. ),
  4422. )
  4423. expect(yield* runPrompt(session, "Fail hosted tool on raw failure").pipe(Effect.flip)).toBe(failure)
  4424. expect(requests).toHaveLength(1)
  4425. const assistant = requireAssistant(yield* session.context(sessionID))
  4426. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4427. expect(bus.map((event) => event.type)).toEqual([
  4428. "session.step.started.1",
  4429. "session.tool.called.1",
  4430. "session.tool.failed.2",
  4431. "session.step.failed.1",
  4432. ])
  4433. expect(
  4434. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4435. ).toHaveLength(1)
  4436. yield* replaySessionProjection(sessionID)
  4437. expect(yield* session.context(sessionID)).toMatchObject([
  4438. { type: "user", text: "Fail hosted tool on raw failure" },
  4439. {
  4440. type: "assistant",
  4441. finish: "error",
  4442. error: { type: "provider.transport", message: "Provider unavailable" },
  4443. content: [{ type: "tool", id: "call-hosted-raw-failure", state: { status: "error" } }],
  4444. },
  4445. ])
  4446. }),
  4447. )
  4448. it.effect("rejects a second text start before the open fragment ends", () =>
  4449. Effect.gen(function* () {
  4450. const session = yield* setup
  4451. yield* TestLLM.push([
  4452. LLMEvent.stepStart({ index: 0 }),
  4453. LLMEvent.textStart({ id: "text-1" }),
  4454. LLMEvent.textStart({ id: "text-2" }),
  4455. ])
  4456. const defect = yield* runPrompt(session, "Two blocks").pipe(Effect.catchDefect(Effect.succeed))
  4457. expect(defect).toBeInstanceOf(Error)
  4458. if (!(defect instanceof Error)) return
  4459. expect(defect.message).toBe("text start before end: text-2")
  4460. }),
  4461. )
  4462. it.effect("projects sequential text fragments as separate content parts", () =>
  4463. Effect.gen(function* () {
  4464. const session = yield* setup
  4465. yield* TestLLM.push(
  4466. TestLLM.stop(
  4467. LLMEvent.textStart({ id: "text-1" }),
  4468. LLMEvent.textDelta({ id: "text-1", text: "First" }),
  4469. LLMEvent.textEnd({ id: "text-1" }),
  4470. LLMEvent.textStart({ id: "text-2" }),
  4471. LLMEvent.textDelta({ id: "text-2", text: "Second" }),
  4472. LLMEvent.textEnd({ id: "text-2" }),
  4473. ),
  4474. )
  4475. yield* runPrompt(session, "Two blocks")
  4476. expect(yield* session.context(sessionID)).toMatchObject([
  4477. { type: "user", text: "Two blocks" },
  4478. {
  4479. type: "assistant",
  4480. content: [
  4481. { type: "text", text: "First" },
  4482. { type: "text", text: "Second" },
  4483. ],
  4484. },
  4485. ])
  4486. }),
  4487. )
  4488. for (const kind of fragmentKinds) {
  4489. it.effect(`broadcasts provider ${kind} deltas without storing projection rewrites`, () =>
  4490. verifyEphemeralDeltas(kind),
  4491. )
  4492. it.effect(`durably closes partial ${kind} when the provider stream fails`, () => verifyPartialFlushOnFailure(kind))
  4493. it.effect(`durably closes partial ${kind} when the provider stream is interrupted`, () =>
  4494. verifyPartialFlushOnInterruption(kind),
  4495. )
  4496. }
  4497. it.effect("rejects duplicate streamed text starts", () =>
  4498. Effect.gen(function* () {
  4499. const session = yield* setup
  4500. yield* TestLLM.push([LLMEvent.textStart({ id: "text-1" }), LLMEvent.textStart({ id: "text-1" })])
  4501. const defect = yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))
  4502. expect(defect).toBeInstanceOf(Error)
  4503. if (!(defect instanceof Error)) return
  4504. expect(defect.message).toBe("Duplicate text start: text-1")
  4505. }),
  4506. )
  4507. it.effect("transitions streamed raw tool input to parsed called input", () =>
  4508. Effect.gen(function* () {
  4509. const session = yield* setup
  4510. yield* TestLLM.push(
  4511. TestLLM.stop(
  4512. LLMEvent.toolInputStart({ id: "call-parsed", name: "web_search" }),
  4513. LLMEvent.toolInputDelta({ id: "call-parsed", name: "web_search", text: '{"query":"hello"}' }),
  4514. LLMEvent.toolInputEnd({ id: "call-parsed", name: "web_search" }),
  4515. hostedCall("call-parsed", "hello"),
  4516. ),
  4517. )
  4518. yield* runPrompt(session, "Call provider tool")
  4519. expect(yield* session.context(sessionID)).toMatchObject([
  4520. { type: "user", text: "Call provider tool" },
  4521. {
  4522. type: "assistant",
  4523. content: [{ type: "tool", id: "call-parsed", state: { status: "error", input: { query: "hello" } } }],
  4524. },
  4525. ])
  4526. }),
  4527. )
  4528. it.effect("rejects malformed streamed tool input ordering", () =>
  4529. Effect.gen(function* () {
  4530. const session = yield* setup
  4531. yield* TestLLM.push([LLMEvent.toolInputDelta({ id: "call-1", name: "read", text: "{}" })])
  4532. const defect = yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))
  4533. expect(defect).toBeInstanceOf(Error)
  4534. if (!(defect instanceof Error)) return
  4535. expect(defect.message).toBe("Tool input delta before start: call-1")
  4536. }),
  4537. )
  4538. })