1
0

session-runner.test.ts 171 KB

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