session-runner.test.ts 175 KB

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