session-runner.test.ts 174 KB

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