session-runner.test.ts 182 KB

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