zcodeTaskServiceAdapter.ts 218 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932
  1. import { formatBotInputClientId, isAuxiliarySessionKind } from "@zcode/shared";
  2. import { createBotTopicAdmission } from "#src/zcode-agent/botTopicAdmission.js";
  3. import {
  4. readBotGroupRuntimeSnapshot,
  5. waitBotGroupExecutionEnd,
  6. } from "#src/zcode-agent/groupRuntimeSnapshot.js";
  7. import { uploadBotGroupAttachments } from "./groupAttachmentUpload.js";
  8. /* oxlint-disable eslint(max-lines) -- 迁移期需要在一个门面里集中维护旧 task projection 到 ZCode session 的协议适配。 */
  9. import { createHash, randomUUID } from "node:crypto";
  10. import { createZCodeAgentConnectionScope } from "#src/zcode-agent/zcodeAgentConnectionScope.js";
  11. import { existsSync, readFileSync } from "node:fs";
  12. import { homedir } from "node:os";
  13. import { join } from "node:path";
  14. import {
  15. Emitter,
  16. Event,
  17. emitNetworkTelemetryObservation,
  18. type NetworkObservation,
  19. } from "@zcode/rpc";
  20. import {
  21. coalesceConsecutiveZCodeAssistants,
  22. createSessionTraceId,
  23. decodeCustomModelValue,
  24. deriveZCodeTaskStatusFromSessionSnapshot,
  25. extractPlanStepsFromToolInput,
  26. extractPlanStepsFromToolOutput,
  27. generateTraceId,
  28. getZCodeGoalActiveIterationCount,
  29. getZCodeGoalIterationByAssistantMessageId,
  30. getZCodeUserVisibleMessages,
  31. isMainAgentToolProjectionSource,
  32. normalizeZCodeApiRetryStatus,
  33. attachZCodeBackgroundTaskNotificationToRaw,
  34. collectZCodeBackgroundTaskNotificationsByToolUseId,
  35. mergeZCodeBackgroundTaskControlItems,
  36. parseZCodeBackgroundTaskControlItems,
  37. parseZCodeBackgroundTaskNotifications,
  38. parseModelPickerValue as parseSharedModelSelection,
  39. resolveWorkspaceKey,
  40. resolveZCodeVisibleSessionTitle,
  41. textFromZCodeMessageParts,
  42. ZCODE_AGENT_PROVIDER,
  43. zcodeBackgroundTaskNotificationFailureText,
  44. zcodeBackgroundTaskNotificationToolUpdateStatus,
  45. appendZCodeStreamingToolInputDelta,
  46. buildZCodeStreamingToolInputPreview,
  47. createZCodeToolProjectionMemory,
  48. finalizeZCodeToolProjectionInput,
  49. forgetZCodeToolProjectionMetadata,
  50. isZCodeModelRetryRecoveryProgressPayload,
  51. markZCodeStreamingToolInputPreviewMaterialized,
  52. resolveZCodeToolProjectionMetadata,
  53. zcodeApiRetryFromModelNetworkStatusPayload,
  54. zcodeApiRetryFromStreamRecoveryPayload,
  55. zcodeTaskNetworkDebugStatusFromPayload,
  56. shouldMaterializeZCodeStreamingToolInputPreview,
  57. type ZCodeApiRetryStatus,
  58. type ZCodeAssistantMessageFeedback,
  59. type ZCodeBackgroundTaskNotificationInfo,
  60. type ZCodeBackgroundTaskControlItem,
  61. type ZCodeBackgroundTurnAttribution,
  62. type ZCodeAutomationBotDeliveryTarget,
  63. type ZCodeCancelTaskCommandResult,
  64. type ZCodeCodexConnectivityCheckResult,
  65. type ZCodeConfigOption,
  66. type ZCodeEnqueueTaskCommandResult,
  67. type ZCodeError,
  68. type ZCodeGoalVerificationTimelineMeta,
  69. type ZCodeImportSessionsResult,
  70. type ZCodeImportableSessionCandidate,
  71. type ZCodeUsage,
  72. type ZCodePersistedMessage,
  73. type ZCodePersistedMessagePart,
  74. type ZCodePersistedToolCall,
  75. type ZCodePromptAttachment,
  76. type ZCodeProvider,
  77. type ZCodeSessionFile,
  78. type ZCodeTaskGoal,
  79. type ZCodeTaskGoalStats,
  80. type ZCodeTaskMode,
  81. type ZCodePlanStep,
  82. type ZCodeSlashCommand,
  83. type ZCodeStreamEvent,
  84. type ZCodeSwitchAgentResult,
  85. type ZCodeSyncTaskSessionBindingResult,
  86. type ZCodeTaskCreateResult,
  87. type ZCodeTaskMeta,
  88. type ZCodeTaskClientMode,
  89. type ZCodeTaskRuntimeCommand,
  90. type ZCodeTaskSnapshot,
  91. type ZCodeTaskSnapshotBody,
  92. type ZCodeTaskSnapshotRefContent,
  93. type ZCodeTaskSnapshotToolCallsSlice,
  94. type ZCodeTaskTokenUsageResult,
  95. type ZCodeTodoGroup,
  96. type ZCodeTurnSteerCommandKind,
  97. type ZCodeTurnSteerSource,
  98. type ZCodeWorkspaceEvent,
  99. type ZCodeWorkspaceTaskListChanged,
  100. type InputId,
  101. type TraceId,
  102. zcodeContextUsageBreakdownSchema,
  103. zcodeSessionSettingsStateSchema,
  104. type ZCodeDeliveryKind,
  105. type ZCodeMessagePart,
  106. type ZCodeMessageWithParts,
  107. type ModelSelection,
  108. type ZCodePermissionOption,
  109. type ZCodePermissionRequestParams,
  110. type ZCodePermissionRequest,
  111. type ZCodeSessionEvent,
  112. type ZCodeSessionMode,
  113. type ZCodeSessionSettingsState,
  114. type ZCodeSessionStateSnapshot,
  115. type ZCodeStateUpdatedNotification,
  116. type ZCodeContextCompactionTimelineMeta,
  117. type ZCodeTimelineMeta,
  118. type ZCodeTimelineStatus,
  119. type ZCodeTimelineTrigger,
  120. type ZCodeToolProjectionMemory,
  121. type ZCodeUserInputRequestParams,
  122. type ZCodeUserInputResponse,
  123. type ZCodeAgentMcpServer,
  124. } from "@zcode/shared";
  125. import type {
  126. ZCodeTaskListQuery,
  127. ZCodeTaskListResult,
  128. ZCodeWorkspaceEventSubscriptionParams,
  129. IZCodeTaskService,
  130. ZCodeArchivedTaskDeletionResult,
  131. ZCodeTaskReadyOutcome,
  132. ZCodeTaskTerminalOutcome,
  133. } from "../session/zcodeTaskService.js";
  134. import { createServiceLogger } from "#src/logger/serviceLogger.js";
  135. import {
  136. AUTOMATION_MUTATION_TOOL_NAMES,
  137. OFF_PEAK_MUTATION_TOOL_NAMES,
  138. } from "#src/zcode-agent/automationToolPolicy.js";
  139. import type { ISettingService } from "#src/setting/setting.js";
  140. import type {
  141. SessionMessageDeliveryResult,
  142. SessionMessageSendRequested,
  143. } from "#src/session/sessionMailbox.js";
  144. import { TaskIndexRepo } from "#src/session/taskIndexRepo.js";
  145. import type {
  146. IZCodeAgentService,
  147. ZCodeAgentServiceEvent,
  148. ZCodeAgentWorkspaceTarget,
  149. } from "./zcodeAgent.js";
  150. import type {
  151. ZCodeTaskIndexReadyEvent,
  152. ZCodeTaskIndexSyncer,
  153. ZCodeTaskIndexTerminalEvent,
  154. } from "./zcodeTaskIndexSyncer.js";
  155. import { readModelTrajectory } from "./modelTrajectory.js";
  156. import {
  157. errorAttributionSchema,
  158. type CommandAck,
  159. type CommandPayloadMap,
  160. } from "@zcode/shared/zcode-protocol-v4";
  161. import {
  162. assertV4CommandAckOk,
  163. createHostCommandEnvelope,
  164. sendHostCasCommandV4,
  165. } from "./zcodeV4HostCommand.js";
  166. import {
  167. getLegacyDeletedTaskSessionSnapshotPath,
  168. getLegacyTaskSessionSnapshotPath,
  169. } from "#src/paths.js";
  170. import { claudeNativeSessionImportRepo } from "#src/session/claude-native/claudeNativeSessionImportRepo.js";
  171. import { importClaudeNativeSessions } from "#src/session/claude-native/claudeNativeSessionImportService.js";
  172. import { repairImportedClaudeSessionSnapshot } from "#src/session/claude-native/importedClaudeHistoryRepair.js";
  173. import { safeParseLegacyTaskSessionFile } from "#src/session/legacyTaskSessionFile.js";
  174. import {
  175. MODEL_CONFIG_ID,
  176. MODE_CONFIG_ID,
  177. THOUGHT_LEVEL_CONFIG_ID,
  178. formatTaskMetaModelSelectionFromSnapshot,
  179. formatModelPickerValue,
  180. getZCodeAgentAvailableModes,
  181. normalizeAvailableZCodeMode,
  182. settingsToConfigOptions,
  183. } from "./zcodeConfigOptions.js";
  184. import type { CuaProductMcpServerResolver } from "#src/cua-permission-broker/index.js";
  185. import { registerMemoryDiagnosticsProvider } from "#src/memoryDiagnostics.js";
  186. interface CreateZCodeTaskServiceAdapterOptions {
  187. zcodeAgentService: IZCodeAgentService;
  188. taskIndexRepo?: TaskIndexRepo;
  189. // syncer 现在持有 workspace emitter 和 broadcast 入口,adapter 必须共用同一实例,
  190. // 否则 desktop-continuous 路径和 task adapter 路径的事件订阅会分裂成两份,UI 收不全。
  191. taskIndexSyncer: ZCodeTaskIndexSyncer;
  192. settingService?: Pick<ISettingService, "get">;
  193. cuaProductMcpServerResolver?: CuaProductMcpServerResolver;
  194. }
  195. interface TaskTarget {
  196. taskId: string;
  197. workspacePath: string;
  198. workspaceIdentity?: string;
  199. cronAutomationId?: string;
  200. remoteSessionId?: string;
  201. }
  202. interface TaskTargetWithMcpServers extends TaskTarget {
  203. additionalDirectories?: string[];
  204. model?: string;
  205. thoughtLevel?: string;
  206. mcpServers?: ZCodeAgentMcpServer[];
  207. toolDenylist?: string[];
  208. }
  209. type WorkspaceEventInput = string | ZCodeWorkspaceEventSubscriptionParams;
  210. type ZCodeSendPromptRuntimeCommand = Extract<ZCodeTaskRuntimeCommand, { type: "send_prompt" }>;
  211. type ZCodeTerminalStreamEvent =
  212. | Extract<ZCodeStreamEvent, { type: "task_complete" }>
  213. | Extract<ZCodeStreamEvent, { type: "task_error" }>;
  214. const GLM_PROVIDER: ZCodeProvider = ZCODE_AGENT_PROVIDER;
  215. const EMPTY_SLASH_COMMANDS: ZCodeSlashCommand[] = [];
  216. const logger = createServiceLogger("zcode-task-service");
  217. const ASK_USER_QUESTION_TOOL_NAME = "AskUserQuestion";
  218. const EXIT_PLAN_MODE_TOOL_NAME = "ExitPlanMode";
  219. const EXIT_PLAN_MODE_APPROVAL_QUESTION = "Review this implementation plan.";
  220. const EXIT_PLAN_MODE_APPROVAL_APPROVE = "approve";
  221. const MAX_LIVE_TOOL_PROJECTION_TASKS = 128;
  222. const MAX_LIVE_TOOL_PROJECTION_TOOLS_PER_TASK = 2000;
  223. interface LiveToolProjection {
  224. order: number;
  225. parentToolUseId: string | null;
  226. tool: ZCodePersistedToolCall;
  227. toolId: string;
  228. }
  229. function padDatePart(value: number): string {
  230. return value.toString().padStart(2, "0");
  231. }
  232. function formatZCodeAgentLogDate(now: Date): string {
  233. return [now.getFullYear(), padDatePart(now.getMonth() + 1), padDatePart(now.getDate())].join("-");
  234. }
  235. function resolveZCodeAgentCurrentLogFilePath(now = new Date()): string {
  236. const configuredLogDir = process.env.ZCODE_LOG_DIR?.trim();
  237. const logDir = configuredLogDir || join(homedir(), ".zcode", "cli", "log");
  238. return join(logDir, `zcode-${formatZCodeAgentLogDate(now)}.jsonl`);
  239. }
  240. export function createZCodeTaskServiceAdapter(
  241. options: CreateZCodeTaskServiceAdapterOptions,
  242. ): IZCodeTaskService {
  243. // Bot 原来绕过连接 facade,导致真实附件 admission 缺少可信身份;复用既有 scope,
  244. // 同一 Bot 接入的附件、命令及对账共用连接,不改变桌面与手机各自的传输模式。
  245. const botConnectionScopes = new Map<string, ReturnType<typeof createZCodeAgentConnectionScope>>();
  246. function botAgent(workspace: ZCodeAgentWorkspaceTarget) {
  247. const key = JSON.stringify([resolveWorkspaceKey(workspace), workspace.remoteSessionId ?? ""]);
  248. let scope = botConnectionScopes.get(key);
  249. if (!scope) {
  250. scope = createZCodeAgentConnectionScope(options.zcodeAgentService, {
  251. connectionId: `bot-${randomUUID()}`,
  252. clientMode: "desktop-continuous",
  253. role: "trusted-host-relay",
  254. });
  255. botConnectionScopes.set(key, scope);
  256. }
  257. return scope.service;
  258. }
  259. const errorEmitter = new Emitter<ZCodeError>();
  260. const taskEmitters = new Map<string, Emitter<ZCodeStreamEvent>>();
  261. const globalTaskEmitters = new Map<string, Emitter<ZCodeStreamEvent>>();
  262. const taskTargets = new Map<string, TaskTarget>();
  263. const topicAdmission = createBotTopicAdmission();
  264. const runtimeCommands = new Map<string, ZCodeTaskRuntimeCommand[]>();
  265. const runtimeCommandDrains = new Map<string, Promise<void>>();
  266. const apiRetryByTaskKey = new Map<string, ZCodeApiRetryStatus | null>();
  267. const backgroundTaskControlsByTaskKey = new Map<string, ZCodeBackgroundTaskControlItem[]>();
  268. const streamedTurnText = new Map<string, { messageId?: string; text: string }>();
  269. const activePromptInputIds = new Map<string, InputId>();
  270. const toolProjectionMemoryByTaskKey = new Map<string, ZCodeToolProjectionMemory>();
  271. const liveToolProjectionsByTaskKey = new Map<string, Map<string, LiveToolProjection>>();
  272. let liveToolProjectionOrder = 0;
  273. const legacySnapshotTaskKeys = new Set<string>();
  274. // 内存诊断计数器(docs/monitoring/memory-diagnostics-log.md):对应审计里 deleteTask
  275. // 不清理的 per-task 表,只读 size。
  276. const memoryDiagnostics = registerMemoryDiagnosticsProvider("task", () => ({
  277. runtimeCommands: runtimeCommands.size,
  278. toolMemoryTasks: toolProjectionMemoryByTaskKey.size,
  279. taskEmitters: taskEmitters.size,
  280. }));
  281. const taskIndexRepo = options.taskIndexRepo ?? new TaskIndexRepo();
  282. const taskIndexSyncer = options.taskIndexSyncer;
  283. // 之前 adapter 自带 notifySyncerSession 时把 syncer 视为可选;现在 syncer 是构造必填项,
  284. // 简化为直接调用,避免每个 callsite 都做空判断。
  285. function notifySyncerSession(target: TaskTarget): void {
  286. taskIndexSyncer.ensureSessionSubscription({
  287. workspacePath: target.workspacePath,
  288. workspaceIdentity: target.workspaceIdentity,
  289. sessionId: target.taskId,
  290. });
  291. }
  292. function unsupported(name: string): never {
  293. throw Object.assign(
  294. new Error(`ZCode task service adapter does not support IZCodeTaskService.${name} yet.`),
  295. {
  296. code: "ZCODE_AGENT_UNSUPPORTED_LEGACY_TASK_METHOD",
  297. },
  298. );
  299. }
  300. function resolvePromptToolDenylist(params: {
  301. automationId?: string;
  302. offPeakTaskId?: string;
  303. toolDenylist?: string[];
  304. }): string[] | undefined {
  305. const toolDenylist = new Set(params.toolDenylist);
  306. // 持久化的 cronAutomationId 不能当成当前 turn 的执行身份,否则定时任务
  307. // 跑过一次后,用户在同一会话主动修改调度也永久看不到 CronUpdate。权限必须只看本轮
  308. // automationId;cronAutomationId 仅保留任务归属和 UI 展示语义。
  309. if (params.automationId) {
  310. for (const toolName of AUTOMATION_MUTATION_TOOL_NAMES) {
  311. toolDenylist.add(toolName);
  312. }
  313. }
  314. // 闲时派发轮纵深隐藏 OffPeakCreate;不与 automation 分支合并(cron 轮放行)。
  315. if (params.offPeakTaskId) {
  316. for (const toolName of OFF_PEAK_MUTATION_TOOL_NAMES) {
  317. toolDenylist.add(toolName);
  318. }
  319. }
  320. return toolDenylist.size > 0 ? [...toolDenylist] : undefined;
  321. }
  322. function turnAttributionOf(
  323. params: ZCodeBackgroundTurnAttribution,
  324. ): ZCodeBackgroundTurnAttribution {
  325. if (params.automationId) return { automationId: params.automationId };
  326. if (params.offPeakTaskId) {
  327. return {
  328. offPeakTaskId: params.offPeakTaskId,
  329. ...(params.offPeakRunType ? { offPeakRunType: params.offPeakRunType } : {}),
  330. };
  331. }
  332. return {};
  333. }
  334. async function resolveProductMcpServers(
  335. servers: ZCodeAgentMcpServer[] | undefined,
  336. ): Promise<ZCodeAgentMcpServer[] | undefined> {
  337. const configuredServers = (servers?.length ?? 0) > 0 ? servers : undefined;
  338. if (!configuredServers || !options.cuaProductMcpServerResolver) {
  339. return configuredServers;
  340. }
  341. return options.cuaProductMcpServerResolver.resolveMcpServers(configuredServers);
  342. }
  343. function workspaceKey(params: { workspacePath: string; workspaceIdentity?: string }): string {
  344. return resolveWorkspaceKey(params);
  345. }
  346. function taskKey(params: { workspacePath: string; workspaceIdentity?: string; taskId: string }) {
  347. return `${workspaceKey(params)}\u0000${params.taskId}`;
  348. }
  349. function createTaskOwnerCommandError(
  350. message: string,
  351. code: "NO_ACTIVE_TASK_OWNER" | "STALE_TASK_OWNER_COMMAND",
  352. ): Error & { code: "NO_ACTIVE_TASK_OWNER" | "STALE_TASK_OWNER_COMMAND" } {
  353. return Object.assign(new Error(message), { code });
  354. }
  355. function assertCurrentOwnerRun(params: TaskTarget, ownerRunId: TraceId | undefined): void {
  356. if (!ownerRunId) {
  357. return;
  358. }
  359. const key = taskKey(params);
  360. const activeRunId = activePromptInputIds.get(key);
  361. if (!activeRunId) {
  362. // 手机端 owner command 到达 host 时,task 可能已经终态收口。
  363. // 没有 active run 时不能再把旧 command 写入 host 队列,否则会在桌面 shared host 上误发旧输入。
  364. throw createTaskOwnerCommandError("No active task owner.", "NO_ACTIVE_TASK_OWNER");
  365. }
  366. if (activeRunId !== ownerRunId) {
  367. // ownerRunId 是远控请求的 stale 防护边界。
  368. // 旧 run 的 enqueue/promote 不能修改当前 task command queue。
  369. throw createTaskOwnerCommandError("Stale task owner command.", "STALE_TASK_OWNER_COMMAND");
  370. }
  371. }
  372. async function sendPromptToAgent(
  373. target: TaskTarget,
  374. params: {
  375. traceId: TraceId;
  376. queryId?: string;
  377. messageId?: string;
  378. content: string;
  379. attachments?: ZCodePromptAttachment[];
  380. toolDenylist?: string[];
  381. botDeliveryTarget?: ZCodeAutomationBotDeliveryTarget;
  382. clientId?: string;
  383. clientMode?: ZCodeTaskClientMode;
  384. logReason?: string;
  385. modelSelection?: CommandPayloadMap["sendText"]["modelSelection"];
  386. modelSelectionBasis?: CommandPayloadMap["sendText"]["modelSelectionBasis"];
  387. modelExecution?: CommandPayloadMap["sendText"]["modelExecution"];
  388. } & ZCodeBackgroundTurnAttribution,
  389. ): Promise<CommandAck | undefined> {
  390. const startedAt = Date.now();
  391. notifySyncerSession(target);
  392. // live tool projection 只用于当前运行的终态收口。
  393. // 新输入开始时必须清掉上一轮 live-only 子工具,避免后续 snapshot 把旧工具补到新回复尾部。
  394. clearLiveToolProjection(target);
  395. clearStreamingToolInputCache(target);
  396. // ZCode task wrapper 的字段仍叫 traceId,但这里语义已经是单次输入 inputId。
  397. // 先记录 inputId,后续 ZCode session 事件回投 ZCode Agent 时才能让 UI 终态按输入轮次收口。
  398. activePromptInputIds.set(taskKey(target), params.traceId);
  399. logger.info(params.traceId, "ZCode task facade sendPrompt 开始", {
  400. attachmentCount: params.attachments?.length ?? 0,
  401. queryId: params.queryId ?? null,
  402. reason: params.logReason ?? "direct",
  403. taskId: target.taskId,
  404. textLength: params.content.length,
  405. workspaceIdentity: target.workspaceIdentity ?? null,
  406. workspaceKey: resolveWorkspaceKey(target),
  407. workspacePath: target.workspacePath,
  408. });
  409. try {
  410. const promptToolDenylist = resolvePromptToolDenylist(params);
  411. // 附件旧路径没有 v4 ACK,保持 undefined。
  412. let ack: CommandAck | undefined;
  413. if (params.attachments?.length) {
  414. // 遗留(附件命令面):v4 sendText 的 attachments 是 attachmentRef 引用模型,
  415. // 上传/寄存命令面尚未建模(CLI 侧 fork-edit-retry.ts 同款裁决“附件命令面后续”)。
  416. // 带附件输入保留旧 session/send,避免手机 replayable 图片/文件输入回归;
  417. // 过渡归宿 = v4 附件命令面(届时由 v4 sendText 承接)。
  418. await options.zcodeAgentService.sendPrompt({
  419. workspacePath: target.workspacePath,
  420. workspaceIdentity: target.workspaceIdentity,
  421. ...(target.remoteSessionId ? { remoteSessionId: target.remoteSessionId } : {}),
  422. sessionId: target.taskId,
  423. inputId: params.traceId,
  424. queryId: params.queryId,
  425. messageId: params.messageId,
  426. content: params.content,
  427. attachments: params.attachments.map((attachment) => ({
  428. ...attachment,
  429. })),
  430. // 附件回退只改变载荷传输,不得丢掉本次已解析的模型或执行范围。
  431. modelSelection: params.modelSelection,
  432. modelSelectionBasis: params.modelSelectionBasis,
  433. modelExecution: params.modelExecution,
  434. ...turnAttributionOf(params),
  435. toolDenylist: promptToolDenylist,
  436. botDeliveryTarget: params.botDeliveryTarget,
  437. ...(params.clientMode ? { clientMode: params.clientMode } : {}),
  438. });
  439. } else {
  440. // send 主路径收敛 v4 sendText。幂等键 inputId→commandId 对齐:
  441. // CLI 侧以 commandId 为 inputId 起 turn,终态事件 inputId 才能与 host command
  442. // queue 的 traceId 对账(completeRuntimeCommandByInputId 语义不变)。
  443. // heldQueueDisposition=keepQueueAndSend:旧 session/send 没有 held choice 闸门,
  444. // replayable 无人机交互路径按“立即发送、不动队列”等价老语义。
  445. const sendAck = await options.zcodeAgentService.sendConversationCommandV4({
  446. workspacePath: target.workspacePath,
  447. workspaceIdentity: target.workspaceIdentity,
  448. ...(target.remoteSessionId ? { remoteSessionId: target.remoteSessionId } : {}),
  449. ...(params.clientMode ? { clientMode: params.clientMode } : {}),
  450. envelope: createHostCommandEnvelope({
  451. type: "sendText",
  452. payload: {
  453. text: params.content,
  454. heldQueueDisposition: "keepQueueAndSend",
  455. ...(params.modelSelection ? { modelSelection: params.modelSelection } : {}),
  456. ...(params.modelSelectionBasis
  457. ? { modelSelectionBasis: params.modelSelectionBasis }
  458. : {}),
  459. ...(params.modelExecution ? { modelExecution: params.modelExecution } : {}),
  460. ...turnAttributionOf(params),
  461. ...(params.botDeliveryTarget ? { botDeliveryTarget: params.botDeliveryTarget } : {}),
  462. ...(promptToolDenylist ? { toolDisallowlist: promptToolDenylist } : {}),
  463. },
  464. sessionId: target.taskId,
  465. commandId: params.traceId,
  466. clientId: params.clientId,
  467. }),
  468. });
  469. // 调用方需要区分 accepted 与 duplicate:duplicate 不会开新一轮,也没有终态事件。
  470. ack = assertV4CommandAckOk("sendText", sendAck, `session=${target.taskId}`);
  471. }
  472. logger.info(params.traceId, "ZCode task facade sendPrompt ACK", {
  473. ackStatus: ack?.status ?? null,
  474. durationMs: Date.now() - startedAt,
  475. queryId: params.queryId ?? null,
  476. reason: params.logReason ?? "direct",
  477. taskId: target.taskId,
  478. workspaceIdentity: target.workspaceIdentity ?? null,
  479. workspaceKey: resolveWorkspaceKey(target),
  480. workspacePath: target.workspacePath,
  481. });
  482. return ack;
  483. } catch (error) {
  484. activePromptInputIds.delete(taskKey(target));
  485. logger.warn(params.traceId, "ZCode task facade sendPrompt 失败", {
  486. durationMs: Date.now() - startedAt,
  487. error: error instanceof Error ? error.message : String(error),
  488. queryId: params.queryId ?? null,
  489. reason: params.logReason ?? "direct",
  490. taskId: target.taskId,
  491. workspaceIdentity: target.workspaceIdentity ?? null,
  492. workspaceKey: resolveWorkspaceKey(target),
  493. workspacePath: target.workspacePath,
  494. });
  495. throw error;
  496. }
  497. }
  498. function setRuntimeCommands(params: TaskTarget, commands: ZCodeTaskRuntimeCommand[]): void {
  499. const key = taskKey(params);
  500. if (commands.length === 0) {
  501. runtimeCommands.delete(key);
  502. return;
  503. }
  504. runtimeCommands.set(key, commands);
  505. }
  506. function markRuntimeCommandRunning(
  507. params: TaskTarget,
  508. command: ZCodeSendPromptRuntimeCommand,
  509. ): ZCodeSendPromptRuntimeCommand {
  510. const key = taskKey(params);
  511. const runningCommand: ZCodeSendPromptRuntimeCommand = {
  512. ...command,
  513. status: "running",
  514. updatedAt: Date.now(),
  515. };
  516. runtimeCommands.set(
  517. key,
  518. (runtimeCommands.get(key) ?? []).map((item) =>
  519. item.commandId === command.commandId ? runningCommand : item,
  520. ),
  521. );
  522. return runningCommand;
  523. }
  524. function markRuntimeCommandFailed(
  525. params: TaskTarget,
  526. command: ZCodeSendPromptRuntimeCommand,
  527. error: unknown,
  528. ): void {
  529. const key = taskKey(params);
  530. const failedCommand: ZCodeSendPromptRuntimeCommand = {
  531. ...command,
  532. status: "failed",
  533. updatedAt: Date.now(),
  534. error: error instanceof Error ? error.message : String(error),
  535. };
  536. runtimeCommands.set(
  537. key,
  538. (runtimeCommands.get(key) ?? []).map((item) =>
  539. item.commandId === command.commandId ? failedCommand : item,
  540. ),
  541. );
  542. }
  543. function removeRuntimeCommand(params: TaskTarget, commandId: string): void {
  544. setRuntimeCommands(
  545. params,
  546. (runtimeCommands.get(taskKey(params)) ?? []).filter(
  547. (command) => command.commandId !== commandId,
  548. ),
  549. );
  550. }
  551. function emitRuntimeCommandSnapshotUpdated(params: TaskTarget, traceId?: TraceId): void {
  552. emitTaskEvent(params, {
  553. type: "task_snapshot_updated",
  554. workspacePath: params.workspacePath,
  555. workspaceIdentity: params.workspaceIdentity,
  556. workspaceKey: workspaceKey(params),
  557. taskId: params.taskId,
  558. traceId: traceId ?? generateTraceId(params.taskId),
  559. reason: "task_status_changed",
  560. });
  561. }
  562. function completeRuntimeCommandByInputId(
  563. params: TaskTarget,
  564. terminalInputId: string | undefined,
  565. terminalType: string,
  566. ): void {
  567. if (!terminalInputId) {
  568. return;
  569. }
  570. const command = (runtimeCommands.get(taskKey(params)) ?? []).find(
  571. (candidate) =>
  572. candidate.type === "send_prompt" &&
  573. candidate.status === "running" &&
  574. candidate.traceId === terminalInputId,
  575. );
  576. if (!command) {
  577. return;
  578. }
  579. // 手机 host command 在 sendPrompt ACK 后仍要保持 running,
  580. // 否则手机刷新拿不到“已开始发送”的 pendingCommands。只有真实终态到达后才能从 host 队列移除。
  581. removeRuntimeCommand(params, command.commandId);
  582. logger.info(command.traceId, "ZCode task command 终态收口", {
  583. commandId: command.commandId,
  584. terminalType,
  585. taskId: params.taskId,
  586. workspaceIdentity: params.workspaceIdentity ?? null,
  587. workspaceKey: resolveWorkspaceKey(params),
  588. workspacePath: params.workspacePath,
  589. });
  590. }
  591. function completeRuntimeCommandForTerminalEvent(
  592. params: TaskTarget,
  593. event: ZCodeTerminalStreamEvent,
  594. ): void {
  595. completeRuntimeCommandByInputId(params, event.inputId ?? event.traceId, event.type);
  596. }
  597. async function drainRuntimeCommands(params: TaskTarget, reason: string): Promise<void> {
  598. const key = taskKey(params);
  599. if (activePromptInputIds.has(key)) {
  600. return;
  601. }
  602. const commands = runtimeCommands.get(key) ?? [];
  603. if (commands.some((command) => command.status === "running")) {
  604. return;
  605. }
  606. const command = commands.find(
  607. (candidate): candidate is ZCodeSendPromptRuntimeCommand =>
  608. candidate.type === "send_prompt" && candidate.status === "accepted",
  609. );
  610. if (!command) {
  611. return;
  612. }
  613. const runningCommand = markRuntimeCommandRunning(params, command);
  614. logger.info(runningCommand.traceId, "ZCode task command drain 开始", {
  615. commandId: runningCommand.commandId,
  616. queryId: runningCommand.queryId ?? null,
  617. reason,
  618. taskId: params.taskId,
  619. workspaceIdentity: params.workspaceIdentity ?? null,
  620. workspaceKey: resolveWorkspaceKey(params),
  621. workspacePath: params.workspacePath,
  622. });
  623. try {
  624. await sendPromptToAgent(params, {
  625. traceId: runningCommand.traceId,
  626. queryId: runningCommand.queryId,
  627. messageId: runningCommand.commandId,
  628. content: runningCommand.content,
  629. attachments: runningCommand.attachments,
  630. ...turnAttributionOf(
  631. runningCommand.automationId ? { automationId: runningCommand.automationId } : {},
  632. ),
  633. // v4 sendText 信封保留手机提交端 clientId(pendingCommands 展示与幂等表按提交端区分)。
  634. clientId: runningCommand.clientId,
  635. logReason: "host-command-drain",
  636. });
  637. } catch (error) {
  638. markRuntimeCommandFailed(params, runningCommand, error);
  639. logger.warn(runningCommand.traceId, "ZCode task command drain 失败", {
  640. commandId: runningCommand.commandId,
  641. error: error instanceof Error ? error.message : String(error),
  642. reason,
  643. taskId: params.taskId,
  644. workspaceIdentity: params.workspaceIdentity ?? null,
  645. workspaceKey: resolveWorkspaceKey(params),
  646. workspacePath: params.workspacePath,
  647. });
  648. }
  649. }
  650. async function drainRuntimeCommandsSafely(params: TaskTarget, reason: string): Promise<void> {
  651. try {
  652. await drainRuntimeCommands(params, reason);
  653. } catch (error) {
  654. logger.warn(undefined, "ZCode task command drain 调度失败", {
  655. error: error instanceof Error ? error.message : String(error),
  656. reason,
  657. taskId: params.taskId,
  658. workspaceIdentity: params.workspaceIdentity ?? null,
  659. workspaceKey: resolveWorkspaceKey(params),
  660. workspacePath: params.workspacePath,
  661. });
  662. }
  663. }
  664. function scheduleRuntimeCommandDrain(params: TaskTarget, reason: string): void {
  665. const key = taskKey(params);
  666. const existingDrain = runtimeCommandDrains.get(key);
  667. if (existingDrain) {
  668. const nextDrainPromise = existingDrain
  669. .finally(() => drainRuntimeCommandsSafely(params, reason))
  670. .finally(() => {
  671. if (runtimeCommandDrains.get(key) === nextDrainPromise) {
  672. runtimeCommandDrains.delete(key);
  673. }
  674. });
  675. runtimeCommandDrains.set(key, nextDrainPromise);
  676. return;
  677. }
  678. const drainPromise = (async () => {
  679. await drainRuntimeCommandsSafely(params, reason);
  680. })().finally(() => {
  681. if (runtimeCommandDrains.get(key) === drainPromise) {
  682. runtimeCommandDrains.delete(key);
  683. }
  684. });
  685. runtimeCommandDrains.set(key, drainPromise);
  686. }
  687. function getLiveToolProjectionMap(params: TaskTarget): Map<string, LiveToolProjection> {
  688. const key = taskKey(params);
  689. let projection = liveToolProjectionsByTaskKey.get(key);
  690. if (!projection) {
  691. projection = new Map<string, LiveToolProjection>();
  692. liveToolProjectionsByTaskKey.set(key, projection);
  693. while (liveToolProjectionsByTaskKey.size > MAX_LIVE_TOOL_PROJECTION_TASKS) {
  694. const oldestKey = liveToolProjectionsByTaskKey.keys().next().value;
  695. if (typeof oldestKey !== "string") break;
  696. liveToolProjectionsByTaskKey.delete(oldestKey);
  697. }
  698. }
  699. return projection;
  700. }
  701. function trimLiveToolProjectionMap(projection: Map<string, LiveToolProjection>): void {
  702. while (projection.size > MAX_LIVE_TOOL_PROJECTION_TOOLS_PER_TASK) {
  703. let oldestKey: string | undefined;
  704. let oldestOrder = Number.POSITIVE_INFINITY;
  705. for (const [toolId, item] of projection) {
  706. if (item.order < oldestOrder) {
  707. oldestOrder = item.order;
  708. oldestKey = toolId;
  709. }
  710. }
  711. if (!oldestKey) return;
  712. projection.delete(oldestKey);
  713. }
  714. }
  715. function clearLiveToolProjection(params: {
  716. workspacePath: string;
  717. workspaceIdentity?: string;
  718. taskId: string;
  719. }): void {
  720. liveToolProjectionsByTaskKey.delete(taskKey(params));
  721. }
  722. function normalizeLiveToolRaw(
  723. raw: unknown,
  724. toolId: string,
  725. parentToolUseId: string | null | undefined,
  726. ): unknown {
  727. const rawRecord = asRecord(raw);
  728. const rawBase =
  729. Object.keys(rawRecord).length > 0 ? rawRecord : raw === undefined ? {} : { raw };
  730. const parentFromRaw =
  731. stringValue(rawRecord.parentToolUseId) ??
  732. stringValue(rawRecord.parentToolCallId) ??
  733. parentToolUseId ??
  734. null;
  735. return {
  736. ...rawBase,
  737. toolCallId: stringValue(rawRecord.toolCallId) ?? toolId,
  738. ...(parentFromRaw
  739. ? {
  740. parentToolCallId: stringValue(rawRecord.parentToolCallId) ?? parentFromRaw,
  741. }
  742. : {}),
  743. };
  744. }
  745. function persistedStatusFromToolUpdate(
  746. status: Extract<ZCodeStreamEvent, { type: "tool_call_update" }>["status"],
  747. ): ZCodePersistedToolCall["status"] | undefined {
  748. return status === "completed" ||
  749. status === "failed" ||
  750. status === "denied" ||
  751. status === "stopped"
  752. ? status
  753. : undefined;
  754. }
  755. function rememberLiveToolProjection(params: TaskTarget, event: ZCodeStreamEvent): void {
  756. if (event.type !== "tool_call" && event.type !== "tool_call_update") {
  757. return;
  758. }
  759. const projection = getLiveToolProjectionMap(params);
  760. const existing = projection.get(event.toolId);
  761. const parentToolUseId = event.parentToolUseId ?? existing?.parentToolUseId ?? null;
  762. const raw = normalizeLiveToolRaw(event.raw, event.toolId, parentToolUseId);
  763. const nextTool: ZCodePersistedToolCall =
  764. event.type === "tool_call"
  765. ? {
  766. ...existing?.tool,
  767. toolName: event.toolName ?? existing?.tool.toolName,
  768. title: event.title ?? existing?.tool.title ?? event.toolName,
  769. kind: event.kind ?? existing?.tool.kind ?? event.toolName,
  770. input: event.input,
  771. raw,
  772. }
  773. : {
  774. ...existing?.tool,
  775. toolName: event.toolName ?? existing?.tool.toolName,
  776. title: event.title ?? existing?.tool.title ?? event.toolName ?? event.kind,
  777. kind: event.kind ?? existing?.tool.kind ?? event.toolName ?? existing?.tool.toolName,
  778. input: event.input !== undefined ? event.input : existing?.tool.input,
  779. output: event.content !== undefined ? event.content : existing?.tool.output,
  780. error: event.error ?? existing?.tool.error,
  781. raw,
  782. status: persistedStatusFromToolUpdate(event.status) ?? existing?.tool.status,
  783. };
  784. projection.set(event.toolId, {
  785. order: existing?.order ?? ++liveToolProjectionOrder,
  786. parentToolUseId,
  787. tool: nextTool,
  788. toolId: event.toolId,
  789. });
  790. trimLiveToolProjectionMap(projection);
  791. }
  792. function persistedToolId(tool: ZCodePersistedToolCall): string | undefined {
  793. return stringValue(asRecord(tool.raw).toolCallId);
  794. }
  795. function mergeToolRaw(snapshotRaw: unknown, liveRaw: unknown): unknown {
  796. const snapshotRecord = asRecord(snapshotRaw);
  797. const liveRecord = asRecord(liveRaw);
  798. if (Object.keys(snapshotRecord).length === 0) {
  799. return liveRaw;
  800. }
  801. if (Object.keys(liveRecord).length === 0) {
  802. return snapshotRaw;
  803. }
  804. return {
  805. ...liveRecord,
  806. ...snapshotRecord,
  807. parentToolCallId:
  808. stringValue(snapshotRecord.parentToolCallId) ?? stringValue(liveRecord.parentToolCallId),
  809. toolCallId: stringValue(snapshotRecord.toolCallId) ?? stringValue(liveRecord.toolCallId),
  810. };
  811. }
  812. function mergePersistedToolCall(
  813. snapshotTool: ZCodePersistedToolCall | undefined,
  814. liveTool: ZCodePersistedToolCall,
  815. ): ZCodePersistedToolCall {
  816. if (!snapshotTool) {
  817. return liveTool;
  818. }
  819. return {
  820. ...liveTool,
  821. ...snapshotTool,
  822. // 终态 snapshot 来自父 session message parts,可能没有 live mirror 的
  823. // subagent parentToolCallId/raw/output。这里把 snapshot 作为终态事实源,同时保留
  824. // live 协议事件已经提供的父子归属和大字段,避免 task_complete 后工具树被覆盖丢失。
  825. input: snapshotTool.input ?? liveTool.input,
  826. output: snapshotTool.output ?? liveTool.output,
  827. raw: mergeToolRaw(snapshotTool.raw, liveTool.raw),
  828. error: snapshotTool.error ?? liveTool.error,
  829. status: snapshotTool.status ?? liveTool.status,
  830. snapshotRefs: snapshotTool.snapshotRefs ?? liveTool.snapshotRefs,
  831. };
  832. }
  833. function findToolLocation(
  834. messages: readonly ZCodePersistedMessage[],
  835. toolId: string,
  836. ): { messageIndex: number; toolIndex: number } | null {
  837. for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {
  838. const message = messages[messageIndex];
  839. if (!message?.tools) continue;
  840. const toolIndex = message.tools.findIndex((tool) => persistedToolId(tool) === toolId);
  841. if (toolIndex >= 0) {
  842. return { messageIndex, toolIndex };
  843. }
  844. }
  845. return null;
  846. }
  847. function latestAssistantMessageIndex(messages: readonly ZCodePersistedMessage[]): number {
  848. for (let index = messages.length - 1; index >= 0; index -= 1) {
  849. if (messages[index]?.role === "assistant") {
  850. return index;
  851. }
  852. }
  853. return -1;
  854. }
  855. function upsertPersistedToolPart(
  856. parts: readonly ZCodePersistedMessagePart[] | undefined,
  857. toolIndex: number,
  858. ): ZCodePersistedMessagePart[] {
  859. if (parts?.some((part) => part.type === "tool-call" && part.toolIndex === toolIndex)) {
  860. return [...parts];
  861. }
  862. return [...(parts ?? []), { type: "tool-call", toolIndex }];
  863. }
  864. function updateSnapshotMessageTool(
  865. message: ZCodePersistedMessage,
  866. toolIndex: number,
  867. tool: ZCodePersistedToolCall,
  868. ): ZCodePersistedMessage {
  869. const tools = [...(message.tools ?? [])];
  870. tools[toolIndex] = mergePersistedToolCall(tools[toolIndex], tool);
  871. return {
  872. ...message,
  873. tools,
  874. parts:
  875. message.role === "assistant"
  876. ? upsertPersistedToolPart(message.parts, toolIndex)
  877. : message.parts,
  878. };
  879. }
  880. function appendSnapshotMessageTool(
  881. message: ZCodePersistedMessage,
  882. tool: ZCodePersistedToolCall,
  883. ): ZCodePersistedMessage {
  884. const tools = [...(message.tools ?? []), tool];
  885. const toolIndex = tools.length - 1;
  886. return {
  887. ...message,
  888. tools,
  889. parts:
  890. message.role === "assistant"
  891. ? upsertPersistedToolPart(message.parts, toolIndex)
  892. : message.parts,
  893. };
  894. }
  895. function mergeLiveToolProjectionIntoSnapshotMessages(
  896. meta: ZCodeTaskMeta,
  897. messages: ZCodePersistedMessage[],
  898. ): ZCodePersistedMessage[] {
  899. const projection = liveToolProjectionsByTaskKey.get(taskKey(meta));
  900. if (!projection || projection.size === 0 || messages.length === 0) {
  901. return messages;
  902. }
  903. let nextMessages = messages;
  904. let changed = false;
  905. let mergedToolCount = 0;
  906. const liveTools = [...projection.values()].sort((a, b) => a.order - b.order);
  907. for (const liveTool of liveTools) {
  908. const existingLocation = findToolLocation(nextMessages, liveTool.toolId);
  909. if (existingLocation) {
  910. nextMessages = nextMessages.map((message, index) =>
  911. index === existingLocation.messageIndex
  912. ? updateSnapshotMessageTool(message, existingLocation.toolIndex, liveTool.tool)
  913. : message,
  914. );
  915. changed = true;
  916. mergedToolCount += 1;
  917. continue;
  918. }
  919. const parentLocation = liveTool.parentToolUseId
  920. ? findToolLocation(nextMessages, liveTool.parentToolUseId)
  921. : null;
  922. const targetMessageIndex =
  923. parentLocation?.messageIndex ?? latestAssistantMessageIndex(nextMessages);
  924. if (targetMessageIndex < 0) {
  925. continue;
  926. }
  927. nextMessages = nextMessages.map((message, index) =>
  928. index === targetMessageIndex ? appendSnapshotMessageTool(message, liveTool.tool) : message,
  929. );
  930. changed = true;
  931. mergedToolCount += 1;
  932. }
  933. if (changed) {
  934. logger.debug(undefined, "ZCode snapshot 合并 live tool projection", {
  935. event: "zcode_task.snapshot.live_tool_projection.merged",
  936. liveToolCount: liveTools.length,
  937. mergedToolCount,
  938. taskId: meta.taskId,
  939. workspaceIdentity: meta.workspaceIdentity,
  940. workspacePath: meta.workspacePath,
  941. });
  942. }
  943. return changed ? nextMessages : messages;
  944. }
  945. function rememberTaskTarget(params: TaskTarget): void {
  946. const existing = taskTargets.get(params.taskId);
  947. taskTargets.set(params.taskId, {
  948. ...params,
  949. // cronAutomationId 是会话的 sticky 归属标记,供 UI 展示和任务关联使用,不参与当前
  950. // turn 的工具权限。resume/onDynamicTaskEvent 等入口不带值时仍需保留权威归属;明确设置
  951. // 或清除只能走 rememberIndexedTaskMeta。
  952. cronAutomationId: params.cronAutomationId ?? existing?.cronAutomationId,
  953. });
  954. }
  955. function getTaskTarget(taskId: string): TaskTarget {
  956. const target = taskTargets.get(taskId);
  957. if (!target) {
  958. throw Object.assign(new Error(`ZCode session target is not loaded: ${taskId}`), {
  959. code: "ZCODE_SESSION_TARGET_NOT_FOUND",
  960. });
  961. }
  962. return target;
  963. }
  964. function getToolProjectionMemory(params: TaskTarget): ZCodeToolProjectionMemory {
  965. const key = taskKey(params);
  966. let memory = toolProjectionMemoryByTaskKey.get(key);
  967. if (!memory) {
  968. memory = createZCodeToolProjectionMemory();
  969. toolProjectionMemoryByTaskKey.set(key, memory);
  970. }
  971. return memory;
  972. }
  973. function clearStreamingToolInputCache(params: TaskTarget): void {
  974. toolProjectionMemoryByTaskKey.get(taskKey(params))?.streamingToolInputById?.clear();
  975. }
  976. // Bugfix: workspace emitter 已上提到 syncer,adapter 通过 syncer 获取共享 emitter,
  977. // 保证 task adapter 路径和 desktop-continuous 路径走同一份订阅,UI 不会漏事件。
  978. function getWorkspaceEmitter(workspace: WorkspaceEventInput): Emitter<ZCodeWorkspaceEvent> {
  979. return taskIndexSyncer.getWorkspaceEmitter(workspace);
  980. }
  981. function getTaskEmitter(params: TaskTarget): Emitter<ZCodeStreamEvent> {
  982. const key = taskKey(params);
  983. let emitter = taskEmitters.get(key);
  984. if (!emitter) {
  985. emitter = new Emitter<ZCodeStreamEvent>();
  986. taskEmitters.set(key, emitter);
  987. }
  988. return emitter;
  989. }
  990. function getGlobalTaskEmitter(taskId: string): Emitter<ZCodeStreamEvent> {
  991. let emitter = globalTaskEmitters.get(taskId);
  992. if (!emitter) {
  993. emitter = new Emitter<ZCodeStreamEvent>();
  994. globalTaskEmitters.set(taskId, emitter);
  995. }
  996. return emitter;
  997. }
  998. function emitTaskEvent(params: TaskTarget, event: ZCodeStreamEvent): void {
  999. getTaskEmitter(params).fire(event);
  1000. getGlobalTaskEmitter(params.taskId).fire(event);
  1001. }
  1002. // 委托到 syncer,让 archive/rename/pin/delete 等 task 元数据变更和
  1003. // desktop-continuous 路径(turn.completed 等)走同一条广播通道。
  1004. // 设计修正:reason 必填,发射点必须声明变更类别。
  1005. function emitWorkspaceTaskListChanged(
  1006. params: {
  1007. workspacePath: string;
  1008. workspaceIdentity?: string;
  1009. taskId?: string;
  1010. },
  1011. taskMeta: ZCodeTaskMeta | undefined,
  1012. reason: ZCodeWorkspaceTaskListChanged["reason"],
  1013. ) {
  1014. taskIndexSyncer.emitWorkspaceTaskListChanged(params, taskMeta, reason);
  1015. }
  1016. function emitWorkspaceConfig(
  1017. params: ZCodeAgentWorkspaceTarget,
  1018. settings: ZCodeSessionSettingsState,
  1019. ) {
  1020. getWorkspaceEmitter(params).fire({
  1021. type: "workspace_config_options_update",
  1022. workspacePath: params.workspacePath,
  1023. workspaceIdentity: params.workspaceIdentity,
  1024. configOptions: settingsToConfigOptions(settings),
  1025. });
  1026. }
  1027. async function resumeSnapshot(
  1028. params: TaskTargetWithMcpServers,
  1029. ): Promise<ZCodeSessionStateSnapshot> {
  1030. rememberTaskTarget(params);
  1031. const thoughtLevel = params.thoughtLevel?.trim();
  1032. const mcpServers = await resolveProductMcpServers(params.mcpServers);
  1033. return options.zcodeAgentService.resumeSession({
  1034. workspacePath: params.workspacePath,
  1035. workspaceIdentity: params.workspaceIdentity,
  1036. sessionId: params.taskId,
  1037. ...(params.additionalDirectories !== undefined
  1038. ? { additionalDirectories: params.additionalDirectories }
  1039. : {}),
  1040. // Bugfix: replayable 手机端恢复仍经 task adapter,但 stale model guard 在
  1041. // session resume 内执行;这里带上当前 UI 模型,避免只保护 desktop continuous 主链路。
  1042. model: params.model ? parseModelPickerValue(params.model) : undefined,
  1043. ...(thoughtLevel ? { thoughtLevel } : {}),
  1044. ...(mcpServers ? { mcpServers } : {}),
  1045. ...(params.toolDenylist ? { toolDenylist: params.toolDenylist } : {}),
  1046. });
  1047. }
  1048. /**
  1049. * 会话级配置写(模型/思考深度/模式)的 v4 CAS 命令提交。
  1050. * host 无本地 v4 投影,revision 用 stale ACK 的 revisionAtDecision 收敛(sendHostCasCommandV4)。
  1051. * 注意与 compact/goal 标注同一坑位:旧协议 stateRevision 与 v4 conversation revision
  1052. * 是两套计数器,这里全程只用 v4 ACK 回报的 revision,绝不混入旧 expectedRevision。
  1053. */
  1054. async function sendConfigCasCommandV4<T extends "switchModelConfig" | "switchCollaborationMode">(
  1055. target: TaskTarget,
  1056. type: T,
  1057. payload: CommandPayloadMap[T],
  1058. contextMessage: string,
  1059. ): Promise<void> {
  1060. await sendHostCasCommandV4({
  1061. send: (envelope) =>
  1062. options.zcodeAgentService.sendConversationCommandV4({
  1063. workspacePath: target.workspacePath,
  1064. workspaceIdentity: target.workspaceIdentity,
  1065. envelope,
  1066. }),
  1067. type,
  1068. payload,
  1069. sessionId: target.taskId,
  1070. contextMessage,
  1071. });
  1072. }
  1073. /**
  1074. * session/setMode → v4 switchCollaborationMode。
  1075. * auto 例外保真:v4 命令值域刻意排除 auto(「auto 非用户可切,不进 UI 命令面」,
  1076. * command.ts 裁决),而旧协议 ZCodeSessionMode 含 auto 且旧 op 接受它——为 UI 行为
  1077. * 零变化,auto 继续走旧 op,其余值一律 v4 原生。过渡归宿 = auto 语义在 v4 侧裁决后收口。
  1078. */
  1079. async function switchCollaborationModeViaProtocol(
  1080. target: TaskTarget,
  1081. mode: ZCodeSessionMode,
  1082. ): Promise<void> {
  1083. if (mode === "auto") {
  1084. await options.zcodeAgentService.setMode({
  1085. workspacePath: target.workspacePath,
  1086. workspaceIdentity: target.workspaceIdentity,
  1087. sessionId: target.taskId,
  1088. mode,
  1089. });
  1090. return;
  1091. }
  1092. await sendConfigCasCommandV4(
  1093. target,
  1094. "switchCollaborationMode",
  1095. { mode },
  1096. `session=${target.taskId} mode=${mode}`,
  1097. );
  1098. }
  1099. async function repairEmptyImportedClaudeSnapshot(
  1100. params: TaskTargetWithMcpServers,
  1101. snapshot: ZCodeSessionStateSnapshot,
  1102. ): Promise<ZCodeSessionStateSnapshot> {
  1103. const repaired = await repairImportedClaudeSessionSnapshot({
  1104. snapshot,
  1105. target: params,
  1106. createSession: (input) => options.zcodeAgentService.createSession(input),
  1107. onRepair: (history) => {
  1108. logger.warn(
  1109. undefined,
  1110. `Claude 导入 protocol session 历史异常,按 ${history.source} 回填 taskId=${params.taskId}`,
  1111. );
  1112. },
  1113. });
  1114. if (!repaired) {
  1115. return snapshot;
  1116. }
  1117. const meta = await syncTaskIndexSnapshot(repaired);
  1118. await updateIndexedPresentation({ ...meta, migrationSource: "claudeCode" });
  1119. return repaired;
  1120. }
  1121. function isSessionMissingError(error: unknown): boolean {
  1122. const message = error instanceof Error ? error.message : String(error ?? "");
  1123. return /\bSession (not found|is not active):/i.test(message);
  1124. }
  1125. async function readLegacyTaskSnapshot(params: TaskTarget): Promise<ZCodeTaskSnapshot | null> {
  1126. const paths = [
  1127. getLegacyTaskSessionSnapshotPath(
  1128. params.workspacePath,
  1129. params.taskId,
  1130. params.workspaceIdentity,
  1131. ),
  1132. getLegacyDeletedTaskSessionSnapshotPath(
  1133. params.workspacePath,
  1134. params.taskId,
  1135. params.workspaceIdentity,
  1136. ),
  1137. ];
  1138. const snapshotPath = paths.find((path) => existsSync(path));
  1139. if (!snapshotPath) {
  1140. return null;
  1141. }
  1142. try {
  1143. const rawSnapshot = JSON.parse(readFileSync(snapshotPath, "utf-8")) as unknown;
  1144. const parsed = safeParseLegacyTaskSessionFile(rawSnapshot);
  1145. if (!parsed.success) {
  1146. logger.warn(
  1147. undefined,
  1148. `读取 legacy task snapshot 非法 taskId=${params.taskId}`,
  1149. parsed.error.flatten(),
  1150. );
  1151. return null;
  1152. }
  1153. const legacyFile = parsed.data;
  1154. const indexedMeta = await taskIndexRepo.getTaskMeta(params).catch(() => null);
  1155. const legacyMeta: ZCodeTaskMeta = {
  1156. ...legacyFile.meta,
  1157. // Bugfix: 旧 ACP task 只落在 ~/.zcode/v2/sessions/*.json,没有写入
  1158. // zcode-cli 的 sqlite session 表。新协议 resume 会把 taskId 当 sessionId
  1159. // 直接报 Session not found;这里按旧快照恢复只读历史内容,并用 task index
  1160. // 补齐用户改名、归档状态和终态 status,避免把旧 task 误当成可订阅的新 session。
  1161. taskId: params.taskId,
  1162. workspacePath: params.workspacePath,
  1163. workspaceIdentity: params.workspaceIdentity ?? legacyFile.meta.workspaceIdentity,
  1164. title: indexedMeta?.title ?? legacyFile.meta.title,
  1165. updatedAt: indexedMeta?.updatedAt ?? legacyFile.meta.updatedAt,
  1166. mode: legacyFile.meta.mode ?? indexedMeta?.mode ?? "default",
  1167. provider: legacyFile.meta.provider ?? indexedMeta?.provider ?? GLM_PROVIDER,
  1168. status: legacyFile.meta.status ?? indexedMeta?.status ?? "completed",
  1169. lastError: legacyFile.meta.lastError ?? indexedMeta?.lastError,
  1170. };
  1171. const snapshot: ZCodeTaskSnapshot = {
  1172. ...legacyFile,
  1173. meta: {
  1174. ...legacyMeta,
  1175. ...(indexedMeta ? { title: indexedMeta.title, unreadAt: indexedMeta.unreadAt } : {}),
  1176. },
  1177. runtime: {
  1178. apiRetry: apiRetryByTaskKey.get(taskKey(params)) ?? null,
  1179. pendingCommands: runtimeCommands.get(taskKey(params)) ?? [],
  1180. },
  1181. };
  1182. legacySnapshotTaskKeys.add(taskKey(params));
  1183. rememberIndexedTaskMeta(snapshot.meta);
  1184. return snapshot;
  1185. } catch (error) {
  1186. logger.warn(undefined, `读取 legacy task snapshot 失败 taskId=${params.taskId}`, error);
  1187. return null;
  1188. }
  1189. }
  1190. async function resumeSnapshotOrLegacy(
  1191. params: TaskTargetWithMcpServers,
  1192. ): Promise<
  1193. | { kind: "session"; snapshot: ZCodeSessionStateSnapshot }
  1194. | { kind: "legacy"; snapshot: ZCodeTaskSnapshot }
  1195. > {
  1196. try {
  1197. const snapshot = await resumeSnapshot(params);
  1198. return {
  1199. kind: "session",
  1200. snapshot: await repairEmptyImportedClaudeSnapshot(params, snapshot),
  1201. };
  1202. } catch (error) {
  1203. if (!isSessionMissingError(error)) {
  1204. throw error;
  1205. }
  1206. const legacySnapshot = await readLegacyTaskSnapshot(params);
  1207. if (!legacySnapshot) {
  1208. throw error;
  1209. }
  1210. if (legacySnapshot.meta.migrationSource === "claudeCode") {
  1211. try {
  1212. const mcpServers = await resolveProductMcpServers(params.mcpServers);
  1213. const snapshot = await options.zcodeAgentService.createSession({
  1214. workspacePath: params.workspacePath,
  1215. workspaceIdentity: params.workspaceIdentity,
  1216. sessionId: params.taskId,
  1217. sessionTraceId: legacySnapshot.meta.traceId ?? createSessionTraceId(),
  1218. persistence: "immediate",
  1219. model: params.model ? parseModelPickerValue(params.model) : undefined,
  1220. ...(mcpServers ? { mcpServers } : {}),
  1221. ...(params.toolDenylist ? { toolDenylist: params.toolDenylist } : {}),
  1222. importedHistory: {
  1223. source: "claudeCode",
  1224. title: legacySnapshot.meta.title,
  1225. createdAt: legacySnapshot.meta.createdAt,
  1226. updatedAt: legacySnapshot.meta.updatedAt,
  1227. messages: legacySnapshot.messages.map((message) => ({
  1228. role: message.role,
  1229. content: message.content,
  1230. timestamp: message.timestamp,
  1231. })),
  1232. },
  1233. });
  1234. const meta = await syncTaskIndexSnapshot(snapshot);
  1235. await updateIndexedPresentation({ ...meta, migrationSource: "claudeCode" });
  1236. logger.info(
  1237. undefined,
  1238. `legacy Claude 导入 task 已升级为 ZCode session taskId=${params.taskId}`,
  1239. );
  1240. return { kind: "session", snapshot };
  1241. } catch (upgradeError) {
  1242. logger.warn(
  1243. undefined,
  1244. `legacy Claude 导入 task 升级为 ZCode session 失败,继续只读恢复 taskId=${params.taskId}`,
  1245. upgradeError,
  1246. );
  1247. }
  1248. }
  1249. logger.warn(
  1250. undefined,
  1251. `ZCode Protocol session 缺失,已按 legacy task snapshot 恢复 taskId=${params.taskId}`,
  1252. error,
  1253. );
  1254. return { kind: "legacy", snapshot: legacySnapshot };
  1255. }
  1256. }
  1257. function snapshotToMeta(snapshot: ZCodeSessionStateSnapshot): ZCodeTaskMeta {
  1258. const target = {
  1259. taskId: snapshot.session.sessionId,
  1260. workspacePath: snapshot.session.workspace.workspacePath,
  1261. workspaceIdentity: snapshot.session.workspace.workspaceIdentity,
  1262. };
  1263. rememberTaskTarget(target);
  1264. return {
  1265. taskId: snapshot.session.sessionId,
  1266. traceId: snapshot.session.traceId ?? generateTraceId(snapshot.session.sessionId),
  1267. title: deriveTitleFromSnapshot(snapshot),
  1268. workspacePath: snapshot.session.workspace.workspacePath,
  1269. workspaceIdentity: snapshot.session.workspace.workspaceIdentity,
  1270. createdAt: snapshot.session.createdAt,
  1271. updatedAt: snapshot.session.updatedAt,
  1272. mode: fromZCodeMode(snapshot.session.mode),
  1273. model: formatTaskMetaModelSelectionFromSnapshot(snapshot),
  1274. thoughtLevel: snapshot.settings.thoughtLevel.current,
  1275. provider: GLM_PROVIDER,
  1276. status: deriveZCodeTaskStatusFromSessionSnapshot(snapshot),
  1277. lastError: snapshot.projection.lastError
  1278. ? {
  1279. code: snapshot.projection.lastError.code ?? snapshot.projection.lastError.type,
  1280. ...(snapshot.projection.lastError.detail
  1281. ? { detail: snapshot.projection.lastError.detail }
  1282. : {}),
  1283. // 修复原因:service snapshot 是 mobile replayable/cold task meta 的来源,不能
  1284. // 让它与 UI 直接投影的 lastError 产生归因漂移。
  1285. ...(snapshot.projection.lastError.attribution
  1286. ? { attribution: snapshot.projection.lastError.attribution }
  1287. : {}),
  1288. message: snapshot.projection.lastError.message,
  1289. }
  1290. : undefined,
  1291. target: snapshot.projection.target
  1292. ? fromZCodeGoal(snapshot.projection.target)
  1293. : snapshot.projection.target,
  1294. };
  1295. }
  1296. function rememberIndexedTaskMeta(meta: ZCodeTaskMeta): ZCodeTaskMeta {
  1297. const existing = taskTargets.get(meta.taskId);
  1298. // 权威归属刷新:index meta 是唯一可以设置/清除 cronAutomationId 的来源,直接以 meta 为准
  1299. // 写入(绕过 rememberTaskTarget 的 merge-preserve),以便解绑/删除 automation 后能真正清空。
  1300. taskTargets.set(meta.taskId, {
  1301. ...existing,
  1302. taskId: meta.taskId,
  1303. workspacePath: meta.workspacePath,
  1304. workspaceIdentity: meta.workspaceIdentity,
  1305. cronAutomationId: meta.cronAutomationId,
  1306. });
  1307. return meta;
  1308. }
  1309. async function resolveTaskIndexResumeHints(
  1310. params: TaskTarget,
  1311. reason: "replayable_snapshot" | "resume_task",
  1312. ): Promise<{ model?: string; thoughtLevel?: string }> {
  1313. const meta = await taskIndexRepo.getTaskMeta(params).catch((error) => {
  1314. logger.warn(undefined, "读取 task index resume hint 失败,继续不带历史配置恢复", {
  1315. error: error instanceof Error ? error.message : String(error),
  1316. reason,
  1317. taskId: params.taskId,
  1318. workspaceIdentity: params.workspaceIdentity ?? null,
  1319. workspacePath: params.workspacePath,
  1320. });
  1321. return null;
  1322. });
  1323. const model = meta?.model?.trim();
  1324. const thoughtLevel = meta?.thoughtLevel?.trim();
  1325. if (model || thoughtLevel) {
  1326. // task-local thoughtLevel 和 model 一样属于历史 session 恢复 hint。
  1327. // 不回填 thoughtLevel 时,同 workspace 的 draft 默认值会在 session/resume 后覆盖 active task。
  1328. logger.info(undefined, "从 task index 回填 ZCode session resume 配置", {
  1329. model: model || null,
  1330. thoughtLevel: thoughtLevel || null,
  1331. reason,
  1332. taskId: params.taskId,
  1333. workspaceIdentity: params.workspaceIdentity ?? null,
  1334. workspacePath: params.workspacePath,
  1335. });
  1336. }
  1337. return {
  1338. ...(model ? { model } : {}),
  1339. ...(thoughtLevel ? { thoughtLevel } : {}),
  1340. };
  1341. }
  1342. async function updateIndexedPresentation(meta: ZCodeTaskMeta): Promise<ZCodeTaskMeta> {
  1343. const {
  1344. mode,
  1345. model,
  1346. thoughtLevel,
  1347. lastError,
  1348. target,
  1349. migrationSource,
  1350. cronAutomationId,
  1351. offPeakTaskId,
  1352. } = meta;
  1353. const presentation = Object.fromEntries(
  1354. Object.entries({
  1355. mode,
  1356. model,
  1357. thoughtLevel,
  1358. lastError,
  1359. target,
  1360. migrationSource,
  1361. cronAutomationId,
  1362. offPeakTaskId,
  1363. }).filter(([, value]) => value !== undefined),
  1364. );
  1365. const indexedMeta = await taskIndexRepo.updateTaskPresentation({ ...meta, presentation });
  1366. return rememberIndexedTaskMeta(indexedMeta ?? meta);
  1367. }
  1368. async function syncTaskIndexSnapshot(
  1369. snapshot: ZCodeSessionStateSnapshot,
  1370. broadcastReason: ZCodeWorkspaceTaskListChanged["reason"] | null = "task_status_changed",
  1371. ): Promise<ZCodeTaskMeta> {
  1372. if (isAuxiliarySessionKind(snapshot.session.sessionKind)) return snapshotToMeta(snapshot);
  1373. return rememberIndexedTaskMeta(
  1374. await taskIndexSyncer.syncSnapshotAndBroadcast(snapshot, {
  1375. broadcastReason,
  1376. }),
  1377. );
  1378. }
  1379. async function updateIndexedTaskState(
  1380. params: TaskTarget,
  1381. patch: { pinned?: boolean; archived?: boolean; unreadAt?: number },
  1382. ): Promise<ZCodeTaskMeta> {
  1383. return taskIndexRepo.updateTaskState({
  1384. workspacePath: params.workspacePath,
  1385. workspaceIdentity: params.workspaceIdentity,
  1386. taskId: params.taskId,
  1387. patch,
  1388. });
  1389. }
  1390. function updateTaskApiRetryFromStreamEvent(params: TaskTarget, event: ZCodeStreamEvent): void {
  1391. const key = taskKey(params);
  1392. if (event.type === "session_info_update" && event.apiRetry !== undefined) {
  1393. apiRetryByTaskKey.set(key, event.apiRetry ?? null);
  1394. return;
  1395. }
  1396. if (event.type === "task_complete" || event.type === "task_error") {
  1397. apiRetryByTaskKey.set(key, null);
  1398. }
  1399. }
  1400. function hasActiveTaskApiRetry(params: TaskTarget): boolean {
  1401. return apiRetryByTaskKey.get(taskKey(params)) != null;
  1402. }
  1403. function snapshotToZCode(
  1404. snapshot: ZCodeSessionStateSnapshot,
  1405. options?: { includeEmptyPendingElicitations?: boolean },
  1406. ): ZCodeTaskSnapshot {
  1407. const meta = snapshotToMeta(snapshot);
  1408. const activeGoalIterationCount = getSnapshotGoalActiveIterationCount(snapshot);
  1409. const goalIterationByAssistantMessageId = getZCodeGoalIterationByAssistantMessageId(
  1410. snapshot.messages,
  1411. {
  1412. ...(activeGoalIterationCount > 0 ? { maxGoalIteration: activeGoalIterationCount } : {}),
  1413. target: snapshot.projection.target,
  1414. },
  1415. );
  1416. const backgroundTaskNotifications = collectZCodeBackgroundTaskNotificationsByToolUseId(
  1417. snapshot.messages,
  1418. );
  1419. const messages = mergeLiveToolProjectionIntoSnapshotMessages(
  1420. meta,
  1421. normalizeGoalVerificationTimelineMessageOrder(
  1422. addGoalVerificationTimelineSnapshotFallback(
  1423. addSessionForkSnapshotFallback(
  1424. coalesceConsecutiveZCodeAssistants(
  1425. getZCodeUserVisibleMessages(snapshot.messages, {
  1426. target: snapshot.projection.target,
  1427. }).map((message) =>
  1428. mapMessage(
  1429. message,
  1430. message.info.role === "assistant"
  1431. ? goalIterationByAssistantMessageId.get(message.info.messageId)
  1432. : undefined,
  1433. backgroundTaskNotifications,
  1434. ),
  1435. ),
  1436. ),
  1437. snapshot,
  1438. ),
  1439. snapshot,
  1440. ),
  1441. ),
  1442. );
  1443. const pendingPermissions: ZCodePermissionRequest[] = snapshot.projection.pendingPermissions
  1444. .filter((permission) => !isUserInputBackedPermissionToolName(permission.toolName))
  1445. .map((permission) => pendingPermissionToStreamEvent(snapshot.session.sessionId, permission));
  1446. const pendingElicitations = snapshot.projection.pendingPermissions
  1447. .filter((permission) => isUserInputBackedPermissionToolName(permission.toolName))
  1448. .map((permission) =>
  1449. pendingUserInputBackedPermissionToElicitationEvent(snapshot.session.sessionId, permission),
  1450. )
  1451. .filter(
  1452. (event): event is Extract<ZCodeStreamEvent, { type: "elicitation_request" }> =>
  1453. event !== null,
  1454. );
  1455. const backgroundTaskControls = parseZCodeBackgroundTaskControlItems(
  1456. snapshot.projection.backgroundJobs,
  1457. );
  1458. setTaskBackgroundTaskControlCache(
  1459. backgroundTaskControlsByTaskKey,
  1460. taskKey(meta),
  1461. backgroundTaskControls,
  1462. );
  1463. return {
  1464. meta,
  1465. messages,
  1466. fileChanges: [],
  1467. configOptions: settingsToConfigOptions(snapshot.settings),
  1468. // agent 协议 snapshot 含有 `/compact` 等命令;task facade 投影时必须保留,
  1469. // 否则 replayable/legacy task restore 会把 UI 的 slashCommands 回填成空。
  1470. slashCommands: snapshot.slashCommands ?? EMPTY_SLASH_COMMANDS,
  1471. runtime: {
  1472. activeTurnKind: snapshot.runtime.activeTurnKind,
  1473. apiRetry: apiRetryByTaskKey.get(taskKey(meta)) ?? null,
  1474. contextUsage:
  1475. contextUsageFromRuntime(snapshot.runtime.contextUsage) ??
  1476. contextUsageFromProjection(snapshot.projection) ??
  1477. undefined,
  1478. pendingPermissions,
  1479. backgroundBashJobs: backgroundTaskControls,
  1480. // 手机 replayable 快照需要用空数组表达“用户输入队列已清空”。
  1481. // desktop-continuous 主链路仍保持原投影形态,避免把 replayable 的集合恢复语义扩散过去。
  1482. ...(pendingElicitations.length > 0 || options?.includeEmptyPendingElicitations
  1483. ? { pendingElicitations }
  1484. : {}),
  1485. pendingCommands: runtimeCommands.get(taskKey(meta)) ?? [],
  1486. // todo 的权威数据在 agent DB;历史恢复时必须随 snapshot 映射给 UI,
  1487. // 不能只依赖 renderer 运行期收到过的 plan stream event。
  1488. plan: sessionTodosToPlanSteps(snapshot.todos),
  1489. goalStats: sessionGoalStatsToRuntime(snapshot.goalStats),
  1490. goalVerifications: snapshot.runtime.goalVerifications ?? null,
  1491. goalVerificationTimeline: snapshot.runtime.goalVerificationTimeline ?? null,
  1492. todoGroups: sessionTodoGroupsToRuntime(snapshot.todoGroups),
  1493. },
  1494. };
  1495. }
  1496. function mapServiceEvent(params: TaskTarget, event: ZCodeAgentServiceEvent): void {
  1497. if (event.type === "snapshot") {
  1498. void syncTaskIndexSnapshot(event.snapshot).catch((error) => {
  1499. logger.warn(undefined, "同步 ZCode snapshot 到 task index 失败", error);
  1500. });
  1501. const snapshotEvent: ZCodeStreamEvent = {
  1502. type: "task_snapshot_updated",
  1503. workspacePath: params.workspacePath,
  1504. workspaceIdentity: params.workspaceIdentity,
  1505. workspaceKey: workspaceKey(params),
  1506. taskId: params.taskId,
  1507. traceId: generateTraceId(params.taskId),
  1508. };
  1509. emitTaskEvent(params, snapshotEvent);
  1510. emitWorkspaceConfig(params, event.snapshot.settings);
  1511. return;
  1512. }
  1513. if (event.type === "state.updated") {
  1514. for (const streamEvent of mapStateUpdated(params, event.notification)) {
  1515. emitTaskEvent(params, streamEvent);
  1516. }
  1517. return;
  1518. }
  1519. if (event.type === "permission.request") {
  1520. emitTaskEvent(params, permissionRequestToStreamEvent(params.taskId, event.request));
  1521. return;
  1522. }
  1523. if (event.type === "userInput.request") {
  1524. emitTaskEvent(params, userInputRequestToElicitationStreamEvent(params.taskId, event.request));
  1525. return;
  1526. }
  1527. if (event.type === "userInput.response") {
  1528. emitTaskEvent(
  1529. params,
  1530. userInputResponseToElicitationStreamEvent(params.taskId, event.requestId, event.response),
  1531. );
  1532. return;
  1533. }
  1534. if (event.type === "providerRuntimeHeaders.request") {
  1535. return;
  1536. }
  1537. if (event.type === "session.event") {
  1538. recordAgentModelNetworkTelemetry(event.event);
  1539. if (event.event.type === "turn.started") {
  1540. const payload = asRecord(event.event.payload);
  1541. const inputId = stringValue(payload.inputId);
  1542. if (inputId) {
  1543. // remote/replayable/fallback 订阅不一定由 sendPrompt 建立。
  1544. // turn.started 是后续 model.streaming 事件归属当前输入的协议事实,必须在 services 投影层同步记录。
  1545. activePromptInputIds.set(taskKey(params), inputId);
  1546. }
  1547. }
  1548. }
  1549. const activePromptInputId = activePromptInputIds.get(taskKey(params));
  1550. const streamEvents = mapSessionEvent(
  1551. params,
  1552. event.event,
  1553. streamedTurnText,
  1554. activePromptInputId,
  1555. getToolProjectionMemory(params),
  1556. backgroundTaskControlsByTaskKey,
  1557. hasActiveTaskApiRetry(params),
  1558. );
  1559. for (const streamEvent of streamEvents) {
  1560. rememberLiveToolProjection(params, streamEvent);
  1561. updateTaskApiRetryFromStreamEvent(params, streamEvent);
  1562. emitTaskEvent(params, streamEvent);
  1563. if (streamEvent.type === "task_complete" || streamEvent.type === "task_error") {
  1564. completeRuntimeCommandForTerminalEvent(params, streamEvent);
  1565. }
  1566. }
  1567. if (event.event.type === "turn.completed" || event.event.type === "turn.failed") {
  1568. activePromptInputIds.delete(taskKey(params));
  1569. }
  1570. }
  1571. let disposed = false;
  1572. function handleTaskIndexTerminalEvent(event: ZCodeTaskIndexTerminalEvent): void {
  1573. const params: TaskTarget = {
  1574. taskId: event.target.sessionId,
  1575. workspacePath: event.target.workspacePath,
  1576. workspaceIdentity: event.target.workspaceIdentity,
  1577. };
  1578. const key = taskKey(params);
  1579. if (!activePromptInputIds.has(key) && !runtimeCommands.has(key)) {
  1580. return;
  1581. }
  1582. // 终态事件源换成 v4 sessions-index 的 phase 迁移,摘要不携带 inputId,
  1583. // 一律用本地记录的 active input 收口(旧协议 payload.inputId 缺失时的兜底路径,语义不变)。
  1584. const terminalInputId = activePromptInputIds.get(key);
  1585. completeRuntimeCommandByInputId(params, terminalInputId, event.kind);
  1586. // turn 终态只说明 stream 收口已到,不代表 agent server 的 active lock 已释放。
  1587. // 这里仅收口当前 input;下一条 host command 必须等 ready 事件触发。
  1588. activePromptInputIds.delete(key);
  1589. }
  1590. const taskIndexTerminalDisposable = taskIndexSyncer.onSessionTerminalEvent((event) => {
  1591. queueMicrotask(() => {
  1592. if (!disposed) {
  1593. handleTaskIndexTerminalEvent(event);
  1594. }
  1595. });
  1596. });
  1597. function handleTaskIndexReadyEvent(event: ZCodeTaskIndexReadyEvent): void {
  1598. const params: TaskTarget = {
  1599. taskId: event.target.sessionId,
  1600. workspacePath: event.target.workspacePath,
  1601. workspaceIdentity: event.target.workspaceIdentity,
  1602. };
  1603. const key = taskKey(params);
  1604. if (!activePromptInputIds.has(key) && !runtimeCommands.has(key)) {
  1605. return;
  1606. }
  1607. const activeInputId = activePromptInputIds.get(key);
  1608. completeRuntimeCommandByInputId(params, activeInputId, event.reason);
  1609. // prompt_completed/prompt_failed 由 agent server 在释放 activeAbortController 后发出。
  1610. // 手机 host command queue 以它作为“下一条可以发送”的 ready 边界,避免 fixed delay 重试,
  1611. // 也不改变桌面 continuous 的 renderer-local queue。
  1612. activePromptInputIds.delete(key);
  1613. scheduleRuntimeCommandDrain(params, "session-ready");
  1614. }
  1615. const taskIndexReadyDisposable = taskIndexSyncer.onSessionReadyEvent((event) => {
  1616. queueMicrotask(() => {
  1617. if (!disposed) {
  1618. handleTaskIndexReadyEvent(event);
  1619. }
  1620. });
  1621. });
  1622. function disposeLocalTaskState(): void {
  1623. taskIndexTerminalDisposable.dispose();
  1624. taskIndexReadyDisposable.dispose();
  1625. taskIndexRepo.close();
  1626. for (const emitter of taskEmitters.values()) emitter.dispose();
  1627. for (const emitter of globalTaskEmitters.values()) emitter.dispose();
  1628. errorEmitter.dispose();
  1629. taskEmitters.clear();
  1630. globalTaskEmitters.clear();
  1631. runtimeCommandDrains.clear();
  1632. streamedTurnText.clear();
  1633. }
  1634. async function disposeZCodeAgentServiceAndWait(): Promise<void> {
  1635. const agentService = options.zcodeAgentService as IZCodeAgentService & {
  1636. disposeAllAndWait?: () => Promise<void>;
  1637. };
  1638. if (agentService.disposeAllAndWait) {
  1639. await agentService.disposeAllAndWait();
  1640. return;
  1641. }
  1642. agentService.disposeAll();
  1643. }
  1644. const service: IZCodeTaskService & {
  1645. disposeAll(): void;
  1646. disposeAllAndWait(): Promise<void>;
  1647. } = {
  1648. async initialize(params) {
  1649. const result = await options.zcodeAgentService.initialize(params);
  1650. return {
  1651. available: result.available,
  1652. version: result.protocolName
  1653. ? `${result.protocolName}/${result.protocolVersion ?? 1}`
  1654. : undefined,
  1655. };
  1656. },
  1657. async releaseWorkspacePreparation(params): Promise<void> {
  1658. await options.zcodeAgentService.disposeWorkspace({
  1659. ...normalizeWorkspaceParams(params),
  1660. releasePreparation: true,
  1661. });
  1662. },
  1663. async checkCodexConnectivity(): Promise<ZCodeCodexConnectivityCheckResult> {
  1664. return { target: "zcode-agent", reachable: true };
  1665. },
  1666. async createTask(params): Promise<ZCodeTaskCreateResult> {
  1667. const target = normalizeWorkspaceParams(params);
  1668. const requestedSelection =
  1669. params.modelSelection ??
  1670. (params.model
  1671. ? {
  1672. ...parseModelPickerValue(params.model),
  1673. ...(params.thoughtLevel ? { options: { reasoningLevel: params.thoughtLevel } } : {}),
  1674. }
  1675. : undefined);
  1676. const mcpServers = await resolveProductMcpServers(params.mcpServers);
  1677. let snapshot: ZCodeSessionStateSnapshot;
  1678. // M5 ③-2 评估标注(生命周期 op,不迁):v4 createSession 命令已原生(desktop
  1679. // v4 UI 在用),但 replayable createTask 需要 mcpServers/model/importedHistory
  1680. // 载荷与 snapshot 返回值(task index 同步依赖),v4 命令面均未建模;
  1681. // 迁移属 ③-3/波次 3 生命周期收口。
  1682. if (params.v4Create === true) {
  1683. const model = requestedSelection;
  1684. const ack = assertV4CommandAckOk(
  1685. "createSession",
  1686. await options.zcodeAgentService.sendConversationCommandV4({
  1687. ...target,
  1688. projectId: params.projectId ?? null,
  1689. envelope: createHostCommandEnvelope({
  1690. type: "createSession",
  1691. sessionId: null,
  1692. payload: {
  1693. workspaceId: target.workspaceIdentity?.trim() || target.workspacePath,
  1694. ...(params.additionalDirectories !== undefined
  1695. ? { additionalDirectories: params.additionalDirectories }
  1696. : {}),
  1697. ...(params.permissionScope ? { permissionScope: params.permissionScope } : {}),
  1698. config: {
  1699. ...(model ? { provider: model.providerId, model: model.modelId } : {}),
  1700. ...(model?.options?.reasoningLevel
  1701. ? { thought: model.options.reasoningLevel }
  1702. : {}),
  1703. ...(params.mode ? { mode: toZCodeMode(params.mode) } : {}),
  1704. },
  1705. ...(mcpServers ? { mcpServers } : {}),
  1706. },
  1707. }),
  1708. }),
  1709. `workspace=${target.workspacePath}`,
  1710. );
  1711. const sessionId = ack.result?.type === "createSession" ? ack.result.sessionId : undefined;
  1712. if (!sessionId) {
  1713. throw new Error("v4 createSession accepted without sessionId result");
  1714. }
  1715. snapshot = await options.zcodeAgentService.readSession({
  1716. ...target,
  1717. sessionId,
  1718. });
  1719. } else {
  1720. snapshot = await options.zcodeAgentService.createSession({
  1721. ...target,
  1722. projectId: params.projectId ?? null,
  1723. additionalDirectories: params.additionalDirectories,
  1724. sessionTraceId: createSessionTraceId(),
  1725. mode: toZCodeMode(params.mode),
  1726. model: requestedSelection,
  1727. thoughtLevel: requestedSelection?.options?.reasoningLevel,
  1728. ...(params.automationId || params.deferPersistenceUntilFirstPrompt
  1729. ? {
  1730. // 修复原因:automation / 闲时任务新建空 session 后会立即 sendText。session_input 有
  1731. // session 外键,必须让 V4 admission 在首发前统一持久化 session 主记录;
  1732. // 否则 create 返回成功后第一条 prompt 会稳定触发 FOREIGN KEY constraint failed。
  1733. persistence: "deferred" as const,
  1734. }
  1735. : {}),
  1736. ...(params.automationId
  1737. ? {
  1738. titleGenerationEnabled: false,
  1739. }
  1740. : {}),
  1741. // Bugfix: replayable task facade 创建 session 时同样会启动 runtime;
  1742. // 之前这里丢掉 mcpServers,导致手机远控路径和 desktop-continuous 的 MCP 行为不一致。
  1743. mcpServers,
  1744. });
  1745. }
  1746. const baseMeta = await syncTaskIndexSnapshot(snapshot, null);
  1747. const meta = await updateIndexedPresentation({
  1748. ...baseMeta,
  1749. ...(params.automationId ? { cronAutomationId: params.automationId } : {}),
  1750. // 闲时派发在创建时即盖章持久归属;月亮图标与后续系统分组归属都只看该标记。
  1751. ...(params.offPeakTaskId ? { offPeakTaskId: params.offPeakTaskId } : {}),
  1752. });
  1753. notifySyncerSession({
  1754. taskId: meta.taskId,
  1755. workspacePath: meta.workspacePath,
  1756. workspaceIdentity: meta.workspaceIdentity,
  1757. });
  1758. emitWorkspaceConfig(target, snapshot.settings);
  1759. // 手机端通过 shared-host 创建 task 时,桌面 renderer 没有本地乐观插入。
  1760. // create 事件必须保留 task_created 语义,否则 UI 会按普通 meta 事件只重排已存在项,远控首页就拿不到新任务。
  1761. emitWorkspaceTaskListChanged(target, meta, "task_created");
  1762. // task 创建结果需要携带 agent 协议快照里的命令列表;否则 replayable 首屏会覆盖为空。
  1763. return {
  1764. ...meta,
  1765. initialSlashCommands: snapshot.slashCommands ?? EMPTY_SLASH_COMMANDS,
  1766. };
  1767. },
  1768. async readBotTopicSummaries(params) {
  1769. const target = taskTargets.get(params.taskId);
  1770. if (target && taskKey(target) !== taskKey(params))
  1771. throw new Error("Topic task workspace mismatch");
  1772. const messages = await options.zcodeAgentService.readSessionMessages({
  1773. workspacePath: params.workspacePath,
  1774. workspaceIdentity: params.workspaceIdentity,
  1775. remoteSessionId: params.remoteSessionId ?? target?.remoteSessionId,
  1776. sessionId: params.taskId,
  1777. limit: 200,
  1778. });
  1779. return messages
  1780. .flatMap(({ info, parts }) => {
  1781. if (info.role !== "user" || info.source !== "bot_topic_context") return [];
  1782. return [
  1783. {
  1784. checkpoint: String(info.metadata?.checkpoint ?? ""),
  1785. text:
  1786. typeof info.metadata?.displayText === "string"
  1787. ? info.metadata.displayText
  1788. : textFromParts(parts),
  1789. },
  1790. ];
  1791. })
  1792. .slice(-20);
  1793. },
  1794. async invalidateBotTopicInputs(params) {
  1795. const target = getTaskTarget(params.taskId);
  1796. if (taskKey(target) !== taskKey(params)) throw new Error("Group task workspace mismatch");
  1797. const key = JSON.stringify([
  1798. taskKey(params),
  1799. params.remoteSessionId ?? target.remoteSessionId ?? null,
  1800. ]);
  1801. await topicAdmission.invalidate(key);
  1802. },
  1803. async readBotTopicExecution(params) {
  1804. const target = getTaskTarget(params.taskId);
  1805. if (taskKey(target) !== taskKey(params)) throw new Error("Group task workspace mismatch");
  1806. const workspace = {
  1807. ...params,
  1808. remoteSessionId: params.remoteSessionId ?? target.remoteSessionId,
  1809. };
  1810. const snapshot = await readBotGroupRuntimeSnapshot(botAgent(workspace), {
  1811. ...workspace,
  1812. sessionId: params.taskId,
  1813. });
  1814. if (snapshot.control.stopState === "idle") return undefined;
  1815. const execution = snapshot.control.activeWorks.find((work) => work.foregroundExecutionId);
  1816. if (!execution?.foregroundExecutionId)
  1817. throw new Error("Topic execution identity is unavailable");
  1818. return {
  1819. executionId: execution.foregroundExecutionId,
  1820. sourceCommandId: execution.sourceCommandId,
  1821. };
  1822. },
  1823. async stopBotTopicExecution(params) {
  1824. const target = getTaskTarget(params.taskId);
  1825. if (taskKey(target) !== taskKey(params)) throw new Error("Group task workspace mismatch");
  1826. const workspace = {
  1827. workspacePath: params.workspacePath,
  1828. workspaceIdentity: params.workspaceIdentity,
  1829. remoteSessionId: params.remoteSessionId ?? target.remoteSessionId,
  1830. };
  1831. const agent = botAgent(workspace);
  1832. // 先注册终态监听再停止,避免快速结束发生在 ACK 与订阅之间。
  1833. const observation = new AbortController();
  1834. const ended = waitBotGroupExecutionEnd(
  1835. agent,
  1836. { ...workspace, sessionId: params.taskId },
  1837. params.executionId,
  1838. observation.signal,
  1839. );
  1840. void ended.catch(() => undefined);
  1841. try {
  1842. const ack = await agent.sendConversationCommandV4({
  1843. ...workspace,
  1844. envelope: createHostCommandEnvelope({
  1845. type: "stop",
  1846. sessionId: params.taskId,
  1847. payload: { expectedForegroundExecutionId: params.executionId },
  1848. }),
  1849. });
  1850. assertV4CommandAckOk("stop", ack, `session=${params.taskId}`);
  1851. await ended;
  1852. } finally {
  1853. observation.abort();
  1854. }
  1855. },
  1856. async getBotGroupTaskBlockReason(params) {
  1857. const target = taskTargets.get(params.taskId);
  1858. if (target && taskKey(target) !== taskKey({ ...params, taskId: params.taskId }))
  1859. throw new Error("Group task workspace mismatch");
  1860. const snapshot = await readBotGroupRuntimeSnapshot(botAgent(params), {
  1861. ...params,
  1862. ...((params.remoteSessionId ?? target?.remoteSessionId)
  1863. ? { remoteSessionId: params.remoteSessionId ?? target?.remoteSessionId }
  1864. : {}),
  1865. sessionId: params.taskId,
  1866. });
  1867. if (snapshot.pendingInteractions.length > 0) return "interaction";
  1868. if (snapshot.control.phase === "running" || snapshot.control.phase === "prewarming")
  1869. return "running";
  1870. if (snapshot.queue.items.length > 0) return "queued";
  1871. return null;
  1872. },
  1873. async cancelBotGroupInput(params) {
  1874. const target = getTaskTarget(params.taskId);
  1875. if (
  1876. params.workspacePath &&
  1877. taskKey(target) !== taskKey({ ...params, workspacePath: params.workspacePath })
  1878. )
  1879. throw new Error("Group task workspace mismatch");
  1880. const workspace = {
  1881. workspacePath: params.workspacePath ?? target.workspacePath,
  1882. workspaceIdentity: params.workspaceIdentity ?? target.workspaceIdentity,
  1883. ...((params.remoteSessionId ?? target.remoteSessionId)
  1884. ? { remoteSessionId: params.remoteSessionId ?? target.remoteSessionId }
  1885. : {}),
  1886. };
  1887. const snapshot = await readBotGroupRuntimeSnapshot(botAgent(workspace), {
  1888. ...workspace,
  1889. sessionId: target.taskId,
  1890. });
  1891. const item = snapshot.queue.items.find(
  1892. (entry) => entry.sourceCommandId === params.sourceCommandId,
  1893. );
  1894. if (!item || item.dispatch.state !== "queued") throw new Error("Input is no longer queued");
  1895. const source = item.botGroupSource;
  1896. if (
  1897. !source ||
  1898. source.botId !== params.botId ||
  1899. source.chatId !== params.chatId ||
  1900. (params.actorId !== params.ownerId && source.senderId !== params.actorId)
  1901. )
  1902. throw new Error("Queue cancellation is not authorized");
  1903. return botAgent(workspace).sendConversationCommandV4({
  1904. ...workspace,
  1905. envelope: createHostCommandEnvelope({
  1906. type: "deleteQueueItem",
  1907. sessionId: target.taskId,
  1908. commandId: params.commandId,
  1909. baseRevision: snapshot.revision,
  1910. payload: { queueItemId: item.queueItemId },
  1911. }),
  1912. });
  1913. },
  1914. async submitBotGroupInput(params) {
  1915. const target = getTaskTarget(params.taskId);
  1916. if (
  1917. params.workspacePath &&
  1918. taskKey(target) !== taskKey({ ...params, workspacePath: params.workspacePath })
  1919. )
  1920. throw new Error("Group task workspace mismatch");
  1921. const workspace = {
  1922. workspacePath: params.workspacePath ?? target.workspacePath,
  1923. workspaceIdentity: params.workspaceIdentity ?? target.workspaceIdentity,
  1924. ...((params.remoteSessionId ?? target.remoteSessionId)
  1925. ? { remoteSessionId: params.remoteSessionId ?? target.remoteSessionId }
  1926. : {}),
  1927. };
  1928. const admissionKey = JSON.stringify([
  1929. taskKey({ ...workspace, taskId: target.taskId }),
  1930. workspace.remoteSessionId ?? null,
  1931. ]);
  1932. const version = topicAdmission.capture(admissionKey);
  1933. // Bug 原因:Host 重启后任务索引仍在,但 CLI 尚未加载原会话;直接 admission
  1934. // 会返回 sessionNotFound。复用后台订阅的冷恢复屏障,不依赖 Desktop 打开任务。
  1935. await readBotGroupRuntimeSnapshot(botAgent(workspace), {
  1936. ...workspace,
  1937. sessionId: target.taskId,
  1938. });
  1939. const attachments = await uploadBotGroupAttachments(
  1940. botAgent(workspace),
  1941. { ...workspace, sessionId: target.taskId },
  1942. params.attachments ?? [],
  1943. );
  1944. // 停止可以发生在附件上传期间;完成上传不代表旧输入仍允许被接受。
  1945. if (params.source.threadId && version !== topicAdmission.capture(admissionKey)) {
  1946. throw new Error("Topic input was cancelled during preparation");
  1947. }
  1948. const envelope = createHostCommandEnvelope({
  1949. type: "sendText",
  1950. sessionId: target.taskId,
  1951. commandId: params.commandId,
  1952. clientId: formatBotInputClientId(params.source),
  1953. payload: {
  1954. text: params.content,
  1955. attachments,
  1956. requestedDelivery: params.source.threadId ? "startNow" : "queue",
  1957. botGroupSource: params.source,
  1958. conversationQuotes: params.conversationQuotes,
  1959. botDeliveryTarget: {
  1960. provider: params.source.provider,
  1961. botId: params.source.botId,
  1962. providerUserId: params.source.chatId,
  1963. chatType: "group",
  1964. ...(params.source.threadId
  1965. ? { threadId: params.source.threadId, rootMessageId: params.source.rootMessageId }
  1966. : {}),
  1967. },
  1968. },
  1969. });
  1970. const send = async () => {
  1971. try {
  1972. return await botAgent(workspace).sendConversationCommandV4({
  1973. ...workspace,
  1974. envelope,
  1975. });
  1976. } catch (error) {
  1977. // ACK 丢失时查询同一个命令,不能生成新 ID 重发输入。
  1978. const query = await botAgent(workspace)
  1979. .queryConversationCommandsV4({
  1980. ...workspace,
  1981. commands: [{ sessionId: target.taskId, commandId: params.commandId }],
  1982. })
  1983. .catch(() => null);
  1984. const result = query?.results[0]?.result;
  1985. if (result && result !== "unknown") return result;
  1986. throw error;
  1987. }
  1988. };
  1989. return params.source.threadId ? topicAdmission.run(admissionKey, version, send) : send();
  1990. },
  1991. async sendPrompt(params): Promise<CommandAck | undefined> {
  1992. const storedTarget = getTaskTarget(params.taskId);
  1993. const target = {
  1994. ...storedTarget,
  1995. ...(params.remoteSessionId ? { remoteSessionId: params.remoteSessionId } : {}),
  1996. };
  1997. return sendPromptToAgent(target, {
  1998. traceId: params.traceId,
  1999. queryId: params.queryId,
  2000. messageId: params.messageId,
  2001. content: params.content,
  2002. attachments: params.attachments,
  2003. ...turnAttributionOf(params),
  2004. toolDenylist: params.toolDenylist,
  2005. botDeliveryTarget: params.botDeliveryTarget,
  2006. clientId: params.clientId,
  2007. clientMode: params.clientMode,
  2008. modelSelection: params.modelSelection,
  2009. modelExecution: params.modelExecution,
  2010. });
  2011. },
  2012. async deliverSessionMessage(
  2013. _request: SessionMessageSendRequested,
  2014. ): Promise<SessionMessageDeliveryResult> {
  2015. unsupported("deliverSessionMessage");
  2016. },
  2017. async sendSessionMessageDeliveryResult(): Promise<void> {
  2018. unsupported("sendSessionMessageDeliveryResult");
  2019. },
  2020. async enqueueTaskCommand(params): Promise<ZCodeEnqueueTaskCommandResult> {
  2021. assertCurrentOwnerRun(params, params.ownerRunId);
  2022. const workspaceKeyValue = workspaceKey(params);
  2023. const command: ZCodeTaskRuntimeCommand = {
  2024. commandId: params.commandId,
  2025. taskId: params.taskId,
  2026. traceId: params.traceId,
  2027. queryId: params.queryId,
  2028. workspacePath: params.workspacePath,
  2029. workspaceIdentity: params.workspaceIdentity,
  2030. workspaceKey: workspaceKeyValue,
  2031. status: "accepted",
  2032. createdAt: Date.now(),
  2033. updatedAt: Date.now(),
  2034. clientId: params.clientId,
  2035. clientLabel: params.clientLabel,
  2036. type: "send_prompt",
  2037. content: params.content,
  2038. attachments: params.attachments,
  2039. // manual run / 手机 replayable 的 prompt 可能先进入 host command queue;
  2040. // 若这里丢 automationId,drain 时会按普通用户输入发送,CronCreate 会重新暴露。
  2041. automationId: params.automationId,
  2042. };
  2043. const key = taskKey(params);
  2044. runtimeCommands.set(key, [...(runtimeCommands.get(key) ?? []), command]);
  2045. // 手机 replayable host command 被 accepted 后,前端本地 drain 会主动跳过 hostCommand。
  2046. // 因此 host 需要在当前 task 已空闲时自行触发消费;桌面 continuous 不调用该入口,不会受影响。
  2047. scheduleRuntimeCommandDrain(params, "enqueue");
  2048. return { accepted: true, command };
  2049. },
  2050. async promoteTaskCommand(params): Promise<ZCodeEnqueueTaskCommandResult> {
  2051. assertCurrentOwnerRun(params, params.ownerRunId);
  2052. const key = taskKey(params);
  2053. const commands = runtimeCommands.get(key) ?? [];
  2054. const command = commands.find((candidate) => candidate.commandId === params.commandId);
  2055. if (!command) {
  2056. throw Object.assign(new Error("Task command not found."), {
  2057. code: "OWNER_COMMAND_FAILED",
  2058. });
  2059. }
  2060. if (command.status === "running") {
  2061. return { accepted: true, command };
  2062. }
  2063. const nextCommand = {
  2064. ...command,
  2065. status: "accepted" as const,
  2066. updatedAt: Date.now(),
  2067. };
  2068. runtimeCommands.set(key, [nextCommand, ...commands.filter((item) => item !== command)]);
  2069. scheduleRuntimeCommandDrain(params, "promote");
  2070. return { accepted: true, command: nextCommand };
  2071. },
  2072. async cancelTaskCommand(params): Promise<ZCodeCancelTaskCommandResult> {
  2073. assertCurrentOwnerRun(params, params.ownerRunId);
  2074. const key = taskKey(params);
  2075. const commands = runtimeCommands.get(key) ?? [];
  2076. const command = commands.find((candidate) => candidate.commandId === params.commandId);
  2077. if (!command) {
  2078. logger.info(undefined, "ZCode task command 取消时已不存在", {
  2079. commandId: params.commandId,
  2080. taskId: params.taskId,
  2081. workspaceIdentity: params.workspaceIdentity ?? null,
  2082. workspaceKey: resolveWorkspaceKey(params),
  2083. workspacePath: params.workspacePath,
  2084. });
  2085. return {
  2086. canceled: true,
  2087. commandId: params.commandId,
  2088. reason: "not_found",
  2089. };
  2090. }
  2091. if (command.status === "running") {
  2092. logger.info(command.traceId, "ZCode task command 已开始运行,跳过取消", {
  2093. commandId: command.commandId,
  2094. taskId: params.taskId,
  2095. workspaceIdentity: params.workspaceIdentity ?? null,
  2096. workspaceKey: resolveWorkspaceKey(params),
  2097. workspacePath: params.workspacePath,
  2098. });
  2099. return {
  2100. canceled: false,
  2101. commandId: command.commandId,
  2102. reason: "already_running",
  2103. status: command.status,
  2104. };
  2105. }
  2106. // 手机 replayable 队列的事实源在 host runtime command queue。
  2107. // 删除按钮不能只清 renderer 本地 store,否则下一次 snapshot 会把已 accepted 的命令恢复回来。
  2108. setRuntimeCommands(
  2109. params,
  2110. commands.filter((item) => item.commandId !== command.commandId),
  2111. );
  2112. emitRuntimeCommandSnapshotUpdated(params, command.traceId);
  2113. logger.info(command.traceId, "ZCode task command 已取消", {
  2114. commandId: command.commandId,
  2115. status: command.status,
  2116. taskId: params.taskId,
  2117. workspaceIdentity: params.workspaceIdentity ?? null,
  2118. workspaceKey: resolveWorkspaceKey(params),
  2119. workspacePath: params.workspacePath,
  2120. });
  2121. return {
  2122. canceled: true,
  2123. commandId: command.commandId,
  2124. status: command.status,
  2125. };
  2126. },
  2127. async stopGeneration(params): Promise<void> {
  2128. const startedAt = Date.now();
  2129. const target = params.workspacePath
  2130. ? {
  2131. taskId: params.taskId,
  2132. workspacePath: params.workspacePath,
  2133. workspaceIdentity: params.workspaceIdentity,
  2134. }
  2135. : getTaskTarget(params.taskId);
  2136. logger.info(params.runId, "ZCode task facade stopGeneration 开始", {
  2137. hasRunId: Boolean(params.runId),
  2138. taskId: params.taskId,
  2139. workspaceIdentity: target.workspaceIdentity ?? null,
  2140. workspaceKey: resolveWorkspaceKey(target),
  2141. workspacePath: target.workspacePath,
  2142. });
  2143. // session/stop → v4 stop 命令(goal-pause barrier 语义由 CLI 原生 handler 承接)。
  2144. const ack = await options.zcodeAgentService.sendConversationCommandV4({
  2145. workspacePath: target.workspacePath,
  2146. workspaceIdentity: target.workspaceIdentity,
  2147. envelope: createHostCommandEnvelope({
  2148. type: "stop",
  2149. // 话题停止必须保留已观察到的执行身份;日志 traceId 不能替代 CLI 执行身份。
  2150. payload: params.expectedForegroundExecutionId
  2151. ? { expectedForegroundExecutionId: params.expectedForegroundExecutionId }
  2152. : {},
  2153. sessionId: params.taskId,
  2154. }),
  2155. });
  2156. assertV4CommandAckOk("stop", ack, `session=${params.taskId}`);
  2157. logger.info(params.runId, "ZCode task facade stopGeneration ACK", {
  2158. durationMs: Date.now() - startedAt,
  2159. taskId: params.taskId,
  2160. workspaceIdentity: target.workspaceIdentity ?? null,
  2161. workspaceKey: resolveWorkspaceKey(target),
  2162. workspacePath: target.workspacePath,
  2163. });
  2164. },
  2165. async compactSession(params) {
  2166. // v4 compact 是 CAS 命令(必带 v4 conversation revision
  2167. // 的 baseRevision),而本 facade 的 expectedRevision 是旧协议 stateRevision——
  2168. // 两套计数器不可互换;replayable 侧拿到 v4 revision 前强行迁移会造成假 stale。
  2169. // 且 v4 compact 无 instructions/runtimeModel 载荷。
  2170. const target = params.workspacePath
  2171. ? {
  2172. taskId: params.taskId,
  2173. workspacePath: params.workspacePath,
  2174. workspaceIdentity: params.workspaceIdentity,
  2175. }
  2176. : getTaskTarget(params.taskId);
  2177. notifySyncerSession(target);
  2178. if (params.inputId) {
  2179. activePromptInputIds.set(taskKey(target), params.inputId);
  2180. }
  2181. try {
  2182. const result = await options.zcodeAgentService.compactSession({
  2183. workspacePath: target.workspacePath,
  2184. workspaceIdentity: target.workspaceIdentity,
  2185. sessionId: params.taskId,
  2186. inputId: params.inputId,
  2187. instructions: params.instructions,
  2188. expectedRevision: params.expectedRevision,
  2189. });
  2190. if (result.compact?.state === "accepted") {
  2191. return result;
  2192. }
  2193. const meta = await syncTaskIndexSnapshot(result.snapshot);
  2194. // compact 收敛是状态同步,不涉及归属;缺省 task_meta_changed 会触发全局 membership 重拉。
  2195. emitWorkspaceTaskListChanged(target, meta, "task_status_changed");
  2196. activePromptInputIds.delete(taskKey(target));
  2197. return result;
  2198. } catch (error) {
  2199. activePromptInputIds.delete(taskKey(target));
  2200. throw error;
  2201. }
  2202. },
  2203. async goalSession(params) {
  2204. // v4 sendGoalCommand 只覆盖 set 语义(text 原文),
  2205. // 本 facade 的 action=resume/clear/replace/status 依赖旧 op 的结构化 action 面
  2206. // (v4 侧 resumeGoal 是 CAS 命令,revision 计数器问题同 compactSession)。
  2207. // 过渡归宿 = replayable v4 读路径收口,与 compactSession 同批。
  2208. const startedAt = Date.now();
  2209. const target = params.workspacePath
  2210. ? {
  2211. taskId: params.taskId,
  2212. workspacePath: params.workspacePath,
  2213. workspaceIdentity: params.workspaceIdentity,
  2214. }
  2215. : getTaskTarget(params.taskId);
  2216. notifySyncerSession(target);
  2217. const mayStartContinuation =
  2218. params.action === "set" || params.action === "replace" || params.action === "resume";
  2219. if (mayStartContinuation) {
  2220. // goal resume 也可能启动新一轮模型输出,不能继承上一轮 live-only 工具。
  2221. clearLiveToolProjection(target);
  2222. clearStreamingToolInputCache(target);
  2223. }
  2224. if (params.inputId && mayStartContinuation) {
  2225. activePromptInputIds.set(taskKey(target), params.inputId);
  2226. }
  2227. logger.info(params.inputId, "[zcode-task-service] goalSession start", {
  2228. action: params.action,
  2229. hasObjective: Boolean(params.objective?.trim()),
  2230. mayStartContinuation,
  2231. taskId: params.taskId,
  2232. workspaceIdentity: target.workspaceIdentity,
  2233. workspacePath: target.workspacePath,
  2234. });
  2235. const result = await options.zcodeAgentService.goalSession({
  2236. workspacePath: target.workspacePath,
  2237. workspaceIdentity: target.workspaceIdentity,
  2238. sessionId: params.taskId,
  2239. inputId: params.inputId,
  2240. action: params.action,
  2241. objective: params.objective,
  2242. expectedRevision: params.expectedRevision,
  2243. });
  2244. logger.info(params.inputId, "[zcode-task-service] goalSession agent 返回", {
  2245. action: params.action,
  2246. durationMs: Date.now() - startedAt,
  2247. responseLength: result.response?.length ?? 0,
  2248. startedTurn: result.startedTurn,
  2249. status: result.snapshot.session.status,
  2250. taskId: params.taskId,
  2251. workspaceIdentity: target.workspaceIdentity,
  2252. workspacePath: target.workspacePath,
  2253. });
  2254. const syncStartedAt = Date.now();
  2255. const meta = await syncTaskIndexSnapshot(result.snapshot);
  2256. // goal 动作后的快照收敛同为状态同步,不涉及归属,避免全局 membership 重拉。
  2257. emitWorkspaceTaskListChanged(target, meta, "task_status_changed");
  2258. logger.info(params.inputId, "[zcode-task-service] goalSession task index 同步完成", {
  2259. action: params.action,
  2260. durationMs: Date.now() - startedAt,
  2261. startedTurn: result.startedTurn,
  2262. status: result.snapshot.session.status,
  2263. syncDurationMs: Date.now() - syncStartedAt,
  2264. taskId: params.taskId,
  2265. workspaceIdentity: target.workspaceIdentity,
  2266. workspacePath: target.workspacePath,
  2267. });
  2268. if (!mayStartContinuation || result.snapshot.session.status !== "running") {
  2269. activePromptInputIds.delete(taskKey(target));
  2270. }
  2271. return result;
  2272. },
  2273. async respondPermission(params): Promise<boolean> {
  2274. const target = params.workspacePath
  2275. ? {
  2276. taskId: params.taskId,
  2277. workspacePath: params.workspacePath,
  2278. workspaceIdentity: params.workspaceIdentity,
  2279. }
  2280. : getTaskTarget(params.taskId);
  2281. // permission 回执收敛 v4 resolveInteraction。
  2282. // interactionId ≡ 业务 requestId(CLI interaction-broker 同源注册);optionId 由
  2283. // CLI 侧 buildProtocolPermissionOptions 精确回映 response(allow_project 的
  2284. // permissionUpdates 持久化规则不丢,见 interaction-broker v4AnswerToPermissionResponse)。
  2285. const ack = await options.zcodeAgentService.sendConversationCommandV4({
  2286. workspacePath: target.workspacePath,
  2287. workspaceIdentity: target.workspaceIdentity,
  2288. envelope: createHostCommandEnvelope({
  2289. type: "resolveInteraction",
  2290. payload: {
  2291. interactionId: params.requestId,
  2292. answer: { optionId: params.optionId },
  2293. },
  2294. sessionId: params.taskId,
  2295. }),
  2296. });
  2297. assertV4CommandAckOk("resolveInteraction", ack, `permission ${params.requestId}`);
  2298. return true;
  2299. },
  2300. async respondElicitation(params): Promise<boolean> {
  2301. const target = params.workspacePath
  2302. ? {
  2303. taskId: params.taskId,
  2304. workspacePath: params.workspacePath,
  2305. workspaceIdentity: params.workspaceIdentity,
  2306. }
  2307. : getTaskTarget(params.taskId);
  2308. // AskUserQuestion/plan-approval 回执收敛 v4 resolveInteraction。
  2309. // answer.action/content 是 additive 扩展(多题答案/注解无损承载,CLI 侧
  2310. // interaction-broker 优先按 action 精确映射,缺省回落 optionId/freeText 兼容路径)。
  2311. const ack = await options.zcodeAgentService.sendConversationCommandV4({
  2312. workspacePath: target.workspacePath,
  2313. workspaceIdentity: target.workspaceIdentity,
  2314. envelope: createHostCommandEnvelope({
  2315. type: "resolveInteraction",
  2316. payload: {
  2317. interactionId: params.requestId,
  2318. answer: {
  2319. action: params.action,
  2320. ...(params.content ? { content: params.content } : {}),
  2321. },
  2322. },
  2323. sessionId: params.taskId,
  2324. }),
  2325. });
  2326. assertV4CommandAckOk("resolveInteraction", ack, `elicitation ${params.requestId}`);
  2327. if (params.clientMode === "web-remote-replayable") {
  2328. // 语义保真(原 agentService.respondUserInput 的 web-remote-replayable 分支):
  2329. // 手机远控应答后,桌面/其它 observer 需要显式响应事件清理同一 requestId 的弹窗;
  2330. // v4 命令路径不再经过旧 respondUserInput,这里由 adapter 本地补投同一事件。
  2331. emitTaskEvent(
  2332. target,
  2333. userInputResponseToElicitationStreamEvent(params.taskId, params.requestId, {
  2334. action: params.action,
  2335. content: params.content,
  2336. }),
  2337. );
  2338. }
  2339. return true;
  2340. },
  2341. async resumeTask(params): Promise<ZCodeTaskMeta> {
  2342. // v4 侧 resume 已走 subscribe 冷恢复钩子
  2343. // (CLI cold-resume),但 replayable resumeTask 还承担 model/thoughtLevel 回填与
  2344. // snapshot→task index 正文索引回源,旧 resumeSession op 保留到 v4 生命周期收口。
  2345. const explicitModel = params.model?.trim();
  2346. const explicitThoughtLevel = params.thoughtLevel?.trim();
  2347. const indexHints =
  2348. explicitModel && explicitThoughtLevel
  2349. ? {}
  2350. : await resolveTaskIndexResumeHints(params, "resume_task");
  2351. const model = explicitModel || indexHints.model;
  2352. const thoughtLevel = explicitThoughtLevel || indexHints.thoughtLevel;
  2353. const restored = await resumeSnapshotOrLegacy({
  2354. taskId: params.taskId,
  2355. workspacePath: params.workspacePath,
  2356. workspaceIdentity: params.workspaceIdentity,
  2357. model,
  2358. thoughtLevel,
  2359. mcpServers: params.mcpServers,
  2360. additionalDirectories: params.additionalDirectories,
  2361. });
  2362. if (restored.kind === "legacy") {
  2363. const meta = await updateIndexedPresentation({
  2364. ...restored.snapshot.meta,
  2365. ...(params.automationId ? { cronAutomationId: params.automationId } : {}),
  2366. // D48:pre-打点会话被闲时续跑恢复时补写归属;backfill 之外的双保险。
  2367. ...(params.offPeakTaskId ? { offPeakTaskId: params.offPeakTaskId } : {}),
  2368. });
  2369. // 打开/恢复任务是快照收敛,不涉及归属,与 resumeSession 广播同语义。
  2370. emitWorkspaceTaskListChanged(params, meta, "task_status_changed");
  2371. return meta;
  2372. }
  2373. const snapshot = restored.snapshot;
  2374. emitWorkspaceConfig(params, snapshot.settings);
  2375. const snapshotMeta = await syncTaskIndexSnapshot(snapshot);
  2376. const meta =
  2377. params.automationId || params.offPeakTaskId
  2378. ? await updateIndexedPresentation({
  2379. ...snapshotMeta,
  2380. ...(params.automationId ? { cronAutomationId: params.automationId } : {}),
  2381. // 续跑时补写闲时归属标记。
  2382. ...(params.offPeakTaskId ? { offPeakTaskId: params.offPeakTaskId } : {}),
  2383. })
  2384. : snapshotMeta;
  2385. notifySyncerSession({
  2386. taskId: meta.taskId,
  2387. workspacePath: meta.workspacePath,
  2388. workspaceIdentity: meta.workspaceIdentity,
  2389. });
  2390. return meta;
  2391. },
  2392. async listTasks(params): Promise<ZCodeTaskMeta[]> {
  2393. const tasks = await taskIndexRepo.listTaskMetas({
  2394. workspacePath: params.workspacePath,
  2395. workspaceIdentity: params.workspaceIdentity,
  2396. provider: GLM_PROVIDER,
  2397. pinned: false,
  2398. archived: false,
  2399. });
  2400. return tasks.map(rememberIndexedTaskMeta);
  2401. },
  2402. async listPinnedTaskIds(): Promise<string[]> {
  2403. const tasks = await taskIndexRepo.listTaskMetas({
  2404. provider: GLM_PROVIDER,
  2405. pinned: true,
  2406. archived: false,
  2407. });
  2408. return tasks.map((task) => task.taskId);
  2409. },
  2410. async listPinnedTasks(params): Promise<ZCodeTaskMeta[]> {
  2411. const tasks = await taskIndexRepo.listTaskMetas({
  2412. workspacePath: params.workspacePath,
  2413. workspaceIdentity: params.workspaceIdentity,
  2414. provider: GLM_PROVIDER,
  2415. pinned: true,
  2416. archived: false,
  2417. });
  2418. return tasks.map(rememberIndexedTaskMeta);
  2419. },
  2420. async listDeletedTaskIds(params): Promise<string[]> {
  2421. return taskIndexRepo.listDeletedTaskIds({
  2422. workspacePath: params.workspacePath,
  2423. workspaceIdentity: params.workspaceIdentity,
  2424. provider: GLM_PROVIDER,
  2425. });
  2426. },
  2427. async listActiveTaskIds(params): Promise<string[]> {
  2428. const key = workspaceKey(params);
  2429. return taskIndexSyncer
  2430. .activeTaskRefs()
  2431. .filter((ref) => workspaceKey(ref) === key)
  2432. .map((ref) => ref.taskId);
  2433. },
  2434. async listPermanentlyDeletedTaskIds(params) {
  2435. return taskIndexRepo.listPermanentlyDeletedTaskIds(params);
  2436. },
  2437. // 保留全局搜索与 Controller 的显式 scopes 查询;项目侧栏不再维护旧远端列表镜像。
  2438. async listTaskList(params: ZCodeTaskListQuery): Promise<ZCodeTaskListResult> {
  2439. const result = await taskIndexRepo.queryTaskList({
  2440. ...params,
  2441. provider: GLM_PROVIDER,
  2442. });
  2443. return {
  2444. ...result,
  2445. items: result.items.map(rememberIndexedTaskMeta),
  2446. };
  2447. },
  2448. async listArchivedTasks(params): Promise<ZCodeTaskMeta[]> {
  2449. const tasks = await taskIndexRepo.listTaskMetas({
  2450. workspacePath: params.workspacePath,
  2451. workspaceIdentity: params.workspaceIdentity,
  2452. provider: GLM_PROVIDER,
  2453. archived: true,
  2454. });
  2455. return tasks.map(rememberIndexedTaskMeta);
  2456. },
  2457. async getTaskSnapshot(params): Promise<ZCodeTaskSnapshot | null> {
  2458. const startedAt = Date.now();
  2459. const resumeStartedAt = Date.now();
  2460. const explicitModel = params.model?.trim();
  2461. const explicitThoughtLevel = params.thoughtLevel?.trim();
  2462. const shouldBackfillTaskIndexResumeHints =
  2463. params.clientMode === "web-remote-replayable" &&
  2464. params.resumeModelPolicy !== "ui-resolved-only" &&
  2465. (!explicitModel || !explicitThoughtLevel);
  2466. const indexHints = shouldBackfillTaskIndexResumeHints
  2467. ? await resolveTaskIndexResumeHints(params, "replayable_snapshot")
  2468. : {};
  2469. const model = explicitModel || indexHints.model;
  2470. const thoughtLevel = explicitThoughtLevel || indexHints.thoughtLevel;
  2471. const restored = await resumeSnapshotOrLegacy({
  2472. taskId: params.taskId,
  2473. workspacePath: params.workspacePath,
  2474. workspaceIdentity: params.workspaceIdentity,
  2475. // 手机 replayable 首屏 snapshot 会先于后续 resumeTask 读取。
  2476. // 这里必须把 task meta 解析出的历史模型和 thoughtLevel 传进 session/resume,
  2477. // 避免冷恢复用 workspace/draft 默认配置污染 context window 与思考强度。
  2478. model,
  2479. thoughtLevel,
  2480. });
  2481. const resumeDurationMs = Date.now() - resumeStartedAt;
  2482. if (restored.kind === "legacy") {
  2483. const limitStartedAt = Date.now();
  2484. const legacySnapshot = limitTaskSnapshotMessages(restored.snapshot, params.messageLimit);
  2485. const limitDurationMs = Date.now() - limitStartedAt;
  2486. const indexStartedAt = Date.now();
  2487. const indexedMeta = (await taskIndexRepo.getTaskMeta(params)) ?? legacySnapshot.meta;
  2488. const indexDurationMs = Date.now() - indexStartedAt;
  2489. logger.info(undefined, "[zcode-task-service] 历史快照读取完成", {
  2490. clientMode: params.clientMode ?? "unknown",
  2491. durationMs: Date.now() - startedAt,
  2492. indexDurationMs,
  2493. limitDurationMs,
  2494. messageLimit: params.messageLimit ?? null,
  2495. resumeDurationMs,
  2496. snapshotKind: "legacy",
  2497. stats: getTaskSnapshotMessageDiagnostics(legacySnapshot),
  2498. taskId: params.taskId,
  2499. workspaceIdentity: params.workspaceIdentity ?? null,
  2500. workspacePath: params.workspacePath,
  2501. });
  2502. return { ...legacySnapshot, meta: indexedMeta };
  2503. }
  2504. const snapshot = restored.snapshot;
  2505. const projectionStartedAt = Date.now();
  2506. const zcodeSnapshot = limitTaskSnapshotMessages(
  2507. snapshotToZCode(snapshot, {
  2508. includeEmptyPendingElicitations: params.clientMode === "web-remote-replayable",
  2509. }),
  2510. params.messageLimit,
  2511. );
  2512. const projectionDurationMs = Date.now() - projectionStartedAt;
  2513. // 恢复先从 CLI 对账事实,再补模型/思考深度/正文;快照不再推导持久状态。
  2514. const indexStartedAt = Date.now();
  2515. const indexedMeta = await syncTaskIndexSnapshot(snapshot);
  2516. const indexDurationMs = Date.now() - indexStartedAt;
  2517. logger.info(undefined, "[zcode-task-service] 历史快照读取完成", {
  2518. clientMode: params.clientMode ?? "unknown",
  2519. durationMs: Date.now() - startedAt,
  2520. indexDurationMs,
  2521. messageLimit: params.messageLimit ?? null,
  2522. projectionDurationMs,
  2523. resumeDurationMs,
  2524. snapshotKind: "session",
  2525. stats: getTaskSnapshotMessageDiagnostics(zcodeSnapshot),
  2526. taskId: params.taskId,
  2527. workspaceIdentity: params.workspaceIdentity ?? null,
  2528. workspacePath: params.workspacePath,
  2529. });
  2530. return { ...zcodeSnapshot, meta: indexedMeta };
  2531. },
  2532. async getTaskSnapshotWithEtag(params) {
  2533. const startedAt = Date.now();
  2534. const snapshot = await service.getTaskSnapshot(params);
  2535. if (!snapshot) {
  2536. logger.info(undefined, "[zcode-task-service] 历史快照 ETag 读取为空", {
  2537. clientMode: params.clientMode ?? "unknown",
  2538. durationMs: Date.now() - startedAt,
  2539. messageLimit: params.messageLimit ?? null,
  2540. taskId: params.taskId,
  2541. workspaceIdentity: params.workspaceIdentity ?? null,
  2542. workspacePath: params.workspacePath,
  2543. });
  2544. return { snapshot: null };
  2545. }
  2546. const etagStartedAt = Date.now();
  2547. const etag = createHash("sha256").update(JSON.stringify(snapshot)).digest("hex");
  2548. const etagDurationMs = Date.now() - etagStartedAt;
  2549. if (params.ifNoneMatch && params.ifNoneMatch === etag) {
  2550. logger.info(undefined, "[zcode-task-service] 历史快照 ETag 命中缓存", {
  2551. clientMode: params.clientMode ?? "unknown",
  2552. durationMs: Date.now() - startedAt,
  2553. etagDurationMs,
  2554. messageLimit: params.messageLimit ?? null,
  2555. stats: getTaskSnapshotMessageDiagnostics(snapshot),
  2556. taskId: params.taskId,
  2557. workspaceIdentity: params.workspaceIdentity ?? null,
  2558. workspacePath: params.workspacePath,
  2559. });
  2560. return { snapshot: null, etag, notModified: true };
  2561. }
  2562. logger.info(undefined, "[zcode-task-service] 历史快照 ETag 生成完成", {
  2563. clientMode: params.clientMode ?? "unknown",
  2564. durationMs: Date.now() - startedAt,
  2565. etagDurationMs,
  2566. messageLimit: params.messageLimit ?? null,
  2567. stats: getTaskSnapshotMessageDiagnostics(snapshot),
  2568. taskId: params.taskId,
  2569. workspaceIdentity: params.workspaceIdentity ?? null,
  2570. workspacePath: params.workspacePath,
  2571. });
  2572. return { snapshot, etag };
  2573. },
  2574. async getTaskSnapshotBody(): Promise<ZCodeTaskSnapshotBody | null> {
  2575. return null;
  2576. },
  2577. async getTaskSnapshotRef(): Promise<ZCodeTaskSnapshotRefContent | null> {
  2578. return null;
  2579. },
  2580. async getTaskSnapshotToolCallsSlice(): Promise<ZCodeTaskSnapshotToolCallsSlice | null> {
  2581. return null;
  2582. },
  2583. async getTaskMeta(params): Promise<ZCodeTaskMeta | null> {
  2584. const meta = await taskIndexRepo.getTaskMeta(params);
  2585. return meta ? rememberIndexedTaskMeta(meta) : null;
  2586. },
  2587. async getTaskConfigOptions(params): Promise<ZCodeConfigOption[]> {
  2588. const snapshot = await resumeSnapshot(getTaskTarget(params.taskId));
  2589. return settingsToConfigOptions(snapshot.settings);
  2590. },
  2591. async getTaskModelSelection(params): Promise<ModelSelection | null> {
  2592. const target = getTaskTarget(params.taskId);
  2593. const snapshot = await options.zcodeAgentService.readSession({
  2594. workspacePath: target.workspacePath,
  2595. workspaceIdentity: target.workspaceIdentity,
  2596. sessionId: params.taskId,
  2597. });
  2598. return snapshot.settings.model.current ?? null;
  2599. },
  2600. async setAssistantMessageFeedback(params): Promise<ZCodeSessionFile> {
  2601. const snapshot = await service.getTaskSnapshot(params);
  2602. if (!snapshot) {
  2603. unsupported("setAssistantMessageFeedback");
  2604. }
  2605. const assistantMessages = snapshot.messages.filter((message) => message.role === "assistant");
  2606. const targetMessage = assistantMessages[params.turnIndex];
  2607. if (targetMessage) {
  2608. targetMessage.feedback = params.feedback as ZCodeAssistantMessageFeedback | undefined;
  2609. }
  2610. return snapshot;
  2611. },
  2612. async syncTaskSessionBinding(): Promise<ZCodeSyncTaskSessionBindingResult> {
  2613. unsupported("syncTaskSessionBinding");
  2614. },
  2615. async switchAgent(): Promise<ZCodeSwitchAgentResult> {
  2616. unsupported("switchAgent");
  2617. },
  2618. async scanImportableClaudeSessions(params: {
  2619. workspacePath?: string;
  2620. workspaceIdentity?: string;
  2621. modifiedSince?: number;
  2622. limit?: number;
  2623. }): Promise<ZCodeImportableSessionCandidate[]> {
  2624. // legacy ACP 下线后 scanImportableClaudeSessions 被留成空桩,迁移向导扫不到 ~/.claude/projects。
  2625. // workspaceIdentity 仅影响导入落盘目录,扫描仍按 jsonl 内 cwd 与可选 workspacePath 过滤。
  2626. void params.workspaceIdentity;
  2627. return claudeNativeSessionImportRepo.scanImportableSessions({
  2628. workspacePath: params.workspacePath,
  2629. modifiedSince: params.modifiedSince,
  2630. limit: params.limit,
  2631. });
  2632. },
  2633. async importClaudeSessions(params: {
  2634. workspacePath?: string;
  2635. workspaceIdentity?: string;
  2636. sessionIds: string[];
  2637. }): Promise<ZCodeImportSessionsResult> {
  2638. return importClaudeNativeSessions({
  2639. taskIndexRepo,
  2640. workspacePath: params.workspacePath,
  2641. workspaceIdentity: params.workspaceIdentity,
  2642. sessionIds: params.sessionIds,
  2643. createImportedSession: async (source) => {
  2644. const targetWorkspaceIdentity = params.workspacePath
  2645. ? params.workspaceIdentity
  2646. : undefined;
  2647. const snapshot = await options.zcodeAgentService.createSession({
  2648. workspacePath: source.workspacePath,
  2649. workspaceIdentity: targetWorkspaceIdentity,
  2650. // 显式重新导入产生新 CLI 会话,不能用来源 hash 覆盖已删除或已继续对话的记录。
  2651. sessionTraceId: createSessionTraceId(),
  2652. persistence: "immediate",
  2653. importedHistory: {
  2654. source: "claudeCode",
  2655. title: source.title,
  2656. createdAt: source.createdAt,
  2657. updatedAt: source.updatedAt,
  2658. messages: source.messages.map((message) => ({
  2659. role: message.role,
  2660. content: message.content,
  2661. timestamp: message.timestamp,
  2662. })),
  2663. },
  2664. });
  2665. const meta = await syncTaskIndexSnapshot(snapshot);
  2666. // 导入后的任务必须是真实 ZCode session,setModel/sendPrompt 才能继续命中 runtime。
  2667. // 同时保留 migrationSource,避免任务列表把 Claude Code 迁移历史当成本地新会话。
  2668. return updateIndexedPresentation({ ...meta, migrationSource: "claudeCode" });
  2669. },
  2670. onTaskImported: (meta) => {
  2671. rememberIndexedTaskMeta(meta);
  2672. emitWorkspaceTaskListChanged(
  2673. {
  2674. workspacePath: meta.workspacePath,
  2675. workspaceIdentity: meta.workspaceIdentity,
  2676. taskId: meta.taskId,
  2677. },
  2678. meta,
  2679. // 导入沿用 task_meta_changed 旧语义。
  2680. "task_meta_changed",
  2681. );
  2682. },
  2683. });
  2684. },
  2685. async setMode(params): Promise<void> {
  2686. // session/setMode → v4 switchCollaborationMode(CAS,revision 收敛见
  2687. // sendHostCasCommandV4)。v4 handler 不发旧 state.updated,观察端一致性与桌面
  2688. // v4 工具条切换同批(读路径 v4 store 收口);发起端由下方 resumeSnapshot 保真。
  2689. const target = getTaskTarget(params.taskId);
  2690. await switchCollaborationModeViaProtocol(target, toZCodeMode(params.mode) ?? "build");
  2691. const snapshot = await resumeSnapshot(target);
  2692. await syncTaskIndexSnapshot(snapshot);
  2693. },
  2694. async setConfigOption(params): Promise<ZCodeConfigOption[]> {
  2695. const target = getTaskTarget(params.taskId);
  2696. if (params.configId === MODEL_CONFIG_ID) {
  2697. return service.setModel({
  2698. taskId: params.taskId,
  2699. traceId: params.traceId,
  2700. modelSelection: parseModelPickerValue(params.value),
  2701. });
  2702. }
  2703. if (params.configId === THOUGHT_LEVEL_CONFIG_ID) {
  2704. // session/setThoughtLevel → v4 switchModelConfig(v4 无独立思考深度命令,
  2705. // thought 字段承载;provider/model 取当前会话选型,与桌面 v4 工具条同一命令面)。
  2706. // 同 provider 同 model 直切,不涉及 runtimeModel(provider 凭据)解析——这正是
  2707. // setModel 尚不能迁移的原因(见下方 setModel 标注)。
  2708. const current = await options.zcodeAgentService.readSession({
  2709. workspacePath: target.workspacePath,
  2710. workspaceIdentity: target.workspaceIdentity,
  2711. sessionId: params.taskId,
  2712. });
  2713. const model = current.settings.model.current;
  2714. // 未绑定会话可以查看,但单独切档位不能猜测 Provider/Model。
  2715. if (!model) throw new Error("请先选择模型,再设置思考档位");
  2716. await sendConfigCasCommandV4(
  2717. target,
  2718. "switchModelConfig",
  2719. {
  2720. provider: model.providerId,
  2721. model: model.modelId,
  2722. thought: params.value,
  2723. },
  2724. `session=${params.taskId} thought=${params.value}`,
  2725. );
  2726. } else if (params.configId === MODE_CONFIG_ID) {
  2727. await switchCollaborationModeViaProtocol(
  2728. target,
  2729. toZCodeMode(params.value as ZCodeTaskMode) ?? "build",
  2730. );
  2731. }
  2732. const snapshot = await resumeSnapshot(target);
  2733. await syncTaskIndexSnapshot(snapshot);
  2734. return settingsToConfigOptions(snapshot.settings);
  2735. },
  2736. async setModel(params): Promise<ZCodeConfigOption[]> {
  2737. // replayable facade 仍依赖 legacy op 返回的 Session
  2738. // Snapshot;模型执行事实已经收敛到目标 Worker Registry,Host 只发送 Selection。
  2739. // 过渡归宿 = task facade 原生消费 V4 config 投影与 revision。
  2740. const target = getTaskTarget(params.taskId);
  2741. await options.zcodeAgentService.setModel({
  2742. workspacePath: target.workspacePath,
  2743. workspaceIdentity: target.workspaceIdentity,
  2744. sessionId: params.taskId,
  2745. // replayable/legacy facade 的 modelId 可能只是 UI 运行态模型名(如 gpt-5.5)。
  2746. // 多个自定义 provider 同名时只能信任 UI 传入的结构化 ModelSelection。
  2747. model: params.modelSelection,
  2748. });
  2749. const snapshot = await resumeSnapshot(target);
  2750. await syncTaskIndexSnapshot(snapshot);
  2751. return settingsToConfigOptions(snapshot.settings);
  2752. },
  2753. async setAutomationSessionConfig(params): Promise<ZCodeConfigOption[]> {
  2754. const target = getTaskTarget(params.taskId);
  2755. const model = params.modelSelection;
  2756. const thoughtLevel = params.thoughtLevel?.trim() ?? "";
  2757. // automation 过去先走 legacy session/setModel,再发 V4 Think。若目标模型
  2758. // 已带相同默认 Think,第二步会 noop 且不产 ModelSelected,导致 runtime 已切换但
  2759. // conversation 投影仍显示旧模型。这里用一条 V4 命令原子更新 runtime 与投影。
  2760. await sendConfigCasCommandV4(
  2761. target,
  2762. "switchModelConfig",
  2763. {
  2764. provider: model.providerId,
  2765. model: model.modelId,
  2766. thought: thoughtLevel,
  2767. },
  2768. `automation session=${params.taskId} model=${model.providerId}/${model.modelId} thought=${thoughtLevel}`,
  2769. );
  2770. if (thoughtLevel) {
  2771. // 跨模型 switchModelConfig 会先采用目标模型默认 Think,避免误用源模型档位。
  2772. // automation 的 thought 已由创建/编辑表单按目标模型校验,可在模型事件落地后
  2773. // 再以同模型命令显式收敛;同默认值时 noop,非默认值时发布第二个 config delta。
  2774. await sendConfigCasCommandV4(
  2775. target,
  2776. "switchModelConfig",
  2777. {
  2778. provider: model.providerId,
  2779. model: model.modelId,
  2780. thought: thoughtLevel,
  2781. },
  2782. `automation session=${params.taskId} thought=${thoughtLevel}`,
  2783. );
  2784. }
  2785. if (params.mode?.trim()) {
  2786. await switchCollaborationModeViaProtocol(target, toZCodeMode(params.mode) ?? "build");
  2787. }
  2788. const snapshot = await resumeSnapshot(target);
  2789. await syncTaskIndexSnapshot(snapshot);
  2790. return settingsToConfigOptions(snapshot.settings);
  2791. },
  2792. async getWorkspaceProviderConfigFile(params) {
  2793. return {
  2794. provider: GLM_PROVIDER,
  2795. path: params.workspacePath,
  2796. exists: false,
  2797. };
  2798. },
  2799. async getTaskNativeSessionLogFile() {
  2800. const path = resolveZCodeAgentCurrentLogFilePath();
  2801. // 返回 ZCode Agent 的结构化日志 JSONL;日志行中的 sessionId 用于按当前任务排查。
  2802. return { provider: GLM_PROVIDER, path, exists: existsSync(path) };
  2803. },
  2804. async getModelTrajectory(params) {
  2805. // ZCode Agent 把 taskId 当作 sessionId 落盘 model-io(见本文件其它 sessionId: params.taskId 用法),
  2806. // 这里按 sessionId 还原该 task 的模型调用轨迹,供 UI 侧边栏可视化。
  2807. const trajectory = await readModelTrajectory(params.taskId, params.limit);
  2808. logger.info(
  2809. `[ZCodeTaskService] getModelTrajectory taskId=${params.taskId} records=${trajectory.records.length} files=${trajectory.sourceFiles.length} truncated=${trajectory.truncated}`,
  2810. );
  2811. return trajectory;
  2812. },
  2813. async getTaskTokenUsage(params): Promise<ZCodeTaskTokenUsageResult> {
  2814. // 摘要面板需要展示 task 的累计模型消耗,不能复用 usage_update 的 context window。
  2815. // 这里通过 ZCode Protocol 读 agent SQLite 的 model_usage 聚合,保持桌面和远控同一事实源。
  2816. return options.zcodeAgentService.getTaskTokenUsage({
  2817. workspacePath: params.workspacePath,
  2818. workspaceIdentity: params.workspaceIdentity,
  2819. sessionId: params.taskId,
  2820. });
  2821. },
  2822. async getTaskSessionFilePath(params) {
  2823. return {
  2824. path: `${params.workspacePath}/${params.taskId}.zcode-session`,
  2825. exists: false,
  2826. };
  2827. },
  2828. async restartWorkspaceProcess(params): Promise<void> {
  2829. await options.zcodeAgentService.disposeWorkspace(normalizeWorkspaceParams(params));
  2830. },
  2831. async previewArchivedTaskDeletion(params) {
  2832. const preview = options.zcodeAgentService.previewSessionDeletion;
  2833. if (!preview) throw new Error("session-data.unavailable");
  2834. const archived = await taskIndexRepo.isTaskArchived(params);
  2835. const result = await preview({
  2836. sessionId: params.taskId,
  2837. workspace: normalizeWorkspaceParams(params),
  2838. });
  2839. if (!archived && !result.completed && !result.incomplete)
  2840. return { ...result, blockedReason: "not-archived" as const };
  2841. return result;
  2842. },
  2843. async previewArchivedTaskDeletions({ tasks }) {
  2844. const preview = options.zcodeAgentService.previewSessionDeletions;
  2845. if (!preview) throw new Error("session-data.unavailable");
  2846. if (!tasks.length) return { results: [] };
  2847. const archived = await Promise.all(tasks.map((task) => taskIndexRepo.isTaskArchived(task)));
  2848. const { results } = await preview({
  2849. items: tasks.map((task) => ({
  2850. sessionId: task.taskId,
  2851. workspace: normalizeWorkspaceParams(task),
  2852. })),
  2853. });
  2854. // 未归档判定与单项预检一致:已在删除或已完成的续删不受归档状态影响。
  2855. return {
  2856. results: results.map((result, index) =>
  2857. "preview" in result &&
  2858. !archived[index] &&
  2859. !result.preview.completed &&
  2860. !result.preview.incomplete
  2861. ? { preview: { ...result.preview, blockedReason: "not-archived" as const } }
  2862. : result,
  2863. ),
  2864. };
  2865. },
  2866. async permanentlyDeleteArchivedTask(params) {
  2867. const execute = options.zcodeAgentService.executeSessionDeletion;
  2868. if (!execute) throw new Error("session-data.unavailable");
  2869. if (!(await taskIndexRepo.reservePermanentDeletion(params)))
  2870. return {
  2871. sessionId: params.taskId,
  2872. status: "blocked" as const,
  2873. sessionIds: [],
  2874. retainedArtifacts: 0,
  2875. reason: "not-archived",
  2876. };
  2877. // 响应丢失时保留准入;重试向 CLI 查询同一身份的持久结果,不把未知结果当作可恢复会话。
  2878. const result = await execute({
  2879. sessionId: params.taskId,
  2880. workspace: normalizeWorkspaceParams(params),
  2881. revision: params.revision,
  2882. operationId: params.operationId,
  2883. });
  2884. if (result.status === "deleted") {
  2885. await taskIndexRepo.completePermanentDeletion(params, result.sessionIds);
  2886. emitWorkspaceTaskListChanged(params, undefined, "task_deleted");
  2887. } else if (result.status === "blocked") await taskIndexRepo.releasePermanentDeletion(params);
  2888. return result;
  2889. },
  2890. async deleteTask(params): Promise<void> {
  2891. await taskIndexSyncer.mutateSessionFacts(
  2892. { ...params, sessionId: params.taskId },
  2893. { type: "delete" },
  2894. );
  2895. },
  2896. async deleteArchivedTask(params): Promise<boolean> {
  2897. const meta = await taskIndexRepo.deleteArchivedTask(params);
  2898. if (!meta) return false;
  2899. await taskIndexSyncer.mutateSessionFacts(
  2900. { ...params, sessionId: params.taskId },
  2901. { type: "delete" },
  2902. );
  2903. emitWorkspaceTaskListChanged(params, meta, "task_deleted");
  2904. return true;
  2905. },
  2906. async deleteArchivedTasks(params): Promise<ZCodeArchivedTaskDeletionResult> {
  2907. const result: ZCodeArchivedTaskDeletionResult = {
  2908. deletedTaskIds: [],
  2909. skippedTaskIds: [],
  2910. failedTaskIds: [],
  2911. };
  2912. const taskIds = [...new Set(params.taskIds)];
  2913. if (taskIds.length === 0) return result;
  2914. const startedAt = Date.now();
  2915. for (const taskId of taskIds) {
  2916. const target = {
  2917. workspacePath: params.workspacePath,
  2918. workspaceIdentity: params.workspaceIdentity,
  2919. taskId,
  2920. };
  2921. try {
  2922. // 保留逐项事务与归档 guard:一项失败不能回滚其它成功项,也不能提前隐藏失败项。
  2923. const meta = await taskIndexRepo.deleteArchivedTask(target);
  2924. if (!meta) {
  2925. result.skippedTaskIds.push(taskId);
  2926. continue;
  2927. }
  2928. await taskIndexSyncer.mutateSessionFacts(
  2929. { ...target, sessionId: taskId },
  2930. { type: "delete" },
  2931. );
  2932. result.deletedTaskIds.push(taskId);
  2933. } catch (error) {
  2934. result.failedTaskIds.push(taskId);
  2935. logger.warn(undefined, "[ArchivedTaskDeletion] 批次目标删除失败", { ...target, error });
  2936. }
  2937. }
  2938. if (result.deletedTaskIds.length > 0) {
  2939. // 根因:循环调用单条接口会逐项广播,驱动 Host 与 UI 各自全量重读。
  2940. // 批次完成只发一次 workspace 事件,仍使所有观察端换代 deleted membership,防止任务复活。
  2941. emitWorkspaceTaskListChanged(params, undefined, "task_deleted");
  2942. }
  2943. logger.info(undefined, "[ArchivedTaskDeletion] batch completed", {
  2944. workspaceKey: resolveWorkspaceKey(params),
  2945. requested: taskIds.length,
  2946. deleted: result.deletedTaskIds.length,
  2947. skipped: result.skippedTaskIds.length,
  2948. failed: result.failedTaskIds.length,
  2949. durationMs: Date.now() - startedAt,
  2950. });
  2951. return result;
  2952. },
  2953. async renameTask(params): Promise<ZCodeTaskMeta> {
  2954. const meta = await taskIndexSyncer.mutateSessionFacts(
  2955. { ...params, sessionId: params.taskId },
  2956. { type: "rename", title: params.title },
  2957. );
  2958. if (!meta) throw new Error("task.not-found");
  2959. return meta;
  2960. },
  2961. async setTaskPinned(params): Promise<ZCodeTaskMeta> {
  2962. const meta = await updateIndexedTaskState(params, {
  2963. pinned: params.pinned,
  2964. });
  2965. emitWorkspaceTaskListChanged(params, meta, params.pinned ? "task_pinned" : "task_unpinned");
  2966. return meta;
  2967. },
  2968. async setTaskUnread(params): Promise<ZCodeTaskMeta> {
  2969. if (!params.unread && typeof params.expectedUnreadAt === "number") {
  2970. const result = await taskIndexRepo.clearTaskUnreadIfMatches({
  2971. taskId: params.taskId,
  2972. workspacePath: params.workspacePath,
  2973. workspaceIdentity: params.workspaceIdentity,
  2974. expectedUnreadAt: params.expectedUnreadAt,
  2975. });
  2976. // Bug 原因:旧手机点击可能晚于新的终态未读到达。CAS 未命中时必须把当前 meta
  2977. // 广播出去让 renderer 对账,不能先乐观清除后留下 renderer-only 已读状态。
  2978. if (result.cleared) {
  2979. emitWorkspaceTaskListChanged(params, result.meta, "task_meta_changed");
  2980. }
  2981. return result.meta;
  2982. }
  2983. const unreadAt = params.unread ? Date.now() : undefined;
  2984. const meta = await updateIndexedTaskState(params, { unreadAt });
  2985. // Bug 原因:repository 可能为避免同毫秒 CAS 版本碰撞而推进 unreadAt;
  2986. // 必须把最终持久值广播给 renderer 对账,否则后续 snapshot 会继续暴露旧 marker。
  2987. // unread 归属在 tasks-index、sessions-index 不携带,必须走 task_meta_changed 触发 membership 重拉。
  2988. emitWorkspaceTaskListChanged(params, meta, "task_meta_changed");
  2989. return meta;
  2990. },
  2991. async archiveTask(params): Promise<ZCodeTaskMeta> {
  2992. const meta = await updateIndexedTaskState(params, { archived: true });
  2993. emitWorkspaceTaskListChanged(params, meta, "task_archived");
  2994. return meta;
  2995. },
  2996. async unarchiveTask(params): Promise<ZCodeTaskMeta> {
  2997. const meta = await updateIndexedTaskState(params, { archived: false });
  2998. emitWorkspaceTaskListChanged(params, meta, "task_unarchived");
  2999. return meta;
  3000. },
  3001. async branchTaskFromPrompt(): Promise<ZCodeTaskCreateResult> {
  3002. unsupported("branchTaskFromPrompt");
  3003. },
  3004. onDynamicStreamEvent(taskId: string): Event<ZCodeStreamEvent> {
  3005. return getGlobalTaskEmitter(taskId).event;
  3006. },
  3007. onDynamicTaskTerminalOutcome(taskId: string): Event<ZCodeTaskTerminalOutcome> {
  3008. // 合并迁移:V4 syncer 只暴露归一化后的终态 kind,不再携带旧协议 event payload。
  3009. // automation 只需要稳定收口运行结果,因此 completed/failed 在此映射为公开 outcome。
  3010. return (listener) =>
  3011. taskIndexSyncer.onSessionTerminalEvent((terminal) => {
  3012. if (terminal.target.sessionId !== taskId) {
  3013. return;
  3014. }
  3015. const target = {
  3016. taskId,
  3017. workspacePath: terminal.target.workspacePath,
  3018. workspaceIdentity: terminal.target.workspaceIdentity,
  3019. };
  3020. const inputId = activePromptInputIds.get(taskKey(target));
  3021. listener({
  3022. taskId,
  3023. ...(inputId ? { inputId } : {}),
  3024. outcome: terminal.kind === "turn.failed" ? "failed" : "succeeded",
  3025. });
  3026. });
  3027. },
  3028. onDynamicTaskReady(taskId: string): Event<ZCodeTaskReadyOutcome> {
  3029. return (listener) =>
  3030. taskIndexSyncer.onSessionReadyEvent((ready) => {
  3031. if (ready.target.sessionId !== taskId) {
  3032. return;
  3033. }
  3034. listener({ taskId, reason: ready.reason });
  3035. });
  3036. },
  3037. onDynamicTaskEvent(params): Event<ZCodeStreamEvent> {
  3038. const target = {
  3039. taskId: params.taskId,
  3040. workspacePath: params.workspacePath,
  3041. workspaceIdentity: params.workspaceIdentity,
  3042. };
  3043. rememberTaskTarget(target);
  3044. return (listener) => {
  3045. const localDisposable = getTaskEmitter(target).event(listener);
  3046. if (legacySnapshotTaskKeys.has(taskKey(target))) {
  3047. // Bugfix: legacy ACP task 没有 zcode-cli sqlite session,恢复后只能作为只读历史。
  3048. // 若继续向 ZCode Protocol 建 desktop-continuous/replayable 订阅,会反复触发
  3049. // Session is not active 并刷爆日志;本地 emitter 已足够承接 rename/archive 等元数据事件。
  3050. return localDisposable;
  3051. }
  3052. // M5 ③-2 复核(2026-07-06):这里仍是 services/ 内旧 session/subscribe 词表的
  3053. // 最后消费点(replayable/bots 的 stream 投影源)。写路径(send/stop/交互回执)
  3054. // 本波已收敛 v4 命令;读路径消费方是 bots handleStreamEvent(10 种事件词表)与
  3055. // host 镜像 taskRealtimePort(词表同为 ZCodeStreamEvent),二者换 v4 帧 = relay
  3056. // 协议 + 手机 store + bots 投影整波重做(且 ui/store 本波由并行 agent 主修,避让)。
  3057. // 死期改判 = replayable 读路径 v4 store 波次(波次 3),与 host/index.ts 镜像、
  3058. // mapStateUpdated/mapServiceEvent、agentService.onDynamicSessionEvent 同批摘除。
  3059. const upstreamDisposable = options.zcodeAgentService.onDynamicSessionEvent({
  3060. workspacePath: params.workspacePath,
  3061. workspaceIdentity: params.workspaceIdentity,
  3062. sessionId: params.taskId,
  3063. deliveryKind: toZCodeDeliveryKind(params.deliveryKind),
  3064. includeSnapshot: params.deliveryKind === "replayable",
  3065. })((event) => mapServiceEvent(target, event));
  3066. return {
  3067. dispose() {
  3068. upstreamDisposable.dispose();
  3069. localDisposable.dispose();
  3070. },
  3071. };
  3072. };
  3073. },
  3074. onDynamicWorkspaceEvent(workspace): Event<ZCodeWorkspaceEvent> {
  3075. return taskIndexSyncer.onDynamicWorkspaceEvent(workspace);
  3076. },
  3077. onError: errorEmitter.event,
  3078. disposeAll(): void {
  3079. if (disposed) {
  3080. return;
  3081. }
  3082. disposed = true;
  3083. memoryDiagnostics.dispose();
  3084. // syncer 持有 agentService 的 v4 帧订阅(sessions-index/workspace-config),
  3085. // 必须在 agentService.disposeAll 前释放,否则 emitter dispose 时仍会回调到已失效的 syncer。
  3086. // workspaceEmitters 已下沉到 syncer,由 syncer.disposeAll 统一回收。
  3087. taskIndexSyncer.disposeAll();
  3088. for (const scope of botConnectionScopes.values()) void scope.dispose();
  3089. botConnectionScopes.clear();
  3090. options.zcodeAgentService.disposeAll();
  3091. disposeLocalTaskState();
  3092. },
  3093. async disposeAllAndWait(): Promise<void> {
  3094. if (disposed) {
  3095. return;
  3096. }
  3097. disposed = true;
  3098. // app 退出必须先断开 task index syncer 的订阅,再等待 agent 进程树完成清理;
  3099. // 否则 host 退出时会把 zcode-cli 的 SIGKILL 兜底 timer 一起带走。
  3100. taskIndexSyncer.disposeAll();
  3101. await Promise.all([...botConnectionScopes.values()].map((scope) => scope.dispose()));
  3102. botConnectionScopes.clear();
  3103. await disposeZCodeAgentServiceAndWait();
  3104. disposeLocalTaskState();
  3105. },
  3106. };
  3107. return service;
  3108. }
  3109. function normalizeWorkspaceParams(params: {
  3110. workspacePath: string;
  3111. workspaceIdentity?: string;
  3112. }): ZCodeAgentWorkspaceTarget {
  3113. return {
  3114. workspacePath: params.workspacePath,
  3115. workspaceIdentity: params.workspaceIdentity,
  3116. };
  3117. }
  3118. function deriveTitleFromSnapshot(snapshot: ZCodeSessionStateSnapshot): string {
  3119. return resolveZCodeVisibleSessionTitle({
  3120. title: snapshot.session.title,
  3121. messages: snapshot.messages,
  3122. target: snapshot.projection.target,
  3123. });
  3124. }
  3125. function normalizeSnapshotMessageLimit(messageLimit: number | undefined): number | undefined {
  3126. if (!messageLimit || !Number.isFinite(messageLimit) || messageLimit <= 0) {
  3127. return undefined;
  3128. }
  3129. return Math.floor(messageLimit);
  3130. }
  3131. function buildSnapshotHistory(
  3132. totalMessages: number,
  3133. messageLimit: number,
  3134. ): NonNullable<ZCodeTaskSnapshot["history"]> {
  3135. return {
  3136. truncatedBefore: totalMessages > messageLimit,
  3137. totalMessages,
  3138. };
  3139. }
  3140. function getTaskSnapshotMessageDiagnostics(snapshot: ZCodeTaskSnapshot) {
  3141. let assistantMessages = 0;
  3142. let userMessages = 0;
  3143. let toolCalls = 0;
  3144. let bodyRefs = 0;
  3145. let toolSliceMessages = 0;
  3146. let contentChars = 0;
  3147. let thoughtChars = 0;
  3148. for (const message of snapshot.messages) {
  3149. if (message.role === "assistant") {
  3150. assistantMessages += 1;
  3151. } else {
  3152. userMessages += 1;
  3153. }
  3154. toolCalls += message.tools?.length ?? 0;
  3155. bodyRefs += message.bodyRefs?.length ?? 0;
  3156. if (message.toolSlice) {
  3157. toolSliceMessages += 1;
  3158. }
  3159. contentChars += message.content.length;
  3160. thoughtChars += message.thought?.length ?? 0;
  3161. }
  3162. return {
  3163. assistantMessages,
  3164. bodyRefs,
  3165. contentChars,
  3166. fileChanges: snapshot.fileChanges?.length ?? 0,
  3167. historyTotalMessages: snapshot.history?.totalMessages ?? snapshot.messages.length,
  3168. messages: snapshot.messages.length,
  3169. slashCommands: snapshot.slashCommands?.length ?? 0,
  3170. thoughtChars,
  3171. toolCalls,
  3172. toolSliceMessages,
  3173. truncatedBefore: snapshot.history?.truncatedBefore ?? false,
  3174. userMessages,
  3175. };
  3176. }
  3177. function limitTaskSnapshotMessages(
  3178. snapshot: ZCodeTaskSnapshot,
  3179. messageLimit: number | undefined,
  3180. ): ZCodeTaskSnapshot {
  3181. const limit = normalizeSnapshotMessageLimit(messageLimit);
  3182. if (!limit) {
  3183. return snapshot;
  3184. }
  3185. const history = buildSnapshotHistory(snapshot.messages.length, limit);
  3186. return {
  3187. ...snapshot,
  3188. messages: history.truncatedBefore ? snapshot.messages.slice(-limit) : snapshot.messages,
  3189. // 手机 replayable 首屏为了性能只拿尾部窗口。
  3190. // UI 不能再用“返回条数是否等于 limit”猜测是否还有更早历史,因为短尾部终态快照也可能是裁剪窗口。
  3191. history,
  3192. };
  3193. }
  3194. function parseModelPickerValue(value: string): ModelSelection {
  3195. const customModel = decodeCustomModelValue(value);
  3196. if (customModel?.providerId && customModel.modelName) {
  3197. // UI 下拉的 custom:provider:model 只是展示态,不能原样传给 zcode-cli。
  3198. // 旧解析会先按冒号截断成 custom,最终下发 glm/custom,触发 Unsupported model。
  3199. return {
  3200. providerId: customModel.providerId,
  3201. modelId: customModel.modelName,
  3202. };
  3203. }
  3204. return parseSharedModelSelection(value);
  3205. }
  3206. function toZCodeMode(mode: ZCodeTaskMode | undefined): ZCodeSessionMode | undefined {
  3207. switch (mode) {
  3208. case "plan":
  3209. return "plan";
  3210. case "edit":
  3211. // automation UI 保存的“自动编辑”使用 canonical edit。旧映射漏掉该值,
  3212. // 调用方的 ?? build 会把权限模式静默降级成“变更前确认”。
  3213. return "edit";
  3214. case "guarded":
  3215. return "guarded";
  3216. case "yolo":
  3217. case "bypassPermissions":
  3218. case "dontAsk":
  3219. return "yolo";
  3220. case "auto":
  3221. return "auto";
  3222. case "build":
  3223. case "default":
  3224. case "acceptEdits":
  3225. case "autoEdit":
  3226. return "build";
  3227. default:
  3228. return undefined;
  3229. }
  3230. }
  3231. function fromZCodeMode(mode: ZCodeSessionMode): ZCodeTaskMode {
  3232. return mode === "build" ? "build" : mode;
  3233. }
  3234. function addSessionForkSnapshotFallback(
  3235. messages: ZCodePersistedMessage[],
  3236. snapshot: ZCodeSessionStateSnapshot,
  3237. ): ZCodePersistedMessage[] {
  3238. const parentSessionId = snapshot.session.parentSessionId;
  3239. if (
  3240. !parentSessionId ||
  3241. messages.some((message) => message.syntheticTimeline?.type === "session_fork")
  3242. ) {
  3243. return messages;
  3244. }
  3245. return [
  3246. ...messages,
  3247. {
  3248. id: `zcode-timeline-fork-${parentSessionId}-`,
  3249. role: "user",
  3250. content: "",
  3251. timestamp: snapshot.session.createdAt,
  3252. // 旧的纯对话 fork 没有落库 synthetic notice,只能从 session.parentSessionId
  3253. // 恢复一个不可跳转的分割线,避免历史 fork 会话完全看不到来源边界。
  3254. syntheticTimeline: {
  3255. version: 1,
  3256. kind: "synthetic",
  3257. type: "session_fork",
  3258. display: "separator",
  3259. parentSessionId,
  3260. targetMessageId: "",
  3261. },
  3262. },
  3263. ];
  3264. }
  3265. function addGoalVerificationTimelineSnapshotFallback(
  3266. messages: ZCodePersistedMessage[],
  3267. snapshot: ZCodeSessionStateSnapshot,
  3268. ): ZCodePersistedMessage[] {
  3269. const timeline = snapshot.runtime.goalVerificationTimeline ?? [];
  3270. if (timeline.length === 0) {
  3271. return messages;
  3272. }
  3273. const existingIds = new Set(
  3274. messages
  3275. .map((message) =>
  3276. message.syntheticTimeline?.type === "goal_verification"
  3277. ? goalVerificationTimelineIdentityKey(message.syntheticTimeline)
  3278. : null,
  3279. )
  3280. .filter((id): id is string => Boolean(id)),
  3281. );
  3282. const timelineMessages = timeline
  3283. .filter((item) => !existingIds.has(goalVerificationTimelineIdentityKey(item)))
  3284. .map<ZCodePersistedMessage>((item) => ({
  3285. id: goalVerificationTimelineMessageId(item),
  3286. role: "assistant",
  3287. content: "",
  3288. timestamp: item.startedAt ?? item.updatedAt,
  3289. // goal verifier lifecycle 是 agent snapshot 的持久状态,不一定有
  3290. // 对应 message history;task facade 也要按 target+iteration 和 anchor 补 divider,避免恢复后重复或错位。
  3291. syntheticTimeline: item,
  3292. }));
  3293. if (timelineMessages.length === 0) {
  3294. return messages;
  3295. }
  3296. return insertGoalVerificationTimelineMessages(messages, timelineMessages);
  3297. }
  3298. function goalVerificationTimelineIdentityKey(
  3299. item: Extract<ZCodeGoalVerificationTimelineMeta, { type: "goal_verification" }>,
  3300. ): string {
  3301. if (typeof item.goalIteration === "number") {
  3302. return `${item.targetId}:${item.goalIteration}`;
  3303. }
  3304. return `verification:${item.verificationId}`;
  3305. }
  3306. function goalVerificationTimelineMessageId(
  3307. item: Extract<ZCodeGoalVerificationTimelineMeta, { type: "goal_verification" }>,
  3308. ): string {
  3309. if (typeof item.goalIteration === "number") {
  3310. return `zcode-goal-verification-${item.targetId}-${item.goalIteration}`;
  3311. }
  3312. return `zcode-goal-verification-${item.verificationId}`;
  3313. }
  3314. function insertGoalVerificationTimelineMessages(
  3315. messages: ZCodePersistedMessage[],
  3316. timelineMessages: ZCodePersistedMessage[],
  3317. ): ZCodePersistedMessage[] {
  3318. const result = [...messages];
  3319. for (const message of [...timelineMessages].sort(
  3320. (left, right) => left.timestamp - right.timestamp,
  3321. )) {
  3322. const timeline = message.syntheticTimeline;
  3323. const anchorIndex =
  3324. timeline?.type === "goal_verification" && timeline.anchorAssistantMessageId
  3325. ? findPersistedMessageIndexById(result, timeline.anchorAssistantMessageId)
  3326. : -1;
  3327. if (anchorIndex >= 0) {
  3328. result.splice(goalVerificationAnchorInsertIndex(result, anchorIndex), 0, message);
  3329. continue;
  3330. }
  3331. result.splice(timestampInsertIndex(result, message.timestamp), 0, message);
  3332. }
  3333. return result;
  3334. }
  3335. function normalizeGoalVerificationTimelineMessageOrder(
  3336. messages: ZCodePersistedMessage[],
  3337. ): ZCodePersistedMessage[] {
  3338. const timelineMessages = messages.filter(
  3339. (message) => message.syntheticTimeline?.type === "goal_verification",
  3340. );
  3341. if (timelineMessages.length === 0) {
  3342. return messages;
  3343. }
  3344. // agent history 已存在的 verifier divider 也可能因为异步到达排到下一条用户输入后面;
  3345. // task facade snapshot 必须按 anchor 重新投影,而不是只给缺失 divider 做 fallback。
  3346. return insertGoalVerificationTimelineMessages(
  3347. messages.filter((message) => message.syntheticTimeline?.type !== "goal_verification"),
  3348. timelineMessages,
  3349. );
  3350. }
  3351. function goalVerificationAnchorInsertIndex(
  3352. messages: readonly ZCodePersistedMessage[],
  3353. anchorIndex: number,
  3354. ): number {
  3355. let index = anchorIndex + 1;
  3356. while (
  3357. index < messages.length &&
  3358. messages[index]?.syntheticTimeline?.type === "goal_verification"
  3359. ) {
  3360. index += 1;
  3361. }
  3362. return index;
  3363. }
  3364. function timestampInsertIndex(
  3365. messages: readonly ZCodePersistedMessage[],
  3366. timestamp: number,
  3367. ): number {
  3368. const index = messages.findIndex((message) => message.timestamp > timestamp);
  3369. return index >= 0 ? index : messages.length;
  3370. }
  3371. function findPersistedMessageIndexById(
  3372. messages: readonly ZCodePersistedMessage[],
  3373. messageId: string,
  3374. ): number {
  3375. return messages.findIndex(
  3376. (message) => message.id === messageId || message.mergedMessageIds?.includes(messageId) === true,
  3377. );
  3378. }
  3379. function getSnapshotGoalActiveIterationCount(snapshot: ZCodeSessionStateSnapshot): number {
  3380. const targetId = snapshot.projection.target?.targetId;
  3381. const timeline =
  3382. snapshot.runtime.goalVerificationTimeline?.filter(
  3383. (item) => !targetId || item.targetId === targetId,
  3384. ) ?? [];
  3385. return getZCodeGoalActiveIterationCount({
  3386. targetStatus: snapshot.projection.target?.status ?? null,
  3387. timeline,
  3388. });
  3389. }
  3390. function toZCodeDeliveryKind(
  3391. deliveryKind: "continuous" | "bot-channel-continuous" | "replayable" | "mixed" | undefined,
  3392. ): ZCodeDeliveryKind {
  3393. return deliveryKind === "replayable" ? "web-remote-replayable" : "desktop-continuous";
  3394. }
  3395. function backgroundTaskNotificationToolUpdatesFromInput(params: {
  3396. input: string | undefined;
  3397. inputId: InputId | undefined;
  3398. originMeta: unknown;
  3399. taskId: string;
  3400. traceId: TraceId;
  3401. }): Extract<ZCodeStreamEvent, { type: "tool_call_update" }>[] {
  3402. // 终态与失败原文优先取本轮 originMeta 的结构化结果,不解析 summary 文本。
  3403. // 合并轮的每条通知各自更新自己的工具。
  3404. return parseZCodeBackgroundTaskNotifications(params.input, params.originMeta).map((parsed) => {
  3405. const status = zcodeBackgroundTaskNotificationToolUpdateStatus(parsed.notification.status);
  3406. return {
  3407. type: "tool_call_update",
  3408. taskId: params.taskId,
  3409. traceId: params.traceId,
  3410. ...(params.inputId ? { inputId: params.inputId } : {}),
  3411. toolId: parsed.toolUseId,
  3412. status,
  3413. content: parsed.notification.result ?? parsed.notification.summary,
  3414. // replayable 动态事件也必须把 notification error 放到标准 tool error,
  3415. // 否则手机远控与桌面 continuous 的失败详情会产生分叉。
  3416. // 修复原因:合并轮没有结构化结果,通知里也没有 <error>,失败详情原来是空的。
  3417. ...(status === "failed"
  3418. ? { error: zcodeBackgroundTaskNotificationFailureText(parsed.notification) }
  3419. : {}),
  3420. raw: attachZCodeBackgroundTaskNotificationToRaw(
  3421. { toolCallId: parsed.toolUseId },
  3422. parsed.notification,
  3423. ),
  3424. };
  3425. });
  3426. }
  3427. function mapMessage(
  3428. message: ZCodeMessageWithParts,
  3429. goalIteration?: number,
  3430. backgroundTaskNotifications?: ReadonlyMap<string, ZCodeBackgroundTaskNotificationInfo>,
  3431. ): ZCodePersistedMessage {
  3432. const tools: ZCodePersistedToolCall[] = [];
  3433. const parts: ZCodePersistedMessagePart[] = [];
  3434. const attachments =
  3435. message.info.role === "user" ? mapPromptAttachmentsFromParts(message.parts) : undefined;
  3436. let syntheticTimeline: ZCodeTimelineMeta | undefined;
  3437. for (const part of message.parts) {
  3438. if (part.type === "text") {
  3439. // fork notice 等结构化 synthetic 消息把 timeline meta 写在 part.metadata 上;
  3440. // 持久化层不带 metadata 字段,所以提取一份挂到 message 级别供 UI 渲染分隔条。
  3441. if (!syntheticTimeline) {
  3442. const fromText = extractSyntheticTimelineFromTextPart(part);
  3443. if (fromText) {
  3444. syntheticTimeline = fromText;
  3445. }
  3446. }
  3447. } else if (part.type === "compaction" && !syntheticTimeline) {
  3448. // compact 的模型 summary/timelineText 属于 agent 内部上下文,不能作为正文透出。
  3449. // 持久化恢复只从结构化字段合成横线,展示文案由 UI/TUI 本地 i18n 决定。
  3450. syntheticTimeline = synthesizeCompactionTimeline(part);
  3451. }
  3452. }
  3453. for (const part of message.parts) {
  3454. if (part.type === "text") {
  3455. parts.push({ type: "content", content: part.text });
  3456. } else if (part.type === "reasoning") {
  3457. parts.push({ type: "thought", content: part.text });
  3458. } else if (part.type === "tool") {
  3459. const toolIndex = tools.length;
  3460. tools.push(mapToolPart(part, backgroundTaskNotifications));
  3461. parts.push({ type: "tool-call", toolIndex });
  3462. }
  3463. }
  3464. return {
  3465. id: message.info.messageId,
  3466. role: message.info.role,
  3467. content: textFromParts(message.parts),
  3468. timestamp: message.info.time.created,
  3469. // 未绑定恢复仍需呈现完整历史,不能为缺失的消息来源补默认模型。
  3470. model: message.info.model ? formatModelPickerValue(message.info.model) : undefined,
  3471. ...(syntheticTimeline ? { syntheticTimeline } : {}),
  3472. ...(attachments ? { attachments } : {}),
  3473. ...(message.info.role === "assistant"
  3474. ? {
  3475. ...(goalIteration ? { goalIteration } : {}),
  3476. durationMs: message.info.time.completed
  3477. ? message.info.time.completed - message.info.time.created
  3478. : undefined,
  3479. thought: reasoningFromParts(message.parts),
  3480. tools: tools.length > 0 ? tools : undefined,
  3481. parts: parts.length > 0 ? parts : undefined,
  3482. }
  3483. : {}),
  3484. };
  3485. }
  3486. function mapPromptAttachmentsFromParts(
  3487. parts: readonly ZCodeMessagePart[],
  3488. ): ZCodePromptAttachment[] | undefined {
  3489. const attachments = parts
  3490. .filter((part): part is Extract<ZCodeMessagePart, { type: "file" }> => part.type === "file")
  3491. .map(mapPromptAttachmentFromFilePart)
  3492. .filter((attachment): attachment is ZCodePromptAttachment => attachment !== undefined);
  3493. return attachments.length > 0 ? attachments : undefined;
  3494. }
  3495. function mapPromptAttachmentFromFilePart(
  3496. part: Extract<ZCodeMessagePart, { type: "file" }>,
  3497. ): ZCodePromptAttachment | undefined {
  3498. const mimeType = part.mime || "application/octet-stream";
  3499. const metadata = asRecord(part.metadata);
  3500. const filename = part.filename?.trim() || filenameFromPathLike(part.url) || "attachment";
  3501. const sizeBytes = numberValue(metadata.sizeBytes);
  3502. const dataBase64 = dataBase64FromDataUrl(part.url);
  3503. const localPath = localPathFromAttachmentPart(part.url, metadata);
  3504. // 历史恢复链路之前只把 file part 当作模型上下文,不回填 UI 的 attachments 字段。
  3505. // 用户消息恢复后附件 chip 因此消失;这里从 agent 持久化的 file part 反投影回发送时的附件形态。
  3506. if (mimeType.startsWith("image/")) {
  3507. return {
  3508. kind: "image",
  3509. filename,
  3510. mimeType,
  3511. ...(sizeBytes !== undefined ? { sizeBytes } : {}),
  3512. ...(dataBase64 ? { dataBase64 } : {}),
  3513. ...(localPath ? { localPath } : {}),
  3514. };
  3515. }
  3516. if (mimeType.startsWith("audio/")) {
  3517. return {
  3518. kind: "audio",
  3519. filename,
  3520. mimeType,
  3521. ...(dataBase64 ? { dataBase64 } : {}),
  3522. ...(localPath ? { localPath } : {}),
  3523. };
  3524. }
  3525. if (mimeType.startsWith("video/")) {
  3526. return {
  3527. kind: "video",
  3528. filename,
  3529. mimeType,
  3530. ...(sizeBytes !== undefined ? { sizeBytes } : {}),
  3531. ...(dataBase64 ? { dataBase64 } : {}),
  3532. ...(localPath ? { localPath } : {}),
  3533. };
  3534. }
  3535. const preview = asRecord(metadata.preview);
  3536. const textContent = !localPath ? stringValue(preview.text) : undefined;
  3537. return {
  3538. kind: "file",
  3539. filename,
  3540. mimeType,
  3541. sizeBytes: sizeBytes ?? 0,
  3542. ...(dataBase64 ? { dataBase64 } : {}),
  3543. ...(textContent !== undefined ? { textContent } : {}),
  3544. ...(localPath ? { localPath } : {}),
  3545. };
  3546. }
  3547. function dataBase64FromDataUrl(value: string): string | undefined {
  3548. const match = /^data:[^;,]+;base64,(.*)$/i.exec(value);
  3549. return match?.[1] || undefined;
  3550. }
  3551. function localPathFromAttachmentPart(
  3552. url: string,
  3553. metadata: Record<string, unknown>,
  3554. ): string | undefined {
  3555. const originalUrl = stringValue(metadata.originalUrl);
  3556. if (originalUrl && isAbsolutePathLike(originalUrl)) {
  3557. return originalUrl;
  3558. }
  3559. return isAbsolutePathLike(url) ? url : undefined;
  3560. }
  3561. function isAbsolutePathLike(value: string): boolean {
  3562. return value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\");
  3563. }
  3564. function filenameFromPathLike(value: string): string | undefined {
  3565. if (value.startsWith("data:")) {
  3566. return undefined;
  3567. }
  3568. const pathPart = value.split(/[?#]/u)[0] ?? "";
  3569. const segments = pathPart.split(/[\\/]/u).filter(Boolean);
  3570. const filename = segments.at(-1)?.trim();
  3571. return filename && !filename.includes("://") ? filename : undefined;
  3572. }
  3573. function extractSyntheticTimelineFromTextPart(
  3574. part: Extract<ZCodeMessagePart, { type: "text" }>,
  3575. ): ZCodeTimelineMeta | undefined {
  3576. const metadata = part.metadata;
  3577. if (!metadata || typeof metadata !== "object") return undefined;
  3578. const forkContext = (metadata as Record<string, unknown>)["forkContext"];
  3579. if (!forkContext || typeof forkContext !== "object") return undefined;
  3580. const ctx = forkContext as Record<string, unknown>;
  3581. if (ctx["kind"] !== "session_fork") return undefined;
  3582. const parentSessionId = typeof ctx["parentSessionId"] === "string" ? ctx["parentSessionId"] : "";
  3583. const targetMessageId = typeof ctx["targetMessageId"] === "string" ? ctx["targetMessageId"] : "";
  3584. const targetCheckpointId =
  3585. typeof ctx["targetCheckpointId"] === "string" ? ctx["targetCheckpointId"] : undefined;
  3586. if (!parentSessionId || !targetMessageId) return undefined;
  3587. return {
  3588. version: 1,
  3589. kind: "synthetic",
  3590. type: "session_fork",
  3591. display: "separator",
  3592. parentSessionId,
  3593. targetMessageId,
  3594. ...(targetCheckpointId ? { targetCheckpointId } : {}),
  3595. ...(typeof ctx["restoredFileCount"] === "number"
  3596. ? { restoredFileCount: ctx["restoredFileCount"] }
  3597. : {}),
  3598. };
  3599. }
  3600. function synthesizeCompactionTimeline(
  3601. part: Extract<ZCodeMessagePart, { type: "compaction" }>,
  3602. ): ZCodeTimelineMeta | undefined {
  3603. const metadata = asRecord(part.metadata);
  3604. const operationId = stringValue(metadata.operationId) ?? part.partId;
  3605. const status = timelineStatusValue(metadata.timelineStatus);
  3606. if (!status && !part.summaryMessageId) {
  3607. // compact summary user message 也带 compaction metadata,
  3608. // 但它是模型上下文,不是 UI timeline;否则 snapshot 恢复会多渲染一条横线。
  3609. return undefined;
  3610. }
  3611. const trigger = timelineTriggerValue(metadata.trigger) ?? (part.auto ? "auto" : "manual");
  3612. const replace = booleanValue(metadata.replace);
  3613. const reason = part.reason ?? stringValue(metadata.reason);
  3614. const boundaryId = stringValue(metadata.boundaryId) ?? part.summaryMessageId;
  3615. const summaryMessageId = part.summaryMessageId ?? stringValue(metadata.summaryMessageId);
  3616. const preCompactTokenCount = numberValue(metadata.preCompactTokenCount);
  3617. const postCompactTokenCount = numberValue(metadata.postCompactTokenCount);
  3618. const truePostCompactTokenCount = numberValue(metadata.truePostCompactTokenCount);
  3619. const attempt = numberValue(metadata.attempt);
  3620. const maxAttempts = numberValue(metadata.maxAttempts);
  3621. const startedAt = numberValue(metadata.startedAt);
  3622. const endedAt = numberValue(metadata.endedAt);
  3623. return {
  3624. version: 1,
  3625. kind: "synthetic",
  3626. type: "context_compaction",
  3627. operationId,
  3628. status: status ?? "completed",
  3629. trigger,
  3630. display: "separator",
  3631. ...(replace !== undefined ? { replace } : {}),
  3632. ...(reason ? { reason } : {}),
  3633. ...(boundaryId ? { boundaryId } : {}),
  3634. ...(summaryMessageId ? { summaryMessageId } : {}),
  3635. ...(preCompactTokenCount !== undefined ? { preCompactTokenCount } : {}),
  3636. ...(postCompactTokenCount !== undefined ? { postCompactTokenCount } : {}),
  3637. ...(truePostCompactTokenCount !== undefined ? { truePostCompactTokenCount } : {}),
  3638. ...(attempt !== undefined ? { attempt } : {}),
  3639. ...(maxAttempts !== undefined ? { maxAttempts } : {}),
  3640. ...(startedAt !== undefined ? { startedAt } : {}),
  3641. ...(endedAt !== undefined ? { endedAt } : {}),
  3642. };
  3643. }
  3644. function mapToolPart(
  3645. part: Extract<ZCodeMessagePart, { type: "tool" }>,
  3646. backgroundTaskNotifications?: ReadonlyMap<string, ZCodeBackgroundTaskNotificationInfo>,
  3647. ): ZCodePersistedToolCall {
  3648. const state = part.state;
  3649. const taskNotification = backgroundTaskNotifications?.get(part.callId);
  3650. // ZCode Protocol 的 part.callId 是实时流和终态 snapshot 共同的工具身份。
  3651. // 以前只保存 metadata 会丢掉 toolCallId,手机 replayable 里 result-only 临时工具就无法被终态快照覆盖。
  3652. const raw = attachZCodeBackgroundTaskNotificationToRaw(
  3653. attachToolCallIdToRaw("metadata" in state ? (state.metadata ?? state) : state, part.callId),
  3654. taskNotification,
  3655. );
  3656. if (state.status === "completed") {
  3657. // snapshot 里的 completed 是 background Agent launch ACK;failed
  3658. // notification 必须在 replayable restore 中覆盖它,但不能顺带改变 stopped 等既有语义。
  3659. const notificationStatus = taskNotification?.status
  3660. ? zcodeBackgroundTaskNotificationToolUpdateStatus(taskNotification.status)
  3661. : undefined;
  3662. const notificationFailed = notificationStatus === "failed";
  3663. return {
  3664. toolName: part.tool,
  3665. title: state.title || part.tool,
  3666. kind: part.tool,
  3667. status: notificationFailed ? "failed" : "completed",
  3668. input: state.input,
  3669. output: state.output,
  3670. ...(notificationFailed && taskNotification
  3671. ? { error: zcodeBackgroundTaskNotificationFailureText(taskNotification) }
  3672. : {}),
  3673. raw,
  3674. };
  3675. }
  3676. if (state.status === "error") {
  3677. return {
  3678. toolName: part.tool,
  3679. title: part.tool,
  3680. kind: part.tool,
  3681. status: "failed",
  3682. input: state.input,
  3683. error: state.error,
  3684. raw,
  3685. };
  3686. }
  3687. return {
  3688. toolName: part.tool,
  3689. title: "title" in state && state.title ? state.title : part.tool,
  3690. kind: part.tool,
  3691. input: state.input,
  3692. raw,
  3693. };
  3694. }
  3695. function attachToolCallIdToRaw(raw: unknown, toolCallId: string): unknown {
  3696. if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
  3697. return { toolCallId, raw };
  3698. }
  3699. return {
  3700. ...raw,
  3701. toolCallId:
  3702. typeof (raw as Record<string, unknown>).toolCallId === "string"
  3703. ? (raw as Record<string, unknown>).toolCallId
  3704. : toolCallId,
  3705. };
  3706. }
  3707. function textFromParts(parts: readonly ZCodeMessagePart[]): string {
  3708. return textFromZCodeMessageParts(parts);
  3709. }
  3710. function reasoningFromParts(parts: readonly ZCodeMessagePart[]): string | undefined {
  3711. const text = parts
  3712. .filter(
  3713. (part): part is Extract<ZCodeMessagePart, { type: "reasoning" }> => part.type === "reasoning",
  3714. )
  3715. .map((part) => part.text)
  3716. .join("");
  3717. return text || undefined;
  3718. }
  3719. function fromZCodeGoal(goal: unknown): ZCodeTaskGoal {
  3720. const record = asRecord(goal);
  3721. const time = asRecord(record.time);
  3722. const status = stringValue(record.status);
  3723. return {
  3724. sessionID: stringValue(record.sessionID) ?? stringValue(record.sessionId) ?? "",
  3725. targetID: stringValue(record.targetID) ?? stringValue(record.targetId) ?? "",
  3726. objective: stringValue(record.objective) ?? "",
  3727. summaryTitle: stringValue(record.summaryTitle) ?? null,
  3728. status: isZCodeTaskGoalStatus(status) ? status : "active",
  3729. tokenBudget: typeof record.tokenBudget === "number" ? record.tokenBudget : null,
  3730. tokensUsed: numberValue(record.tokensUsed) ?? 0,
  3731. timeUsedSeconds: numberValue(record.timeUsedSeconds) ?? 0,
  3732. time: {
  3733. created: numberValue(time.created) ?? numberValue(record.createdAt) ?? 0,
  3734. updated: numberValue(time.updated) ?? numberValue(record.updatedAt) ?? 0,
  3735. },
  3736. };
  3737. }
  3738. function isZCodeTaskGoalStatus(status: string | undefined): status is ZCodeTaskGoal["status"] {
  3739. return (
  3740. status === "active" ||
  3741. status === "paused" ||
  3742. status === "budget_limited" ||
  3743. status === "complete"
  3744. );
  3745. }
  3746. function sessionTodosToPlanSteps(
  3747. todos: ZCodeSessionStateSnapshot["todos"],
  3748. ): ZCodePlanStep[] | null {
  3749. if (!todos || todos.length === 0) {
  3750. return null;
  3751. }
  3752. return todos.map((todo, index) => ({
  3753. id: `todo-${index}`,
  3754. status: todo.status,
  3755. title: todo.content,
  3756. }));
  3757. }
  3758. function sessionGoalStatsToRuntime(
  3759. stats: ZCodeSessionStateSnapshot["goalStats"],
  3760. ): ZCodeTaskGoalStats | null {
  3761. return stats ? { ...stats } : null;
  3762. }
  3763. function sessionTodoGroupsToRuntime(
  3764. groups: ZCodeSessionStateSnapshot["todoGroups"],
  3765. ): ZCodeTodoGroup[] | null {
  3766. if (!groups || groups.length === 0) {
  3767. return null;
  3768. }
  3769. return groups.map((group) => ({
  3770. id: group.id,
  3771. source: group.source,
  3772. ...(group.goalIteration ? { goalIteration: group.goalIteration } : {}),
  3773. ...(group.targetId ? { targetId: group.targetId } : {}),
  3774. ...(group.startedAt ? { startedAt: group.startedAt } : {}),
  3775. ...(group.updatedAt ? { updatedAt: group.updatedAt } : {}),
  3776. todos: group.todos.map((todo, index) => ({
  3777. id: `${group.id}-todo-${index}`,
  3778. status: todo.status,
  3779. title: todo.content,
  3780. })),
  3781. }));
  3782. }
  3783. function mapStateUpdated(
  3784. params: TaskTarget,
  3785. notification: ZCodeStateUpdatedNotification,
  3786. ): ZCodeStreamEvent[] {
  3787. const parsedSettings = zcodeSessionSettingsStateSchema.safeParse(notification.patch);
  3788. if (!parsedSettings.success) {
  3789. return [];
  3790. }
  3791. const traceId = generateTraceId(params.taskId);
  3792. return [
  3793. {
  3794. type: "mode_update",
  3795. taskId: params.taskId,
  3796. traceId,
  3797. currentModeId: normalizeAvailableZCodeMode(parsedSettings.data.mode.current),
  3798. availableModes: getZCodeAgentAvailableModes(),
  3799. },
  3800. {
  3801. type: "glm_agent_model_state_update",
  3802. taskId: params.taskId,
  3803. traceId,
  3804. version: 1,
  3805. sessionId: params.taskId,
  3806. reason:
  3807. notification.reason === "thought_level_changed"
  3808. ? "thought_level_changed"
  3809. : notification.reason === "model_changed"
  3810. ? "model_changed"
  3811. : "session_initialized",
  3812. model: {
  3813. currentValue: formatModelPickerValue(parsedSettings.data.model.current),
  3814. },
  3815. thoughtLevel: {
  3816. enabled: parsedSettings.data.thoughtLevel.enabled,
  3817. currentValue: parsedSettings.data.thoughtLevel.current,
  3818. options: parsedSettings.data.thoughtLevel.available.map((option) => ({
  3819. value: option.value,
  3820. name: option.label,
  3821. })),
  3822. },
  3823. contextWindow: {
  3824. tokens:
  3825. parsedSettings.data.model.available.find(
  3826. (option) =>
  3827. formatModelPickerValue(option.ref) ===
  3828. formatModelPickerValue(parsedSettings.data.model.current),
  3829. )?.contextWindow ?? 0,
  3830. },
  3831. },
  3832. ];
  3833. }
  3834. function mapSessionEvent(
  3835. params: TaskTarget,
  3836. event: ZCodeSessionEvent,
  3837. streamedTurnText: Map<string, { messageId?: string; text: string }>,
  3838. activePromptInputId?: InputId,
  3839. toolProjectionMemory?: ZCodeToolProjectionMemory,
  3840. backgroundTaskControlsByTaskKey?: Map<string, ZCodeBackgroundTaskControlItem[]>,
  3841. hasActiveApiRetry = false,
  3842. ): ZCodeStreamEvent[] {
  3843. const protocolTraceId = event.traceId ?? generateTraceId(params.taskId);
  3844. const payload = asRecord(event.payload);
  3845. const inputId = stringValue(payload.inputId);
  3846. const queryId = stringValue(payload.queryId);
  3847. // 兼容层对外的 traceId 语义是“一次用户输入到本轮回复结束”的轮次标识。
  3848. // ZCode Protocol runtime trace 只在事件没有 inputId 时兜底,避免同一轮 chunk/tool/complete 被拆成不同 trace。
  3849. const eventInputId = inputId ?? activePromptInputId;
  3850. const traceId = eventInputId ?? protocolTraceId;
  3851. if (eventInputId && eventInputId !== protocolTraceId) {
  3852. logger.debug(
  3853. eventInputId,
  3854. `对齐 ZCode prompt inputId eventType=${event.type} protocolTrace=${protocolTraceId}`,
  3855. );
  3856. }
  3857. const turnKey = `${resolveWorkspaceKey(params)}:${event.sessionId}:${event.turnId ?? eventInputId ?? traceId}`;
  3858. if (event.type === "turn.started") {
  3859. streamedTurnText.delete(turnKey);
  3860. const inputOrigin = asRecord(payload.intent).inputOrigin;
  3861. const runStartedEvent: ZCodeStreamEvent = {
  3862. ...(inputOrigin === "desktop" || inputOrigin === "mobile" ? { inputOrigin } : {}),
  3863. type: "task_run_started",
  3864. taskId: params.taskId,
  3865. traceId,
  3866. ...(eventInputId ? { inputId: eventInputId } : {}),
  3867. ...(event.turnId ? { turnId: event.turnId } : {}),
  3868. startedAt: event.timestamp,
  3869. };
  3870. const taskNotificationToolUpdates = backgroundTaskNotificationToolUpdatesFromInput({
  3871. input: stringValue(payload.input),
  3872. originMeta: payload.originMeta,
  3873. taskId: params.taskId,
  3874. traceId,
  3875. inputId: eventInputId,
  3876. });
  3877. if (taskNotificationToolUpdates.length > 0) {
  3878. return [runStartedEvent, ...taskNotificationToolUpdates];
  3879. }
  3880. if (
  3881. stringValue(payload.inputSource) === "goal-continuation" &&
  3882. stringValue(payload.inputVisibility) === "model-only"
  3883. ) {
  3884. return [
  3885. runStartedEvent,
  3886. {
  3887. type: "goal_iteration_started",
  3888. taskId: params.taskId,
  3889. traceId,
  3890. ...(eventInputId ? { inputId: eventInputId } : {}),
  3891. ...(stringValue(payload.targetId) ? { targetId: stringValue(payload.targetId) } : {}),
  3892. startedAt: event.timestamp,
  3893. },
  3894. ];
  3895. }
  3896. return [runStartedEvent];
  3897. }
  3898. const compactTimeline = mapCompactTimelinePayload(params.taskId, traceId, eventInputId, payload);
  3899. if (compactTimeline) {
  3900. return [compactTimeline];
  3901. }
  3902. const partTimeline = mapSyntheticTimelinePartPayload(
  3903. params.taskId,
  3904. traceId,
  3905. eventInputId,
  3906. payload,
  3907. );
  3908. if (partTimeline) {
  3909. return [partTimeline];
  3910. }
  3911. const modelStreaming = mapModelStreaming(
  3912. params.taskId,
  3913. traceId,
  3914. eventInputId,
  3915. payload,
  3916. toolProjectionMemory,
  3917. );
  3918. const apiRetryClearEvent = maybeBuildApiRetryClearOnModelProgress(
  3919. hasActiveApiRetry,
  3920. params.taskId,
  3921. traceId,
  3922. eventInputId,
  3923. payload,
  3924. );
  3925. if (modelStreaming) {
  3926. if (modelStreaming.type === "agent_message_chunk" && !modelStreaming.parentToolUseId) {
  3927. const previous = streamedTurnText.get(turnKey);
  3928. const messageId = modelStreaming.messageId;
  3929. const sameMessage = !messageId || !previous?.messageId || messageId === previous.messageId;
  3930. streamedTurnText.set(turnKey, {
  3931. messageId: messageId ?? previous?.messageId,
  3932. text: (sameMessage ? (previous?.text ?? "") : "") + modelStreaming.content,
  3933. });
  3934. }
  3935. return apiRetryClearEvent ? [apiRetryClearEvent, modelStreaming] : [modelStreaming];
  3936. }
  3937. if (apiRetryClearEvent) {
  3938. return [apiRetryClearEvent];
  3939. }
  3940. if (event.type === "tool.updated") {
  3941. // 工具调用前的前言不是最终回答;下一条模型消息需要独立核对已接收正文。
  3942. if (payload.kind === "scheduled" && !parentToolUseIdFromToolPayload(payload)) {
  3943. streamedTurnText.delete(turnKey);
  3944. }
  3945. return mapToolUpdated(params.taskId, traceId, eventInputId, payload, toolProjectionMemory);
  3946. }
  3947. if (event.type === "permission.requested") {
  3948. const toolCallId = stringValue(payload.toolCallId);
  3949. const toolName = stringValue(payload.toolName);
  3950. if (toolCallId && toolName) {
  3951. toolProjectionMemory?.toolNameById?.set(toolCallId, toolName);
  3952. }
  3953. if (isUserInputBackedPermissionToolName(toolName)) {
  3954. // AskUserQuestion/ExitPlanMode 的 permission.requested 只是 core 的等待态标记;
  3955. // 真正需要展示的问题会通过 interaction/requestUserInput 到达。继续把它投成普通权限,
  3956. // UI 会出现 Allow/Deny 弹窗且无法把答案写回工具 input。
  3957. return [];
  3958. }
  3959. return [permissionPayloadToStreamEvent(params.taskId, traceId, eventInputId, payload)];
  3960. }
  3961. if (event.type === "permission.resolved") {
  3962. return permissionResolvedPayloadToStreamEvents(
  3963. params.taskId,
  3964. traceId,
  3965. eventInputId,
  3966. payload,
  3967. toolProjectionMemory?.toolNameById,
  3968. );
  3969. }
  3970. if (event.type === "turn.steerQueued") {
  3971. const source = turnSteerSourceValue(payload.source);
  3972. return [
  3973. {
  3974. type: "turn_steer_queued",
  3975. taskId: params.taskId,
  3976. traceId,
  3977. ...(eventInputId ? { inputId: eventInputId } : {}),
  3978. ...(queryId ? { queryId } : {}),
  3979. pendingInputId: stringValue(payload.pendingInputId) ?? event.eventId,
  3980. messageId: eventInputId,
  3981. ...(turnSteerCommandKindValue(payload.commandKind)
  3982. ? { commandKind: turnSteerCommandKindValue(payload.commandKind) }
  3983. : {}),
  3984. ...(source ? { source } : {}),
  3985. targetTurnId: stringValue(payload.targetTurnId),
  3986. content: stringValue(payload.input) ?? "",
  3987. raw: payload,
  3988. },
  3989. ];
  3990. }
  3991. if (event.type === "turn.steerDrained") {
  3992. return [
  3993. {
  3994. type: "turn_steer_status",
  3995. taskId: params.taskId,
  3996. traceId,
  3997. ...(eventInputId ? { inputId: eventInputId } : {}),
  3998. ...(stringArray(payload.queryIds).length > 0
  3999. ? { queryIds: stringArray(payload.queryIds) }
  4000. : {}),
  4001. status: "drained",
  4002. pendingInputIds: stringArray(payload.pendingInputIds),
  4003. injectedMessageIds: stringArray(payload.injectedMessageIds),
  4004. targetTurnId: stringValue(payload.targetTurnId),
  4005. raw: payload,
  4006. },
  4007. ];
  4008. }
  4009. if (event.type === "turn.completed") {
  4010. const events: ZCodeStreamEvent[] = [];
  4011. const response = stringValue(payload.response);
  4012. // Bugfix: 只记录“本轮收到过文字”会让工具前言屏蔽最终回答兜底。
  4013. // 在终态之前补齐当前模型消息缺少的后缀;完整正文已到达时不重复投递。
  4014. const streamed = streamedTurnText.get(turnKey)?.text ?? "";
  4015. const missingResponse = response?.startsWith(streamed)
  4016. ? response.slice(streamed.length)
  4017. : response;
  4018. if (missingResponse) {
  4019. events.push({
  4020. type: "agent_message_chunk",
  4021. taskId: params.taskId,
  4022. traceId,
  4023. ...(eventInputId ? { inputId: eventInputId } : {}),
  4024. content: missingResponse,
  4025. });
  4026. }
  4027. events.push({
  4028. type: "task_complete",
  4029. taskId: params.taskId,
  4030. traceId,
  4031. ...(eventInputId ? { inputId: eventInputId } : {}),
  4032. stopReason: stringValue(payload.resultType) ?? "complete",
  4033. usage: usageFromPayload(payload.usage),
  4034. });
  4035. toolProjectionMemory?.streamingToolInputById?.clear();
  4036. streamedTurnText.delete(turnKey);
  4037. return events;
  4038. }
  4039. if (event.type === "turn.failed") {
  4040. toolProjectionMemory?.streamingToolInputById?.clear();
  4041. streamedTurnText.delete(turnKey);
  4042. const errorPayload = asRecord(payload.error);
  4043. if (stringValue(payload.turnPhase) === "compact") {
  4044. return [
  4045. compactFailureToTimelineEvent(
  4046. params.taskId,
  4047. traceId,
  4048. eventInputId,
  4049. stringValue(errorPayload.message) ?? "ZCode compact failed",
  4050. ),
  4051. ];
  4052. }
  4053. const attribution = errorAttributionSchema.safeParse(errorPayload.attribution);
  4054. // dynamic task event 也会写入 task index;只修 snapshot 读路径仍会丢 live 归因。
  4055. return [
  4056. {
  4057. type: "task_error",
  4058. taskId: params.taskId,
  4059. traceId,
  4060. ...(eventInputId ? { inputId: eventInputId } : {}),
  4061. error: stringValue(errorPayload.message) ?? "ZCode session failed",
  4062. // type 是外层错误分类,code 才是 provider/subagent 要展示的真实错误码。
  4063. code: stringValue(errorPayload.code) ?? stringValue(errorPayload.type),
  4064. detail: stringValue(errorPayload.detail),
  4065. ...(attribution.success ? { attribution: attribution.data } : {}),
  4066. },
  4067. ];
  4068. }
  4069. return mapSessionInfoLikePayload(
  4070. params.taskId,
  4071. traceId,
  4072. eventInputId,
  4073. event.eventId,
  4074. payload,
  4075. backgroundTaskControlsByTaskKey,
  4076. `${resolveWorkspaceKey(params)}\u0000${params.taskId}`,
  4077. );
  4078. }
  4079. function maybeBuildApiRetryClearOnModelProgress(
  4080. hasActiveApiRetry: boolean,
  4081. taskId: string,
  4082. traceId: TraceId,
  4083. inputId: InputId | undefined,
  4084. payload: Record<string, unknown>,
  4085. ): Extract<ZCodeStreamEvent, { type: "session_info_update" }> | null {
  4086. if (!hasActiveApiRetry || !isZCodeModelRetryRecoveryProgressPayload(payload)) {
  4087. return null;
  4088. }
  4089. // 重试请求开始不代表恢复成功,立即清会让输入栏闪烁;
  4090. // 只有 retry attempt 真的产出模型内容,才清掉“重试中”运行态。
  4091. return {
  4092. type: "session_info_update",
  4093. taskId,
  4094. traceId,
  4095. ...(inputId ? { inputId } : {}),
  4096. apiRetry: null,
  4097. };
  4098. }
  4099. function mapModelStreaming(
  4100. taskId: string,
  4101. traceId: TraceId,
  4102. inputId: InputId | undefined,
  4103. payload: Record<string, unknown>,
  4104. toolProjectionMemory?: ZCodeToolProjectionMemory,
  4105. ): ZCodeStreamEvent | null {
  4106. const kind = stringValue(payload.kind);
  4107. const delta = stringValue(payload.delta);
  4108. const parentToolUseId = parentToolUseIdFromToolPayload(payload);
  4109. if (kind === "text_delta") {
  4110. if (!delta) {
  4111. return null;
  4112. }
  4113. return {
  4114. type: "agent_message_chunk",
  4115. taskId,
  4116. traceId,
  4117. ...(inputId ? { inputId } : {}),
  4118. ...(parentToolUseId ? { parentToolUseId } : {}),
  4119. messageId: stringValue(payload.assistantMessageId),
  4120. content: delta,
  4121. };
  4122. }
  4123. if (kind === "reasoning_delta") {
  4124. if (!delta) {
  4125. return null;
  4126. }
  4127. return {
  4128. type: "agent_thought_chunk",
  4129. taskId,
  4130. traceId,
  4131. ...(inputId ? { inputId } : {}),
  4132. ...(parentToolUseId ? { parentToolUseId } : {}),
  4133. content: delta,
  4134. };
  4135. }
  4136. return mapToolInputStreaming(taskId, traceId, inputId, payload, toolProjectionMemory);
  4137. }
  4138. function mapToolInputStreaming(
  4139. taskId: string,
  4140. traceId: TraceId,
  4141. inputId: InputId | undefined,
  4142. payload: Record<string, unknown>,
  4143. toolProjectionMemory?: ZCodeToolProjectionMemory,
  4144. ): ZCodeStreamEvent | null {
  4145. const streamingToolInputById = toolProjectionMemory?.streamingToolInputById;
  4146. const toolNameById = toolProjectionMemory?.toolNameById;
  4147. const kind = stringValue(payload.kind);
  4148. const toolId = stringValue(payload.toolCallId);
  4149. if (!toolId) {
  4150. return null;
  4151. }
  4152. const toolName = stringValue(payload.toolName) ?? toolNameById?.get(toolId);
  4153. if (toolName) {
  4154. toolNameById?.set(toolId, toolName);
  4155. }
  4156. const title = toolName ?? "tool";
  4157. const parentToolUseId = parentToolUseIdFromToolPayload(payload);
  4158. const buildRaw = (input: unknown, rawInput: string | undefined) => ({
  4159. ...payload,
  4160. ...(input !== undefined ? { input } : {}),
  4161. ...(rawInput ? { streamingRawInputLength: rawInput.length } : {}),
  4162. });
  4163. if (kind === "tool_input_start") {
  4164. streamingToolInputById?.set(toolId, { rawInput: "" });
  4165. logStreamingToolInputProjection(traceId, {
  4166. inputKeys: [],
  4167. kind,
  4168. projectedType: "tool_call",
  4169. rawInputLength: 0,
  4170. taskId,
  4171. toolId,
  4172. toolName,
  4173. });
  4174. return {
  4175. type: "tool_call",
  4176. taskId,
  4177. traceId,
  4178. ...(inputId ? { inputId } : {}),
  4179. toolId,
  4180. parentToolUseId,
  4181. input: {},
  4182. toolName,
  4183. kind: title,
  4184. title,
  4185. raw: buildRaw({}, undefined),
  4186. };
  4187. }
  4188. if (kind === "tool_input_delta") {
  4189. const state = appendZCodeStreamingToolInputDelta(
  4190. streamingToolInputById?.get(toolId),
  4191. stringValue(payload.delta) ?? "",
  4192. );
  4193. streamingToolInputById?.set(toolId, state);
  4194. if (!shouldMaterializeZCodeStreamingToolInputPreview(state, { toolName })) {
  4195. // 性能修复:services 兼容投影曾经每个 delta 都解析累计 JSON,并把 rawInput 全量塞进 raw。
  4196. // 这里先只维护 tombstone buffer,达到预算或控制边界再 emit,避免 host/renderer 双端 O(n²)。
  4197. return null;
  4198. }
  4199. const preview = buildZCodeStreamingToolInputPreview(state.rawInput);
  4200. markZCodeStreamingToolInputPreviewMaterialized(state);
  4201. const previewToolName = toolName ?? inferStreamingToolInputToolName(preview.input);
  4202. const previewTitle = previewToolName ?? title;
  4203. if (previewToolName && !toolName) {
  4204. toolNameById?.set(toolId, previewToolName);
  4205. }
  4206. logStreamingToolInputProjection(traceId, {
  4207. inputKeys: inputPreviewKeys(preview.input),
  4208. kind,
  4209. projectedType: "tool_call_update",
  4210. rawInputLength: state.rawInput.length,
  4211. taskId,
  4212. toolId,
  4213. toolName: previewToolName,
  4214. });
  4215. return {
  4216. type: "tool_call_update",
  4217. taskId,
  4218. traceId,
  4219. ...(inputId ? { inputId } : {}),
  4220. toolId,
  4221. parentToolUseId,
  4222. status: "pending",
  4223. title: previewTitle,
  4224. toolName: previewToolName,
  4225. kind: previewTitle,
  4226. input: preview.input,
  4227. raw: buildRaw(preview.input, preview.rawInput),
  4228. };
  4229. }
  4230. if (kind === "tool_input_end") {
  4231. const state = streamingToolInputById?.get(toolId) ?? { rawInput: "" };
  4232. const previewToolName = toolName ?? title;
  4233. const previewTitle = previewToolName ?? title;
  4234. logStreamingToolInputProjection(traceId, {
  4235. inputKeys: [],
  4236. kind,
  4237. projectedType: "tool_call_update",
  4238. rawInputLength: state.rawInput.length,
  4239. taskId,
  4240. toolId,
  4241. toolName: previewToolName,
  4242. });
  4243. return {
  4244. type: "tool_call_update",
  4245. taskId,
  4246. traceId,
  4247. ...(inputId ? { inputId } : {}),
  4248. toolId,
  4249. parentToolUseId,
  4250. status: "pending",
  4251. title: previewTitle,
  4252. toolName: previewToolName,
  4253. kind: previewTitle,
  4254. // 性能修复:tool_input_end 与最终 tool_call 相邻时不再重复解析同一份大 JSON;
  4255. // end 只作为生命周期边界,完整 input 交给 tool_call 一次性落库/渲染。
  4256. raw: buildRaw(undefined, state.rawInput),
  4257. };
  4258. }
  4259. if (kind === "tool_call") {
  4260. const state = streamingToolInputById?.get(toolId);
  4261. const rawInput = state?.rawInput ?? "";
  4262. const hasCompleteInput = "input" in payload;
  4263. const completeInput = hasCompleteInput ? payload.input : undefined;
  4264. const preview = buildZCodeStreamingToolInputPreview(
  4265. rawInput,
  4266. hasCompleteInput ? completeInput : undefined,
  4267. );
  4268. const previewToolName = toolName ?? inferStreamingToolInputToolName(preview.input);
  4269. const previewTitle = previewToolName ?? title;
  4270. if (previewToolName && !toolName) {
  4271. toolNameById?.set(toolId, previewToolName);
  4272. }
  4273. if ((hasCompleteInput || preview.complete) && toolProjectionMemory) {
  4274. finalizeZCodeToolProjectionInput(toolId, preview.input, toolProjectionMemory);
  4275. }
  4276. streamingToolInputById?.set(toolId, {
  4277. // 性能修复:最终 tool_call 已经持有完整 input,compat projection 不再长期保留
  4278. // streaming raw buffer,避免并发长任务时 host 侧内存和序列化成本继续放大。
  4279. rawInput: "",
  4280. deltaCount: state?.deltaCount,
  4281. lastPreviewAt: Date.now(),
  4282. lastPreviewRawInputLength: rawInput.length,
  4283. });
  4284. logStreamingToolInputProjection(traceId, {
  4285. inputKeys: inputPreviewKeys(preview.input),
  4286. kind,
  4287. projectedType: "tool_call_update",
  4288. rawInputLength: rawInput.length,
  4289. taskId,
  4290. toolId,
  4291. toolName: previewToolName,
  4292. });
  4293. return {
  4294. type: "tool_call_update",
  4295. taskId,
  4296. traceId,
  4297. ...(inputId ? { inputId } : {}),
  4298. toolId,
  4299. parentToolUseId,
  4300. status: "pending",
  4301. title: previewTitle,
  4302. toolName: previewToolName,
  4303. kind: previewTitle,
  4304. input: preview.input,
  4305. raw: buildRaw(preview.input, preview.rawInput),
  4306. };
  4307. }
  4308. return null;
  4309. }
  4310. function logStreamingToolInputProjection(
  4311. traceId: TraceId,
  4312. details: {
  4313. inputKeys: string[];
  4314. kind: string;
  4315. projectedType: "tool_call" | "tool_call_update";
  4316. rawInputLength: number;
  4317. taskId: string;
  4318. toolId: string;
  4319. toolName?: string;
  4320. },
  4321. ): void {
  4322. logger.debug(traceId, "ZCode streaming tool input projected", {
  4323. ...details,
  4324. event: "zcode.task.streaming_tool_input.projected",
  4325. });
  4326. }
  4327. function inputPreviewKeys(input: unknown): string[] {
  4328. return Object.keys(asRecord(input));
  4329. }
  4330. function inferStreamingToolInputToolName(input: unknown): string | undefined {
  4331. const record = asRecord(input);
  4332. const filePath = readStreamingToolInputStringField(record, [
  4333. "file_path",
  4334. "filePath",
  4335. "path",
  4336. "target_path",
  4337. "targetPath",
  4338. "filename",
  4339. "file",
  4340. ]);
  4341. if (!filePath) {
  4342. return undefined;
  4343. }
  4344. if (
  4345. readStreamingToolInputStringField(record, ["old_string", "oldString", "old_text", "oldText"])
  4346. ) {
  4347. return "Edit";
  4348. }
  4349. if (
  4350. readStreamingToolInputStringField(record, [
  4351. "content",
  4352. "new_string",
  4353. "newString",
  4354. "new_text",
  4355. "newText",
  4356. ]) !== undefined
  4357. ) {
  4358. return "Write";
  4359. }
  4360. return undefined;
  4361. }
  4362. function readStreamingToolInputStringField(
  4363. record: Record<string, unknown>,
  4364. keys: readonly string[],
  4365. ): string | undefined {
  4366. for (const key of keys) {
  4367. const value = record[key];
  4368. if (typeof value === "string") {
  4369. return value;
  4370. }
  4371. }
  4372. return undefined;
  4373. }
  4374. function mapCompactTimelinePayload(
  4375. taskId: string,
  4376. traceId: TraceId,
  4377. inputId: InputId | undefined,
  4378. payload: Record<string, unknown>,
  4379. ): Extract<ZCodeStreamEvent, { type: "agent_message_chunk" }> | null {
  4380. const timeline = compactTimelineMetaFromPayload(payload, inputId);
  4381. if (!timeline) {
  4382. return null;
  4383. }
  4384. const messageId = stringValue(payload.messageId);
  4385. return {
  4386. type: "agent_message_chunk",
  4387. taskId,
  4388. traceId,
  4389. ...(inputId ? { inputId } : {}),
  4390. ...(messageId ? { messageId } : {}),
  4391. // compact lifecycle 是结构化状态事件,不是 assistant 正文。
  4392. // 即使上游误带 text,也不能把内部 summary/prompt 投影到聊天区。
  4393. content: "",
  4394. zcodeTimeline: timeline,
  4395. };
  4396. }
  4397. function mapSyntheticTimelinePartPayload(
  4398. taskId: string,
  4399. traceId: TraceId,
  4400. inputId: InputId | undefined,
  4401. payload: Record<string, unknown>,
  4402. ): Extract<ZCodeStreamEvent, { type: "agent_message_chunk" }> | null {
  4403. const part = asRecord(payload.part);
  4404. if (part.type !== "text") {
  4405. return null;
  4406. }
  4407. const timeline = extractSyntheticTimelineFromTextPart(
  4408. part as Extract<ZCodeMessagePart, { type: "text" }>,
  4409. );
  4410. if (!timeline) {
  4411. return null;
  4412. }
  4413. const messageId = stringValue(part.messageId) ?? stringValue(payload.messageId);
  4414. return {
  4415. type: "agent_message_chunk",
  4416. taskId,
  4417. traceId,
  4418. ...(inputId ? { inputId } : {}),
  4419. ...(messageId ? { messageId } : {}),
  4420. content: stringValue(part.text) ?? "",
  4421. // fork notice 是 part.upserted 里的结构化 synthetic text,不是模型正文 delta。
  4422. // 这里提前投成 timeline divider,避免 UI 按普通消息渲染后丢掉横线。
  4423. zcodeTimeline: timeline,
  4424. };
  4425. }
  4426. function compactTimelineMetaFromPayload(
  4427. payload: Record<string, unknown>,
  4428. inputId: InputId | undefined,
  4429. ): ZCodeContextCompactionTimelineMeta | null {
  4430. const operationId = stringValue(payload.operationId);
  4431. const status = timelineStatusValue(payload.status ?? payload.timelineStatus);
  4432. if (!operationId || !status) {
  4433. return null;
  4434. }
  4435. const trigger = timelineTriggerValue(payload.trigger) ?? "manual";
  4436. const replace = booleanValue(payload.replace);
  4437. const reason = stringValue(payload.reason);
  4438. const boundaryId = stringValue(payload.boundaryId);
  4439. const summaryMessageId = stringValue(payload.summaryMessageId);
  4440. const preCompactTokenCount = numberValue(payload.preCompactTokenCount);
  4441. const postCompactTokenCount = numberValue(payload.postCompactTokenCount);
  4442. const truePostCompactTokenCount = numberValue(payload.truePostCompactTokenCount);
  4443. const attempt = numberValue(payload.attempt);
  4444. const maxAttempts = numberValue(payload.maxAttempts);
  4445. const startedAt = numberValue(payload.startedAt);
  4446. const endedAt = numberValue(payload.endedAt);
  4447. return {
  4448. version: 1,
  4449. kind: "synthetic",
  4450. type: "context_compaction",
  4451. operationId,
  4452. status,
  4453. trigger,
  4454. display: "separator",
  4455. ...(inputId ? { inputId } : {}),
  4456. ...(replace !== undefined ? { replace } : {}),
  4457. ...(reason ? { reason } : {}),
  4458. ...(boundaryId ? { boundaryId } : {}),
  4459. ...(summaryMessageId ? { summaryMessageId } : {}),
  4460. ...(preCompactTokenCount !== undefined ? { preCompactTokenCount } : {}),
  4461. ...(postCompactTokenCount !== undefined ? { postCompactTokenCount } : {}),
  4462. ...(truePostCompactTokenCount !== undefined ? { truePostCompactTokenCount } : {}),
  4463. ...(attempt !== undefined ? { attempt } : {}),
  4464. ...(maxAttempts !== undefined ? { maxAttempts } : {}),
  4465. ...(startedAt !== undefined ? { startedAt } : {}),
  4466. ...(endedAt !== undefined ? { endedAt } : {}),
  4467. };
  4468. }
  4469. function compactFailureToTimelineEvent(
  4470. taskId: string,
  4471. traceId: TraceId,
  4472. inputId: InputId | undefined,
  4473. reason: string,
  4474. ): Extract<ZCodeStreamEvent, { type: "agent_message_chunk" }> {
  4475. return {
  4476. type: "agent_message_chunk",
  4477. taskId,
  4478. traceId,
  4479. ...(inputId ? { inputId } : {}),
  4480. content: "",
  4481. zcodeTimeline: {
  4482. version: 1,
  4483. kind: "synthetic",
  4484. type: "context_compaction",
  4485. operationId: `compact-failed-${inputId ?? traceId}`,
  4486. status: /abort|cancel|interrupt|stop/i.test(reason) ? "interrupted" : "failed",
  4487. trigger: "manual",
  4488. display: "separator",
  4489. ...(inputId ? { inputId } : {}),
  4490. reason,
  4491. endedAt: Date.now(),
  4492. },
  4493. };
  4494. }
  4495. function mapToolUpdated(
  4496. taskId: string,
  4497. traceId: TraceId,
  4498. inputId: InputId | undefined,
  4499. payload: Record<string, unknown>,
  4500. toolProjectionMemory?: ZCodeToolProjectionMemory,
  4501. ): ZCodeStreamEvent[] {
  4502. const toolId = stringValue(payload.toolCallId);
  4503. if (!toolId) {
  4504. return [];
  4505. }
  4506. const parentToolUseId = parentToolUseIdFromToolPayload(payload);
  4507. const memory = toolProjectionMemory ?? {};
  4508. const toolNameById = memory.toolNameById;
  4509. const rememberedTool = resolveZCodeToolProjectionMetadata(payload, toolId, memory);
  4510. const rememberedToolName = rememberedTool.toolName;
  4511. const rememberedInput = rememberedTool.hasInput ? rememberedTool.input : undefined;
  4512. if ("input" in payload && "toolName" in payload) {
  4513. const toolName = rememberedToolName ?? "tool";
  4514. toolNameById?.set(toolId, toolName);
  4515. finalizeZCodeToolProjectionInput(toolId, payload.input, memory);
  4516. const toolEvent: ZCodeStreamEvent = {
  4517. type: "tool_call",
  4518. taskId,
  4519. traceId,
  4520. ...(inputId ? { inputId } : {}),
  4521. toolId,
  4522. parentToolUseId,
  4523. input: payload.input,
  4524. toolName,
  4525. kind: toolName,
  4526. title: toolName,
  4527. raw: payload,
  4528. };
  4529. const planSteps = isMainAgentToolProjectionSource(payload)
  4530. ? extractPlanStepsFromToolInput({
  4531. title: toolName,
  4532. kind: toolName,
  4533. input: payload.input,
  4534. })
  4535. : null;
  4536. if (!planSteps) {
  4537. return [toolEvent];
  4538. }
  4539. return [
  4540. toolEvent,
  4541. {
  4542. type: "plan",
  4543. taskId,
  4544. traceId,
  4545. ...(inputId ? { inputId } : {}),
  4546. steps: planSteps,
  4547. },
  4548. ];
  4549. }
  4550. if ("result" in payload) {
  4551. const result = asRecord(payload.result);
  4552. // ZCode Protocol 的 ToolCallResult 只有 toolCallId/result,不再重复带 toolName。
  4553. // 去掉 ZCode Agent 后如果不记住前序 ToolCallScheduled 的 TodoWrite 名称,result 里的 todos
  4554. // 就只能当普通字符串输出,无法继续投射成顶部 todo/plan 事件。
  4555. const toolName = rememberedToolName;
  4556. const content = normalizeToolResultContent(toolName, result);
  4557. const status = toolResultStatus(toolName, result);
  4558. const toolEvent: ZCodeStreamEvent = {
  4559. type: "tool_call_update",
  4560. taskId,
  4561. traceId,
  4562. ...(inputId ? { inputId } : {}),
  4563. toolId,
  4564. parentToolUseId,
  4565. toolName,
  4566. kind: toolName,
  4567. title: toolName,
  4568. ...(rememberedInput !== undefined ? { input: rememberedInput } : {}),
  4569. status,
  4570. content,
  4571. error: stringValue(asRecord(result.error).message),
  4572. raw: payload,
  4573. };
  4574. if (status !== "in_progress") {
  4575. forgetZCodeToolProjectionMetadata(toolId, memory);
  4576. }
  4577. const planSteps = isMainAgentToolProjectionSource(payload)
  4578. ? extractPlanStepsFromToolOutput({
  4579. title: toolName,
  4580. kind: toolName,
  4581. output: content ?? result,
  4582. })
  4583. : null;
  4584. if (!planSteps) {
  4585. return [toolEvent];
  4586. }
  4587. return [
  4588. toolEvent,
  4589. {
  4590. type: "plan",
  4591. taskId,
  4592. traceId,
  4593. ...(inputId ? { inputId } : {}),
  4594. steps: planSteps,
  4595. },
  4596. ];
  4597. }
  4598. if ("error" in payload) {
  4599. forgetZCodeToolProjectionMetadata(toolId, memory);
  4600. return [
  4601. {
  4602. type: "tool_call_update",
  4603. taskId,
  4604. traceId,
  4605. ...(inputId ? { inputId } : {}),
  4606. toolId,
  4607. parentToolUseId,
  4608. toolName: rememberedToolName,
  4609. kind: rememberedToolName,
  4610. title: rememberedToolName,
  4611. ...(rememberedInput !== undefined ? { input: rememberedInput } : {}),
  4612. status: "failed",
  4613. error: stringValue(asRecord(payload.error).message) ?? "Tool failed",
  4614. raw: payload,
  4615. },
  4616. ];
  4617. }
  4618. return [
  4619. {
  4620. type: "tool_call_update",
  4621. taskId,
  4622. traceId,
  4623. ...(inputId ? { inputId } : {}),
  4624. toolId,
  4625. parentToolUseId,
  4626. toolName: rememberedToolName,
  4627. kind: rememberedToolName,
  4628. title: rememberedToolName,
  4629. ...(rememberedInput !== undefined && payload.inputOmitted !== true
  4630. ? { input: rememberedInput }
  4631. : {}),
  4632. status: "in_progress",
  4633. raw: payload,
  4634. },
  4635. ];
  4636. }
  4637. function toolResultStatus(
  4638. toolName: string | undefined,
  4639. result: Record<string, unknown>,
  4640. ): Extract<ZCodeStreamEvent, { type: "tool_call_update" }>["status"] {
  4641. if (result.success === false) {
  4642. return "failed";
  4643. }
  4644. if (isBackgroundAgentLaunchResult(toolName, result)) {
  4645. // Agent 后台启动 ACK 只是子 agent 已创建,不代表子 agent 已完成;
  4646. // 投影成 completed 会让前端在真实 completion 前把 subagent 卡片误标为完成。
  4647. return "in_progress";
  4648. }
  4649. return "completed";
  4650. }
  4651. function isBackgroundAgentLaunchResult(
  4652. toolName: string | undefined,
  4653. result: Record<string, unknown>,
  4654. ): boolean {
  4655. const content = stringValue(result.content);
  4656. if (!content) {
  4657. return false;
  4658. }
  4659. if (
  4660. (isSubagentDispatchToolName(toolName) || toolName === undefined) &&
  4661. isBackgroundAgentLaunchAcknowledgement(content)
  4662. ) {
  4663. return true;
  4664. }
  4665. const parsed = parseJsonRecord(content);
  4666. const parsedStatus = stringValue(parsed?.status);
  4667. return (
  4668. parsed !== null &&
  4669. (isSubagentDispatchToolName(toolName) || stringValue(parsed.agentId) !== undefined) &&
  4670. ((parsedStatus === "backgrounded" && stringValue(parsed.backgroundTaskId) !== undefined) ||
  4671. (parsedStatus === "async_launched" &&
  4672. stringValue(parsed.agentId) !== undefined &&
  4673. stringValue(parsed.outputFile) !== undefined))
  4674. );
  4675. }
  4676. function isBackgroundAgentLaunchAcknowledgement(content: string): boolean {
  4677. // subagent async launch 的模型可见 ACK 从 backgroundTaskId/outputFile 文案迁到 output_file 文案;
  4678. // service projection 需要同时识别新旧格式,否则会把启动确认当成已完成结果发给 UI。
  4679. return (
  4680. isLegacyBackgroundAgentLaunchAcknowledgement(content) ||
  4681. isPreviousBackgroundAgentLaunchAcknowledgement(content) ||
  4682. isCurrentBackgroundAgentLaunchAcknowledgement(content)
  4683. );
  4684. }
  4685. function isLegacyBackgroundAgentLaunchAcknowledgement(content: string): boolean {
  4686. return (
  4687. content.includes("backgroundTaskId:") &&
  4688. content.includes("Runtime will wait for this background Agent")
  4689. );
  4690. }
  4691. function isPreviousBackgroundAgentLaunchAcknowledgement(content: string): boolean {
  4692. return (
  4693. content.startsWith("Agent ") &&
  4694. content.includes(" started in background.") &&
  4695. content.includes("agentId:") &&
  4696. content.includes("outputFile:") &&
  4697. content.includes("You will be notified when the Agent completes.")
  4698. );
  4699. }
  4700. function isCurrentBackgroundAgentLaunchAcknowledgement(content: string): boolean {
  4701. return (
  4702. content.startsWith("Async agent launched successfully.") &&
  4703. content.includes("agentId:") &&
  4704. content.includes("The agent is working in the background.") &&
  4705. content.includes("notified automatically when it completes")
  4706. );
  4707. }
  4708. function isSubagentDispatchToolName(toolName: string | undefined): boolean {
  4709. return toolName === "Agent" || toolName === "Task";
  4710. }
  4711. function parentToolUseIdFromToolPayload(payload: Record<string, unknown>): string | null {
  4712. // ZCode Protocol 发送的父级字段叫 parentToolCallId;
  4713. // UI stream 模型统一消费 parentToolUseId,必须在服务投影层完成一次性归一。
  4714. return (
  4715. stringValue(payload.parentToolUseId) ??
  4716. stringValue(payload.parentToolCallId) ??
  4717. rawClaudeParentToolUseId(payload)
  4718. );
  4719. }
  4720. function rawClaudeParentToolUseId(raw: unknown): string | null {
  4721. const meta = asRecord(raw)._meta;
  4722. const claudeCode = asRecord(meta).claudeCode;
  4723. return stringValue(asRecord(claudeCode).parentToolUseId) ?? null;
  4724. }
  4725. function normalizeToolResultContent(
  4726. toolName: string | undefined,
  4727. result: Record<string, unknown>,
  4728. ): unknown {
  4729. const content = result.content;
  4730. const agentActivity = parseAgentActivityResultContent(toolName, content);
  4731. return agentActivity ?? stringValue(content);
  4732. }
  4733. function parseAgentActivityResultContent(
  4734. toolName: string | undefined,
  4735. content: unknown,
  4736. ): { kind: "agent_activity"; content: string; thought?: string } | null {
  4737. if (typeof content !== "string" || content.trim().length === 0) {
  4738. return null;
  4739. }
  4740. const parsed = parseJsonRecord(content);
  4741. if (!parsed) {
  4742. return null;
  4743. }
  4744. const isAgentResult =
  4745. toolName === "Agent" ||
  4746. toolName === "Task" ||
  4747. stringValue(parsed.agentId) !== undefined ||
  4748. stringValue(parsed.agentType) !== undefined;
  4749. if (!isAgentResult) {
  4750. return null;
  4751. }
  4752. // Agent 工具结果是 JSON 字符串,最终摘要在 content[].text;
  4753. // 服务层先转成 agent_activity,避免 UI 每条渲染路径都猜原始 JSON。
  4754. const output = agentTextFromContentField(parsed.content);
  4755. if (!output) {
  4756. return null;
  4757. }
  4758. const thought = stringValue(parsed.thought);
  4759. return {
  4760. kind: "agent_activity",
  4761. content: output,
  4762. ...(thought ? { thought } : {}),
  4763. };
  4764. }
  4765. function parseJsonRecord(value: string): Record<string, unknown> | null {
  4766. try {
  4767. return asRecord(JSON.parse(value));
  4768. } catch {
  4769. return null;
  4770. }
  4771. }
  4772. function agentTextFromContentField(value: unknown): string | undefined {
  4773. if (typeof value === "string" && value.trim().length > 0) {
  4774. return value;
  4775. }
  4776. if (!Array.isArray(value)) {
  4777. return undefined;
  4778. }
  4779. const text = value
  4780. .map((item) => stringValue(asRecord(item).text))
  4781. .filter((item): item is string => Boolean(item))
  4782. .join("\n");
  4783. return text || undefined;
  4784. }
  4785. function permissionRequestToStreamEvent(
  4786. taskId: string,
  4787. request: ZCodePermissionRequestParams,
  4788. ): ZCodePermissionRequest {
  4789. return {
  4790. type: "permission_request",
  4791. taskId,
  4792. traceId: generateTraceId(taskId),
  4793. requestId: request.requestId,
  4794. description: request.reason || request.toolName,
  4795. kind: request.toolName,
  4796. title: request.toolName,
  4797. options: request.options,
  4798. ...(request.origin ? { origin: request.origin } : {}),
  4799. raw: request,
  4800. };
  4801. }
  4802. function pendingPermissionToStreamEvent(
  4803. taskId: string,
  4804. permission: ZCodeSessionStateSnapshot["projection"]["pendingPermissions"][number],
  4805. ): ZCodePermissionRequest {
  4806. return {
  4807. type: "permission_request",
  4808. taskId,
  4809. traceId: generateTraceId(taskId),
  4810. requestId: permission.requestId,
  4811. description: permission.reason || permission.toolName,
  4812. kind: permission.toolName,
  4813. title: permission.toolName,
  4814. options: permission.options,
  4815. ...(permission.origin ? { origin: permission.origin } : {}),
  4816. raw: permission,
  4817. };
  4818. }
  4819. function userInputRequestToElicitationStreamEvent(
  4820. taskId: string,
  4821. request: ZCodeUserInputRequestParams,
  4822. ): ZCodeStreamEvent {
  4823. const questions =
  4824. request.questions?.map((question) => ({
  4825. question: question.question,
  4826. header: question.header,
  4827. options: question.options.map((option) => ({
  4828. value: option.value,
  4829. label: option.label,
  4830. description: option.description,
  4831. })),
  4832. ...(question.multiSelect ? { multiSelect: true } : {}),
  4833. })) ?? [];
  4834. const firstQuestion = questions[0];
  4835. const requestSchema = asRecord(request.schema);
  4836. const requestInput = asRecord(request.input);
  4837. const plan =
  4838. requestSchema.interaction === "plan_approval" &&
  4839. typeof requestInput.plan === "string" &&
  4840. requestInput.plan.trim()
  4841. ? requestInput.plan.trim()
  4842. : undefined;
  4843. return {
  4844. type: "elicitation_request",
  4845. taskId,
  4846. traceId: generateTraceId(taskId),
  4847. requestId: request.requestId,
  4848. message: firstQuestion?.question ?? request.prompt ?? "Input required",
  4849. header: firstQuestion?.header,
  4850. options: firstQuestion?.options ?? [],
  4851. ...(firstQuestion?.multiSelect ? { multiSelect: true } : {}),
  4852. ...(questions.length > 0 ? { questions } : {}),
  4853. ...(request.origin ? { origin: request.origin } : {}),
  4854. // ExitPlanMode 的 request 同时携带 schema 和 input;直接取 `schema ?? input`
  4855. // 会丢掉 input.plan,审批投影因而缺少正文。
  4856. // 这里只合入 plan,保持普通 elicitation 以及其他工具 input 的数据边界。
  4857. schema: plan ? { ...requestSchema, plan } : (request.schema ?? request.input),
  4858. };
  4859. }
  4860. function userInputResponseToElicitationStreamEvent(
  4861. taskId: string,
  4862. requestId: string,
  4863. response: ZCodeUserInputResponse,
  4864. ): Extract<ZCodeStreamEvent, { type: "elicitation_response" }> {
  4865. return {
  4866. type: "elicitation_response",
  4867. taskId,
  4868. traceId: generateTraceId(taskId),
  4869. requestId,
  4870. action: response.action,
  4871. ...(response.content ? { content: response.content } : {}),
  4872. };
  4873. }
  4874. type PendingElicitationQuestion = {
  4875. question: string;
  4876. header: string;
  4877. options: Array<{ value: string; label: string; description?: string }>;
  4878. multiSelect?: boolean;
  4879. };
  4880. function pendingUserInputBackedPermissionToElicitationEvent(
  4881. taskId: string,
  4882. permission: ZCodeSessionStateSnapshot["projection"]["pendingPermissions"][number],
  4883. ): Extract<ZCodeStreamEvent, { type: "elicitation_request" }> | null {
  4884. if (isAskUserQuestionToolName(permission.toolName)) {
  4885. return pendingAskUserQuestionToElicitationEvent(taskId, permission);
  4886. }
  4887. if (isExitPlanModeToolName(permission.toolName)) {
  4888. return pendingExitPlanModeToElicitationEvent(taskId, permission);
  4889. }
  4890. return null;
  4891. }
  4892. function pendingAskUserQuestionToElicitationEvent(
  4893. taskId: string,
  4894. permission: ZCodeSessionStateSnapshot["projection"]["pendingPermissions"][number],
  4895. ): Extract<ZCodeStreamEvent, { type: "elicitation_request" }> | null {
  4896. const questions = askUserQuestionInputToElicitationQuestions(permission.input);
  4897. if (questions.length === 0) {
  4898. return null;
  4899. }
  4900. const firstQuestion = questions[0];
  4901. return {
  4902. type: "elicitation_request",
  4903. taskId,
  4904. traceId: generateTraceId(taskId),
  4905. requestId: permission.requestId,
  4906. message: firstQuestion?.question ?? permission.reason,
  4907. header: firstQuestion?.header,
  4908. options: firstQuestion?.options ?? [],
  4909. ...(firstQuestion?.multiSelect ? { multiSelect: true } : {}),
  4910. questions,
  4911. ...(permission.origin ? { origin: permission.origin } : {}),
  4912. schema: permission.input,
  4913. };
  4914. }
  4915. function pendingExitPlanModeToElicitationEvent(
  4916. taskId: string,
  4917. permission: ZCodeSessionStateSnapshot["projection"]["pendingPermissions"][number],
  4918. ): Extract<ZCodeStreamEvent, { type: "elicitation_request" }> {
  4919. const questions = createExitPlanModeApprovalQuestions();
  4920. const firstQuestion = questions[0];
  4921. const input = asRecord(permission.input);
  4922. const plan = typeof input.plan === "string" && input.plan.trim() ? input.plan.trim() : undefined;
  4923. return {
  4924. type: "elicitation_request",
  4925. taskId,
  4926. traceId: generateTraceId(taskId),
  4927. requestId: permission.requestId,
  4928. message: firstQuestion.question,
  4929. header: firstQuestion.header,
  4930. options: firstQuestion.options,
  4931. questions,
  4932. ...(permission.origin ? { origin: permission.origin } : {}),
  4933. // 计划审批投影必须展示本次 ExitPlanMode 对应的计划正文;
  4934. // 这里只定向投影 plan,避免把其他 permission input 泄漏到通用 elicitation schema。
  4935. schema: {
  4936. interaction: "plan_approval",
  4937. toolName: permission.toolName,
  4938. ...(plan ? { plan } : {}),
  4939. },
  4940. };
  4941. }
  4942. function setTaskBackgroundTaskControlCache(
  4943. cache: Map<string, ZCodeBackgroundTaskControlItem[]> | undefined,
  4944. cacheKey: string,
  4945. jobs: ZCodeBackgroundTaskControlItem[],
  4946. ) {
  4947. cache?.set(cacheKey, jobs);
  4948. }
  4949. function updateTaskBackgroundTaskControlCacheFromPayload(
  4950. cache: Map<string, ZCodeBackgroundTaskControlItem[]> | undefined,
  4951. cacheKey: string,
  4952. payload: Record<string, unknown>,
  4953. ): ZCodeBackgroundTaskControlItem[] | null {
  4954. const parsedJobs = parseZCodeBackgroundTaskControlItems([payload]);
  4955. if (parsedJobs.length === 0) {
  4956. return null;
  4957. }
  4958. if (!cache) {
  4959. return parsedJobs;
  4960. }
  4961. const nextJobs = mergeZCodeBackgroundTaskControlItems(cache.get(cacheKey) ?? [], parsedJobs);
  4962. cache.set(cacheKey, nextJobs);
  4963. return nextJobs;
  4964. }
  4965. function createExitPlanModeApprovalQuestions(): [PendingElicitationQuestion] {
  4966. return [
  4967. {
  4968. header: "Plan",
  4969. options: [
  4970. {
  4971. description: "Exit plan mode and start implementation.",
  4972. label: "Approve",
  4973. value: EXIT_PLAN_MODE_APPROVAL_APPROVE,
  4974. },
  4975. ],
  4976. question: EXIT_PLAN_MODE_APPROVAL_QUESTION,
  4977. },
  4978. ];
  4979. }
  4980. function askUserQuestionInputToElicitationQuestions(input: unknown): PendingElicitationQuestion[] {
  4981. type ElicitationOption = PendingElicitationQuestion["options"][number];
  4982. const questions = asRecord(input).questions;
  4983. if (!Array.isArray(questions)) {
  4984. return [];
  4985. }
  4986. return questions
  4987. .map((question) => {
  4988. const record = asRecord(question);
  4989. const questionText = stringValue(record.question);
  4990. const header = stringValue(record.header) ?? questionText;
  4991. const rawOptions = Array.isArray(record.options) ? record.options : [];
  4992. const options: ElicitationOption[] = rawOptions
  4993. .map((option) => {
  4994. const optionRecord = asRecord(option);
  4995. const label = stringValue(optionRecord.label);
  4996. if (!label) {
  4997. return null;
  4998. }
  4999. const description = stringValue(optionRecord.description);
  5000. const parsedOption: ElicitationOption = {
  5001. value: label,
  5002. label,
  5003. ...(description ? { description } : {}),
  5004. };
  5005. return parsedOption;
  5006. })
  5007. .filter((option): option is ElicitationOption => option !== null);
  5008. if (!questionText || !header || options.length === 0) {
  5009. return null;
  5010. }
  5011. const parsedQuestion: PendingElicitationQuestion = {
  5012. question: questionText,
  5013. header,
  5014. options,
  5015. ...(record.multiSelect === true ? { multiSelect: true } : {}),
  5016. };
  5017. return parsedQuestion;
  5018. })
  5019. .filter((question): question is PendingElicitationQuestion => question !== null);
  5020. }
  5021. function permissionPayloadToStreamEvent(
  5022. taskId: string,
  5023. traceId: TraceId,
  5024. inputId: InputId | undefined,
  5025. payload: Record<string, unknown>,
  5026. ): ZCodeStreamEvent {
  5027. return {
  5028. type: "permission_request",
  5029. taskId,
  5030. traceId,
  5031. ...(inputId ? { inputId } : {}),
  5032. requestId: stringValue(payload.requestId) ?? stringValue(payload.toolCallId) ?? "unknown",
  5033. description:
  5034. stringValue(payload.reason) ?? stringValue(payload.toolName) ?? "Permission required",
  5035. kind: stringValue(payload.toolName) ?? "tool",
  5036. title: stringValue(payload.toolName),
  5037. options: permissionOptionsFromPayload(payload),
  5038. raw: payload,
  5039. };
  5040. }
  5041. function permissionOptionsFromPayload(payload: Record<string, unknown>): ZCodePermissionOption[] {
  5042. return Array.isArray(payload.options) ? (payload.options as ZCodePermissionOption[]) : [];
  5043. }
  5044. function permissionResolvedPayloadToStreamEvents(
  5045. taskId: string,
  5046. traceId: TraceId,
  5047. inputId: InputId | undefined,
  5048. payload: Record<string, unknown>,
  5049. toolNameById?: Map<string, string>,
  5050. ): ZCodeStreamEvent[] {
  5051. const toolCallId = stringValue(payload.toolCallId);
  5052. const toolName =
  5053. stringValue(payload.toolName) ?? (toolCallId ? toolNameById?.get(toolCallId) : undefined);
  5054. const decision = stringValue(payload.decision);
  5055. const requestId = stringValue(payload.requestId) ?? toolCallId ?? "unknown";
  5056. if (isUserInputBackedPermissionToolName(toolName)) {
  5057. return [
  5058. {
  5059. type: "elicitation_response",
  5060. taskId,
  5061. traceId,
  5062. ...(inputId ? { inputId } : {}),
  5063. requestId,
  5064. action: decision === "deny" ? "decline" : "accept",
  5065. },
  5066. ];
  5067. }
  5068. const permissionResponse = {
  5069. type: "permission_response",
  5070. taskId,
  5071. traceId,
  5072. ...(inputId ? { inputId } : {}),
  5073. requestId,
  5074. optionId: decision ?? "allow",
  5075. response: {
  5076. decision: decision === "deny" ? "deny" : "allow",
  5077. },
  5078. } as Extract<ZCodeStreamEvent, { type: "permission_response" }>;
  5079. if (decision !== "deny" || !toolCallId) {
  5080. return [permissionResponse];
  5081. }
  5082. // Plan mode 等运行时拒绝会先发 permission.resolved,
  5083. // 但不一定有对应 tool.updated(error) 实时事件;只清权限请求会让已 started 的工具卡一直转。
  5084. return [
  5085. permissionResponse,
  5086. {
  5087. type: "tool_call_update",
  5088. taskId,
  5089. traceId,
  5090. ...(inputId ? { inputId } : {}),
  5091. toolId: toolCallId,
  5092. parentToolUseId: parentToolUseIdFromToolPayload(payload),
  5093. status: "failed",
  5094. toolName,
  5095. kind: toolName,
  5096. title: toolName,
  5097. error: stringValue(payload.reason) ?? "Permission denied",
  5098. raw: payload,
  5099. },
  5100. ];
  5101. }
  5102. function mapSessionInfoLikePayload(
  5103. taskId: string,
  5104. traceId: TraceId,
  5105. inputId: InputId | undefined,
  5106. eventId: string | undefined,
  5107. payload: Record<string, unknown>,
  5108. backgroundTaskControlsByTaskKey?: Map<string, ZCodeBackgroundTaskControlItem[]>,
  5109. cacheKey = taskId,
  5110. ): ZCodeStreamEvent[] {
  5111. const events: ZCodeStreamEvent[] = [];
  5112. // event.taskId 是对外 session id;内部 cache 必须沿用 workspace-aware taskKey,
  5113. // 否则 replayable snapshot seed 和后续 live update 会分裂成两份 background job 状态。
  5114. const backgroundTaskControlCacheKey = cacheKey;
  5115. const tokenUsageDelta = taskTokenUsageDeltaFromPayload(
  5116. taskId,
  5117. traceId,
  5118. inputId,
  5119. eventId,
  5120. payload,
  5121. );
  5122. if (tokenUsageDelta) {
  5123. events.push(tokenUsageDelta);
  5124. }
  5125. const networkDebugStatus = zcodeTaskNetworkDebugStatusFromPayload({
  5126. taskId,
  5127. traceId,
  5128. ...(inputId ? { inputId } : {}),
  5129. ...(eventId ? { eventId } : {}),
  5130. payload,
  5131. });
  5132. if (networkDebugStatus) {
  5133. events.push(networkDebugStatus);
  5134. }
  5135. const contextUsage = contextUsageFromPayload(payload);
  5136. if (contextUsage) {
  5137. events.push({
  5138. type: "usage_update",
  5139. taskId,
  5140. traceId,
  5141. ...(inputId ? { inputId } : {}),
  5142. used: contextUsage.used,
  5143. size: contextUsage.size,
  5144. cost: contextUsage.cost ?? null,
  5145. ...(contextUsage.cache ? { cache: contextUsage.cache } : {}),
  5146. ...(contextUsage.breakdown ? { breakdown: contextUsage.breakdown } : {}),
  5147. });
  5148. }
  5149. const title = stringValue(payload.title);
  5150. if (title) {
  5151. events.push({
  5152. type: "session_info_update",
  5153. taskId,
  5154. traceId,
  5155. ...(inputId ? { inputId } : {}),
  5156. title,
  5157. });
  5158. }
  5159. const apiRetry = apiRetryFromSessionInfoPayload(payload);
  5160. if (apiRetry !== undefined) {
  5161. events.push({
  5162. type: "session_info_update",
  5163. taskId,
  5164. traceId,
  5165. ...(inputId ? { inputId } : {}),
  5166. apiRetry,
  5167. });
  5168. }
  5169. if ("target" in payload && ("action" in payload || "source" in payload)) {
  5170. events.push({
  5171. type: "session_info_update",
  5172. taskId,
  5173. traceId,
  5174. ...(inputId ? { inputId } : {}),
  5175. target: {
  5176. action: stringValue(payload.action) === "cleared" ? "cleared" : "set",
  5177. source: stringValue(payload.source) === "tool" ? "tool" : "runtime",
  5178. target: payload.target ? fromZCodeGoal(payload.target as never) : null,
  5179. previousTarget: payload.previousTarget
  5180. ? fromZCodeGoal(payload.previousTarget as never)
  5181. : undefined,
  5182. },
  5183. });
  5184. }
  5185. const projection = asRecord(payload.projection);
  5186. if (Array.isArray(projection.backgroundJobs)) {
  5187. const jobs = parseZCodeBackgroundTaskControlItems(projection.backgroundJobs);
  5188. setTaskBackgroundTaskControlCache(
  5189. backgroundTaskControlsByTaskKey,
  5190. backgroundTaskControlCacheKey,
  5191. jobs,
  5192. );
  5193. events.push({
  5194. type: "background_bash_jobs_update",
  5195. taskId,
  5196. traceId,
  5197. ...(inputId ? { inputId } : {}),
  5198. jobs,
  5199. });
  5200. }
  5201. const backgroundJobUpdate = updateTaskBackgroundTaskControlCacheFromPayload(
  5202. backgroundTaskControlsByTaskKey,
  5203. backgroundTaskControlCacheKey,
  5204. payload,
  5205. );
  5206. if (backgroundJobUpdate) {
  5207. events.push({
  5208. type: "background_bash_jobs_update",
  5209. taskId,
  5210. traceId,
  5211. ...(inputId ? { inputId } : {}),
  5212. jobs: backgroundJobUpdate,
  5213. });
  5214. }
  5215. return events;
  5216. }
  5217. function taskTokenUsageDeltaFromPayload(
  5218. taskId: string,
  5219. traceId: TraceId,
  5220. inputId: InputId | undefined,
  5221. eventId: string | undefined,
  5222. payload: Record<string, unknown>,
  5223. ): Extract<ZCodeStreamEvent, { type: "task_token_usage_delta" }> | null {
  5224. if (!isModelCompleteUsagePayload(payload)) {
  5225. return null;
  5226. }
  5227. const usage = usageFromPayload(payload.usage);
  5228. if (!usage || usage.totalTokens <= 0) {
  5229. return null;
  5230. }
  5231. const querySource = stringValue(payload.querySource);
  5232. const queryId = stringValue(payload.queryId);
  5233. // 累计 Token 要跟随每次模型完成实时更新,而不是等 task_complete 的整轮汇总;
  5234. // eventId 是 protocol 流的稳定单事件标识,用它去重可避免前后台 monitor 重复记账。
  5235. const eventKey =
  5236. eventId ??
  5237. `${traceId}:${inputId ?? "no-input"}:${queryId ?? "no-query"}:${querySource ?? "unknown"}:${usage.inputTokens}:` +
  5238. `${usage.outputTokens}:${usage.totalTokens}`;
  5239. return {
  5240. type: "task_token_usage_delta",
  5241. taskId,
  5242. traceId,
  5243. ...(inputId ? { inputId } : {}),
  5244. ...(queryId ? { queryId } : {}),
  5245. eventKey,
  5246. ...(eventId ? { eventId } : {}),
  5247. ...(querySource ? { querySource } : {}),
  5248. usage,
  5249. };
  5250. }
  5251. function isModelCompleteUsagePayload(payload: Record<string, unknown>): boolean {
  5252. if (!("usage" in payload)) {
  5253. return false;
  5254. }
  5255. return (
  5256. stringValue(payload.stopReason) !== undefined ||
  5257. "contextWindow" in payload ||
  5258. stringValue(payload.querySource) !== undefined
  5259. );
  5260. }
  5261. function apiRetryFromSessionInfoPayload(
  5262. payload: Record<string, unknown>,
  5263. ): ZCodeApiRetryStatus | null | undefined {
  5264. if ("apiRetry" in payload) {
  5265. return normalizeZCodeApiRetryStatus(payload.apiRetry);
  5266. }
  5267. const runtimeRetry = normalizeZCodeApiRetryStatus(asRecord(payload.runtime).apiRetry);
  5268. if (runtimeRetry !== undefined) {
  5269. return runtimeRetry;
  5270. }
  5271. const metaRetry = normalizeZCodeApiRetryStatus(asRecord(asRecord(payload._meta).zcode).apiRetry);
  5272. if (metaRetry !== undefined) {
  5273. return metaRetry;
  5274. }
  5275. return (
  5276. zcodeApiRetryFromStreamRecoveryPayload(payload) ??
  5277. zcodeApiRetryFromModelNetworkStatusPayload(payload)
  5278. );
  5279. }
  5280. function recordAgentModelNetworkTelemetry(event: ZCodeSessionEvent): void {
  5281. const observation = agentModelNetworkObservationFromEvent(event);
  5282. if (!observation) {
  5283. return;
  5284. }
  5285. try {
  5286. emitNetworkTelemetryObservation(observation);
  5287. } catch (error) {
  5288. // 修复原因:agent 模型网络遥测属于旁路指标,sink 异常不能影响主会话消息流。
  5289. logger.warn(undefined, "上报 agent 模型网络遥测失败", error);
  5290. }
  5291. }
  5292. function agentModelNetworkObservationFromEvent(
  5293. event: ZCodeSessionEvent,
  5294. ): NetworkObservation | null {
  5295. const payload = asRecord(event.payload);
  5296. const type = stringValue(payload.type);
  5297. if (type !== "model_request_completed" && type !== "model_request_failed") {
  5298. return null;
  5299. }
  5300. // 修复原因:retryable failed 只是同一次逻辑请求的中间 attempt,最终 completed/failed 会带总 attempt。
  5301. // 如果这里也计数,会把成功率、失败率和重试率同时放大。
  5302. if (type === "model_request_failed" && booleanValue(payload.retryable) === true) {
  5303. return null;
  5304. }
  5305. const durationMs = Math.max(0, Math.round(numberValue(payload.durationMs) ?? 0));
  5306. const statusCode = nonNegativeIntegerValue(payload.statusCode);
  5307. const ok = type === "model_request_completed";
  5308. return {
  5309. transport: "http",
  5310. interface: buildAgentModelNetworkInterface(payload),
  5311. durationMs,
  5312. ok,
  5313. ...(statusCode !== undefined ? { statusCode } : {}),
  5314. ...(ok ? {} : { errorKind: classifyAgentModelNetworkError(payload, statusCode) }),
  5315. attempt: positiveIntegerValue(payload.attempt) ?? 1,
  5316. };
  5317. }
  5318. function buildAgentModelNetworkInterface(payload: Record<string, unknown>): string {
  5319. const providerKind = safeNetworkDimension(stringValue(payload.providerKind)) ?? "unknown";
  5320. const transport = safeNetworkDimension(stringValue(payload.transport)) ?? "unknown";
  5321. const base = normalizeAgentModelBaseUrl(stringValue(payload.baseURL));
  5322. return `zcode_agent.model.${providerKind}.${transport}.${base}`;
  5323. }
  5324. function normalizeAgentModelBaseUrl(value: string | undefined): string {
  5325. if (!value) {
  5326. return "unknown";
  5327. }
  5328. try {
  5329. const parsed = new URL(value);
  5330. const pathname = parsed.pathname.replace(/\/+$/u, "") || "/";
  5331. const safePath = pathname.length > 80 ? `${pathname.slice(0, 80)}...` : pathname;
  5332. return `${parsed.host}${safePath}`;
  5333. } catch {
  5334. return safeNetworkDimension(value, 120) ?? "unknown";
  5335. }
  5336. }
  5337. function safeNetworkDimension(value: string | undefined, maxLength = 48): string | undefined {
  5338. const trimmed = value?.trim();
  5339. if (!trimmed) {
  5340. return undefined;
  5341. }
  5342. const safe = trimmed.replace(/[?#[\]{}|\\^`"'<>\s]+/gu, "_");
  5343. return safe.length > maxLength ? `${safe.slice(0, maxLength)}...` : safe;
  5344. }
  5345. function classifyAgentModelNetworkError(
  5346. payload: Record<string, unknown>,
  5347. statusCode: number | undefined,
  5348. ): string {
  5349. const reason = stringValue(payload.reason);
  5350. switch (reason) {
  5351. case "timeout":
  5352. case "stream_idle_timeout":
  5353. return "timeout";
  5354. case "network_error":
  5355. case "stale_connection":
  5356. return "connection_reset";
  5357. case "proxy_error":
  5358. return "proxy_error";
  5359. case "tls_error":
  5360. return "tls_error";
  5361. default:
  5362. if (statusCode !== undefined && statusCode >= 500) {
  5363. return "server_error";
  5364. }
  5365. if (statusCode !== undefined && statusCode >= 400) {
  5366. return "client_error";
  5367. }
  5368. return "other";
  5369. }
  5370. }
  5371. type ContextUsageUpdate = Pick<
  5372. Extract<ZCodeStreamEvent, { type: "usage_update" }>,
  5373. "used" | "size" | "cost" | "cache" | "breakdown"
  5374. >;
  5375. function contextUsageFromProjection(
  5376. projection: ZCodeSessionStateSnapshot["projection"],
  5377. ): ContextUsageUpdate | null {
  5378. if (projection.contextWindow <= 0 || projection.contextUsed <= 0) {
  5379. return null;
  5380. }
  5381. return {
  5382. used: projection.contextUsed,
  5383. size: projection.contextWindow,
  5384. cost: null,
  5385. };
  5386. }
  5387. function contextUsageFromRuntime(
  5388. runtimeUsage: ZCodeSessionStateSnapshot["runtime"]["contextUsage"] | undefined,
  5389. ): ContextUsageUpdate | null {
  5390. if (!runtimeUsage || runtimeUsage.size <= 0 || runtimeUsage.used <= 0) {
  5391. return null;
  5392. }
  5393. // session resume 时 protocol projection 可能还没重放主轮次 usage。
  5394. // runtime.contextUsage 来自持久化 assistant token 记录,应优先用于恢复旧 task UI。
  5395. return {
  5396. used: runtimeUsage.used,
  5397. size: runtimeUsage.size,
  5398. cost: runtimeUsage.cost ?? null,
  5399. ...(runtimeUsage.cache ? { cache: runtimeUsage.cache } : {}),
  5400. ...(runtimeUsage.breakdown ? { breakdown: runtimeUsage.breakdown } : {}),
  5401. };
  5402. }
  5403. function contextUsageFromPayload(payload: Record<string, unknown>): ContextUsageUpdate | null {
  5404. const projection = asRecord(payload.projection);
  5405. const usage = asRecord(payload.usage);
  5406. const size = numberValue(payload.contextWindow ?? projection.contextWindow);
  5407. const explicitUsed = numberValue(payload.contextUsed ?? projection.contextUsed);
  5408. const useModelUsageForContext = shouldUseModelUsageForContext(payload);
  5409. const modelUsageUsed = useModelUsageForContext ? contextUsageTokensFromPayload(usage) : undefined;
  5410. const used =
  5411. modelUsageUsed ??
  5412. // 主轮次模型返回 usage 时必须以真实网络 token 统计为准;
  5413. // context window 是 input + output 共享窗口,不能再只用 inputTokens 渲染 meter。
  5414. // projection.contextUsed 是 runtime 估算/恢复事实源,只在缺少 usage 时兜底。
  5415. explicitUsed;
  5416. if (size === undefined || size <= 0) {
  5417. return null;
  5418. }
  5419. // ZCode Protocol 的 session.updated 里 contextUsed/contextWindow 是 projection 事实源;
  5420. // 旧 task stream 只认识 usage_update,adapter 不转换就会让右下角 context meter 永远拿不到数据。
  5421. // used=0 只表示初始化或异常兜底,不能渲染成可用的 context meter。
  5422. if (used === undefined || used <= 0) {
  5423. return null;
  5424. }
  5425. return {
  5426. used,
  5427. size,
  5428. cost: null,
  5429. ...(useModelUsageForContext ? optionalContextCacheUsageFromPayload(payload, usage) : {}),
  5430. ...(useModelUsageForContext ? optionalContextUsageBreakdownFromPayload(payload) : {}),
  5431. };
  5432. }
  5433. function optionalContextUsageBreakdownFromPayload(
  5434. payload: Record<string, unknown>,
  5435. ): Pick<ContextUsageUpdate, "breakdown"> {
  5436. const parsed = zcodeContextUsageBreakdownSchema.safeParse(payload.contextUsageBreakdown);
  5437. return parsed.success && parsed.data.length > 0 ? { breakdown: parsed.data } : {};
  5438. }
  5439. function contextUsageTokensFromPayload(usage: Record<string, unknown>): number | undefined {
  5440. const inputTokens = positiveIntegerValue(usage.inputTokens ?? usage.input);
  5441. if (inputTokens !== undefined) {
  5442. // AI SDK v6 已把 Anthropic cache read/write 并入 inputTokens。
  5443. // adapter 只需要加 output;再加 cacheReadTokens 会把输入栏 context meter 算大。
  5444. return inputTokens + (nonNegativeIntegerValue(usage.outputTokens ?? usage.output) ?? 0);
  5445. }
  5446. const totalTokens = positiveIntegerValue(usage.totalTokens ?? usage.total);
  5447. if (totalTokens !== undefined) {
  5448. return totalTokens;
  5449. }
  5450. const cacheTokens =
  5451. (nonNegativeIntegerValue(usage.cachedReadTokens ?? usage.cacheReadTokens) ?? 0) +
  5452. (nonNegativeIntegerValue(usage.cachedWriteTokens ?? usage.cacheWriteTokens) ?? 0);
  5453. return cacheTokens > 0
  5454. ? cacheTokens + (nonNegativeIntegerValue(usage.outputTokens ?? usage.output) ?? 0)
  5455. : undefined;
  5456. }
  5457. function optionalContextCacheUsageFromPayload(
  5458. payload: Record<string, unknown>,
  5459. usage: Record<string, unknown>,
  5460. ): Pick<ContextUsageUpdate, "cache"> {
  5461. const cache = contextCacheUsageFromPayload(payload, usage);
  5462. return cache ? { cache } : {};
  5463. }
  5464. function shouldUseModelUsageForContext(payload: Record<string, unknown>): boolean {
  5465. const querySource = stringValue(payload.querySource);
  5466. // 只有主会话模型请求的 inputTokens 才代表当前可见上下文。
  5467. // 标题、压缩、prompt enhance 等 sidecar 请求即使带 contextWindow,也不能覆盖输入栏 context meter。
  5468. return querySource === undefined || querySource === "main_turn";
  5469. }
  5470. function contextCacheUsageFromPayload(
  5471. payload: Record<string, unknown>,
  5472. usage: Record<string, unknown>,
  5473. ): ContextUsageUpdate["cache"] {
  5474. const aggregate = asRecord(payload.cacheHit);
  5475. if (Object.keys(aggregate).length > 0) {
  5476. const inputTokens = nonNegativeIntegerValue(aggregate.inputTokens) ?? 0;
  5477. const cacheReadTokens = nonNegativeIntegerValue(aggregate.cacheReadTokens) ?? 0;
  5478. const cacheWriteTokens = nonNegativeIntegerValue(aggregate.cacheWriteTokens) ?? 0;
  5479. const latestHitRate = numberValue(aggregate.latestHitRate);
  5480. const hitRate = numberValue(aggregate.hitRate);
  5481. const hitRateRequestCount = nonNegativeIntegerValue(aggregate.hitRateRequestCount);
  5482. const totalInputTokens = nonNegativeIntegerValue(aggregate.totalInputTokens);
  5483. const totalCacheReadTokens = nonNegativeIntegerValue(aggregate.totalCacheReadTokens);
  5484. const totalCacheWriteTokens = nonNegativeIntegerValue(aggregate.totalCacheWriteTokens);
  5485. return {
  5486. inputTokens,
  5487. cacheReadTokens,
  5488. cacheWriteTokens,
  5489. ...(latestHitRate !== undefined ? { latestHitRate: Math.max(0, latestHitRate) } : {}),
  5490. ...(hitRateRequestCount !== undefined ? { hitRateRequestCount } : {}),
  5491. ...(totalInputTokens !== undefined ? { totalInputTokens } : {}),
  5492. ...(totalCacheReadTokens !== undefined ? { totalCacheReadTokens } : {}),
  5493. ...(totalCacheWriteTokens !== undefined ? { totalCacheWriteTokens } : {}),
  5494. hitRate: hitRate !== undefined ? Math.max(0, hitRate) : null,
  5495. };
  5496. }
  5497. const hasCacheRead = "cachedReadTokens" in usage || "cacheReadTokens" in usage;
  5498. const hasCacheWrite = "cachedWriteTokens" in usage || "cacheWriteTokens" in usage;
  5499. const hasHitRate = "cacheHitRate" in usage || "hitRate" in usage;
  5500. if (!hasCacheRead && !hasCacheWrite && !hasHitRate) {
  5501. return undefined;
  5502. }
  5503. const inputTokens = nonNegativeIntegerValue(usage.inputTokens ?? usage.input) ?? 0;
  5504. const cacheReadTokens =
  5505. nonNegativeIntegerValue(usage.cachedReadTokens ?? usage.cacheReadTokens) ?? 0;
  5506. const cacheWriteTokens =
  5507. nonNegativeIntegerValue(usage.cachedWriteTokens ?? usage.cacheWriteTokens) ?? 0;
  5508. const explicitHitRate = numberValue(usage.cacheHitRate ?? usage.hitRate);
  5509. return {
  5510. inputTokens,
  5511. cacheReadTokens,
  5512. cacheWriteTokens,
  5513. latestHitRate:
  5514. explicitHitRate !== undefined
  5515. ? Math.max(0, explicitHitRate)
  5516. : inputTokens > 0
  5517. ? cacheReadTokens / inputTokens
  5518. : null,
  5519. // UI 展示的是 agent/app 协议返回的命中率;provider 没直接给时,
  5520. // 在 adapter 侧按 provider usage 归一化一次,避免各 UI 入口重复理解 token 字段。
  5521. hitRate:
  5522. explicitHitRate !== undefined
  5523. ? Math.max(0, explicitHitRate)
  5524. : inputTokens > 0
  5525. ? cacheReadTokens / inputTokens
  5526. : null,
  5527. };
  5528. }
  5529. function usageFromPayload(value: unknown): ZCodeUsage | undefined {
  5530. const usage = asRecord(value);
  5531. if (Object.keys(usage).length === 0) {
  5532. return undefined;
  5533. }
  5534. const inputTokens = numberValue(usage.inputTokens ?? usage.input) ?? 0;
  5535. const outputTokens = numberValue(usage.outputTokens ?? usage.output) ?? 0;
  5536. const reasoningTokens = numberValue(usage.reasoningTokens ?? usage.reasoning);
  5537. const cachedInputTokens = numberValue(usage.cachedReadTokens ?? usage.cacheReadTokens);
  5538. const cachedWriteInputTokens = numberValue(usage.cachedWriteTokens ?? usage.cacheWriteTokens);
  5539. const inputSideTokens =
  5540. inputTokens > 0 ? inputTokens : (cachedInputTokens ?? 0) + (cachedWriteInputTokens ?? 0);
  5541. const totalTokens =
  5542. numberValue(usage.totalTokens ?? usage.total) ?? inputSideTokens + outputTokens;
  5543. return {
  5544. inputTokens,
  5545. outputTokens,
  5546. totalTokens,
  5547. reasoningTokens,
  5548. cachedInputTokens,
  5549. cachedWriteInputTokens,
  5550. };
  5551. }
  5552. function asRecord(value: unknown): Record<string, unknown> {
  5553. return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {};
  5554. }
  5555. function stringValue(value: unknown): string | undefined {
  5556. return typeof value === "string" && value.length > 0 ? value : undefined;
  5557. }
  5558. function isAskUserQuestionToolName(value: string | undefined): boolean {
  5559. return value === ASK_USER_QUESTION_TOOL_NAME;
  5560. }
  5561. function isExitPlanModeToolName(value: string | undefined): boolean {
  5562. return value === EXIT_PLAN_MODE_TOOL_NAME;
  5563. }
  5564. function isUserInputBackedPermissionToolName(value: string | undefined): boolean {
  5565. return isAskUserQuestionToolName(value) || isExitPlanModeToolName(value);
  5566. }
  5567. function numberValue(value: unknown): number | undefined {
  5568. return typeof value === "number" && Number.isFinite(value) ? value : undefined;
  5569. }
  5570. function nonNegativeIntegerValue(value: unknown): number | undefined {
  5571. return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined;
  5572. }
  5573. function positiveIntegerValue(value: unknown): number | undefined {
  5574. return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : undefined;
  5575. }
  5576. function booleanValue(value: unknown): boolean | undefined {
  5577. return typeof value === "boolean" ? value : undefined;
  5578. }
  5579. function timelineStatusValue(value: unknown): ZCodeTimelineStatus | undefined {
  5580. return value === "started" ||
  5581. value === "retrying" ||
  5582. value === "skipped" ||
  5583. value === "completed" ||
  5584. value === "failed" ||
  5585. value === "interrupted"
  5586. ? value
  5587. : undefined;
  5588. }
  5589. function timelineTriggerValue(value: unknown): ZCodeTimelineTrigger | undefined {
  5590. return value === "manual" ||
  5591. value === "auto" ||
  5592. value === "reactive" ||
  5593. value === "partial" ||
  5594. value === "session_memory"
  5595. ? value
  5596. : undefined;
  5597. }
  5598. function stringArray(value: unknown): string[] {
  5599. return Array.isArray(value)
  5600. ? value.filter((item): item is string => typeof item === "string")
  5601. : [];
  5602. }
  5603. function turnSteerSourceValue(value: unknown): ZCodeTurnSteerSource | undefined {
  5604. return value === "plan_approval_feedback" || value === "workflow_refine_feedback"
  5605. ? value
  5606. : undefined;
  5607. }
  5608. function turnSteerCommandKindValue(value: unknown): ZCodeTurnSteerCommandKind | undefined {
  5609. return value === "sendGoalCommand" || value === "sendText" || value === "compact"
  5610. ? value
  5611. : undefined;
  5612. }