session-runner.test.ts 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702
  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: options ?? tool.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, boundary: { type: "before", 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("Changed 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, "Changed context"])
  1062. expect(systemTexts(requests.at(-1)!)).toContain("Latest context")
  1063. const { db } = yield* Database.Service
  1064. const bus = yield* Bus.Service
  1065. const recorded = yield* db
  1066. .select()
  1067. .from(EventTable)
  1068. .where(eq(EventTable.aggregate_id, forked.id))
  1069. .orderBy(asc(EventTable.seq))
  1070. .all()
  1071. yield* bus.remove(forked.id)
  1072. yield* db.delete(SessionTable).where(eq(SessionTable.id, forked.id)).run()
  1073. yield* bus.replayAll(
  1074. recorded.map((event) => ({
  1075. id: event.id,
  1076. created: DateTime.makeUnsafe(event.created),
  1077. aggregateID: event.aggregate_id,
  1078. seq: event.seq,
  1079. type: event.type,
  1080. data: event.data,
  1081. })),
  1082. )
  1083. expect(
  1084. yield* db.select().from(InstructionStateTable).where(eq(InstructionStateTable.session_id, forked.id)).get(),
  1085. ).toMatchObject({ current_values: { "test/context": Instructions.hash("Latest context") } })
  1086. }),
  1087. )
  1088. it.effect("keeps nested forks self-contained", () =>
  1089. Effect.gen(function* () {
  1090. const session = yield* setup
  1091. yield* runPrompt(session, "First")
  1092. systemBaseline = "Changed context"
  1093. const second = yield* runPrompt(session, "Second")
  1094. const child = yield* session.fork({ sessionID, boundary: { type: "before", messageID: second.id } })
  1095. const inheritedFirst = (yield* session.messages({ sessionID: child.id })).find(
  1096. (message) => message.type === "user" && message.text === "First",
  1097. )
  1098. if (!inheritedFirst) return yield* Effect.die(new Error("Nested fork boundary message not found"))
  1099. const grandchild = yield* session.fork({
  1100. sessionID: child.id,
  1101. boundary: { type: "before", messageID: inheritedFirst.id },
  1102. })
  1103. expect(
  1104. yield* (yield* Database.Service).db
  1105. .select()
  1106. .from(InstructionStateTable)
  1107. .where(eq(InstructionStateTable.session_id, grandchild.id))
  1108. .get(),
  1109. ).toMatchObject({
  1110. initial_values: { "test/context": Instructions.hash("Changed context") },
  1111. current_values: { "test/context": Instructions.hash("Changed context") },
  1112. })
  1113. return undefined
  1114. }),
  1115. )
  1116. it.effect("rebuilds a missing instruction cache without admitting another delta", () =>
  1117. Effect.gen(function* () {
  1118. const session = yield* setup
  1119. const { db } = yield* Database.Service
  1120. yield* runPrompt(session, "First")
  1121. yield* db.delete(InstructionStateTable).where(eq(InstructionStateTable.session_id, sessionID)).run()
  1122. yield* admit(session, "Second")
  1123. requests.length = 0
  1124. yield* session.resume(sessionID)
  1125. expect(requests).toHaveLength(1)
  1126. expect(requests[0]?.system.map((part) => part.text)).toEqual([defaultSystem, "Initial context"])
  1127. expect(messageRoles(requests[0])).toEqual(["user", "user"])
  1128. expect(
  1129. yield* db
  1130. .select({ id: EventTable.id })
  1131. .from(EventTable)
  1132. .where(eq(EventTable.type, "session.instructions.updated.2"))
  1133. .all(),
  1134. ).toHaveLength(1)
  1135. expect(yield* db.select().from(InstructionStateTable).get()).toMatchObject({
  1136. initial_values: { "test/context": Instructions.hash("Initial context") },
  1137. current_values: { "test/context": Instructions.hash("Initial context") },
  1138. })
  1139. }),
  1140. )
  1141. it.effect("keeps the initial instructions stable and derives a chronological update from values", () =>
  1142. Effect.gen(function* () {
  1143. const session = yield* setup
  1144. yield* runPrompt(session, "First")
  1145. systemBaseline = "Changed context"
  1146. yield* runPrompt(session, "Second")
  1147. expect(
  1148. PromptCacheDiagnostics.compare(
  1149. PromptCacheDiagnostics.snapshot(requests[0]),
  1150. PromptCacheDiagnostics.snapshot(requests[1]),
  1151. ),
  1152. ).toEqual({ status: "append-only", previousMessages: 1, currentMessages: 3 })
  1153. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1154. [defaultSystem, "Initial context"],
  1155. [defaultSystem, "Initial context"],
  1156. ])
  1157. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1158. expect(requests[1]?.messages.at(1)?.content).toEqual([{ type: "text", text: "Changed context" }])
  1159. expect(yield* session.messages({ sessionID })).toHaveLength(2)
  1160. const { db } = yield* Database.Service
  1161. const updates = yield* db
  1162. .select({ data: EventTable.data })
  1163. .from(EventTable)
  1164. .where(eq(EventTable.type, "session.instructions.updated.2"))
  1165. .orderBy(asc(EventTable.seq))
  1166. .all()
  1167. .pipe(Effect.orDie)
  1168. expect(updates).toHaveLength(2)
  1169. expect(updates[0]?.data).toMatchObject({
  1170. sessionID,
  1171. delta: { "test/context": Instructions.hash("Initial context") },
  1172. })
  1173. expect(updates[1]?.data).toEqual({
  1174. sessionID,
  1175. delta: { "test/context": Instructions.hash("Changed context") },
  1176. })
  1177. yield* replaySessionProjection(sessionID)
  1178. expect(yield* session.messages({ sessionID })).toHaveLength(2)
  1179. }),
  1180. )
  1181. it.effect("uses the selected model family prompt when the agent does not override it", () =>
  1182. Effect.gen(function* () {
  1183. const session = yield* setup
  1184. currentModel = Model.make({ id: "gpt-5", provider: "openai", route: OpenAIChat.route })
  1185. yield* admit(session, "First")
  1186. yield* TestLLM.push(TestLLM.text("Done", "text-provider-prompt"))
  1187. yield* session.resume(sessionID)
  1188. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([
  1189. expect.stringContaining("You are OpenCode, You and the user share the same workspace"),
  1190. "Initial context",
  1191. ])
  1192. }),
  1193. )
  1194. it.effect("uses the selected model family prompt when the agent system override is empty", () =>
  1195. Effect.gen(function* () {
  1196. const session = yield* setup
  1197. currentModel = Model.make({ id: "gpt-5", provider: "openai", route: OpenAIChat.route })
  1198. const agent = yield* Agent.Service
  1199. yield* agent.transform((editor) =>
  1200. editor.update(Agent.ID.make("build"), (agent) => {
  1201. agent.system = ""
  1202. agent.mode = "primary"
  1203. }),
  1204. )
  1205. yield* admit(session, "First")
  1206. yield* TestLLM.push(TestLLM.text("Done", "text-empty-agent-system"))
  1207. yield* session.resume(sessionID)
  1208. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([
  1209. expect.stringContaining("You are OpenCode, You and the user share the same workspace"),
  1210. "Initial context",
  1211. ])
  1212. }),
  1213. )
  1214. it.effect("includes the effective default agent system before durable context", () =>
  1215. Effect.gen(function* () {
  1216. const session = yield* setup
  1217. const agent = yield* Agent.Service
  1218. yield* agent.transform((editor) =>
  1219. editor.update(Agent.ID.make("build"), (agent) => {
  1220. agent.system = "Build agent instructions"
  1221. agent.mode = "primary"
  1222. }),
  1223. )
  1224. yield* admit(session, "First")
  1225. yield* TestLLM.push(TestLLM.text("Done", "text-build"))
  1226. yield* session.resume(sessionID)
  1227. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Build agent instructions", "Initial context"])
  1228. }),
  1229. )
  1230. it.effect("uses the configured default agent system for omitted-agent sessions", () =>
  1231. Effect.gen(function* () {
  1232. const session = yield* setup
  1233. const agent = yield* Agent.Service
  1234. yield* agent.transform((editor) => {
  1235. editor.update(Agent.ID.make("build"), (agent) => {
  1236. agent.system = "Build agent instructions"
  1237. agent.mode = "primary"
  1238. })
  1239. editor.update(Agent.ID.make("reviewer"), (agent) => {
  1240. agent.system = "Reviewer instructions"
  1241. agent.mode = "primary"
  1242. })
  1243. editor.default(Agent.ID.make("reviewer"))
  1244. })
  1245. yield* admit(session, "First")
  1246. yield* TestLLM.push(TestLLM.text("Done", "text-reviewer"))
  1247. yield* session.resume(sessionID)
  1248. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Reviewer instructions", "Initial context"])
  1249. expect((yield* session.messages({ sessionID }))[0]).toMatchObject({ type: "assistant", agent: "reviewer" })
  1250. }),
  1251. )
  1252. it.effect("uses only the agent prompt and initial instructions as system parts", () =>
  1253. Effect.gen(function* () {
  1254. const session = yield* setup
  1255. const agent = yield* Agent.Service
  1256. yield* agent.transform((editor) =>
  1257. editor.update(Agent.ID.make("build"), (agent) => {
  1258. agent.system = "Build agent instructions"
  1259. agent.mode = "primary"
  1260. }),
  1261. )
  1262. yield* admit(session, "First")
  1263. yield* TestLLM.push(TestLLM.text("Done", "text-no-system"))
  1264. yield* session.resume(sessionID)
  1265. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Build agent instructions", "Initial context"])
  1266. }),
  1267. )
  1268. it.effect("uses an explicitly selected non-build agent system", () =>
  1269. Effect.gen(function* () {
  1270. const session = yield* setup
  1271. const { db } = yield* Database.Service
  1272. const agent = yield* Agent.Service
  1273. yield* agent.transform((editor) =>
  1274. editor.update(Agent.ID.make("reviewer"), (agent) => {
  1275. agent.system = "Reviewer instructions"
  1276. agent.mode = "primary"
  1277. }),
  1278. )
  1279. yield* db
  1280. .update(SessionTable)
  1281. .set({ agent: "reviewer" })
  1282. .where(eq(SessionTable.id, sessionID))
  1283. .run()
  1284. .pipe(Effect.orDie)
  1285. yield* admit(session, "First")
  1286. yield* TestLLM.push(TestLLM.text("Done", "text-selected"))
  1287. yield* session.resume(sessionID)
  1288. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual(["Reviewer instructions", "Initial context"])
  1289. expect((yield* session.messages({ sessionID }))[0]).toMatchObject({ type: "assistant", agent: "reviewer" })
  1290. }),
  1291. )
  1292. it.effect("fails before the model request when the selected agent is unavailable", () =>
  1293. Effect.gen(function* () {
  1294. yield* setup
  1295. const { db } = yield* Database.Service
  1296. yield* db
  1297. .update(SessionTable)
  1298. .set({ agent: "explore" })
  1299. .where(eq(SessionTable.id, sessionID))
  1300. .run()
  1301. .pipe(Effect.orDie)
  1302. const session = yield* Session.Service
  1303. yield* session.prompt({ sessionID, text: "Inspect files", resume: false })
  1304. requests.length = 0
  1305. yield* TestLLM.push([])
  1306. const failure = yield* session.resume(sessionID).pipe(Effect.flip)
  1307. expect(failure).toMatchObject({
  1308. _tag: "Session.AgentNotFoundError",
  1309. sessionID,
  1310. agent: "explore",
  1311. })
  1312. expect(requests).toHaveLength(0)
  1313. }),
  1314. )
  1315. it.effect("waits for initial plugin readiness before constructing the model request", () =>
  1316. Effect.gen(function* () {
  1317. yield* setup
  1318. const release = yield* Deferred.make<void>()
  1319. pluginFlushHook = Deferred.await(release)
  1320. const session = yield* Session.Service
  1321. yield* session.prompt({ sessionID, text: "Wait for plugins", resume: false })
  1322. requests.length = 0
  1323. yield* TestLLM.push([])
  1324. const running = yield* session.resume(sessionID).pipe(Effect.forkChild({ startImmediately: true }))
  1325. yield* Effect.yieldNow
  1326. expect(requests).toHaveLength(0)
  1327. expect(running.pollUnsafe()).toBeUndefined()
  1328. yield* Deferred.succeed(release, undefined)
  1329. yield* Fiber.join(running)
  1330. expect(requests).toHaveLength(1)
  1331. }),
  1332. )
  1333. it.effect("updates selected-agent skill instructions after an agent switch", () =>
  1334. Effect.gen(function* () {
  1335. const session = yield* setup
  1336. const bus = yield* Bus.Service
  1337. const agents = yield* Agent.Service
  1338. yield* agents.transform((draft) =>
  1339. draft.update(Agent.ID.make("reviewer"), (agent) => {
  1340. agent.mode = "primary"
  1341. }),
  1342. )
  1343. skillBaselines.set(Agent.ID.make("build"), "Build skills")
  1344. yield* runPrompt(session, "First")
  1345. skillBaselines.set(Agent.ID.make("reviewer"), "Reviewer skills")
  1346. yield* bus.publish(SessionEvent.AgentSelected, {
  1347. sessionID,
  1348. agent: Agent.ID.make("reviewer"),
  1349. })
  1350. yield* runPrompt(session, "Second")
  1351. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1352. [defaultSystem, "Initial context\n\nBuild skills"],
  1353. [defaultSystem, "Initial context\n\nBuild skills"],
  1354. ])
  1355. expect(systemTexts(requests[1])).toContainEqual(expect.stringContaining("Reviewer skills"))
  1356. }),
  1357. )
  1358. it.effect("keeps the sampled agent when selection changes during observation", () =>
  1359. Effect.gen(function* () {
  1360. const session = yield* setup
  1361. const bus = yield* Bus.Service
  1362. skillBaselines.set(Agent.ID.make("build"), "Build skills")
  1363. skillBaselines.set(Agent.ID.make("reviewer"), "Reviewer skills")
  1364. let switched = false
  1365. systemLoadHook = Effect.suspend(() => {
  1366. if (switched) return Effect.void
  1367. switched = true
  1368. return bus
  1369. .publish(SessionEvent.AgentSelected, {
  1370. sessionID,
  1371. agent: Agent.ID.make("reviewer"),
  1372. })
  1373. .pipe(Effect.asVoid)
  1374. })
  1375. yield* runPrompt(session, "First")
  1376. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1377. [defaultSystem, "Initial context\n\nBuild skills"],
  1378. ])
  1379. }),
  1380. )
  1381. it.effect("keeps the sampled model when selection changes during model resolution", () =>
  1382. Effect.gen(function* () {
  1383. const session = yield* setup
  1384. const bus = yield* Bus.Service
  1385. let switched = false
  1386. modelResolveHook = Effect.suspend(() => {
  1387. if (switched) return Effect.void
  1388. switched = true
  1389. return bus
  1390. .publish(SessionEvent.ModelSelected, {
  1391. sessionID,
  1392. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  1393. })
  1394. .pipe(Effect.asVoid)
  1395. })
  1396. yield* runPrompt(session, "First")
  1397. expect(requests.map((request) => request.model)).toEqual([model])
  1398. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1399. [defaultSystem, "Initial context"],
  1400. ])
  1401. }),
  1402. )
  1403. it.effect("admits removed context as a chronological System message", () =>
  1404. Effect.gen(function* () {
  1405. const session = yield* setup
  1406. yield* runPrompt(session, "First")
  1407. systemRemoved = true
  1408. yield* runPrompt(session, "Second")
  1409. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1410. expect(requests[1]?.messages.at(1)?.content).toEqual([
  1411. { type: "text", text: "System context source removed: test/context" },
  1412. ])
  1413. expect(yield* session.messages({ sessionID })).toHaveLength(2)
  1414. }),
  1415. )
  1416. it.effect("renders API context entries through add, change, and removal", () =>
  1417. Effect.gen(function* () {
  1418. const session = yield* setup
  1419. const contextEntries = yield* InstructionEntry.Service
  1420. yield* contextEntries.put({ sessionID, key: "deploy-target", value: "production" })
  1421. yield* runPrompt(session, "First")
  1422. // String values render verbatim inside the initial tagged block.
  1423. expect(requests[0]?.system.map((part) => part.text)).toEqual([
  1424. defaultSystem,
  1425. ["Initial context", "", '<context key="deploy-target">', "production", "</context>"].join("\n"),
  1426. ])
  1427. // Non-string JSON pretty-prints; the change narrates as a System update.
  1428. yield* contextEntries.put({ sessionID, key: "deploy-target", value: { region: "us-east-1" } })
  1429. yield* runPrompt(session, "Second")
  1430. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1431. expect(requests[1]?.messages.at(1)?.content).toEqual([
  1432. {
  1433. type: "text",
  1434. text: [
  1435. 'The context under "deploy-target" changed and supersedes the previous value:',
  1436. '<context key="deploy-target">',
  1437. "{",
  1438. ' "region": "us-east-1"',
  1439. "}",
  1440. "</context>",
  1441. ].join("\n"),
  1442. },
  1443. ])
  1444. expect(yield* contextEntries.list(sessionID)).toEqual([{ key: "deploy-target", value: { region: "us-east-1" } }])
  1445. // Deleting the row announces removal through the stored removal text.
  1446. yield* contextEntries.remove({ sessionID, key: "deploy-target" })
  1447. yield* runPrompt(session, "Third")
  1448. expect(messageRoles(requests[2])).toEqual(["user", "system", "user", "system", "user"])
  1449. expect(requests[2]?.messages.at(-2)?.content).toEqual([
  1450. { type: "text", text: 'The context under "deploy-target" no longer applies. Disregard it.' },
  1451. ])
  1452. expect(yield* contextEntries.list(sessionID)).toEqual([])
  1453. }),
  1454. )
  1455. it.effect("retains JSON null API entries as values", () =>
  1456. Effect.gen(function* () {
  1457. const session = yield* setup
  1458. const entries = yield* InstructionEntry.Service
  1459. yield* entries.put({ sessionID, key: "nullable", value: "present" })
  1460. yield* runPrompt(session, "First")
  1461. yield* entries.put({ sessionID, key: "nullable", value: null })
  1462. yield* runPrompt(session, "Second")
  1463. expect(requests[1]?.messages.at(1)?.content).toEqual([
  1464. {
  1465. type: "text",
  1466. text: [
  1467. 'The context under "nullable" changed and supersedes the previous value:',
  1468. '<context key="nullable">',
  1469. "null",
  1470. "</context>",
  1471. ].join("\n"),
  1472. },
  1473. ])
  1474. expect(yield* entries.list(sessionID)).toEqual([{ key: "nullable", value: null }])
  1475. }),
  1476. )
  1477. it.effect("rejects API instruction entries larger than 8KB", () =>
  1478. Effect.gen(function* () {
  1479. yield* setup
  1480. const entries = yield* InstructionEntry.Service
  1481. const exit = yield* entries
  1482. .put({ sessionID, key: "oversized", value: "x".repeat(InstructionEntry.MaxValueBytes) })
  1483. .pipe(Effect.exit)
  1484. expect(Exit.isFailure(exit)).toBe(true)
  1485. if (Exit.isFailure(exit)) expect(Cause.squash(exit.cause)).toBeInstanceOf(InstructionEntry.ValueTooLargeError)
  1486. expect(yield* entries.list(sessionID)).toEqual([])
  1487. }),
  1488. )
  1489. it.effect("keeps initial instructions and chronological updates after a model switch", () =>
  1490. Effect.gen(function* () {
  1491. const session = yield* setup
  1492. const bus = yield* Bus.Service
  1493. yield* runPrompt(session, "First")
  1494. systemBaseline = "Changed context"
  1495. yield* runPrompt(session, "Second")
  1496. yield* bus.publish(SessionEvent.ModelSelected, {
  1497. sessionID,
  1498. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  1499. })
  1500. systemBaseline = "Replacement context"
  1501. yield* runPrompt(session, "Third")
  1502. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1503. [defaultSystem, "Initial context"],
  1504. [defaultSystem, "Initial context"],
  1505. [defaultSystem, "Initial context"],
  1506. ])
  1507. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1508. expect(requests[2]?.messages.filter((message) => message.role === "system")).toHaveLength(2)
  1509. expect((yield* session.context(sessionID)).map((message) => message.type)).toEqual([
  1510. "user",
  1511. "user",
  1512. "model-switched",
  1513. "user",
  1514. ])
  1515. yield* replaySessionProjection(sessionID)
  1516. expect(yield* session.messages({ sessionID })).toHaveLength(4)
  1517. yield* runPrompt(session, "Fourth")
  1518. }),
  1519. )
  1520. it.effect("preserves instruction values while a source is temporarily unavailable", () =>
  1521. Effect.gen(function* () {
  1522. const session = yield* setup
  1523. const bus = yield* Bus.Service
  1524. yield* runPrompt(session, "First")
  1525. yield* bus.publish(SessionEvent.ModelSelected, {
  1526. sessionID,
  1527. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  1528. })
  1529. systemUnavailable = true
  1530. yield* runPrompt(session, "Second")
  1531. systemUnavailable = false
  1532. systemBaseline = "Replacement context"
  1533. yield* runPrompt(session, "Third")
  1534. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1535. [defaultSystem, "Initial context"],
  1536. [defaultSystem, "Initial context"],
  1537. [defaultSystem, "Initial context"],
  1538. ])
  1539. }),
  1540. )
  1541. it.effect("moves the epoch at compaction and narrates later changes", () =>
  1542. Effect.gen(function* () {
  1543. const session = yield* setup
  1544. const bus = yield* Bus.Service
  1545. yield* runPrompt(session, "First")
  1546. yield* bus.publish(SessionEvent.Compaction.Started, {
  1547. sessionID,
  1548. reason: "manual",
  1549. recent: "",
  1550. })
  1551. yield* bus.publish(SessionEvent.Compaction.Ended, {
  1552. sessionID,
  1553. reason: "manual",
  1554. text: "summary",
  1555. recent: "",
  1556. })
  1557. systemBaseline = "Replacement context"
  1558. yield* runPrompt(session, "Second")
  1559. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  1560. [defaultSystem, "Initial context"],
  1561. [defaultSystem, "Initial context"],
  1562. ])
  1563. expect(messageRoles(requests[1])).toEqual(["user", "system", "user"])
  1564. expect(requests[1]?.messages.at(1)?.content).toEqual([{ type: "text", text: "Replacement context" }])
  1565. yield* replaySessionProjection(sessionID)
  1566. yield* runPrompt(session, "Third")
  1567. }),
  1568. )
  1569. it.effect("runs one durable compaction barrier after tool settlement and before later inputs", () =>
  1570. Effect.gen(function* () {
  1571. const session = yield* setup
  1572. currentModel = recoveryModel
  1573. const stream = yield* TestLLM.gate
  1574. yield* TestLLM.push(
  1575. TestLLM.tool("call-active", "echo", { text: "active" }),
  1576. [LLMEvent.textDelta({ id: "summary", text: "durable summary" })],
  1577. TestLLM.text("Steer complete", "text-steer"),
  1578. TestLLM.text("Queue complete", "text-queue"),
  1579. )
  1580. yield* admit(session, "Active work")
  1581. const active = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1582. yield* stream.started
  1583. const first = yield* session.compact({ sessionID })
  1584. const second = yield* session.compact({ sessionID })
  1585. expect(second.id).toBe(first.id)
  1586. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toMatchObject({
  1587. id: first.id,
  1588. })
  1589. expect((yield* session.messages({ sessionID })).find((message) => message.id === first.id)).toBeUndefined()
  1590. yield* admit(session, "Steer after compaction")
  1591. yield* session.synthetic({ sessionID, text: "Completion after compaction", resume: false })
  1592. yield* session.prompt({
  1593. sessionID,
  1594. text: "Queue after compaction",
  1595. delivery: "queue",
  1596. resume: false,
  1597. })
  1598. expect(yield* SessionPending.has((yield* Database.Service).db, sessionID, "steer")).toBe(false)
  1599. yield* stream.release
  1600. yield* Fiber.join(active)
  1601. expect(requests).toHaveLength(4)
  1602. expect(userTexts(requests[1])[0]).toContain("Create a new anchored summary")
  1603. expect(userTexts(requests[2])).toContain("Steer after compaction")
  1604. expect(userTexts(requests[2])).toContain("Completion after compaction")
  1605. expect(userTexts(requests[3])).toContain("Queue after compaction")
  1606. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1607. expect((yield* session.messages({ sessionID })).find((message) => message.id === first.id)).toMatchObject({
  1608. type: "compaction",
  1609. status: "completed",
  1610. summary: "durable summary",
  1611. })
  1612. }),
  1613. )
  1614. it.effect("releases queued prompts when durable compaction fails", () =>
  1615. Effect.gen(function* () {
  1616. const session = yield* setup
  1617. currentModel = recoveryModel
  1618. const stream = yield* TestLLM.gate
  1619. yield* TestLLM.push(
  1620. TestLLM.text("Active complete", "text-active-failure"),
  1621. [],
  1622. TestLLM.text("Continued", "text-after-failure"),
  1623. )
  1624. yield* admit(session, "Active work")
  1625. const active = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1626. yield* stream.started
  1627. const compaction = yield* session.compact({ sessionID })
  1628. yield* session.prompt({
  1629. sessionID,
  1630. text: "Continue after failure",
  1631. delivery: "queue",
  1632. resume: false,
  1633. })
  1634. yield* stream.release
  1635. yield* Fiber.join(active)
  1636. expect(requests).toHaveLength(3)
  1637. expect(userTexts(requests[2])).toContain("Continue after failure")
  1638. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1639. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1640. type: "compaction",
  1641. status: "failed",
  1642. })
  1643. expect(
  1644. (yield* recordedEventTypes(sessionID)).filter(
  1645. (type) => type === Bus.versionedType(SessionEvent.Compaction.Failed.type, 1),
  1646. ),
  1647. ).toHaveLength(1)
  1648. }),
  1649. )
  1650. it.effect("explains when manual compaction has no history", () =>
  1651. Effect.gen(function* () {
  1652. yield* setup
  1653. const session = yield* Session.Service
  1654. const compaction = yield* session.compact({ sessionID })
  1655. modelResolveHook = Effect.die("model resolution should not run")
  1656. yield* session.resume(sessionID)
  1657. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1658. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1659. type: "compaction",
  1660. status: "failed",
  1661. reason: "manual",
  1662. error: { type: "compaction.unavailable", message: "Nothing to compact yet" },
  1663. })
  1664. expect(
  1665. (yield* recordedEventTypes(sessionID)).filter(
  1666. (type) => type === Bus.versionedType(SessionEvent.Compaction.Failed.type, 1),
  1667. ),
  1668. ).toHaveLength(1)
  1669. }),
  1670. )
  1671. it.effect("manually compacts when the model has no context limit", () =>
  1672. Effect.gen(function* () {
  1673. const session = yield* setup
  1674. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-unknown-history"))
  1675. yield* runPrompt(session, "Earlier question")
  1676. requests.length = 0
  1677. yield* TestLLM.push(TestLLM.text("Manual summary", "text-manual-unknown-summary"))
  1678. const compaction = yield* session.compact({ sessionID })
  1679. yield* session.resume(sessionID)
  1680. expect(requests).toHaveLength(1)
  1681. expect(userTexts(requests[0])[0]).toContain("Earlier question")
  1682. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1683. type: "compaction",
  1684. status: "completed",
  1685. summary: "Manual summary",
  1686. })
  1687. }),
  1688. )
  1689. it.effect("preserves provider errors from manual compaction", () =>
  1690. Effect.gen(function* () {
  1691. const session = yield* setup
  1692. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-provider-history"))
  1693. yield* runPrompt(session, "Earlier question")
  1694. yield* TestLLM.push([LLMEvent.providerError({ message: "summary unavailable" })])
  1695. const compaction = yield* session.compact({ sessionID })
  1696. yield* session.resume(sessionID)
  1697. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1698. type: "compaction",
  1699. status: "failed",
  1700. error: { type: "provider.error", message: "summary unavailable" },
  1701. })
  1702. }),
  1703. )
  1704. it.effect("preserves typed provider failures from manual compaction", () =>
  1705. Effect.gen(function* () {
  1706. const session = yield* setup
  1707. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-failure-history"))
  1708. yield* runPrompt(session, "Earlier question")
  1709. yield* TestLLM.push(Stream.fail(providerUnavailable()))
  1710. const compaction = yield* session.compact({ sessionID })
  1711. yield* session.resume(sessionID)
  1712. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1713. type: "compaction",
  1714. status: "failed",
  1715. error: { type: "provider.transport", message: "Provider unavailable" },
  1716. })
  1717. }),
  1718. )
  1719. it.effect("records cancelled manual compaction without surfacing an internal failure", () =>
  1720. Effect.gen(function* () {
  1721. const session = yield* setup
  1722. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-interrupt-history"))
  1723. yield* runPrompt(session, "Earlier question")
  1724. const streamed = yield* Deferred.make<void>()
  1725. const partial = fragmentFixture("text", "text-manual-interrupt-summary", ["Partial summary"])
  1726. yield* TestLLM.push(
  1727. Stream.concat(
  1728. Stream.fromIterable(partial.partialEvents),
  1729. Stream.fromEffect(Deferred.succeed(streamed, undefined)).pipe(Stream.flatMap(() => Stream.never)),
  1730. ),
  1731. )
  1732. const compaction = yield* session.compact({ sessionID })
  1733. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1734. yield* Deferred.await(streamed)
  1735. yield* session.interrupt(sessionID)
  1736. yield* Fiber.await(run)
  1737. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1738. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1739. type: "compaction",
  1740. status: "failed",
  1741. reason: "manual",
  1742. error: { type: "aborted", message: "Compaction cancelled" },
  1743. })
  1744. }),
  1745. )
  1746. it.effect("settles an admitted manual compaction when pre-start resolution throws", () =>
  1747. Effect.gen(function* () {
  1748. const session = yield* setup
  1749. yield* TestLLM.push(TestLLM.text("Earlier answer", "text-manual-resolution-history"))
  1750. yield* runPrompt(session, "Earlier question")
  1751. const compaction = yield* session.compact({ sessionID })
  1752. modelResolveHook = Effect.die("model resolution failed")
  1753. expect(yield* Effect.exit(session.resume(sessionID))).toMatchObject({ _tag: "Failure" })
  1754. expect(yield* SessionPending.compaction((yield* Database.Service).db, sessionID)).toBeUndefined()
  1755. expect((yield* session.messages({ sessionID })).find((message) => message.id === compaction.id)).toMatchObject({
  1756. type: "compaction",
  1757. status: "failed",
  1758. reason: "manual",
  1759. })
  1760. expect(
  1761. (yield* recordedEventTypes(sessionID)).filter(
  1762. (type) => type === Bus.versionedType(SessionEvent.Compaction.Failed.type, 1),
  1763. ),
  1764. ).toHaveLength(1)
  1765. }),
  1766. )
  1767. it.effect("automatically compacts into a completed summary and retained recent turn", () =>
  1768. Effect.gen(function* () {
  1769. const session = yield* setup
  1770. yield* TestLLM.push(TestLLM.textWithUsage("Earlier answer", "text-first", 3_950))
  1771. yield* runPrompt(session, "Earlier question ".repeat(180))
  1772. currentModel = compactModel
  1773. requests.length = 0
  1774. yield* TestLLM.push(
  1775. TestLLM.text("## Objective\n- Preserve the task", "text-summary"),
  1776. TestLLM.textWithUsage("Continued", "text-final", 3_950),
  1777. )
  1778. yield* runPrompt(session, "Recent exact request ".repeat(180))
  1779. expect(requests).toHaveLength(2)
  1780. expect(userTexts(requests[0])[0]).toContain("## Objective")
  1781. expect(userTexts(requests[1])).toHaveLength(1)
  1782. expect(userTexts(requests[1])[0]).toContain("<summary>\n## Objective\n- Preserve the task\n</summary>")
  1783. expect(userTexts(requests[1])[0]).toContain(`[User]: ${"Recent exact request ".repeat(180)}`)
  1784. const context = yield* (yield* SessionStore.Service).context(sessionID)
  1785. expect(context.map((message) => message.type)).toEqual(["compaction", "assistant"])
  1786. expect(context[0]).toMatchObject({
  1787. type: "compaction",
  1788. summary: "## Objective\n- Preserve the task",
  1789. })
  1790. requests.length = 0
  1791. executions.length = 0
  1792. yield* TestLLM.push(
  1793. TestLLM.text("## Objective\n- Preserve the updated task", "text-summary-2"),
  1794. TestLLM.text("Continued again", "text-final-2"),
  1795. )
  1796. yield* runPrompt(session, "Newest exact request ".repeat(180))
  1797. expect(requests).toHaveLength(2)
  1798. expect(userTexts(requests[0])[0]).toContain(
  1799. "<previous-summary>\n## Objective\n- Preserve the task\n</previous-summary>",
  1800. )
  1801. expect(userTexts(requests[0])[0]).toContain("Recent exact request")
  1802. expect((yield* (yield* SessionStore.Service).context(sessionID))[0]).toMatchObject({
  1803. type: "compaction",
  1804. summary: "## Objective\n- Preserve the updated task",
  1805. })
  1806. }),
  1807. )
  1808. it.effect("does not compact immediately when the advertised output limit fills the context", () =>
  1809. Effect.gen(function* () {
  1810. const session = yield* setup
  1811. currentModel = fullOutputModel
  1812. yield* TestLLM.push(TestLLM.textWithUsage("Earlier answer", "text-full-output-first", 9_500))
  1813. yield* runPrompt(session, "Earlier question")
  1814. requests.length = 0
  1815. yield* TestLLM.push(TestLLM.text("Continued", "text-full-output-final"))
  1816. yield* runPrompt(session, "Continue")
  1817. expect(requests).toHaveLength(1)
  1818. expect(userTexts(requests[0])).toContain("Continue")
  1819. expect(yield* session.context(sessionID)).not.toContainEqual(expect.objectContaining({ type: "compaction" }))
  1820. }),
  1821. )
  1822. it.effect("stops after required automatic compaction fails", () =>
  1823. Effect.gen(function* () {
  1824. const session = yield* setup
  1825. yield* TestLLM.push(TestLLM.textWithUsage("Earlier answer", "text-before-failed-compaction", 3_950))
  1826. yield* runPrompt(session, "Earlier question ".repeat(180))
  1827. currentModel = compactModel
  1828. requests.length = 0
  1829. yield* TestLLM.push(
  1830. [LLMEvent.providerError({ message: "Unsupported parameter: max_output_tokens" })],
  1831. TestLLM.text("Must not run", "text-after-failed-compaction"),
  1832. )
  1833. yield* admit(session, "Recent exact request ".repeat(180))
  1834. expect(yield* Effect.exit(session.resume(sessionID))).toMatchObject({ _tag: "Failure" })
  1835. expect(requests).toHaveLength(1)
  1836. expect(requests[0]?.generation).toBeUndefined()
  1837. expect(yield* session.context(sessionID)).toContainEqual(
  1838. expect.objectContaining({
  1839. type: "compaction",
  1840. status: "failed",
  1841. reason: "auto",
  1842. error: expect.objectContaining({ message: "Unsupported parameter: max_output_tokens" }),
  1843. }),
  1844. )
  1845. }),
  1846. )
  1847. it.effect("forces one compaction and retries after provider context overflow", () =>
  1848. Effect.gen(function* () {
  1849. const session = yield* setupOverflowRecovery
  1850. yield* TestLLM.push(
  1851. [
  1852. LLMEvent.stepStart({ index: 0 }),
  1853. LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" }),
  1854. ],
  1855. TestLLM.text("## Objective\n- Recover overflow", "text-summary"),
  1856. TestLLM.text("Recovered", "text-final"),
  1857. )
  1858. yield* runPrompt(session, "Continue")
  1859. expect(requests).toHaveLength(3)
  1860. expect(userTexts(requests[1])[0]).toContain("## Objective")
  1861. expect(userTexts(requests[2])[0]).toContain("<summary>\n## Objective\n- Recover overflow\n</summary>")
  1862. expect(yield* session.context(sessionID)).toMatchObject([
  1863. { type: "compaction", summary: "## Objective\n- Recover overflow" },
  1864. { type: "assistant", finish: "stop" },
  1865. ])
  1866. yield* replaySessionProjection(sessionID)
  1867. expect(yield* session.context(sessionID)).toMatchObject([
  1868. { type: "compaction" },
  1869. { type: "assistant", finish: "stop" },
  1870. ])
  1871. }),
  1872. )
  1873. it.effect("recovers from provider context overflow without a configured context limit", () =>
  1874. Effect.gen(function* () {
  1875. const session = yield* setupOverflowRecovery
  1876. currentModel = model
  1877. yield* TestLLM.push(
  1878. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  1879. TestLLM.text("## Objective\n- Recover unknown limit", "text-summary-unknown-limit"),
  1880. TestLLM.text("Recovered", "text-final-unknown-limit"),
  1881. )
  1882. yield* runPrompt(session, "Continue")
  1883. expect(requests).toHaveLength(3)
  1884. expect(yield* session.context(sessionID)).toMatchObject([
  1885. { type: "compaction", summary: "## Objective\n- Recover unknown limit" },
  1886. { type: "assistant", finish: "stop" },
  1887. ])
  1888. }),
  1889. )
  1890. it.effect("recovers from provider context overflow despite an undersized configured context limit", () =>
  1891. Effect.gen(function* () {
  1892. const session = yield* setupOverflowRecovery
  1893. currentModel = undersizedContextModel
  1894. yield* TestLLM.push(
  1895. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  1896. TestLLM.text("## Objective\n- Recover undersized limit", "text-summary-undersized-limit"),
  1897. TestLLM.text("Recovered", "text-final-undersized-limit"),
  1898. )
  1899. yield* runPrompt(session, "Continue")
  1900. expect(requests).toHaveLength(3)
  1901. expect(yield* session.context(sessionID)).toMatchObject([
  1902. { type: "compaction", summary: "## Objective\n- Recover undersized limit" },
  1903. { type: "assistant", finish: "stop" },
  1904. ])
  1905. }),
  1906. )
  1907. it.effect("persists a second context overflow after one recovery", () =>
  1908. Effect.gen(function* () {
  1909. const session = yield* setupOverflowRecovery
  1910. const overflow = () => [
  1911. LLMEvent.stepStart({ index: 0 }),
  1912. LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" }),
  1913. ]
  1914. yield* TestLLM.push(overflow(), TestLLM.text("## Objective\n- Recover once", "text-summary"), overflow())
  1915. yield* admit(session, "Continue")
  1916. expect((yield* session.resume(sessionID).pipe(Effect.flip)).message).toBe("prompt too long")
  1917. expect(requests).toHaveLength(3)
  1918. expect(yield* session.context(sessionID)).toMatchObject([
  1919. { type: "compaction" },
  1920. { type: "assistant", finish: "error", error: { message: "prompt too long" } },
  1921. ])
  1922. }),
  1923. )
  1924. it.effect("recovers once from a raw context overflow failure", () =>
  1925. Effect.gen(function* () {
  1926. const session = yield* setupOverflowRecovery
  1927. yield* TestLLM.push(
  1928. Stream.fail(
  1929. new LLMError({
  1930. module: "test",
  1931. method: "stream",
  1932. reason: new InvalidRequestReason({
  1933. message: "prompt too long",
  1934. classification: "context-overflow",
  1935. }),
  1936. }),
  1937. ),
  1938. )
  1939. yield* TestLLM.push(
  1940. TestLLM.text("## Objective\n- Recover raw overflow", "text-summary"),
  1941. TestLLM.text("Recovered", "text-final"),
  1942. )
  1943. yield* runPrompt(session, "Continue")
  1944. expect(requests).toHaveLength(3)
  1945. expect(yield* session.context(sessionID)).toMatchObject([
  1946. { type: "compaction", summary: "## Objective\n- Recover raw overflow" },
  1947. { type: "assistant", finish: "stop" },
  1948. ])
  1949. }),
  1950. )
  1951. it.effect("publishes the original overflow when recovery summarization fails", () =>
  1952. Effect.gen(function* () {
  1953. const session = yield* setupOverflowRecovery
  1954. yield* TestLLM.push(
  1955. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  1956. [LLMEvent.providerError({ message: "summary unavailable" })],
  1957. )
  1958. yield* admit(session, "Continue")
  1959. expect((yield* session.resume(sessionID).pipe(Effect.flip)).message).toBe("prompt too long")
  1960. expect(requests).toHaveLength(2)
  1961. const context = yield* session.context(sessionID)
  1962. expect(context).toContainEqual(
  1963. expect.objectContaining({
  1964. type: "compaction",
  1965. status: "failed",
  1966. reason: "auto",
  1967. error: { type: "provider.error", message: "summary unavailable" },
  1968. }),
  1969. )
  1970. expect(context.slice(-3)).toMatchObject([
  1971. { type: "user", text: "Continue" },
  1972. { type: "compaction", status: "failed", reason: "auto" },
  1973. { type: "assistant", finish: "error", error: { message: "prompt too long" } },
  1974. ])
  1975. }),
  1976. )
  1977. it.effect("interrupts overflow recovery while the summary provider is running", () =>
  1978. Effect.gen(function* () {
  1979. const session = yield* setupOverflowRecovery
  1980. yield* TestLLM.push(
  1981. [LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" })],
  1982. TestLLM.text("## Objective\n- Interrupted", "text-summary"),
  1983. )
  1984. const first = yield* TestLLM.gate
  1985. yield* admit(session, "Continue")
  1986. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  1987. yield* first.started
  1988. const summary = yield* TestLLM.gate
  1989. yield* first.release
  1990. yield* summary.started
  1991. yield* session.interrupt(sessionID)
  1992. const exit = yield* Fiber.await(run)
  1993. expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBeTrue()
  1994. expect(yield* session.context(sessionID)).toContainEqual(
  1995. expect.objectContaining({
  1996. type: "compaction",
  1997. status: "failed",
  1998. reason: "auto",
  1999. error: { type: "compaction.interrupted", message: "Compaction was interrupted" },
  2000. }),
  2001. )
  2002. }),
  2003. )
  2004. it.effect("uses epoch values after compaction while a source is unavailable", () =>
  2005. Effect.gen(function* () {
  2006. const session = yield* setup
  2007. const bus = yield* Bus.Service
  2008. yield* runPrompt(session, "First")
  2009. systemBaseline = "Changed context"
  2010. yield* runPrompt(session, "Second")
  2011. yield* bus.publish(SessionEvent.Compaction.Started, {
  2012. sessionID,
  2013. reason: "manual",
  2014. recent: "",
  2015. })
  2016. yield* bus.publish(SessionEvent.Compaction.Ended, {
  2017. sessionID,
  2018. reason: "manual",
  2019. text: "summary",
  2020. recent: "",
  2021. })
  2022. systemUnavailable = true
  2023. yield* runPrompt(session, "Third")
  2024. // Compaction already moved current values into the new epoch before the unavailable read.
  2025. expect(requests.at(-1)?.system.map((part) => part.text)).toEqual([defaultSystem, "Changed context"])
  2026. expect(systemTexts(requests.at(-1)!)).not.toContain("Changed context")
  2027. }),
  2028. )
  2029. it.effect("projects reasoning and tool events without executing or continuing tools", () =>
  2030. Effect.gen(function* () {
  2031. const session = yield* setup
  2032. yield* admit(session, "Use tools")
  2033. yield* TestLLM.push(
  2034. TestLLM.complete(
  2035. {
  2036. reason: { normalized: "tool-calls" },
  2037. usage: {
  2038. inputTokens: 10,
  2039. nonCachedInputTokens: 8,
  2040. outputTokens: 4,
  2041. reasoningTokens: 1,
  2042. cacheReadInputTokens: 2,
  2043. },
  2044. },
  2045. LLMEvent.reasoningStart({ id: "reasoning-1" }),
  2046. LLMEvent.reasoningDelta({ id: "reasoning-1", text: "Think" }),
  2047. LLMEvent.reasoningEnd({ id: "reasoning-1" }),
  2048. LLMEvent.toolInputStart({ id: "call-error", name: "write" }),
  2049. LLMEvent.toolInputDelta({ id: "call-error", name: "write", text: '{"path":"README.md"}' }),
  2050. LLMEvent.toolInputEnd({ id: "call-error", name: "write" }),
  2051. LLMEvent.toolCall({ id: "call-error", name: "write", input: { path: "README.md" }, providerExecuted: true }),
  2052. LLMEvent.toolError({ id: "call-error", name: "write", message: "Denied" }),
  2053. LLMEvent.toolResult({ id: "call-error", name: "write", result: { type: "error", value: "Denied" } }),
  2054. LLMEvent.toolCall({
  2055. id: "call-provider",
  2056. name: "web_search",
  2057. input: { query: "hello" },
  2058. providerExecuted: true,
  2059. providerMetadata: { openai: { source: "provider" } },
  2060. }),
  2061. LLMEvent.toolResult({
  2062. id: "call-provider",
  2063. name: "web_search",
  2064. result: {
  2065. type: "content",
  2066. value: [
  2067. { type: "text", text: "Hello" },
  2068. { type: "file", uri: "data:image/png;base64,aGVsbG8=", mime: "image/png", name: "hello.png" },
  2069. ],
  2070. },
  2071. providerExecuted: true,
  2072. providerMetadata: { openai: { source: "provider" } },
  2073. }),
  2074. ),
  2075. )
  2076. yield* session.resume(sessionID)
  2077. expect(requests).toHaveLength(1)
  2078. expect(requests[0]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail"])
  2079. expect(yield* session.context(sessionID)).toMatchObject([
  2080. { type: "user", text: "Use tools" },
  2081. {
  2082. type: "assistant",
  2083. finish: "tool-calls",
  2084. cost: 0,
  2085. tokens: { input: 8, output: 3, reasoning: 1, cache: { read: 2, write: 0 } },
  2086. content: [
  2087. { type: "reasoning", text: "Think" },
  2088. {
  2089. type: "tool",
  2090. id: "call-error",
  2091. name: "write",
  2092. state: {
  2093. status: "error",
  2094. input: { path: "README.md" },
  2095. error: { type: "tool.execution", message: "Denied" },
  2096. },
  2097. },
  2098. {
  2099. type: "tool",
  2100. id: "call-provider",
  2101. name: "web_search",
  2102. executed: true,
  2103. providerState: { source: "provider" },
  2104. providerResultState: { source: "provider" },
  2105. state: {
  2106. status: "completed",
  2107. input: { query: "hello" },
  2108. content: [
  2109. { type: "text", text: "Hello" },
  2110. { type: "file", mime: "image/png", uri: "data:image/png;base64,aGVsbG8=", name: "hello.png" },
  2111. ],
  2112. },
  2113. },
  2114. ],
  2115. },
  2116. ])
  2117. }),
  2118. )
  2119. it.effect("continues with reloaded history after durably settling one local tool call", () =>
  2120. Effect.gen(function* () {
  2121. const session = yield* setup
  2122. yield* admit(session, "Echo this")
  2123. yield* TestLLM.push(TestLLM.tool("call-echo", "echo", { text: "hello" }), TestLLM.text("Done", "text-final"))
  2124. yield* session.resume(sessionID)
  2125. expect(requests).toHaveLength(2)
  2126. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "tool"])
  2127. expect(authorizations).toMatchObject([{ sessionID, callID: "call-echo" }])
  2128. expect(executions).toEqual(["hello"])
  2129. const context = yield* session.context(sessionID)
  2130. expect(context).toMatchObject([
  2131. { type: "user", text: "Echo this" },
  2132. {
  2133. type: "assistant",
  2134. finish: "tool-calls",
  2135. content: [
  2136. {
  2137. type: "tool",
  2138. id: "call-echo",
  2139. name: "echo",
  2140. state: {
  2141. status: "completed",
  2142. input: { text: "hello" },
  2143. content: [{ type: "text", text: "hello" }],
  2144. },
  2145. },
  2146. ],
  2147. },
  2148. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Done" }] },
  2149. ])
  2150. const assistant = requireAssistant(context)
  2151. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  2152. "session.step.started.1",
  2153. "session.tool.called.1",
  2154. "session.tool.success.2",
  2155. "session.step.ended.1",
  2156. ])
  2157. }),
  2158. )
  2159. it.effect("reloads a model switch before a tool-driven continuation step", () =>
  2160. Effect.gen(function* () {
  2161. const session = yield* setup
  2162. const bus = yield* Bus.Service
  2163. yield* admit(session, "Echo this")
  2164. yield* TestLLM.push(TestLLM.tool("call-echo", "echo", { text: "hello" }), TestLLM.stop())
  2165. const tools = yield* blockTools()
  2166. const run = yield* Effect.forkChild(session.resume(sessionID))
  2167. yield* tools.started
  2168. yield* bus.publish(SessionEvent.ModelSelected, {
  2169. sessionID,
  2170. model: { id: ID.make("replacement"), providerID: Provider.ID.make("fake") },
  2171. })
  2172. systemBaseline = "Replacement context"
  2173. yield* tools.release
  2174. yield* Fiber.join(run)
  2175. expect(requests.map((request) => request.model)).toEqual([model, replacementModel])
  2176. expect(requests.map((request) => request.system.map((part) => part.text))).toEqual([
  2177. [defaultSystem, "Initial context"],
  2178. [defaultSystem, "Initial context"],
  2179. ])
  2180. expect(systemTexts(requests[1])).toContain("Replacement context")
  2181. }),
  2182. )
  2183. it.effect("restores durable reasoning provider metadata in the next request", () =>
  2184. Effect.gen(function* () {
  2185. const session = yield* setup
  2186. yield* admit(session, "Think first")
  2187. yield* TestLLM.push(
  2188. TestLLM.stop(
  2189. LLMEvent.reasoningStart({ id: "reasoning-anthropic" }),
  2190. LLMEvent.reasoningDelta({ id: "reasoning-anthropic", text: "Signed thought" }),
  2191. LLMEvent.reasoningEnd({
  2192. id: "reasoning-anthropic",
  2193. providerMetadata: { openai: { signature: "sig_1" }, anthropic: { ignored: true } },
  2194. }),
  2195. LLMEvent.reasoningStart({
  2196. id: "reasoning-openai",
  2197. providerMetadata: {
  2198. openai: { itemId: "rs_1", reasoningEncryptedContent: null },
  2199. anthropic: { ignored: true },
  2200. },
  2201. }),
  2202. LLMEvent.reasoningDelta({ id: "reasoning-openai", text: "Encrypted thought" }),
  2203. LLMEvent.reasoningEnd({
  2204. id: "reasoning-openai",
  2205. providerMetadata: {
  2206. openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" },
  2207. anthropic: { ignored: true },
  2208. },
  2209. }),
  2210. ),
  2211. )
  2212. yield* session.resume(sessionID)
  2213. yield* replaySessionProjection(sessionID)
  2214. expect(yield* session.context(sessionID)).toMatchObject([
  2215. { type: "user", text: "Think first" },
  2216. {
  2217. type: "assistant",
  2218. content: [
  2219. {
  2220. type: "reasoning",
  2221. text: "Signed thought",
  2222. state: { signature: "sig_1" },
  2223. },
  2224. {
  2225. type: "reasoning",
  2226. text: "Encrypted thought",
  2227. state: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" },
  2228. },
  2229. ],
  2230. },
  2231. ])
  2232. yield* admit(session, "Continue")
  2233. yield* TestLLM.push([])
  2234. yield* session.resume(sessionID)
  2235. expect(requests[1]?.messages[1]?.content).toEqual([
  2236. {
  2237. type: "reasoning",
  2238. text: "Signed thought",
  2239. providerMetadata: { openai: { signature: "sig_1" } },
  2240. },
  2241. {
  2242. type: "reasoning",
  2243. text: "Encrypted thought",
  2244. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
  2245. },
  2246. ])
  2247. }),
  2248. )
  2249. it.effect("restores durable text provider metadata in the next request", () =>
  2250. Effect.gen(function* () {
  2251. const session = yield* setup
  2252. yield* admit(session, "Check first")
  2253. yield* TestLLM.push(
  2254. TestLLM.stop(
  2255. LLMEvent.textStart({ id: "commentary", providerMetadata: { openai: { phase: "commentary" } } }),
  2256. LLMEvent.textDelta({ id: "commentary", text: "Checking." }),
  2257. LLMEvent.textEnd({
  2258. id: "commentary",
  2259. providerMetadata: { openai: { phase: "commentary" }, anthropic: { ignored: true } },
  2260. }),
  2261. ),
  2262. )
  2263. yield* session.resume(sessionID)
  2264. yield* replaySessionProjection(sessionID)
  2265. expect(yield* session.context(sessionID)).toMatchObject([
  2266. { type: "user", text: "Check first" },
  2267. {
  2268. type: "assistant",
  2269. content: [{ type: "text", text: "Checking.", state: { phase: "commentary" } }],
  2270. },
  2271. ])
  2272. yield* admit(session, "Continue")
  2273. yield* TestLLM.push([])
  2274. yield* session.resume(sessionID)
  2275. expect(requests[1]?.messages[1]?.content).toEqual([
  2276. {
  2277. type: "text",
  2278. text: "Checking.",
  2279. providerMetadata: { openai: { phase: "commentary" } },
  2280. },
  2281. ])
  2282. }),
  2283. )
  2284. it.effect("replays durable provider-executed tool results inline in the next request", () =>
  2285. Effect.gen(function* () {
  2286. const session = yield* setup
  2287. yield* admit(session, "Search first")
  2288. yield* TestLLM.push(
  2289. TestLLM.stop(
  2290. LLMEvent.toolCall({
  2291. id: "hosted-search",
  2292. name: "web_search",
  2293. input: { query: "Effect" },
  2294. providerExecuted: true,
  2295. providerMetadata: { openai: { itemId: "hosted-search" }, fake: { ignored: true } },
  2296. }),
  2297. LLMEvent.toolResult({
  2298. id: "hosted-search",
  2299. name: "web_search",
  2300. result: { type: "json", value: [{ title: "Effect" }] },
  2301. providerExecuted: true,
  2302. providerMetadata: { openai: { blockType: "web_search_tool_result" }, anthropic: { ignored: true } },
  2303. }),
  2304. ),
  2305. )
  2306. yield* session.resume(sessionID)
  2307. yield* replaySessionProjection(sessionID)
  2308. yield* admit(session, "Continue")
  2309. yield* TestLLM.push([])
  2310. yield* session.resume(sessionID)
  2311. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "user"])
  2312. expect(requests[1]?.messages[1]?.content).toMatchObject([
  2313. {
  2314. type: "tool-call",
  2315. id: "hosted-search",
  2316. name: "web_search",
  2317. input: { query: "Effect" },
  2318. providerExecuted: true,
  2319. providerMetadata: { openai: { itemId: "hosted-search" } },
  2320. },
  2321. {
  2322. type: "tool-result",
  2323. id: "hosted-search",
  2324. name: "web_search",
  2325. // The generic replay result derives from canonical stored content.
  2326. result: { type: "text", value: '[{"title":"Effect"}]' },
  2327. providerExecuted: true,
  2328. providerMetadata: { openai: { blockType: "web_search_tool_result" } },
  2329. },
  2330. ])
  2331. }),
  2332. )
  2333. it.effect("starts recorded local tools eagerly and awaits settlement before continuing", () =>
  2334. Effect.gen(function* () {
  2335. const session = yield* setup
  2336. yield* admit(session, "Echo five times")
  2337. const tools = yield* blockTools(5)
  2338. const providerGate = yield* Deferred.make<void>()
  2339. const initial = Stream.fromIterable([
  2340. LLMEvent.stepStart({ index: 0 }),
  2341. ...Array.from({ length: 5 }, (_, index) =>
  2342. LLMEvent.toolCall({ id: `call-echo-${index}`, name: "echo", input: { text: `${index}` } }),
  2343. ),
  2344. ])
  2345. const final = Stream.fromIterable([
  2346. LLMEvent.stepFinish({ index: 0, reason: { normalized: "tool-calls" } }),
  2347. LLMEvent.finish({ reason: { normalized: "tool-calls" } }),
  2348. ])
  2349. yield* TestLLM.push(
  2350. Stream.concat(initial, Stream.fromEffect(Deferred.await(providerGate)).pipe(Stream.flatMap(() => final))),
  2351. )
  2352. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2353. yield* tools.started
  2354. expect(executions).toHaveLength(5)
  2355. expect(yield* tools.maxActive).toBe(5)
  2356. expect(yield* session.context(sessionID)).toMatchObject([
  2357. { type: "user", text: "Echo five times" },
  2358. {
  2359. type: "assistant",
  2360. content: Array.from({ length: 5 }, (_, index) => ({
  2361. type: "tool",
  2362. id: `call-echo-${index}`,
  2363. state: { status: "running", input: { text: `${index}` } },
  2364. })),
  2365. },
  2366. ])
  2367. yield* Deferred.succeed(providerGate, undefined)
  2368. yield* Effect.yieldNow
  2369. expect(requests).toHaveLength(1)
  2370. yield* tools.release
  2371. yield* Fiber.join(run)
  2372. expect(executions).toHaveLength(5)
  2373. expect(yield* tools.maxActive).toBe(5)
  2374. expect(requests).toHaveLength(2)
  2375. }),
  2376. )
  2377. it.effect("settles repeated provider-local tool call IDs against their owning assistant messages", () =>
  2378. Effect.gen(function* () {
  2379. const session = yield* setup
  2380. yield* admit(session, "Echo twice")
  2381. yield* TestLLM.push(
  2382. TestLLM.tool("tool_0", "echo", { text: "first" }),
  2383. TestLLM.tool("tool_0", "echo", { text: "second" }),
  2384. [],
  2385. )
  2386. yield* session.resume(sessionID)
  2387. const expected = [
  2388. { type: "user", text: "Echo twice" },
  2389. {
  2390. type: "assistant",
  2391. content: [
  2392. {
  2393. type: "tool",
  2394. id: "tool_0",
  2395. state: { status: "completed", content: [{ type: "text", text: "first" }] },
  2396. },
  2397. ],
  2398. },
  2399. {
  2400. type: "assistant",
  2401. content: [
  2402. {
  2403. type: "tool",
  2404. id: "tool_0",
  2405. state: { status: "completed", content: [{ type: "text", text: "second" }] },
  2406. },
  2407. ],
  2408. },
  2409. ]
  2410. expect(executions).toEqual(["first", "second"])
  2411. expect(requests).toHaveLength(3)
  2412. expect(yield* session.context(sessionID)).toMatchObject(expected)
  2413. yield* replaySessionProjection(sessionID)
  2414. expect(yield* session.context(sessionID)).toMatchObject(expected)
  2415. }),
  2416. )
  2417. it.effect("joins concurrent resume calls into one active provider run", () =>
  2418. Effect.gen(function* () {
  2419. const session = yield* setup
  2420. yield* admit(session, "Run once")
  2421. yield* TestLLM.push(TestLLM.text("Once", "text-once"))
  2422. const stream = yield* TestLLM.gate
  2423. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2424. yield* stream.started
  2425. const second = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2426. yield* Effect.yieldNow
  2427. expect(requests).toHaveLength(1)
  2428. yield* stream.release
  2429. yield* Fiber.join(first)
  2430. yield* Fiber.join(second)
  2431. expect(requests).toHaveLength(1)
  2432. expect(yield* session.context(sessionID)).toMatchObject([
  2433. { type: "user", text: "Run once" },
  2434. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Once" }] },
  2435. ])
  2436. }),
  2437. )
  2438. it.effect("steers an active step with newly recorded prompts", () =>
  2439. Effect.gen(function* () {
  2440. const session = yield* setup
  2441. yield* admit(session, "Start working")
  2442. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop())
  2443. const stream = yield* TestLLM.gate
  2444. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2445. yield* stream.started
  2446. yield* session.prompt({ sessionID, text: "Change direction" })
  2447. yield* stream.release
  2448. yield* Fiber.join(first)
  2449. yield* Effect.yieldNow
  2450. expect(requests).toHaveLength(2)
  2451. expect(userTexts(requests[0])).toEqual(["Start working"])
  2452. expect(userTexts(requests[1])).toEqual(["Start working", "Change direction"])
  2453. expect((yield* session.context(sessionID)).map((message) => message.type)).toEqual([
  2454. "user",
  2455. "assistant",
  2456. "user",
  2457. "assistant",
  2458. ])
  2459. }),
  2460. )
  2461. it.effect("promotes queued input after continuation ends", () =>
  2462. Effect.gen(function* () {
  2463. const session = yield* setup
  2464. yield* admit(session, "Start working")
  2465. yield* TestLLM.push(TestLLM.tool("call-echo", "echo", { text: "hello" }), TestLLM.stop(), TestLLM.stop())
  2466. const stream = yield* TestLLM.gate
  2467. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2468. yield* stream.started
  2469. yield* session.prompt({
  2470. sessionID,
  2471. text: "Wait until continuation ends",
  2472. delivery: "queue",
  2473. })
  2474. yield* stream.release
  2475. yield* Fiber.join(first)
  2476. expect(requests).toHaveLength(3)
  2477. expect(userTexts(requests[0])).toEqual(["Start working"])
  2478. expect(userTexts(requests[1])).toEqual(["Start working"])
  2479. expect(userTexts(requests[2])).toEqual(["Start working", "Wait until continuation ends"])
  2480. }),
  2481. )
  2482. it.effect("preserves durable queued input for a later wake after interruption", () =>
  2483. Effect.gen(function* () {
  2484. const session = yield* setup
  2485. const { db } = yield* Database.Service
  2486. yield* admit(session, "Interrupt current work")
  2487. yield* TestLLM.push([], TestLLM.stop())
  2488. const stream = yield* TestLLM.gate
  2489. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2490. yield* stream.started
  2491. yield* session.prompt({
  2492. sessionID,
  2493. text: "Run after interrupt",
  2494. delivery: "queue",
  2495. })
  2496. yield* session.interrupt(sessionID)
  2497. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  2498. expect(requests).toHaveLength(1)
  2499. expect(yield* SessionPending.has(db, sessionID, "queue")).toBe(true)
  2500. const resumed = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2501. yield* stream.started
  2502. yield* stream.release
  2503. yield* Fiber.join(resumed)
  2504. expect(requests).toHaveLength(2)
  2505. expect(userTexts(requests[0])).toEqual(["Interrupt current work"])
  2506. expect(userTexts(requests[1])).toEqual(["Interrupt current work", "Run after interrupt"])
  2507. }),
  2508. )
  2509. it.effect("preserves durable steering input for a later resume after interruption", () =>
  2510. Effect.gen(function* () {
  2511. const session = yield* setup
  2512. const { db } = yield* Database.Service
  2513. yield* admit(session, "Interrupt current work")
  2514. yield* TestLLM.push([], TestLLM.stop())
  2515. const stream = yield* TestLLM.gate
  2516. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2517. yield* stream.started
  2518. yield* session.prompt({
  2519. sessionID,
  2520. text: "Steer after interrupt",
  2521. })
  2522. yield* session.interrupt(sessionID)
  2523. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  2524. expect(requests).toHaveLength(1)
  2525. expect(yield* SessionPending.has(db, sessionID, "steer")).toBe(true)
  2526. const resumed = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2527. yield* stream.started
  2528. yield* stream.release
  2529. yield* Fiber.join(resumed)
  2530. expect(requests).toHaveLength(2)
  2531. expect(userTexts(requests[0])).toEqual(["Interrupt current work"])
  2532. expect(userTexts(requests[1])).toEqual(["Interrupt current work", "Steer after interrupt"])
  2533. }),
  2534. )
  2535. it.effect("promotes queued inputs one at a time in FIFO order", () =>
  2536. Effect.gen(function* () {
  2537. const session = yield* setup
  2538. yield* admit(session, "Start working")
  2539. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop(), TestLLM.stop())
  2540. const stream = yield* TestLLM.gate
  2541. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2542. yield* stream.started
  2543. yield* session.prompt({ sessionID, text: "Queue first", delivery: "queue" })
  2544. yield* session.prompt({ sessionID, text: "Queue second", delivery: "queue" })
  2545. yield* stream.release
  2546. yield* Fiber.join(first)
  2547. expect(requests).toHaveLength(3)
  2548. expect(userTexts(requests[0])).toEqual(["Start working"])
  2549. expect(userTexts(requests[1])).toEqual(["Start working", "Queue first"])
  2550. expect(userTexts(requests[2])).toEqual(["Start working", "Queue first", "Queue second"])
  2551. }),
  2552. )
  2553. it.effect("promotes queued input after steering continuation ends", () =>
  2554. Effect.gen(function* () {
  2555. const session = yield* setup
  2556. yield* admit(session, "Start steering")
  2557. yield* session.prompt({
  2558. sessionID,
  2559. text: "Queue for later",
  2560. delivery: "queue",
  2561. resume: false,
  2562. })
  2563. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop())
  2564. yield* session.resume(sessionID)
  2565. expect(requests).toHaveLength(2)
  2566. expect(userTexts(requests[0])).toEqual(["Start steering"])
  2567. expect(userTexts(requests[1])).toEqual(["Start steering", "Queue for later"])
  2568. }),
  2569. )
  2570. it.effect("promotes steers before the next queued input", () =>
  2571. Effect.gen(function* () {
  2572. const session = yield* setup
  2573. yield* admit(session, "Start working")
  2574. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop(), TestLLM.stop(), TestLLM.stop())
  2575. const firstStream = yield* TestLLM.gate
  2576. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2577. yield* firstStream.started
  2578. yield* session.prompt({ sessionID, text: "Queue first", delivery: "queue" })
  2579. yield* session.prompt({ sessionID, text: "Queue second", delivery: "queue" })
  2580. const secondStream = yield* TestLLM.gate
  2581. yield* firstStream.release
  2582. yield* secondStream.started
  2583. yield* session.prompt({ sessionID, text: "Steer before next queued input" })
  2584. yield* session.prompt({
  2585. sessionID,
  2586. text: "Also steer before next queued input",
  2587. })
  2588. yield* session.synthetic({ sessionID, text: "Background completion before next queued input" })
  2589. yield* secondStream.release
  2590. yield* Fiber.join(first)
  2591. expect(requests).toHaveLength(4)
  2592. expect(userTexts(requests[0])).toEqual(["Start working"])
  2593. expect(userTexts(requests[1])).toEqual(["Start working", "Queue first"])
  2594. expect(userTexts(requests[2])).toEqual([
  2595. "Start working",
  2596. "Queue first",
  2597. "Steer before next queued input",
  2598. "Also steer before next queued input",
  2599. "Background completion before next queued input",
  2600. ])
  2601. expect(userTexts(requests[3])).toEqual([
  2602. "Start working",
  2603. "Queue first",
  2604. "Steer before next queued input",
  2605. "Also steer before next queued input",
  2606. "Background completion before next queued input",
  2607. "Queue second",
  2608. ])
  2609. }),
  2610. )
  2611. it.effect("coalesces multiple active steering prompts into one continuation step", () =>
  2612. Effect.gen(function* () {
  2613. const session = yield* setup
  2614. yield* admit(session, "Start working")
  2615. yield* TestLLM.push(TestLLM.stop(), TestLLM.stop())
  2616. const stream = yield* TestLLM.gate
  2617. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2618. yield* stream.started
  2619. yield* session.prompt({ sessionID, text: "First steer" })
  2620. yield* session.prompt({ sessionID, text: "Second steer" })
  2621. yield* stream.release
  2622. yield* Fiber.join(first)
  2623. yield* Effect.yieldNow
  2624. expect(requests).toHaveLength(2)
  2625. expect(userTexts(requests[1])).toEqual(["Start working", "First steer", "Second steer"])
  2626. yield* (yield* SessionExecution.Service).wake(sessionID)
  2627. yield* Effect.yieldNow
  2628. expect(requests).toHaveLength(2)
  2629. }),
  2630. )
  2631. it.effect("runs steering input accepted while the active step fails", () =>
  2632. Effect.gen(function* () {
  2633. const session = yield* setup
  2634. yield* admit(session, "Start working")
  2635. const failure = invalidRequest()
  2636. yield* TestLLM.push(Stream.fail(failure))
  2637. const stream = yield* TestLLM.gate
  2638. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2639. yield* stream.started
  2640. yield* session.prompt({ sessionID, text: "Recover with this" })
  2641. yield* stream.release
  2642. expect(yield* Fiber.join(first).pipe(Effect.flip)).toBe(failure)
  2643. yield* TestLLM.push([])
  2644. yield* session.wait(sessionID)
  2645. expect(requests).toHaveLength(2)
  2646. expect(userTexts(requests[1])).toEqual(["Start working", "Recover with this"])
  2647. }),
  2648. )
  2649. it.effect("durably fails local tools left running by a prior process before continuing", () =>
  2650. Effect.gen(function* () {
  2651. const session = yield* setup
  2652. const bus = yield* Bus.Service
  2653. yield* admit(session, "Recover interrupted tool")
  2654. yield* SessionPending.promote((yield* Database.Service).db, bus, sessionID, "steer")
  2655. const assistantMessageID = SessionMessage.ID.create()
  2656. yield* bus.publish(SessionEvent.Step.Started, {
  2657. sessionID,
  2658. assistantMessageID,
  2659. agent: Agent.ID.make("build"),
  2660. model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") },
  2661. })
  2662. yield* bus.publish(SessionEvent.Tool.Input.Started, {
  2663. sessionID,
  2664. assistantMessageID,
  2665. callID: "call-interrupted",
  2666. name: "echo",
  2667. })
  2668. yield* bus.publish(SessionEvent.Tool.Input.Ended, {
  2669. sessionID,
  2670. assistantMessageID,
  2671. callID: "call-interrupted",
  2672. text: '{"text":"stale"}',
  2673. })
  2674. yield* bus.publish(SessionEvent.Tool.Called, {
  2675. sessionID,
  2676. assistantMessageID,
  2677. callID: "call-interrupted",
  2678. input: { text: "stale" },
  2679. executed: false,
  2680. })
  2681. requests.length = 0
  2682. yield* TestLLM.push([])
  2683. yield* session.resume(sessionID)
  2684. expect(requests).toHaveLength(1)
  2685. expect(messageRoles(requests[0])).toEqual(["user", "assistant", "tool"])
  2686. expect(yield* session.context(sessionID)).toMatchObject([
  2687. { type: "user", text: "Recover interrupted tool" },
  2688. {
  2689. type: "assistant",
  2690. content: [
  2691. {
  2692. type: "tool",
  2693. id: "call-interrupted",
  2694. state: {
  2695. status: "error",
  2696. error: { type: "aborted", message: "Tool execution interrupted: echo" },
  2697. },
  2698. },
  2699. ],
  2700. },
  2701. ])
  2702. }),
  2703. )
  2704. it.effect("durably fails hosted tools left running by a prior process before continuing inline", () =>
  2705. Effect.gen(function* () {
  2706. const session = yield* setup
  2707. const bus = yield* Bus.Service
  2708. yield* admit(session, "Recover interrupted hosted tool")
  2709. yield* SessionPending.promote((yield* Database.Service).db, bus, sessionID, "steer")
  2710. const assistantMessageID = SessionMessage.ID.create()
  2711. yield* bus.publish(SessionEvent.Step.Started, {
  2712. sessionID,
  2713. assistantMessageID,
  2714. agent: Agent.ID.make("build"),
  2715. model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") },
  2716. })
  2717. yield* bus.publish(SessionEvent.Tool.Input.Started, {
  2718. sessionID,
  2719. assistantMessageID,
  2720. callID: "call-hosted-interrupted",
  2721. name: "web_search",
  2722. })
  2723. yield* bus.publish(SessionEvent.Tool.Input.Ended, {
  2724. sessionID,
  2725. assistantMessageID,
  2726. callID: "call-hosted-interrupted",
  2727. text: '{"query":"stale"}',
  2728. })
  2729. yield* bus.publish(SessionEvent.Tool.Called, {
  2730. sessionID,
  2731. assistantMessageID,
  2732. callID: "call-hosted-interrupted",
  2733. input: { query: "stale" },
  2734. executed: true,
  2735. state: { itemId: "call-hosted-interrupted" },
  2736. })
  2737. requests.length = 0
  2738. yield* TestLLM.push([])
  2739. yield* session.resume(sessionID)
  2740. expect(requests).toHaveLength(1)
  2741. expect(messageRoles(requests[0])).toEqual(["user", "assistant"])
  2742. expect(requests[0]?.messages[1]?.content).toMatchObject([
  2743. {
  2744. type: "tool-call",
  2745. id: "call-hosted-interrupted",
  2746. providerExecuted: true,
  2747. providerMetadata: { openai: { itemId: "call-hosted-interrupted" } },
  2748. },
  2749. { type: "tool-result", id: "call-hosted-interrupted", providerExecuted: true, result: { type: "error" } },
  2750. ])
  2751. }),
  2752. )
  2753. it.effect("durably fails pending tool input left by a prior process before continuing", () =>
  2754. Effect.gen(function* () {
  2755. const session = yield* setup
  2756. const bus = yield* Bus.Service
  2757. yield* admit(session, "Recover interrupted tool input")
  2758. yield* SessionPending.promote((yield* Database.Service).db, bus, sessionID, "steer")
  2759. const assistantMessageID = SessionMessage.ID.create()
  2760. yield* bus.publish(SessionEvent.Step.Started, {
  2761. sessionID,
  2762. assistantMessageID,
  2763. agent: Agent.ID.make("build"),
  2764. model: { id: ID.make("fake-model"), providerID: Provider.ID.make("fake") },
  2765. })
  2766. yield* bus.publish(SessionEvent.Tool.Input.Started, {
  2767. sessionID,
  2768. assistantMessageID,
  2769. callID: "call-pending-interrupted",
  2770. name: "echo",
  2771. })
  2772. requests.length = 0
  2773. yield* TestLLM.push([])
  2774. yield* session.resume(sessionID)
  2775. expect(requests).toHaveLength(1)
  2776. expect(messageRoles(requests[0])).toEqual(["user", "assistant", "tool"])
  2777. expect(yield* session.context(sessionID)).toMatchObject([
  2778. { type: "user", text: "Recover interrupted tool input" },
  2779. { type: "assistant", content: [{ type: "tool", id: "call-pending-interrupted", state: { status: "error" } }] },
  2780. ])
  2781. }),
  2782. )
  2783. it.effect("promotes the first queued input when woken while idle", () =>
  2784. Effect.gen(function* () {
  2785. const session = yield* setup
  2786. yield* session.prompt({
  2787. sessionID,
  2788. text: "Wait in queue",
  2789. delivery: "queue",
  2790. resume: false,
  2791. })
  2792. const stream = yield* TestLLM.gate
  2793. yield* (yield* SessionExecution.Service).wake(sessionID)
  2794. yield* stream.started
  2795. yield* stream.release
  2796. expect(requests).toHaveLength(1)
  2797. expect(userTexts(requests[0])).toEqual(["Wait in queue"])
  2798. }),
  2799. )
  2800. it.effect("retries inbox input after prompt projection rolls back", () =>
  2801. Effect.gen(function* () {
  2802. const session = yield* setup
  2803. const bus = yield* Bus.Service
  2804. const defect = new Error("fail after prompt promotion")
  2805. let fail = true
  2806. yield* bus.project(SessionEvent.InputPromoted, () => (fail ? Effect.die(defect) : Effect.void))
  2807. yield* admit(session, "Recover promoted input")
  2808. expect(yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))).toBe(defect)
  2809. fail = false
  2810. requests.length = 0
  2811. yield* TestLLM.push(TestLLM.stop())
  2812. const stream = yield* TestLLM.gate
  2813. yield* (yield* SessionExecution.Service).wake(sessionID)
  2814. yield* stream.started
  2815. yield* stream.release
  2816. expect(userTexts(requests[0])).toEqual(["Recover promoted input"])
  2817. }),
  2818. )
  2819. it.effect("does not strand a committed promotion when a post-commit listener defects", () =>
  2820. Effect.gen(function* () {
  2821. const session = yield* setup
  2822. const bus = yield* Bus.Service
  2823. yield* bus.listen((event) =>
  2824. event.type === SessionEvent.InputPromoted.type
  2825. ? Effect.die("fail after prompt promotion commits")
  2826. : Effect.void,
  2827. )
  2828. yield* runPrompt(session, "Run committed promotion")
  2829. expect(requests).toHaveLength(1)
  2830. expect(userTexts(requests[0])).toEqual(["Run committed promotion"])
  2831. }),
  2832. )
  2833. it.effect("adds session correlation headers to model requests", () =>
  2834. Effect.gen(function* () {
  2835. const session = yield* setup
  2836. yield* runPrompt(session, "Run correlated request")
  2837. expect(requests[0]?.http?.headers).toEqual({
  2838. "x-session-affinity": sessionID,
  2839. "X-Session-Id": sessionID,
  2840. "User-Agent": App.useragent(App.make()),
  2841. "x-opencode-project": Project.ID.global,
  2842. "x-opencode-session": sessionID,
  2843. "x-opencode-client": "opencode",
  2844. })
  2845. }),
  2846. )
  2847. it.effect("adds the parent session header to child model requests", () =>
  2848. Effect.gen(function* () {
  2849. const session = yield* setup
  2850. const parentID = Session.ID.make("ses_runner_parent")
  2851. const { db } = yield* Database.Service
  2852. yield* db
  2853. .update(SessionTable)
  2854. .set({ parent_id: parentID })
  2855. .where(eq(SessionTable.id, sessionID))
  2856. .run()
  2857. .pipe(Effect.orDie)
  2858. yield* runPrompt(session, "Run child request")
  2859. expect(requests[0]?.http?.headers?.["x-parent-session-id"]).toBe(parentID)
  2860. }),
  2861. )
  2862. it.effect("runs different sessions concurrently", () =>
  2863. Effect.gen(function* () {
  2864. const session = yield* setup
  2865. yield* insertSession(otherSessionID)
  2866. yield* admit(session, "Run first")
  2867. yield* session.prompt({
  2868. sessionID: otherSessionID,
  2869. text: "Run second",
  2870. resume: false,
  2871. })
  2872. const stream = yield* TestLLM.gate
  2873. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2874. yield* stream.started
  2875. const second = yield* session.resume(otherSessionID).pipe(Effect.forkChild)
  2876. yield* stream.started
  2877. expect(requests).toHaveLength(2)
  2878. expect(requests.map((request) => request.providerOptions?.openai?.promptCacheKey)).toEqual([
  2879. sessionID,
  2880. otherSessionID,
  2881. ])
  2882. yield* stream.release
  2883. yield* Fiber.join(first)
  2884. yield* Fiber.join(second)
  2885. }),
  2886. )
  2887. it.effect("bounds 64-character session prompt cache keys", () =>
  2888. Effect.gen(function* () {
  2889. const session = yield* setup
  2890. const longSessionID = Session.ID.make(`ses_${"a".repeat(64)}`)
  2891. const otherLongSessionID = Session.ID.make(`ses_${"b".repeat(64)}`)
  2892. yield* insertSession(longSessionID)
  2893. yield* insertSession(otherLongSessionID)
  2894. yield* session.prompt({
  2895. sessionID: longSessionID,
  2896. text: "Run long session",
  2897. resume: false,
  2898. })
  2899. yield* session.prompt({
  2900. sessionID: otherLongSessionID,
  2901. text: "Run other long session",
  2902. resume: false,
  2903. })
  2904. yield* session.resume(longSessionID)
  2905. yield* session.resume(otherLongSessionID)
  2906. const keys = requests.map((request) => request.providerOptions?.openai?.promptCacheKey)
  2907. expect(keys).toEqual([longSessionID.slice(4), otherLongSessionID.slice(4)])
  2908. expect(keys.every((key) => typeof key === "string" && key.length === 64)).toBe(true)
  2909. expect(keys[0]).not.toBe(keys[1])
  2910. }),
  2911. )
  2912. it.effect("fans out one failed run and allows a later retry", () =>
  2913. Effect.gen(function* () {
  2914. const session = yield* setup
  2915. yield* admit(session, "Retry after failure")
  2916. yield* TestLLM.push(Stream.fail(invalidRequest()))
  2917. const stream = yield* TestLLM.gate
  2918. const first = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2919. yield* stream.started
  2920. const second = yield* session.resume(sessionID).pipe(Effect.forkChild)
  2921. yield* Effect.yieldNow
  2922. expect(requests).toHaveLength(1)
  2923. yield* stream.release
  2924. const [firstExit, secondExit] = yield* Effect.all([Fiber.await(first), Fiber.await(second)])
  2925. expect(secondExit).toEqual(firstExit)
  2926. yield* TestLLM.push([])
  2927. yield* session.resume(sessionID)
  2928. expect(requests).toHaveLength(2)
  2929. }),
  2930. )
  2931. it.effect("durably settles local tool failures before continuing", () =>
  2932. Effect.gen(function* () {
  2933. const session = yield* setup
  2934. yield* admit(session, "Call missing")
  2935. yield* TestLLM.push(TestLLM.tool("call-missing", "missing", {}), TestLLM.text("Recovered", "text-after-error"))
  2936. yield* session.resume(sessionID)
  2937. expect(requests).toHaveLength(2)
  2938. expect(yield* session.context(sessionID)).toMatchObject([
  2939. { type: "user", text: "Call missing" },
  2940. {
  2941. type: "assistant",
  2942. content: [
  2943. {
  2944. type: "tool",
  2945. id: "call-missing",
  2946. state: {
  2947. status: "error",
  2948. error: { type: "tool.execution", message: "Unknown tool: missing" },
  2949. },
  2950. },
  2951. ],
  2952. },
  2953. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  2954. ])
  2955. }),
  2956. )
  2957. it.effect("returns unexpected local tool defects to the model and continues", () =>
  2958. Effect.gen(function* () {
  2959. const session = yield* setup
  2960. yield* admit(session, "Call defect")
  2961. yield* TestLLM.push(TestLLM.tool("call-defect", "defect", {}), TestLLM.text("Recovered", "text-after-defect"))
  2962. yield* session.resume(sessionID)
  2963. expect(requests).toHaveLength(2)
  2964. expect(messageRoles(requests[1])).toEqual(["user", "assistant", "tool"])
  2965. const context = yield* session.context(sessionID)
  2966. expect(context).toMatchObject([
  2967. { type: "user", text: "Call defect" },
  2968. {
  2969. type: "assistant",
  2970. content: [
  2971. {
  2972. type: "tool",
  2973. id: "call-defect",
  2974. state: {
  2975. status: "error",
  2976. error: { type: "unknown", message: "unexpected tool defect" },
  2977. },
  2978. },
  2979. ],
  2980. },
  2981. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  2982. ])
  2983. const assistant = requireAssistant(context)
  2984. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  2985. "session.step.started.1",
  2986. "session.tool.called.1",
  2987. "session.tool.failed.2",
  2988. "session.step.ended.1",
  2989. ])
  2990. }),
  2991. )
  2992. it.effect("returns tool-wrapped policy blocks to the model and continues", () =>
  2993. Effect.gen(function* () {
  2994. const session = yield* setup
  2995. const registry = yield* Tool.Service
  2996. yield* transformTools(
  2997. registry,
  2998. {
  2999. blocked: {
  3000. name: "blocked",
  3001. description: "Fail because policy blocked execution",
  3002. input: Schema.Struct({}),
  3003. output: Schema.Struct({}),
  3004. execute: () =>
  3005. Effect.fail(new Permission.BlockedError({ rules: [], permission: "blocked", resources: ["*"] })).pipe(
  3006. Effect.mapError(() => new Tool.Error({ message: "Permission blocked" })),
  3007. ),
  3008. },
  3009. },
  3010. { codemode: false },
  3011. )
  3012. yield* admit(session, "Call blocked")
  3013. yield* TestLLM.push(TestLLM.tool("call-blocked", "blocked", {}), TestLLM.stop())
  3014. yield* session.resume(sessionID)
  3015. expect(requests).toHaveLength(2)
  3016. expect(yield* session.context(sessionID)).toMatchObject([
  3017. { type: "user", text: "Call blocked" },
  3018. {
  3019. type: "assistant",
  3020. content: [
  3021. { type: "tool", id: "call-blocked", state: { status: "error", error: { message: "Permission blocked" } } },
  3022. ],
  3023. },
  3024. { type: "assistant", finish: "stop" },
  3025. ])
  3026. }),
  3027. )
  3028. it.effect("interrupts runner continuation when permission approval is declined", () =>
  3029. Effect.gen(function* () {
  3030. const session = yield* setup
  3031. const registry = yield* Tool.Service
  3032. yield* transformTools(
  3033. registry,
  3034. {
  3035. declined: {
  3036. name: "declined",
  3037. description: "Fail because the user declined approval",
  3038. input: Schema.Struct({}),
  3039. output: Schema.Struct({}),
  3040. execute: () => Effect.die(new Permission.DeclinedError()),
  3041. },
  3042. },
  3043. { codemode: false },
  3044. )
  3045. yield* admit(session, "Call declined")
  3046. yield* TestLLM.push(TestLLM.tool("call-declined", "declined", {}))
  3047. const exit = yield* session.resume(sessionID).pipe(Effect.exit)
  3048. expect(exit._tag).toBe("Failure")
  3049. if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
  3050. expect(requests).toHaveLength(1)
  3051. expect(yield* session.context(sessionID)).toMatchObject([
  3052. { type: "user", text: "Call declined" },
  3053. {
  3054. type: "assistant",
  3055. content: [
  3056. {
  3057. type: "tool",
  3058. id: "call-declined",
  3059. state: { status: "error", error: { type: "aborted", message: "The user declined this tool call" } },
  3060. },
  3061. ],
  3062. },
  3063. ])
  3064. }),
  3065. )
  3066. it.effect("returns permission corrections to the model and continues", () =>
  3067. Effect.gen(function* () {
  3068. const session = yield* setup
  3069. const registry = yield* Tool.Service
  3070. yield* transformTools(
  3071. registry,
  3072. {
  3073. corrected: {
  3074. name: "corrected",
  3075. description: "Fail with user correction feedback",
  3076. input: Schema.Struct({}),
  3077. output: Schema.Struct({}),
  3078. execute: () =>
  3079. Effect.fail(new Permission.CorrectedError({ feedback: "Use another tool" })).pipe(
  3080. Effect.mapError(() => new Tool.Error({ message: "Use another tool" })),
  3081. ),
  3082. },
  3083. },
  3084. { codemode: false },
  3085. )
  3086. yield* admit(session, "Call corrected")
  3087. yield* TestLLM.push(TestLLM.tool("call-corrected", "corrected", {}), TestLLM.stop())
  3088. yield* session.resume(sessionID)
  3089. expect(requests).toHaveLength(2)
  3090. expect(yield* session.context(sessionID)).toMatchObject([
  3091. { type: "user", text: "Call corrected" },
  3092. {
  3093. type: "assistant",
  3094. content: [
  3095. { type: "tool", id: "call-corrected", state: { status: "error", error: { message: "Use another tool" } } },
  3096. ],
  3097. },
  3098. { type: "assistant", finish: "stop" },
  3099. ])
  3100. }),
  3101. )
  3102. it.effect("returns configured permission denials to the model and continues", () =>
  3103. Effect.gen(function* () {
  3104. const session = yield* setup
  3105. const registry = yield* Tool.Service
  3106. yield* transformTools(registry, { permissionfail: permissionFail }, { codemode: false })
  3107. yield* admit(session, "Reject permission")
  3108. yield* TestLLM.push(TestLLM.tool("call-permission", "permissionfail", {}), [
  3109. LLMEvent.stepStart({ index: 0 }),
  3110. LLMEvent.stepFinish({ index: 0, reason: { normalized: "stop" } }),
  3111. ])
  3112. yield* session.resume(sessionID)
  3113. expect(requests).toHaveLength(2)
  3114. expect(yield* session.context(sessionID)).toMatchObject([
  3115. { type: "user" },
  3116. {
  3117. type: "assistant",
  3118. content: [
  3119. {
  3120. type: "tool",
  3121. id: "call-permission",
  3122. state: {
  3123. status: "error",
  3124. error: {
  3125. type: "permission.rejected",
  3126. message: "Permission denied: edit",
  3127. },
  3128. },
  3129. },
  3130. ],
  3131. },
  3132. { type: "assistant", finish: "stop" },
  3133. ])
  3134. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.step.failed.1")
  3135. }),
  3136. )
  3137. it.effect("interrupts runner continuation when a question is cancelled", () =>
  3138. Effect.gen(function* () {
  3139. const session = yield* setup
  3140. const registry = yield* Tool.Service
  3141. yield* transformTools(
  3142. registry,
  3143. {
  3144. question: {
  3145. name: "question",
  3146. description: "Ask the user",
  3147. input: Schema.Struct({}),
  3148. output: Schema.Struct({}),
  3149. execute: () => Effect.die(new QuestionTool.CancelledError()),
  3150. },
  3151. },
  3152. { codemode: false },
  3153. )
  3154. yield* admit(session, "Ask then stop")
  3155. yield* TestLLM.push(TestLLM.tool("call-question", "question", {}), [])
  3156. const run = yield* session.resume(sessionID).pipe(Effect.exit, Effect.forkChild)
  3157. const exit = yield* Fiber.join(run)
  3158. expect(exit._tag).toBe("Failure")
  3159. if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
  3160. expect(requests).toHaveLength(1)
  3161. expect(yield* session.context(sessionID)).toMatchObject([
  3162. { type: "user", text: "Ask then stop" },
  3163. {
  3164. type: "assistant",
  3165. content: [
  3166. {
  3167. type: "tool",
  3168. id: "call-question",
  3169. state: { status: "error", error: { type: "aborted", message: "The user dismissed this question" } },
  3170. },
  3171. ],
  3172. },
  3173. ])
  3174. }),
  3175. )
  3176. it.effect("awaits started local tools before surfacing provider stream failure", () =>
  3177. Effect.gen(function* () {
  3178. const session = yield* setup
  3179. yield* admit(session, "Settle before failing")
  3180. const failure = providerUnavailable()
  3181. const tools = yield* blockTools()
  3182. yield* TestLLM.push(
  3183. TestLLM.failAfter(
  3184. failure,
  3185. LLMEvent.stepStart({ index: 0 }),
  3186. LLMEvent.toolCall({ id: "call-before-failure", name: "echo", input: { text: "settle" } }),
  3187. ),
  3188. )
  3189. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3190. yield* tools.started
  3191. yield* tools.release
  3192. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  3193. const context = yield* session.context(sessionID)
  3194. expect(context).toMatchObject([
  3195. { type: "user", text: "Settle before failing" },
  3196. {
  3197. type: "assistant",
  3198. content: [
  3199. {
  3200. type: "tool",
  3201. id: "call-before-failure",
  3202. state: { status: "completed", content: [{ type: "text", text: "settle" }] },
  3203. },
  3204. ],
  3205. },
  3206. ])
  3207. const assistant = requireAssistant(context)
  3208. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  3209. "session.step.started.1",
  3210. "session.tool.called.1",
  3211. "session.tool.success.2",
  3212. "session.step.failed.1",
  3213. ])
  3214. }),
  3215. )
  3216. it.effect("durably fails blocked local tools when a step is interrupted", () =>
  3217. Effect.gen(function* () {
  3218. const session = yield* setup
  3219. yield* admit(session, "Interrupt blocked tool")
  3220. const tools = yield* blockTools()
  3221. yield* TestLLM.push(
  3222. TestLLM.hangAfter(
  3223. LLMEvent.stepStart({ index: 0 }),
  3224. LLMEvent.toolCall({ id: "call-before-interrupt", name: "echo", input: { text: "blocked" } }),
  3225. ),
  3226. )
  3227. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3228. yield* tools.started
  3229. yield* session.interrupt(sessionID)
  3230. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  3231. yield* session.interrupt(sessionID)
  3232. const context = yield* session.context(sessionID)
  3233. expect(context).toMatchObject([
  3234. { type: "user", text: "Interrupt blocked tool" },
  3235. {
  3236. type: "assistant",
  3237. content: [
  3238. {
  3239. type: "tool",
  3240. id: "call-before-interrupt",
  3241. state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } },
  3242. },
  3243. ],
  3244. },
  3245. ])
  3246. const assistant = requireAssistant(context)
  3247. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  3248. "session.step.started.1",
  3249. "session.tool.called.1",
  3250. "session.tool.failed.2",
  3251. "session.step.failed.1",
  3252. ])
  3253. yield* replaySessionProjection(sessionID)
  3254. expect(yield* session.context(sessionID)).toMatchObject([
  3255. { type: "user", text: "Interrupt blocked tool" },
  3256. { type: "assistant", content: [{ type: "tool", id: "call-before-interrupt", state: { status: "error" } }] },
  3257. ])
  3258. requests.length = 0
  3259. yield* TestLLM.push([])
  3260. yield* session.resume(sessionID)
  3261. expect(messageRoles(requests[0])).toEqual(["user", "assistant", "tool"])
  3262. }),
  3263. )
  3264. it.effect("interrupts a blocked step without local tool execution", () =>
  3265. Effect.gen(function* () {
  3266. const session = yield* setup
  3267. yield* admit(session, "Interrupt provider")
  3268. const stream = yield* TestLLM.gate
  3269. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3270. yield* stream.started
  3271. yield* session.interrupt(sessionID)
  3272. const exit = yield* Fiber.await(run)
  3273. expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBeTrue()
  3274. expect(requests).toHaveLength(1)
  3275. expect(yield* session.context(sessionID)).toMatchObject([
  3276. { type: "user", text: "Interrupt provider" },
  3277. { type: "assistant", finish: "error", error: { type: "aborted", message: "Step interrupted" } },
  3278. ])
  3279. expect(yield* recordedEventTypes(sessionID)).toContain("session.step.failed.1")
  3280. yield* session.interrupt(sessionID)
  3281. }),
  3282. )
  3283. it.effect("durably fails blocked local tools when interrupted while awaiting settlement", () =>
  3284. Effect.gen(function* () {
  3285. const session = yield* setup
  3286. yield* admit(session, "Interrupt tool settlement")
  3287. const tools = yield* blockTools()
  3288. yield* TestLLM.push(TestLLM.tool("call-await-interrupt", "echo", { text: "blocked" }))
  3289. const runner = yield* SessionRunner.Service
  3290. const run = yield* runner.drain({ sessionID, force: true }).pipe(Effect.forkChild)
  3291. yield* tools.started
  3292. yield* Fiber.interrupt(run)
  3293. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  3294. expect(yield* session.context(sessionID)).toMatchObject([
  3295. { type: "user", text: "Interrupt tool settlement" },
  3296. {
  3297. type: "assistant",
  3298. finish: "error",
  3299. error: { type: "aborted", message: "Step interrupted" },
  3300. content: [
  3301. {
  3302. type: "tool",
  3303. id: "call-await-interrupt",
  3304. state: { status: "error", error: { type: "aborted", message: "Tool execution interrupted" } },
  3305. },
  3306. ],
  3307. },
  3308. ])
  3309. const eventTypes = yield* recordedEventTypes(sessionID)
  3310. expect(eventTypes).toContain("session.step.failed.1")
  3311. expect(eventTypes).not.toContain("session.step.ended.1")
  3312. }),
  3313. )
  3314. it.effect("forces a text response on an agent's configured final step", () =>
  3315. Effect.gen(function* () {
  3316. const session = yield* setup
  3317. const agents = yield* Agent.Service
  3318. yield* agents.transform((editor) =>
  3319. editor.update(Agent.ID.make("build"), (agent) => {
  3320. agent.steps = 2
  3321. }),
  3322. )
  3323. yield* admit(session, "Finish at the limit")
  3324. yield* TestLLM.push(
  3325. TestLLM.tool("call-terminal", "echo", { text: "done" }),
  3326. TestLLM.tool("call-forbidden", "echo", { text: "forbidden" }),
  3327. )
  3328. yield* session.resume(sessionID)
  3329. expect(requests).toHaveLength(2)
  3330. expect(requests[0]?.toolChoice).toBeUndefined()
  3331. expect(requests[1]?.toolChoice).toMatchObject({ type: "none" })
  3332. // Protocols with native "none" keep these definitions for prompt caching.
  3333. expect(requests[1]?.tools.map((tool) => tool.name)).toContain("echo")
  3334. expect(requests[1]?.messages.at(-1)).toMatchObject({
  3335. role: "assistant",
  3336. content: [{ type: "text", text: expect.stringContaining("MAXIMUM STEPS REACHED") }],
  3337. })
  3338. expect(executions).toEqual(["done"])
  3339. expect(yield* session.context(sessionID)).toMatchObject([
  3340. { type: "user", text: "Finish at the limit" },
  3341. { type: "assistant", content: [{ type: "tool", id: "call-terminal", state: { status: "completed" } }] },
  3342. { type: "assistant", content: [{ type: "tool", id: "call-forbidden", state: { status: "error" } }] },
  3343. ])
  3344. }),
  3345. )
  3346. it.effect("resets the configured step allowance when steering input promotes", () =>
  3347. Effect.gen(function* () {
  3348. const session = yield* setup
  3349. const agents = yield* Agent.Service
  3350. yield* agents.transform((editor) =>
  3351. editor.update(Agent.ID.make("build"), (agent) => {
  3352. agent.steps = 2
  3353. }),
  3354. )
  3355. yield* admit(session, "Start work")
  3356. yield* TestLLM.push(
  3357. TestLLM.tool("call-before-steer", "echo", { text: "before" }),
  3358. TestLLM.tool("call-after-steer", "echo", { text: "after" }),
  3359. TestLLM.stop(),
  3360. )
  3361. const stream = yield* TestLLM.gate
  3362. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3363. yield* stream.started
  3364. yield* session.prompt({ sessionID, text: "Change direction" })
  3365. yield* stream.release
  3366. yield* Fiber.join(run)
  3367. expect(requests).toHaveLength(3)
  3368. expect(requests[1]?.toolChoice).toBeUndefined()
  3369. expect(requests[1]?.tools).not.toEqual([])
  3370. expect(requests[2]?.toolChoice).toMatchObject({ type: "none" })
  3371. expect(executions).toEqual(["before", "after"])
  3372. }),
  3373. )
  3374. it.effect("projects provider errors as terminal assistant step failures", () =>
  3375. Effect.gen(function* () {
  3376. const session = yield* setup
  3377. yield* TestLLM.push([
  3378. LLMEvent.stepStart({ index: 0 }),
  3379. LLMEvent.providerError({ message: "Provider unavailable" }),
  3380. ])
  3381. expect((yield* runPrompt(session, "Fail durably").pipe(Effect.flip)).message).toBe("Provider unavailable")
  3382. expect(requests).toHaveLength(1)
  3383. expect(yield* session.context(sessionID)).toMatchObject([
  3384. { type: "user", text: "Fail durably" },
  3385. { type: "assistant", finish: "error", error: { type: "provider.unknown", message: "Provider unavailable" } },
  3386. ])
  3387. }),
  3388. )
  3389. it.effect("projects provider errors emitted before assistant step start", () =>
  3390. Effect.gen(function* () {
  3391. const session = yield* setup
  3392. yield* TestLLM.push([LLMEvent.providerError({ message: "Provider unavailable" })])
  3393. expect((yield* runPrompt(session, "Fail before step").pipe(Effect.flip)).message).toBe("Provider unavailable")
  3394. expect(requests).toHaveLength(1)
  3395. expect(yield* session.context(sessionID)).toMatchObject([
  3396. { type: "user", text: "Fail before step" },
  3397. { type: "assistant", finish: "error", error: { type: "provider.unknown", message: "Provider unavailable" } },
  3398. ])
  3399. }),
  3400. )
  3401. it.effect("projects content-filter finishes as visible terminal failures", () =>
  3402. Effect.gen(function* () {
  3403. const session = yield* setup
  3404. yield* TestLLM.push(
  3405. TestLLM.complete(
  3406. {
  3407. reason: { normalized: "content-filter" },
  3408. usage: { nonCachedInputTokens: 8, outputTokens: 3, reasoningTokens: 1 },
  3409. },
  3410. LLMEvent.textStart({ id: "partial" }),
  3411. LLMEvent.textDelta({ id: "partial", text: "Partial" }),
  3412. ),
  3413. )
  3414. expect((yield* runPrompt(session, "Blocked response").pipe(Effect.flip)).message).toBe(
  3415. "Provider blocked the response",
  3416. )
  3417. expect(yield* session.context(sessionID)).toMatchObject([
  3418. { type: "user" },
  3419. {
  3420. type: "assistant",
  3421. finish: "error",
  3422. error: { type: "provider.content-filter" },
  3423. cost: 0,
  3424. tokens: { input: 8, output: 2, reasoning: 1, cache: { read: 0, write: 0 } },
  3425. content: [{ type: "text", text: "Partial" }],
  3426. },
  3427. ])
  3428. expect(yield* session.get(sessionID)).toMatchObject({
  3429. cost: 0,
  3430. tokens: { input: 8, output: 2, reasoning: 1, cache: { read: 0, write: 0 } },
  3431. })
  3432. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.step.ended.1")
  3433. }),
  3434. )
  3435. it.effect("settles a local tool before one content-filter step failure", () =>
  3436. Effect.gen(function* () {
  3437. const session = yield* setup
  3438. yield* admit(session, "Tool before blocked response")
  3439. const tools = yield* blockTools()
  3440. yield* TestLLM.push(
  3441. TestLLM.complete(
  3442. { reason: { normalized: "content-filter" } },
  3443. LLMEvent.toolCall({ id: "call-before-content-filter", name: "echo", input: { text: "settled" } }),
  3444. ),
  3445. )
  3446. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3447. yield* tools.started
  3448. yield* tools.release
  3449. expect((yield* Fiber.join(run).pipe(Effect.flip)).message).toBe("Provider blocked the response")
  3450. const assistant = requireAssistant(yield* session.context(sessionID))
  3451. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  3452. expect(bus.map((event) => event.type)).toEqual([
  3453. "session.step.started.1",
  3454. "session.tool.called.1",
  3455. "session.tool.success.2",
  3456. "session.step.failed.1",
  3457. ])
  3458. expect(
  3459. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  3460. ).toHaveLength(1)
  3461. }),
  3462. )
  3463. it.effect("does not recover context overflow after durable assistant output", () =>
  3464. Effect.gen(function* () {
  3465. const session = yield* setup
  3466. yield* TestLLM.push([
  3467. LLMEvent.stepStart({ index: 0 }),
  3468. LLMEvent.textStart({ id: "text-partial" }),
  3469. LLMEvent.textDelta({ id: "text-partial", text: "Partial" }),
  3470. LLMEvent.textEnd({ id: "text-partial" }),
  3471. LLMEvent.providerError({ message: "prompt too long", classification: "context-overflow" }),
  3472. ])
  3473. expect((yield* runPrompt(session, "Fail after output").pipe(Effect.flip)).message).toBe("prompt too long")
  3474. expect(requests).toHaveLength(1)
  3475. expect(yield* session.context(sessionID)).toMatchObject([
  3476. { type: "user", text: "Fail after output" },
  3477. {
  3478. type: "assistant",
  3479. finish: "error",
  3480. error: { message: "prompt too long" },
  3481. content: [{ type: "text", text: "Partial" }],
  3482. },
  3483. ])
  3484. }),
  3485. )
  3486. it.effect("projects raw provider stream failures as terminal assistant step failures", () =>
  3487. Effect.gen(function* () {
  3488. const session = yield* setup
  3489. const failure = invalidRequest()
  3490. yield* TestLLM.push(Stream.fail(failure))
  3491. expect(yield* runPrompt(session, "Fail raw stream durably").pipe(Effect.flip)).toBe(failure)
  3492. yield* replaySessionProjection(sessionID)
  3493. expect(yield* session.context(sessionID)).toMatchObject([
  3494. { type: "user", text: "Fail raw stream durably" },
  3495. { type: "assistant", finish: "error", error: { type: "provider.invalid-request", message: "Invalid request" } },
  3496. ])
  3497. }),
  3498. )
  3499. it.effect("retries eligible pre-output failures after exponential backoff", () =>
  3500. Effect.gen(function* () {
  3501. const session = yield* setup
  3502. yield* admit(session, "Retry transport")
  3503. yield* TestLLM.push(Stream.fail(providerUnavailable()))
  3504. yield* TestLLM.push(TestLLM.text("Recovered", "retry-success"))
  3505. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3506. yield* TestLLM.wait(1)
  3507. yield* TestClock.adjust("1999 millis")
  3508. expect(requests).toHaveLength(1)
  3509. yield* TestClock.adjust("1 millis")
  3510. yield* Fiber.join(run)
  3511. expect(requests).toHaveLength(2)
  3512. const eventTypes = yield* recordedEventTypes(sessionID)
  3513. expect(eventTypes).toContain("session.retry.scheduled.1")
  3514. expect(eventTypes.filter((type) => type === "session.step.started.1")).toHaveLength(2)
  3515. expect(yield* session.context(sessionID)).toMatchObject([
  3516. { type: "user" },
  3517. { type: "assistant", finish: "stop", content: [{ type: "text", text: "Recovered" }] },
  3518. ])
  3519. yield* replaySessionProjection(sessionID)
  3520. expect((yield* session.context(sessionID)).filter((message) => message.type === "assistant")).toHaveLength(1)
  3521. }),
  3522. )
  3523. it.effect("uses a larger provider retry-after delay", () =>
  3524. Effect.gen(function* () {
  3525. const session = yield* setup
  3526. yield* admit(session, "Retry rate limit")
  3527. yield* TestLLM.push(Stream.fail(rateLimited(5_000)))
  3528. yield* TestLLM.push(TestLLM.text("Recovered", "retry-after-success"))
  3529. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3530. yield* TestLLM.wait(1)
  3531. yield* TestClock.adjust("4999 millis")
  3532. expect(requests).toHaveLength(1)
  3533. yield* TestClock.adjust("1 millis")
  3534. yield* Fiber.join(run)
  3535. expect(requests).toHaveLength(2)
  3536. }),
  3537. )
  3538. it.effect("does not retry eligible failures after observable output", () =>
  3539. Effect.gen(function* () {
  3540. const session = yield* setup
  3541. const failure = rateLimited()
  3542. yield* TestLLM.push(
  3543. TestLLM.failAfter(
  3544. failure,
  3545. LLMEvent.stepStart({ index: 0 }),
  3546. LLMEvent.textStart({ id: "partial-rate-limit" }),
  3547. LLMEvent.textDelta({ id: "partial-rate-limit", text: "Partial" }),
  3548. ),
  3549. )
  3550. expect(yield* runPrompt(session, "Do not replay partial output").pipe(Effect.flip)).toBe(failure)
  3551. expect(requests).toHaveLength(1)
  3552. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.retry.scheduled.1")
  3553. expect(yield* session.context(sessionID)).toMatchObject([
  3554. { type: "user" },
  3555. {
  3556. type: "assistant",
  3557. finish: "error",
  3558. error: { type: "provider.rate-limit" },
  3559. content: [{ type: "text", text: "Partial" }],
  3560. },
  3561. ])
  3562. }),
  3563. )
  3564. it.effect("stops after five total retry attempts", () =>
  3565. Effect.gen(function* () {
  3566. const session = yield* setup
  3567. yield* admit(session, "Exhaust retries")
  3568. const failure = providerUnavailable()
  3569. yield* TestLLM.always(Stream.fail(failure))
  3570. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3571. yield* TestLLM.wait(1)
  3572. for (const [index, delay] of [2_000, 4_000, 8_000, 16_000].entries()) {
  3573. yield* TestClock.adjust(delay)
  3574. yield* TestLLM.wait(index + 2)
  3575. }
  3576. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  3577. expect(requests).toHaveLength(5)
  3578. const database = (yield* Database.Service).db
  3579. const retries = yield* database
  3580. .select({ data: EventTable.data })
  3581. .from(EventTable)
  3582. .where(eq(EventTable.type, "session.retry.scheduled.1"))
  3583. .orderBy(asc(EventTable.seq))
  3584. .all()
  3585. .pipe(Effect.orDie)
  3586. expect(retries.map((event) => event.data)).toMatchObject([
  3587. { attempt: 2, at: 2_000 },
  3588. { attempt: 3, at: 6_000 },
  3589. { attempt: 4, at: 14_000 },
  3590. { attempt: 5, at: 30_000 },
  3591. ])
  3592. expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.step.started.1")).toHaveLength(5)
  3593. const assistant = requireAssistant(yield* session.context(sessionID))
  3594. expect(yield* recordedStepSettlementEvents(sessionID, assistant.id)).toMatchObject([
  3595. { type: "session.step.started.1" },
  3596. { type: "session.step.started.1" },
  3597. { type: "session.step.started.1" },
  3598. { type: "session.step.started.1" },
  3599. { type: "session.step.started.1" },
  3600. { type: "session.step.failed.1" },
  3601. ])
  3602. }),
  3603. )
  3604. it.effect("retries a model call without consuming the logical agent step", () =>
  3605. Effect.gen(function* () {
  3606. const session = yield* setup
  3607. const agents = yield* Agent.Service
  3608. yield* agents.transform((editor) =>
  3609. editor.update(Agent.ID.make("build"), (agent) => {
  3610. agent.steps = 2
  3611. }),
  3612. )
  3613. yield* admit(session, "Retry without consuming a step")
  3614. const failure = providerUnavailable()
  3615. yield* TestLLM.push(Stream.fail(failure))
  3616. yield* TestLLM.push(TestLLM.tool("call-after-retry", "echo", { text: "recovered" }), TestLLM.stop())
  3617. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3618. yield* TestLLM.wait(1)
  3619. yield* TestClock.adjust("2 seconds")
  3620. yield* Fiber.join(run)
  3621. expect(requests).toHaveLength(3)
  3622. expect(requests[0]?.toolChoice).toBeUndefined()
  3623. expect(requests[0]?.tools.map((tool) => tool.name)).toContain("echo")
  3624. expect(requests[1]?.toolChoice).toBeUndefined()
  3625. expect(requests[1]?.tools.map((tool) => tool.name)).toContain("echo")
  3626. expect(requests[1]?.messages.at(-1)).not.toMatchObject({
  3627. role: "assistant",
  3628. content: [{ type: "text", text: expect.stringContaining("MAXIMUM STEPS REACHED") }],
  3629. })
  3630. expect(requests[2]?.toolChoice).toMatchObject({ type: "none" })
  3631. // The final step keeps tool definitions to preserve provider prompt caching.
  3632. expect(requests[2]?.tools.map((tool) => tool.name)).toContain("echo")
  3633. expect(requests[2]?.messages.at(-1)).toMatchObject({
  3634. role: "assistant",
  3635. content: [{ type: "text", text: expect.stringContaining("MAXIMUM STEPS REACHED") }],
  3636. })
  3637. expect(executions).toEqual(["recovered"])
  3638. const eventTypes = yield* recordedEventTypes(sessionID)
  3639. expect(eventTypes.filter((type) => type === "session.step.started.1")).toHaveLength(3)
  3640. expect(eventTypes.filter((type) => type === "session.retry.scheduled.1")).toHaveLength(1)
  3641. expect((yield* session.context(sessionID)).filter((message) => message.type === "assistant")).toHaveLength(2)
  3642. }),
  3643. )
  3644. it.effect("does not retry non-eligible provider failures", () =>
  3645. Effect.gen(function* () {
  3646. const session = yield* setup
  3647. const failure = invalidRequest()
  3648. yield* TestLLM.push(Stream.fail(failure))
  3649. expect(yield* runPrompt(session, "Do not retry").pipe(Effect.flip)).toBe(failure)
  3650. expect(requests).toHaveLength(1)
  3651. expect(yield* recordedEventTypes(sessionID)).not.toContain("session.retry.scheduled.1")
  3652. }),
  3653. )
  3654. it.effect("settles malformed streamed tool input before the provider failure", () =>
  3655. Effect.gen(function* () {
  3656. const session = yield* setup
  3657. const failure = new LLMError({
  3658. module: "test",
  3659. method: "stream",
  3660. reason: new InvalidProviderOutputReason({ message: "Invalid JSON input for tool call echo" }),
  3661. })
  3662. yield* TestLLM.push(
  3663. TestLLM.failAfter(
  3664. failure,
  3665. LLMEvent.stepStart({ index: 0 }),
  3666. LLMEvent.toolInputStart({ id: "call-malformed", name: "echo" }),
  3667. LLMEvent.toolInputDelta({ id: "call-malformed", name: "echo", text: '{"text":"partial' }),
  3668. ),
  3669. )
  3670. expect(yield* runPrompt(session, "Call a malformed tool").pipe(Effect.flip)).toBe(failure)
  3671. const assistant = requireAssistant(yield* session.context(sessionID))
  3672. yield* TestLLM.push(TestLLM.stop())
  3673. yield* runPrompt(session, "Continue")
  3674. expect(yield* recordedStepSettlementEvents(sessionID, assistant.id)).toMatchObject([
  3675. { type: "session.step.started.1" },
  3676. {
  3677. type: "session.tool.failed.2",
  3678. data: {
  3679. callID: "call-malformed",
  3680. error: { type: "provider.invalid-output", message: "Invalid JSON input for tool call echo" },
  3681. },
  3682. },
  3683. {
  3684. type: "session.step.failed.1",
  3685. data: { error: { type: "provider.invalid-output", message: "Invalid JSON input for tool call echo" } },
  3686. },
  3687. ])
  3688. }),
  3689. )
  3690. it.effect("continues after malformed local tool input without exposing raw arguments", () =>
  3691. Effect.gen(function* () {
  3692. const session = yield* setup
  3693. const marker = "raw-malformed-marker"
  3694. const raw = `{"text":"${marker}`
  3695. yield* TestLLM.push(
  3696. TestLLM.toolCalls(
  3697. LLMEvent.toolInputStart({ id: "call-malformed", name: "echo" }),
  3698. LLMEvent.toolInputDelta({ id: "call-malformed", name: "echo", text: raw }),
  3699. LLMEvent.toolInputEnd({ id: "call-malformed", name: "echo" }),
  3700. LLMEvent.toolInputError({
  3701. id: "call-malformed",
  3702. name: "echo",
  3703. raw,
  3704. }),
  3705. ),
  3706. TestLLM.stop(),
  3707. )
  3708. yield* runPrompt(session, "Recover malformed tool input")
  3709. expect(requests).toHaveLength(2)
  3710. expect(executions).toEqual([])
  3711. expect(JSON.stringify(requests[1])).not.toContain(marker)
  3712. expect(requests[1]?.messages).toEqual(
  3713. expect.arrayContaining([
  3714. expect.objectContaining({
  3715. role: "assistant",
  3716. content: expect.arrayContaining([
  3717. expect.objectContaining({ type: "tool-call", id: "call-malformed", name: "echo", input: {} }),
  3718. ]),
  3719. }),
  3720. expect.objectContaining({
  3721. role: "tool",
  3722. content: expect.arrayContaining([
  3723. expect.objectContaining({
  3724. type: "tool-result",
  3725. id: "call-malformed",
  3726. result: expect.objectContaining({
  3727. type: "error",
  3728. value: expect.objectContaining({
  3729. error: expect.objectContaining({
  3730. message: "Tool call arguments were malformed JSON and were not executed. Retry with valid JSON.",
  3731. }),
  3732. }),
  3733. }),
  3734. }),
  3735. ]),
  3736. }),
  3737. ]),
  3738. )
  3739. const context = yield* session.context(sessionID)
  3740. const failed = context.find(
  3741. (message): message is SessionMessage.Assistant =>
  3742. message.type === "assistant" && message.content.some((item) => item.type === "tool"),
  3743. )
  3744. expect(failed).toMatchObject({
  3745. content: [
  3746. {
  3747. type: "tool",
  3748. id: "call-malformed",
  3749. executed: false,
  3750. state: {
  3751. status: "error",
  3752. input: {},
  3753. error: {
  3754. type: "tool.input-json",
  3755. message: "Tool call arguments were malformed JSON and were not executed. Retry with valid JSON.",
  3756. },
  3757. },
  3758. },
  3759. ],
  3760. })
  3761. if (!failed) throw new Error("Malformed tool assistant missing")
  3762. expect(failed.error).toBeUndefined()
  3763. expect(yield* recordedStepSettlementTypes(sessionID, failed.id)).toEqual([
  3764. "session.step.started.1",
  3765. "session.tool.failed.2",
  3766. "session.step.ended.1",
  3767. ])
  3768. const database = (yield* Database.Service).db
  3769. const durable = yield* database
  3770. .select({ type: EventTable.type, data: EventTable.data })
  3771. .from(EventTable)
  3772. .where(eq(EventTable.aggregate_id, sessionID))
  3773. .all()
  3774. .pipe(Effect.orDie)
  3775. expect(durable.find((event) => event.type === "session.tool.input.ended.1")?.data).toMatchObject({
  3776. callID: "call-malformed",
  3777. text: raw,
  3778. })
  3779. }),
  3780. )
  3781. it.effect("settles a valid sibling before recovering malformed tool input", () =>
  3782. Effect.gen(function* () {
  3783. const session = yield* setup
  3784. yield* admit(session, "Run parallel tools")
  3785. const tools = yield* blockTools()
  3786. yield* TestLLM.push(
  3787. TestLLM.toolCalls(
  3788. LLMEvent.toolCall({ id: "call-valid", name: "echo", input: { text: "valid" } }),
  3789. LLMEvent.toolInputError({
  3790. id: "call-malformed",
  3791. name: "echo",
  3792. raw: '{"text":"partial',
  3793. }),
  3794. ),
  3795. TestLLM.stop(),
  3796. )
  3797. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3798. yield* tools.started
  3799. expect(requests).toHaveLength(1)
  3800. yield* tools.release
  3801. yield* Fiber.join(run)
  3802. expect(requests).toHaveLength(2)
  3803. expect(executions).toEqual(["valid"])
  3804. const request = requests[1]
  3805. if (!request) throw new Error("Malformed recovery request missing")
  3806. expect(request.messages.flatMap((message) => (message.role === "tool" ? message.content : []))).toEqual(
  3807. expect.arrayContaining([
  3808. expect.objectContaining({ id: "call-valid", type: "tool-result" }),
  3809. expect.objectContaining({ id: "call-malformed", type: "tool-result" }),
  3810. ]),
  3811. )
  3812. }),
  3813. )
  3814. it.effect("does not recover malformed input after sibling execution is interrupted", () =>
  3815. Effect.gen(function* () {
  3816. const session = yield* setup
  3817. yield* admit(session, "Interrupt malformed recovery")
  3818. const tools = yield* blockTools()
  3819. yield* TestLLM.push(
  3820. TestLLM.toolCalls(
  3821. LLMEvent.toolCall({ id: "call-valid", name: "echo", input: { text: "blocked" } }),
  3822. LLMEvent.toolInputError({
  3823. id: "call-malformed",
  3824. name: "echo",
  3825. raw: '{"text":"partial',
  3826. }),
  3827. ),
  3828. )
  3829. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3830. yield* tools.started
  3831. while (
  3832. !(yield* session.context(sessionID)).some(
  3833. (message) =>
  3834. message.type === "assistant" &&
  3835. message.content.some((item) => item.type === "tool" && item.id === "call-malformed"),
  3836. )
  3837. )
  3838. yield* Effect.yieldNow
  3839. yield* session.interrupt(sessionID)
  3840. expect(yield* Fiber.await(run)).toMatchObject({ _tag: "Failure" })
  3841. expect(requests).toHaveLength(1)
  3842. expect(yield* session.context(sessionID)).toMatchObject([
  3843. { type: "user", text: "Interrupt malformed recovery" },
  3844. {
  3845. type: "assistant",
  3846. error: { type: "aborted", message: "Step interrupted" },
  3847. content: [
  3848. { type: "tool", id: "call-valid", state: { status: "error", error: { type: "aborted" } } },
  3849. { type: "tool", id: "call-malformed", state: { status: "error" } },
  3850. ],
  3851. },
  3852. ])
  3853. }),
  3854. )
  3855. it.effect("records malformed provider-executed input as executed", () =>
  3856. Effect.gen(function* () {
  3857. const session = yield* setup
  3858. const failure = new LLMError({
  3859. module: "test",
  3860. method: "stream",
  3861. reason: new InvalidProviderOutputReason({ message: "Invalid hosted tool input" }),
  3862. })
  3863. yield* TestLLM.push(
  3864. TestLLM.failAfter(
  3865. failure,
  3866. LLMEvent.stepStart({ index: 0 }),
  3867. LLMEvent.toolInputStart({ id: "call-hosted", name: "web_search", providerExecuted: true }),
  3868. LLMEvent.toolInputDelta({ id: "call-hosted", name: "web_search", text: '{"query":"partial' }),
  3869. ),
  3870. )
  3871. expect(yield* runPrompt(session, "Fail malformed hosted input").pipe(Effect.flip)).toBe(failure)
  3872. expect(requireAssistant(yield* session.context(sessionID))).toMatchObject({
  3873. error: { type: "provider.invalid-output", message: "Invalid hosted tool input" },
  3874. content: [
  3875. {
  3876. type: "tool",
  3877. id: "call-hosted",
  3878. executed: true,
  3879. state: { status: "error", error: { type: "provider.invalid-output" } },
  3880. },
  3881. ],
  3882. })
  3883. }),
  3884. )
  3885. it.effect("records a provider failure after malformed input", () =>
  3886. Effect.gen(function* () {
  3887. const session = yield* setup
  3888. const failure = new LLMError({
  3889. module: "test",
  3890. method: "stream",
  3891. reason: new InvalidProviderOutputReason({ message: "Provider failed after malformed input" }),
  3892. })
  3893. yield* TestLLM.push(
  3894. TestLLM.failAfter(
  3895. failure,
  3896. LLMEvent.stepStart({ index: 0 }),
  3897. LLMEvent.toolInputError({
  3898. id: "call-malformed",
  3899. name: "echo",
  3900. raw: '{"text":"partial',
  3901. }),
  3902. ),
  3903. )
  3904. expect(yield* runPrompt(session, "Fail after malformed input").pipe(Effect.flip)).toBe(failure)
  3905. expect(requireAssistant(yield* session.context(sessionID))).toMatchObject({
  3906. error: { type: "provider.invalid-output", message: "Provider failed after malformed input" },
  3907. content: [
  3908. {
  3909. type: "tool",
  3910. id: "call-malformed",
  3911. executed: false,
  3912. state: { status: "error", error: { type: "tool.input-json" } },
  3913. },
  3914. ],
  3915. })
  3916. expect(requests).toHaveLength(1)
  3917. }),
  3918. )
  3919. it.effect("continues after repeated malformed tool input", () =>
  3920. Effect.gen(function* () {
  3921. const session = yield* setup
  3922. const malformed = (id: string) =>
  3923. TestLLM.toolCalls(
  3924. LLMEvent.toolInputError({
  3925. id,
  3926. name: "echo",
  3927. raw: '{"text":"partial',
  3928. }),
  3929. )
  3930. yield* TestLLM.push(
  3931. malformed("call-first"),
  3932. TestLLM.tool("call-valid-between", "echo", { text: "valid" }),
  3933. malformed("call-second"),
  3934. TestLLM.stop(),
  3935. )
  3936. yield* runPrompt(session, "Keep producing malformed tools")
  3937. expect(requests).toHaveLength(4)
  3938. expect(executions).toEqual(["valid"])
  3939. expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.step.failed.1")).toHaveLength(0)
  3940. }),
  3941. )
  3942. it.effect("does not continue malformed tool input past the agent step limit", () =>
  3943. Effect.gen(function* () {
  3944. const session = yield* setup
  3945. const agents = yield* Agent.Service
  3946. yield* agents.transform((editor) =>
  3947. editor.update(Agent.ID.make("build"), (agent) => {
  3948. agent.steps = 2
  3949. }),
  3950. )
  3951. const malformed = (id: string) =>
  3952. TestLLM.toolCalls(
  3953. LLMEvent.toolInputError({
  3954. id,
  3955. name: "echo",
  3956. raw: '{"text":"partial',
  3957. }),
  3958. )
  3959. yield* TestLLM.push(malformed("call-first"), malformed("call-at-limit"))
  3960. yield* runPrompt(session, "Stop malformed tools at the step limit")
  3961. expect(requests).toHaveLength(2)
  3962. expect(requests[0]?.toolChoice).toBeUndefined()
  3963. expect(requests[1]?.toolChoice).toMatchObject({ type: "none" })
  3964. expect((yield* recordedEventTypes(sessionID)).filter((type) => type === "session.tool.failed.2")).toHaveLength(2)
  3965. }),
  3966. )
  3967. it.effect("does not continue automatically after a provider error follows a local tool call", () =>
  3968. Effect.gen(function* () {
  3969. const session = yield* setup
  3970. yield* admit(session, "Do not continue failed provider")
  3971. const tools = yield* blockTools()
  3972. yield* TestLLM.push([
  3973. LLMEvent.stepStart({ index: 0 }),
  3974. LLMEvent.toolCall({ id: "call-before-provider-error", name: "echo", input: { text: "settled" } }),
  3975. LLMEvent.providerError({ message: "Provider unavailable" }),
  3976. ])
  3977. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  3978. yield* tools.started
  3979. yield* tools.release
  3980. expect((yield* Fiber.join(run).pipe(Effect.flip)).message).toBe("Provider unavailable")
  3981. expect(requests).toHaveLength(1)
  3982. expect(executions).toEqual(["settled"])
  3983. const context = yield* session.context(sessionID)
  3984. const assistant = requireAssistant(context)
  3985. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  3986. "session.step.started.1",
  3987. "session.tool.called.1",
  3988. "session.tool.success.2",
  3989. "session.step.failed.1",
  3990. ])
  3991. }),
  3992. )
  3993. it.effect("durably fails a hosted tool when its provider errors before returning a result", () =>
  3994. Effect.gen(function* () {
  3995. const session = yield* setup
  3996. yield* TestLLM.push([
  3997. LLMEvent.stepStart({ index: 0 }),
  3998. hostedCall("call-hosted-provider-error", "effect"),
  3999. LLMEvent.providerError({ message: "Provider unavailable" }),
  4000. ])
  4001. expect((yield* runPrompt(session, "Fail hosted tool durably").pipe(Effect.flip)).message).toBe(
  4002. "Provider unavailable",
  4003. )
  4004. expect(requests).toHaveLength(1)
  4005. const context = yield* session.context(sessionID)
  4006. expect(context).toMatchObject([
  4007. { type: "user", text: "Fail hosted tool durably" },
  4008. {
  4009. type: "assistant",
  4010. content: [{ type: "tool", id: "call-hosted-provider-error", state: { status: "error" } }],
  4011. },
  4012. ])
  4013. const assistant = requireAssistant(context)
  4014. expect(yield* recordedStepSettlementTypes(sessionID, assistant.id)).toEqual([
  4015. "session.step.started.1",
  4016. "session.tool.called.1",
  4017. "session.tool.failed.2",
  4018. "session.step.failed.1",
  4019. ])
  4020. }),
  4021. )
  4022. it.effect("preserves a tool defect before provider failure settlement", () =>
  4023. Effect.gen(function* () {
  4024. const session = yield* setup
  4025. yield* TestLLM.push([
  4026. LLMEvent.stepStart({ index: 0 }),
  4027. LLMEvent.toolCall({ id: "call-defect-provider-error", name: "defect", input: {} }),
  4028. LLMEvent.providerError({ message: "Provider unavailable" }),
  4029. ])
  4030. expect((yield* runPrompt(session, "Defect while provider fails").pipe(Effect.flip)).message).toBe(
  4031. "Provider unavailable",
  4032. )
  4033. const context = yield* session.context(sessionID)
  4034. const assistant = requireAssistant(context)
  4035. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4036. expect(bus.map((event) => event.type)).toEqual([
  4037. "session.step.started.1",
  4038. "session.tool.called.1",
  4039. "session.tool.failed.2",
  4040. "session.step.failed.1",
  4041. ])
  4042. expect(bus[2]?.data.error).toMatchObject({ type: "unknown", message: "unexpected tool defect" })
  4043. }),
  4044. )
  4045. it.effect("preserves the provider failure when tool output persistence also fails", () =>
  4046. Effect.gen(function* () {
  4047. const session = yield* setup
  4048. yield* admit(session, "Storage fails while provider fails")
  4049. yield* TestLLM.push([
  4050. LLMEvent.stepStart({ index: 0 }),
  4051. LLMEvent.toolCall({ id: "call-store-provider-error", name: "storefail", input: {} }),
  4052. LLMEvent.providerError({ message: "Provider unavailable" }),
  4053. ])
  4054. expect(yield* session.resume(sessionID).pipe(Effect.exit)).toMatchObject({
  4055. _tag: "Failure",
  4056. })
  4057. expect(requireAssistant(yield* session.context(sessionID))).toMatchObject({
  4058. error: { type: "provider.unknown", message: "Provider unavailable" },
  4059. })
  4060. }),
  4061. )
  4062. it.effect("durably fails a hosted tool left unresolved at normal provider EOF", () =>
  4063. Effect.gen(function* () {
  4064. const session = yield* setup
  4065. yield* TestLLM.push([LLMEvent.stepStart({ index: 0 }), hostedCall("call-hosted-eof", "effect")])
  4066. expect((yield* runPrompt(session, "Fail hosted tool at EOF").pipe(Effect.flip)).message).toBe(
  4067. "Provider did not return a tool result",
  4068. )
  4069. const assistant = requireAssistant(yield* session.context(sessionID))
  4070. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4071. expect(bus.map((event) => event.type)).toEqual([
  4072. "session.step.started.1",
  4073. "session.tool.called.1",
  4074. "session.tool.failed.2",
  4075. "session.step.failed.1",
  4076. ])
  4077. expect(
  4078. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4079. ).toHaveLength(1)
  4080. yield* replaySessionProjection(sessionID)
  4081. expect(yield* session.context(sessionID)).toMatchObject([
  4082. { type: "user", text: "Fail hosted tool at EOF" },
  4083. {
  4084. type: "assistant",
  4085. finish: "error",
  4086. error: { type: "tool.result-missing" },
  4087. content: [{ type: "tool", id: "call-hosted-eof", state: { status: "error" } }],
  4088. },
  4089. ])
  4090. }),
  4091. )
  4092. it.effect("fails an unresolved hosted tool before one clean step end", () =>
  4093. Effect.gen(function* () {
  4094. const session = yield* setup
  4095. yield* TestLLM.push(TestLLM.stop(hostedCall("call-hosted-clean-end", "effect")))
  4096. yield* runPrompt(session, "Settle hosted tool before ending")
  4097. const assistant = requireAssistant(yield* session.context(sessionID))
  4098. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4099. expect(bus.map((event) => event.type)).toEqual([
  4100. "session.step.started.1",
  4101. "session.tool.called.1",
  4102. "session.tool.failed.2",
  4103. "session.step.ended.1",
  4104. ])
  4105. expect(
  4106. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4107. ).toHaveLength(1)
  4108. }),
  4109. )
  4110. it.effect("settles unresolved local and hosted tools before one raw provider failure", () =>
  4111. Effect.gen(function* () {
  4112. const session = yield* setup
  4113. yield* admit(session, "Fail unresolved tools")
  4114. const failure = invalidRequest()
  4115. const providerFailed = yield* Deferred.make<void>()
  4116. const tools = yield* blockTools()
  4117. yield* TestLLM.push(
  4118. Stream.concat(
  4119. Stream.fromIterable([
  4120. LLMEvent.stepStart({ index: 0 }),
  4121. LLMEvent.toolCall({ id: "call-local-raw-failure", name: "defect", input: {} }),
  4122. hostedCall("call-hosted-raw-failure-pair", "effect"),
  4123. ]),
  4124. Stream.fromEffect(Deferred.succeed(providerFailed, undefined)).pipe(
  4125. Stream.flatMap(() => Stream.fail(failure)),
  4126. ),
  4127. ),
  4128. )
  4129. const run = yield* session.resume(sessionID).pipe(Effect.forkChild)
  4130. yield* Deferred.await(providerFailed)
  4131. yield* tools.release
  4132. expect(yield* Fiber.join(run).pipe(Effect.flip)).toBe(failure)
  4133. const assistant = requireAssistant(yield* session.context(sessionID))
  4134. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4135. expect(bus.map((event) => ({ type: event.type, callID: event.data.callID }))).toEqual([
  4136. { type: "session.step.started.1", callID: undefined },
  4137. { type: "session.tool.called.1", callID: "call-local-raw-failure" },
  4138. { type: "session.tool.called.1", callID: "call-hosted-raw-failure-pair" },
  4139. { type: "session.tool.failed.2", callID: "call-local-raw-failure" },
  4140. { type: "session.tool.failed.2", callID: "call-hosted-raw-failure-pair" },
  4141. { type: "session.step.failed.1", callID: undefined },
  4142. ])
  4143. expect(
  4144. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4145. ).toHaveLength(1)
  4146. }),
  4147. )
  4148. it.effect("durably fails a hosted tool left unresolved by a raw provider stream failure", () =>
  4149. Effect.gen(function* () {
  4150. const session = yield* setup
  4151. const failure = providerUnavailable()
  4152. yield* TestLLM.push(
  4153. Stream.concat(
  4154. Stream.fromIterable([LLMEvent.stepStart({ index: 0 }), hostedCall("call-hosted-raw-failure", "effect")]),
  4155. Stream.fail(failure),
  4156. ),
  4157. )
  4158. expect(yield* runPrompt(session, "Fail hosted tool on raw failure").pipe(Effect.flip)).toBe(failure)
  4159. expect(requests).toHaveLength(1)
  4160. const assistant = requireAssistant(yield* session.context(sessionID))
  4161. const bus = yield* recordedStepSettlementEvents(sessionID, assistant.id)
  4162. expect(bus.map((event) => event.type)).toEqual([
  4163. "session.step.started.1",
  4164. "session.tool.called.1",
  4165. "session.tool.failed.2",
  4166. "session.step.failed.1",
  4167. ])
  4168. expect(
  4169. bus.filter((event) => event.type.startsWith("session.step.") && event.type !== "session.step.started.1"),
  4170. ).toHaveLength(1)
  4171. yield* replaySessionProjection(sessionID)
  4172. expect(yield* session.context(sessionID)).toMatchObject([
  4173. { type: "user", text: "Fail hosted tool on raw failure" },
  4174. {
  4175. type: "assistant",
  4176. finish: "error",
  4177. error: { type: "provider.transport", message: "Provider unavailable" },
  4178. content: [{ type: "tool", id: "call-hosted-raw-failure", state: { status: "error" } }],
  4179. },
  4180. ])
  4181. }),
  4182. )
  4183. it.effect("rejects a second text start before the open fragment ends", () =>
  4184. Effect.gen(function* () {
  4185. const session = yield* setup
  4186. yield* TestLLM.push([
  4187. LLMEvent.stepStart({ index: 0 }),
  4188. LLMEvent.textStart({ id: "text-1" }),
  4189. LLMEvent.textStart({ id: "text-2" }),
  4190. ])
  4191. const defect = yield* runPrompt(session, "Two blocks").pipe(Effect.catchDefect(Effect.succeed))
  4192. expect(defect).toBeInstanceOf(Error)
  4193. if (!(defect instanceof Error)) return
  4194. expect(defect.message).toBe("text start before end: text-2")
  4195. }),
  4196. )
  4197. it.effect("projects sequential text fragments as separate content parts", () =>
  4198. Effect.gen(function* () {
  4199. const session = yield* setup
  4200. yield* TestLLM.push(
  4201. TestLLM.stop(
  4202. LLMEvent.textStart({ id: "text-1" }),
  4203. LLMEvent.textDelta({ id: "text-1", text: "First" }),
  4204. LLMEvent.textEnd({ id: "text-1" }),
  4205. LLMEvent.textStart({ id: "text-2" }),
  4206. LLMEvent.textDelta({ id: "text-2", text: "Second" }),
  4207. LLMEvent.textEnd({ id: "text-2" }),
  4208. ),
  4209. )
  4210. yield* runPrompt(session, "Two blocks")
  4211. expect(yield* session.context(sessionID)).toMatchObject([
  4212. { type: "user", text: "Two blocks" },
  4213. {
  4214. type: "assistant",
  4215. content: [
  4216. { type: "text", text: "First" },
  4217. { type: "text", text: "Second" },
  4218. ],
  4219. },
  4220. ])
  4221. }),
  4222. )
  4223. for (const kind of fragmentKinds) {
  4224. it.effect(`broadcasts provider ${kind} deltas without storing projection rewrites`, () =>
  4225. verifyEphemeralDeltas(kind),
  4226. )
  4227. it.effect(`durably closes partial ${kind} when the provider stream fails`, () => verifyPartialFlushOnFailure(kind))
  4228. it.effect(`durably closes partial ${kind} when the provider stream is interrupted`, () =>
  4229. verifyPartialFlushOnInterruption(kind),
  4230. )
  4231. }
  4232. it.effect("rejects duplicate streamed text starts", () =>
  4233. Effect.gen(function* () {
  4234. const session = yield* setup
  4235. yield* TestLLM.push([LLMEvent.textStart({ id: "text-1" }), LLMEvent.textStart({ id: "text-1" })])
  4236. const defect = yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))
  4237. expect(defect).toBeInstanceOf(Error)
  4238. if (!(defect instanceof Error)) return
  4239. expect(defect.message).toBe("Duplicate text start: text-1")
  4240. }),
  4241. )
  4242. it.effect("transitions streamed raw tool input to parsed called input", () =>
  4243. Effect.gen(function* () {
  4244. const session = yield* setup
  4245. yield* TestLLM.push(
  4246. TestLLM.stop(
  4247. LLMEvent.toolInputStart({ id: "call-parsed", name: "web_search" }),
  4248. LLMEvent.toolInputDelta({ id: "call-parsed", name: "web_search", text: '{"query":"hello"}' }),
  4249. LLMEvent.toolInputEnd({ id: "call-parsed", name: "web_search" }),
  4250. hostedCall("call-parsed", "hello"),
  4251. ),
  4252. )
  4253. yield* runPrompt(session, "Call provider tool")
  4254. expect(yield* session.context(sessionID)).toMatchObject([
  4255. { type: "user", text: "Call provider tool" },
  4256. {
  4257. type: "assistant",
  4258. content: [{ type: "tool", id: "call-parsed", state: { status: "error", input: { query: "hello" } } }],
  4259. },
  4260. ])
  4261. }),
  4262. )
  4263. it.effect("rejects malformed streamed tool input ordering", () =>
  4264. Effect.gen(function* () {
  4265. const session = yield* setup
  4266. yield* TestLLM.push([LLMEvent.toolInputDelta({ id: "call-1", name: "read", text: "{}" })])
  4267. const defect = yield* session.resume(sessionID).pipe(Effect.catchDefect(Effect.succeed))
  4268. expect(defect).toBeInstanceOf(Error)
  4269. if (!(defect instanceof Error)) return
  4270. expect(defect.message).toBe("Tool input delta before start: call-1")
  4271. }),
  4272. )
  4273. })