@usine/server 0.4.1-next.262.g0f4d653 → 0.4.1-next.264.gfdecd7e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +7 -9
  2. package/dist/backend.d.ts +4 -5
  3. package/dist/backend.d.ts.map +1 -1
  4. package/dist/backend.js +1 -3
  5. package/dist/backend.js.map +1 -1
  6. package/dist/configuration/catalog.d.ts +5 -0
  7. package/dist/configuration/catalog.d.ts.map +1 -0
  8. package/dist/configuration/catalog.js +38 -0
  9. package/dist/configuration/catalog.js.map +1 -0
  10. package/dist/http.d.ts +3 -1
  11. package/dist/http.d.ts.map +1 -1
  12. package/dist/http.js +8 -19
  13. package/dist/http.js.map +1 -1
  14. package/dist/up.d.ts.map +1 -1
  15. package/dist/up.js +4 -2
  16. package/dist/up.js.map +1 -1
  17. package/dist/web/assets/Match-BsHjCE-9.js +1 -0
  18. package/dist/web/assets/_agent-CK1JZbEZ.js +1 -0
  19. package/dist/web/assets/_label-CkDrdgxa.js +1 -0
  20. package/dist/web/assets/_loop-DLKJmqFq.js +1 -0
  21. package/dist/web/assets/_name--06G9LKw.js +1 -0
  22. package/dist/web/assets/_name-BzeOsU08.js +1 -0
  23. package/dist/web/assets/_name-CCrJHJTI.js +1 -0
  24. package/dist/web/assets/_name-LWtfT5Eq.js +2 -0
  25. package/dist/web/assets/_number-BzeOsU08.js +1 -0
  26. package/dist/web/assets/{_number-BFZW4AfX.js → _number-CpU9ru_u.js} +1 -1
  27. package/dist/web/assets/_number-n4iejSEq.js +1 -0
  28. package/dist/web/assets/_run-BzeOsU08.js +1 -0
  29. package/dist/web/assets/_run-CHrGLkXR.js +5 -0
  30. package/dist/web/assets/_worker-BvlkSKMd.js +1 -0
  31. package/dist/web/assets/action-DQzkdVHs.js +1 -0
  32. package/dist/web/assets/actions-CG0hkpe7.js +1 -0
  33. package/dist/web/assets/agents-CgWsAMoz.js +1 -0
  34. package/dist/web/assets/agents-D3eAK_60.js +1 -0
  35. package/dist/web/assets/code-block-Y9Y-8fHK.js +4 -0
  36. package/dist/web/assets/collapsible-BKcakxvM.js +1 -0
  37. package/dist/web/assets/drawer-ClcvABkO.js +1 -0
  38. package/dist/web/assets/dropdown-menu-BHKHYfLs.js +1 -0
  39. package/dist/web/assets/edit-and-retry-DZ5FH7N6.js +1 -0
  40. package/dist/web/assets/error-alert-hABzwCSY.js +1 -0
  41. package/dist/web/assets/{file-error-Befud4JV.js → file-error-B5tv6DhJ.js} +1 -1
  42. package/dist/web/assets/heading-zIOXe3qT.js +1 -0
  43. package/dist/web/assets/history-PYEz5wbe.js +1 -0
  44. package/dist/web/assets/index-C_S4sA5L.css +2 -0
  45. package/dist/web/assets/index-Dki55xSv.js +10 -0
  46. package/dist/web/assets/{label-badge-nrvxD46n.js → label-badge-JdNthOHh.js} +1 -1
  47. package/dist/web/assets/labels-Dr9t-xYj.js +1 -0
  48. package/dist/web/assets/lazyRouteComponent-BnRF0Crs.js +1 -0
  49. package/dist/web/assets/list-NcxSR9Ja.js +1 -0
  50. package/dist/web/assets/loops-DI4kElkX.js +1 -0
  51. package/dist/web/assets/mark-uyeJ8aPC.js +1 -0
  52. package/dist/web/assets/model-87X7P9Uh.js +1 -0
  53. package/dist/web/assets/moves-DS1ecXd6.js +1 -0
  54. package/dist/web/assets/native-select-BzF8xUnx.js +1 -0
  55. package/dist/web/assets/{not-found-Bexl2Syq.js → not-found-D7GT8Sj7.js} +1 -1
  56. package/dist/web/assets/outcome-DvqnSso3.js +5 -0
  57. package/dist/web/assets/{overview-CVIU9T_Q.js → overview-C73v5kbv.js} +1 -1
  58. package/dist/web/assets/page-C47YAWAl.js +1 -0
  59. package/dist/web/assets/preload-helper-BLdHbfdN.js +1 -0
  60. package/dist/web/assets/pull-request-marks-B4f7z4xa.js +1 -0
  61. package/dist/web/assets/queries-BZMW2wiD.js +1 -0
  62. package/dist/web/assets/queries-oea_Y4on.js +1 -0
  63. package/dist/web/assets/repositories-CZBhubWh.js +1 -0
  64. package/dist/web/assets/route-BtU2HI1M.js +1 -0
  65. package/dist/web/assets/route-CD6OvH-7.js +1 -0
  66. package/dist/web/assets/route-status-DGpeFNCC.js +1 -0
  67. package/dist/web/assets/routes-BzeOsU08.js +1 -0
  68. package/dist/web/assets/routes-g6SHTgCO.js +65 -0
  69. package/dist/web/assets/run-again-DPa5c27z.js +1 -0
  70. package/dist/web/assets/{section-DkPPj0Qz.js → section-BZs0sQLB.js} +1 -1
  71. package/dist/web/assets/section-eyIYzZrG.js +24 -0
  72. package/dist/web/assets/settings-DusVdmgP.js +1 -0
  73. package/dist/web/assets/skeleton-87E84B2f.js +1 -0
  74. package/dist/web/assets/sortable.esm-Lp8AM6j2.js +5 -0
  75. package/dist/web/assets/{strings-skTeG228.js → strings-Bexnszes.js} +1 -1
  76. package/dist/web/assets/{strings-DONjvHz8.js → strings-DXB6PB2g.js} +69 -61
  77. package/dist/web/assets/tasks-BzeOsU08.js +1 -0
  78. package/dist/web/assets/tasks-ClShPUFW.js +1 -0
  79. package/dist/web/assets/usage-BMYuEDo9.js +1 -0
  80. package/dist/web/assets/use-open-run-B8nD_BT1.js +1 -0
  81. package/dist/web/assets/useAnchoredPopupScrollLock-NN99o6YU.js +1 -0
  82. package/dist/web/assets/useControlled-B5kAMgo-.js +1 -0
  83. package/dist/web/assets/useSelector-CRBsgquS.js +1 -0
  84. package/dist/web/assets/useSuspenseQuery-DbhQN-t-.js +1 -0
  85. package/dist/web/assets/visuallyHidden-BUGCJ1D9.js +1 -0
  86. package/dist/web/assets/workers-CDWbu1Tb.js +1 -0
  87. package/dist/web/index.html +20 -13
  88. package/package.json +9 -9
  89. package/dist/web/assets/X.es-ClvLjC9g.js +0 -1
  90. package/dist/web/assets/_agent-DAEoPdV-.js +0 -1
  91. package/dist/web/assets/_loop-vCYTiV8K.js +0 -1
  92. package/dist/web/assets/_name-BU5JK5xh.js +0 -1
  93. package/dist/web/assets/_name-BzehryAG.js +0 -1
  94. package/dist/web/assets/_name-CqC1_Tkp.js +0 -1
  95. package/dist/web/assets/_name-PTdpQrSQ.js +0 -6
  96. package/dist/web/assets/_number-BzehryAG.js +0 -1
  97. package/dist/web/assets/_number-CTGqOC7Y.js +0 -1
  98. package/dist/web/assets/_run-BzehryAG.js +0 -1
  99. package/dist/web/assets/_run-CobdymLR.js +0 -8
  100. package/dist/web/assets/_worker-o45ziAln.js +0 -1
  101. package/dist/web/assets/action-D59leH3d.js +0 -1
  102. package/dist/web/assets/agents-DejXWwOW.js +0 -1
  103. package/dist/web/assets/agents-_VTnE2uR.js +0 -1
  104. package/dist/web/assets/collapsible-DfWPTljV.js +0 -1
  105. package/dist/web/assets/drawer-CG2uC8mz.js +0 -1
  106. package/dist/web/assets/dropdown-menu-BuVimdT5.js +0 -1
  107. package/dist/web/assets/edit-and-retry-DoBXzKs4.js +0 -1
  108. package/dist/web/assets/error-alert-B1wP9JKx.js +0 -1
  109. package/dist/web/assets/heading-CmCH5X04.js +0 -1
  110. package/dist/web/assets/index-C1tcW0Kz.js +0 -10
  111. package/dist/web/assets/index-Y-UpTvwI.css +0 -2
  112. package/dist/web/assets/list-C0Krf4aU.js +0 -1
  113. package/dist/web/assets/loops-BUL6rqOz.js +0 -1
  114. package/dist/web/assets/model-CYcw80ka.js +0 -1
  115. package/dist/web/assets/moves-BP3lsIkJ.js +0 -1
  116. package/dist/web/assets/outcome-CzVmfAHO.js +0 -5
  117. package/dist/web/assets/page-BuzrT_cg.js +0 -1
  118. package/dist/web/assets/pull-request-marks-oqSgsb3K.js +0 -1
  119. package/dist/web/assets/queries-CMOWVU8o.js +0 -1
  120. package/dist/web/assets/queries-DPtA2w4k.js +0 -1
  121. package/dist/web/assets/reload-DepSabvQ.js +0 -1
  122. package/dist/web/assets/repositories-C_W6sMMC.js +0 -1
  123. package/dist/web/assets/route-CEwJ12I0.js +0 -1
  124. package/dist/web/assets/route-DSZaQYtb.js +0 -1
  125. package/dist/web/assets/routes-BzehryAG.js +0 -1
  126. package/dist/web/assets/routes-CwATPoN5.js +0 -65
  127. package/dist/web/assets/run-again-hwgO0X30.js +0 -1
  128. package/dist/web/assets/section-DKHXjfWs.js +0 -1
  129. package/dist/web/assets/settings-BqZbr0qg.js +0 -1
  130. package/dist/web/assets/tasks-BzehryAG.js +0 -1
  131. package/dist/web/assets/tasks-DeTOoEpw.js +0 -1
  132. package/dist/web/assets/usage-BQwJd-Ch.js +0 -1
  133. package/dist/web/assets/useAnchoredPopupScrollLock-D1zkXMhu.js +0 -1
  134. package/dist/web/assets/usePositioner-BRxzSVtE.js +0 -1
  135. package/dist/web/assets/useTimeout-BC05Ghyu.js +0 -1
  136. package/dist/web/assets/workers-Oh2L44Fk.js +0 -1
@@ -33,7 +33,7 @@ var e=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:retu
33
33
  json_extract(${JR.envelope}, '$.payload._tag') = 'InterventionApplied'
34
34
  OR (json_extract(${JR.envelope}, '$.payload._tag') = 'SessionEvent'
35
35
  AND json_extract(${JR.envelope}, '$.payload.event._tag') IN ('SessionStarted', 'SessionIdle', 'SessionResumed', 'SessionFinished'))
36
- )`)).groupBy(J`coalesce(json_extract(${JR.envelope}, '$.payload.event.session.id'), json_extract(${JR.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${JR.envelope}, '$.payload._tag')`,J`json_extract(${JR.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:JR.sequence,tokens:J`max(json_extract(${JR.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(JR).where(cM(Y(JR.attemptId,t),J`json_extract(${JR.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${JR.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${JR.envelope}, '$.payload.event.session.id')`).as(`highest`);return hM(JR.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(JR.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>cM(Y(JR.attemptId,e),dM(JR.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>vr(t,{onNone:()=>Y(JR.attemptId,e),onSome:t=>cM(Y(JR.attemptId,e),pM(JR.sequence,t))})}),r=e.select({sequence:JR.sequence,attemptId:JR.attemptId,direction:JR.direction,envelope:JR.envelope,receivedAt:JR.receivedAt}).from(JR).where(n);return(yield*cV(yield*kk(t,{TranscriptWorkerQuery:()=>r.orderBy(jM(JR.sequence)).limit(1).execute(),TranscriptSessionsQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(AM(JR.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(jM(JR.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(FV).sort((e,t)=>e.sequence-t.sequence)})}),JV=(e,t)=>K_(t.openedAt)-K_(e.openedAt)||t.runId.localeCompare(e.runId),YV={eventId:VR.eventId,dedupKey:VR.dedupKey,payload:VR.payloadJson,receivedAt:VR.receivedAt,itemKey:Z.itemKey,loop:Z.loopName,step:Z.stepName,approval:Z.approval,permissions:Z.permissions,cycleLimit:Z.cycleLimit,cycleGeneration:Z.cycleGeneration,repository:Z.repository,revision:Z.revision,task:Z.task,agent:Z.agentJson,parentModel:Z.parentModel},XV=YL(VR,`approval_event`),ZV={itemKey:Z.itemKey,runId:Q.runId,eventId:Q.eventId,loop:Q.loopName,state:Q.stateJson,resolvedFailureAttemptId:Q.resolvedFailureAttemptId,openedAt:Q.openedAt,closedAt:Q.closedAt,repository:Q.repository,revision:Q.revision,task:Q.task,agent:Q.agentJson,parentModel:Q.parentModel,stepName:qR.stepName,result:qR.result,approvedAt:XV.receivedAt,approvalChannel:YR.channel,approver:YR.approver,againFrom:XR.fromRunId,againRequestedBy:XR.requestedBy},QV={attemptId:$.attemptId,runId:$.runId,stepName:$.stepName,worker:$.workerName,number:$.attemptNumber,brain:$.brainJson,task:$.task,agent:$.agent,operatorIntervened:$.operatorIntervened,parentModel:$.parentModel,startedAt:$.startedAt,outcome:$.outcomeJson,endedAt:$.endedAt,salvage:$.salvageJson,start:$.startJson,failureResolution:$.failureResolutionJson,reattachedAt:$.reattachedAt,comments:$.commentsJson,outOfMemory:$.outOfMemoryJson},$V=J`json_extract(${Q.stateJson}, '$._tag')`,eH=hM($V,[...AA]),tH=hM($V,[...MA]),nH=e=>Kw(IE)(SV(e)),rH=e=>{let t=O(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*$B(yield*e.select(YV).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(VR.dedupKey,t)).execute())}),n=O(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*$B(yield*e.select(YV).from(Q).innerJoin(VR,Y(VR.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(ZV).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(qR,Y(qR.runId,Q.runId)).leftJoin(YR,Y(YR.runId,Q.runId)).leftJoin(XV,Y(XV.eventId,YR.eventId)).leftJoin(XR,Y(XR.eventId,Q.eventId)),i=O(`RunStoreQueries.runRows`)(function*(e){return yield*nV(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>T(function*(){let n=yield*e.select({attemptId:$.attemptId,worker:$.workerName,repository:Q.repository,runId:$.runId,loop:Z.loopName,itemKey:Z.itemKey,number:$.attemptNumber,permissions:Z.permissions,outcome:J`coalesce(json_extract(${$.outcomeJson}, '$._tag'), '')`,salvage:$.salvageJson}).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(_M($.leftoversDiscardedAt),...t)).execute();return(yield*Hw(N(M({attemptId:sF,worker:EN,repository:Xk,runId:HA,loop:aA,itemKey:nI,number:cF,permissions:lA,outcome:j,salvage:I($P)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:ZP(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?b(n):y()}))}),o=O(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=O(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*D({attemptId:e}),ea(yield*a(Y($.attemptId,e)))}),c=O(`RunStoreQueries.attemptRows`)(function*(t){return yield*iV(yield*e.select(QV).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=O(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*Nh([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new iz({runId:e}):new IB({event:EV(s),itemKey:s.itemKey,run:kV(o),step:MV(o),attempts:r.map(NV),resolvedFailureAttemptId:Sr(o.resolvedFailureAttemptId),closedAt:Sr(o.closedAt),approval:AV(o),runAgain:jV(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:Sr(o.parentModel),permissions:s.permissions})}),u=O(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=da((yield*Ph(ua(t.map(({runId:e})=>e),100),t=>e.select(QV).from($).where(hM($.runId,t)).orderBy(AM($.runId),AM($.attemptNumber)).execute().pipe(E(iV)))).flat(),({runId:e})=>e);return t.map(e=>PV(e,n[e.runId]??[]))}),d=O(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*Ph(ua([...new Set(e)],100),e=>r().where(hM(Z.itemKey,e)).execute().pipe(E(nV)))).flat().sort(JV);return yield*u(t)}),f=O(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*Nh([r().where(eH).orderBy(jM(Q.openedAt),jM(Q.runId)).execute().pipe(E(nV)),r().where(gM($V,[...AA])).orderBy(jM(Q.openedAt),jM(Q.runId)).limit(e).execute().pipe(E(nV))]),i=[...t,...n].sort(JV);return yield*u(i)}),p=O(`RunStoreQueries.runEvents`)(function*(t){return(yield*Ph(ua([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:VR.eventId,dedupKey:VR.dedupKey,payload:VR.payloadJson,receivedAt:VR.receivedAt}).from(Q).innerJoin(VR,Y(VR.eventId,Q.eventId)).where(hM(Q.runId,t)).execute().pipe(E(rV)))).flat().map(DV)}),m=O(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(gM($V,[...AA])).orderBy(jM(Q.closedAt),jM(Q.runId)).limit(e).execute().pipe(E(nV));return yield*u(t)}),h=O(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=gM($V,[...AA]),n=yield*r().where(vr(e,{onNone:()=>t,onSome:e=>cM(t,fM(Q.closedAt,uV(e)))})).orderBy(jM(Q.closedAt),jM(Q.runId)).execute().pipe(E(nV));return yield*u(n)}),g=O(`RunStoreQueries.projectionRevision`)(function*(){return Sr((yield*sV(yield*e.select({revision:rz.revision}).from(rz).where(Y(rz.singleton,1)).limit(1).execute()))[0]?.revision)}),_=O(`RunStoreQueries.updateState`)(function*(t,n,r){let i=TA(n)?null:uV(r??(yield*B_));if((yield*e.update(Q).set({stateJson:dV(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new iz({runId:t})}),v=O(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*D({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:_V(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),ee=O(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:CV(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:C(t.parentModel),startedAt:uV(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:vr(t.start,{onNone:()=>null,onSome:vV})}).execute()}),te=O(`RunStoreQueries.recordReattach`)(function*(t,n){yield*D({attemptId:t}),yield*e.update($).set({reattachedAt:uV(n)}).where(Y($.attemptId,t)).execute()}),ne=O(`RunStoreQueries.nextStart`)(function*(t){return Sr((yield*yV(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),re=O(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:vr(n,{onNone:()=>null,onSome:vV})}).where(Y(Q.runId,t)).execute()}),ie=O(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:pV(n)}).where(Y($.attemptId,t)).execute(),n._tag===`Retained`&&S(n.pushFailure)&&(yield*e.update($).set({outcomeJson:fV(new qP({failure:n.pushFailure.value}))}).where(cM(Y($.attemptId,t),J`json_extract(${$.outcomeJson}, '$._tag') = 'Failed'`,J`json_extract(${$.outcomeJson}, '$.failure._tag') != 'GitHubPushFailure'`)).execute())}),ae=O(`RunStoreQueries.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:mV(n)}).where(Y($.attemptId,t)).execute()}),oe=O(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=qi(((yield*gV(yield*e.select({outOfMemory:$.outOfMemoryJson}).from($).where(Y($.attemptId,t)).execute()))[0]?.outOfMemory??[]).filter(({container:e})=>e!==n.container),n);return yield*e.update($).set({outOfMemoryJson:hV(r)}).where(Y($.attemptId,t)).execute(),gF(r)}),se=O(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:fV(n),endedAt:uV(r)}).where(cM(Y($.attemptId,t),_M($.outcomeJson))).execute()}),ce=O(`RunStoreQueries.amend`)(function*(t,n){yield*D({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:nH(n.agent),parentModel:C(n.parentModel)}).where(Y(Q.runId,t)).execute()}),le=O(`RunStoreQueries.markIntervened`)(function*(t){yield*D({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),ue=O(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),de=O(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(qR).set({result:bV(r)}).where(cM(Y(qR.runId,t),Y(qR.stepName,n))).execute()}),fe=O(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(YR,Y(YR.runId,t)).execute())>0}),pe=O(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(VR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:lV(n.payload),receivedAt:uV(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(YR).values({runId:t,eventId:n.id,channel:r.channel,approver:C(r.approver)}).execute()}),me=O(`RunStoreQueries.createRun`)(function*(t,n,r){let i=YL(Z,`candidate`),a=YL(Q,`candidate_run`),o=YL(ZR,`ignored`);yield*e.insert(ZR).select(e.select({eventId:i.eventId,reason:J`'superseded'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).leftJoin(o,Y(o.eventId,i.eventId)).where(cM(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),oM(i.eventId,n),_M(a.runId),_M(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:dV(new mA),openedAt:uV(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:nH(t.agent),parentModel:C(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(qR).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),he=O(`RunStoreQueries.runForEvent`)(function*(t){return yield*aV(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),ge=O(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*oV(yield*e.select({reason:ZR.reason}).from(ZR).where(Y(ZR.eventId,t)).execute())}),_e=O(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n),eH)).orderBy(jM(Q.openedAt)).limit(1).execute())}),ve=O(`RunStoreQueries.newestReopening`)(function*(t){return Or(Sr((yield*eV(yield*e.select({...YV,reopening:Z.reopening}).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(Z.reopensEventId,t)).orderBy(jM(Z.reopening)).limit(1).execute()))[0]),e=>({submission:OV(e),reopening:e.reopening}))}),ye=O(`RunStoreQueries.reopenedEvent`)(function*(t){let n=YL(VR,`reopened_event`);return Sr((yield*tV(yield*e.select({eventId:n.eventId,dedupKey:n.dedupKey}).from(Z).innerJoin(n,Y(n.eventId,Z.reopensEventId)).where(Y(Z.eventId,t)).execute()))[0])}),be=O(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(XR).values({eventId:t,fromRunId:n.from,requestedBy:C(n.requestedBy)}).execute()}),xe=O(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=y()){yield*e.insert(VR).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:lV(n.event.payload),receivedAt:uV(n.event.receivedAt)}).onConflictDoNothing().execute();let i=(yield*t(n.event.dedupKey))[0];return i===void 0?(yield*e.insert(Z).values({eventId:n.event.id,itemKey:n.itemKey,loopName:n.loop,stepName:n.step,approval:n.approval,permissions:n.permissions,cycleLimit:C(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:nH(n.agent),parentModel:C(n.parentModel),reopensEventId:C(Or(r,({eventId:e})=>e)),reopening:vr(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):OV(i)}),Se=O(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return y();let i=yield*KV(e).suppression(r.loop,r.itemKey);if(S(i))return yield*k(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),y();let a=yield*$B(yield*e.select(YV).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).leftJoin(Q,Y(Q.eventId,VR.eventId)).leftJoin(ZR,Y(ZR.eventId,VR.eventId)).where(cM(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),VV(e).currentEvent,_M(Q.runId),_M(ZR.eventId))).orderBy(jM(VR.receivedAt)).execute());return Sr(a[0]).pipe(Or(e=>({submission:OV(e),eventIds:a.map(e=>e.eventId)})))}),Ce=O(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*aV(yield*e.select({runId:Q.runId}).from(Q).where(cM(eH,oM($V,`Waiting`))).execute())).map(({runId:e})=>e)}),we=O(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(ZR,Y(ZR.eventId,Z.eventId)).leftJoin(UR,Y(UR.itemKey,Z.itemKey)).leftJoin(HR,cM(Y(HR.loopName,Z.loopName),Y(HR.itemKey,Z.itemKey))).where(cM(_M(Q.runId),_M(ZR.eventId),_M(UR.askJson),_M(HR.suppressedByRunId),VV(e).currentEvent)).execute();return(yield*Ph(yield*Hw(N(M({loop:aA,itemKey:nI})))(t),({loop:t,itemKey:n})=>T(function*(){return(yield*_e(t,n)).length>0?[]:yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(jM(Q.openedAt),jM(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Te=O(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=YL(Z,`candidate`),a=YL(Q,`candidate_run`);return(yield*e.insert(ZR).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(cM(Y(i.loopName,t),Y(i.itemKey,n),hM(i.eventId,r),_M(a.runId)))).onConflictDoNothing().returning({eventId:ZR.eventId}).execute()).length}),Ee=O(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n),tH)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Te(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:VV(e),loopItems:KV(e),...qV(e),addAttempt:ee,recordReattach:te,nextStart:ne,setNextStart:re,recordSalvage:ie,recordComments:ae,recordOutOfMemory:oe,amend:ce,markIntervened:le,approvalExists:fe,blockingRun:_e,closeAttempt:se,createRun:me,eventRouteByRun:n,ignoredEvent:ge,newestReopening:ve,nextQueued:Se,reopenedEvent:ye,recordRunAgain:be,pendingContinuations:we,recordTriggerEvent:xe,runIdsToDrive:Ce,recordApproval:pe,revision:g,revokeQueued:Te,revokeUnstarted:Ee,runSummaries:f,closedRunSummaries:m,closedRunSummariesSince:h,itemRunSummaries:d,runEvents:p,runForEvent:he,snapshot:l,updateStepResult:de,updateAttemptParentModel:ue,updateState:_,resolveFailure:v}},iH=T(function*(){let e=yield*iN,t=rH(e),n=O(`RunReader.inspect`)(e=>t.snapshot(e).pipe(TV(`read run`))),r=O(`RunReader.evidence`)(function*(t){yield*D({runId:t});let n=yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t);return new RB({snapshot:r,transcript:(yield*Ph(r.attempts,({id:e})=>n.transcript(new bB({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(TV(`read run evidence`));return yield*A(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=O(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(TV(`list runs`))),a=O(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(TV(`list closed runs`))),o=O(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(TV(`list runs closed since a time`))),s=O(`RunReader.revision`)(()=>t.revision().pipe(TV(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:O(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(TV(`read item run histories`))),events:O(`RunReader.events`)(e=>t.runEvents(e).pipe(TV(`read the events of runs`))),revision:s,transcript:O(`RunReader.transcript`)(e=>t.transcript(e).pipe(TV(`read attempt transcript`))),attemptsByWorker:O(`RunReader.attemptsByWorker`)(()=>RV(e).attemptCountsByWorker().pipe(TV(`count attempts by worker`))),sightings:O(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(TV(`read loop sightings`)))}}),aH=class e extends Rr()(`@usine/engine/RunReader`){static layer=Xf(e,iH)},oH=class extends V(`@usine/orchestrator/UsageCostView`)({usd:TP,estimate:lT}){},sH=class extends V(`@usine/orchestrator/SessionUsageView`)({attemptId:sF,session:hP,pool:kP,tokens:dP,cost:I(oH)}){},cH=class extends V(`@usine/orchestrator/PoolUsageView`)({pool:kP,tokens:dP,cost:I(oH)}){},lH=class extends V(`@usine/orchestrator/RunUsageView`)({tokens:dP,pools:N(cH),sessions:N(sH)}){},uH=class extends V(`@usine/orchestrator/TaskPoolUsageView`)({pool:kP,tokens:dP,cost:I(oH),unpriced:lT}){},dH=class extends V(`@usine/orchestrator/TaskUsageView`)({durationMillis:R.check(HT(0)),runningSince:N(j),unmeasured:R.check(HT(0)),tokens:dP,pools:N(uH),cost:I(oH)}){},fH=[`apiKeys`,`claudePlan`,`chatgptPlan`],pH=(e,t)=>vr(t,{onNone:()=>null,onSome:t=>new oH({usd:t,estimate:e!==`apiKeys`})}),mH=({session:e,costUsd:t,breakdown:n})=>S(t)||e.brain.harness!==`codex`?t:kr(n,t=>FB(e.brain.model,t)),hH=e=>{let t=new Map;for(let{attemptId:n,envelope:r}of e){let e=r.payload;if(e._tag!==`SessionEvent`||e.event._tag!==`SessionTokensUpdated`)continue;let i=`${n} ${e.event.session.id}`,a=t.get(i);a!==void 0&&a.report.totalTokens>=e.event.totalTokens||t.set(i,{attemptId:n,report:e.event})}let n=[...t.values()].map(e=>({...e,price:mH(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=jP(t.session);return new sH({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:pH(r,n)})}),i=new Set(n.flatMap(({report:e,price:t})=>x(t)&&e.session.brain.harness===`codex`&&S(e.breakdown)?[e.session.brain.model]:[])),a=fH.flatMap(e=>{let t=r.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new cH({pool:e,tokens:dP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:pH(e,n.length===t.length?b(TP.make(n.reduce((e,t)=>e+t,0))):y())})]});return{view:new lH({tokens:dP.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},gH=(e,t)=>{let n=0,r=0,i=[];for(let{attempts:t}of e)for(let{startedAt:e,endedAt:a,outcome:o}of t)o===null?i.push(e):a===null?r+=1:n+=Math.max(0,Date.parse(a)-Date.parse(e));let a=e.flatMap(({id:e})=>t.get(e)?.sessions??[]),o=fH.flatMap(e=>{let t=a.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new uH({pool:e,tokens:dP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:pH(e,n.length===0?y():b(TP.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new dH({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:dP.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new oH({usd:TP.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},_H=T(function*(){let e=yield*aH,t=yield*zh(()=>new Map),n=yield*zh(()=>new Set),r=O(`RunUsageReader.attemptReports`)(function*(n){let r=t.get(n.id);if(r!==void 0)return{reports:r,read:!1};let i=yield*e.transcript(new CB({attemptId:n.id}));return S(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:O(`RunUsageReader.read`)(function*(e){yield*D({runId:e.run.id});let t=yield*Ph(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=hH(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*e_(`The OpenAI price table has no rates for a Codex model, so its sessions have no cost`,{model:t,runId:e.run.id}));return yield*A(`Read Run usage`,{runId:e.run.id,sessions:i.sessions.length,tokens:i.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),i})}});(class e extends Rr()(`@usine/orchestrator/RunUsageReader`){static layer=Xf(e,_H)});var vH=F(jA),yH=I(j),bH=class extends V(`@usine/orchestrator/EditAndRetry`)({task:lF,agent:fN}){},xH=class extends V(`@usine/orchestrator/SessionIntervention`)({attemptId:sF,target:WF.pipe(DT(w({_tag:`Parent`}))),action:BF}){};NE(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:fN,message:j}),NE(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:aA,message:j});var SH=class extends V(`@usine/orchestrator/ApprovalView`)({approvedAt:j,source:I(pI)}){},CH=class extends V(`@usine/orchestrator/RunView`)({id:HA,itemKey:nI,loop:aA,repository:Xk,agent:fN,agentBrain:dN,state:vH,loopPaused:lT,openedAt:j,closedAt:I(j),task:j,attempts:N(Kz),approval:I(SH),runAgain:I(Dz),resultMessage:yH,pullRequestUrl:yH,canApprove:lT,canRetry:lT,canResolveFailure:lT,canCancel:lT,canRunAgain:lT}){},wH=R.check(HT(0)),TH=R.check(HT(0)),EH=class extends V(`@usine/orchestrator/RunDurationView`)({endedMillis:wH,runningSince:I(j),unmeasured:TH}){},DH=class extends V(`@usine/orchestrator/UnconfirmedStopView`)({runId:HA,attemptNumber:cF,worker:EN}){},OH=class extends V(`@usine/orchestrator/RunDetailView`)({run:CH,agentDefinitionChanged:lT,eventDedupKey:j,eventPayload:IE,transcript:N(OB),sessionState:N(OB),earlierTranscript:N(kB),worker:I(EN).pipe(TT(w(null))),settledItemState:I(xz).pipe(TT(w(null))),duration:EH.pipe(TT(w(new EH({endedMillis:0,runningSince:null,unmeasured:0})))),usage:lH.pipe(TT(w(new lH({tokens:dP.make(0),pools:[],sessions:[]})))),unconfirmedStop:I(DH).pipe(TT(w(null))),machine:I(aB).pipe(TT(w(null)))}){},kH=z.pipe(L(`BoardLaneId`)),AH=F([`authored`,`proposed`,`fallback`]),jH=class extends V(`@usine/orchestrator/BoardItemLink`)({itemKey:nI,kind:F([`issue`,`pr`]),number:rI,title:j,url:z,state:bz}){},MH=class extends V(`@usine/orchestrator/BoardPullRequestView`)({number:rI,url:z,state:F([`pr-open`,`pr-merged`])}){},NH=class extends V(`@usine/orchestrator/BoardTaskView`)({...jH.fields,labels:N(fz),items:N(jH).check(qT()),pullRequest:I(MH),runs:N(CH),run:I(CH),needsYou:lT,conflicting:lT,loops:N(aA),usage:dH}){},PH={id:kH,name:yz,sources:N(Tz),origin:AH,items:N(NH)},FH=class extends H(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...PH,origin:rT(`authored`),labels:N(fz).check(qT())}){},IH=class extends H(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,PH){},LH=P([FH,IH]),RH=class extends NE(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:Xk,itemKey:nI,message:z}){},zH=class extends V(`@usine/orchestrator/BoardView`)({lanes:N(LH),failures:N(RH)}){},BH=class extends V(`@usine/orchestrator/LabelView`)({name:fz,color:I(j),description:I(j)}){};V(`@usine/orchestrator/BoardMove`)({repository:Xk,item:rI,toLane:kH});var VH=class extends NE(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:Xk}){},HH=class extends NE(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:Xk,item:rI}){};NE(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:Xk,lane:kH}),NE(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:Xk,lane:kH});var UH=j.check(PT(/^(?:[A-Za-z_][A-Za-z0-9_.]*|list<[A-Za-z_][A-Za-z0-9_.]*>|map<[A-Za-z_][A-Za-z0-9_.]*,[A-Za-z_][A-Za-z0-9_.]*>)$/u,{message:`Expected a CEL type reference`})).pipe(L(`CelTypeReference`)),WH=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),GH=j.check(PT(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),KH=e=>NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),qH=class extends V(`@usine/expression/ObjectField`)({name:WH,type:UH,nullable:lT.pipe(TT(w(!1)))}){},JH=class extends V(`@usine/expression/ObjectType`)({name:GH,fields:N(qH).check(KH(`Expected unique CEL object-field names`))}){},YH=class extends V(`@usine/expression/Variable`)({name:WH,type:UH}){},XH=class extends V(`@usine/expression/Environment`)({types:N(JH).check(KH(`Expected unique CEL object-type names`)),variables:N(YH).check(KH(`Expected unique CEL variable names`))}){},ZH=j.check(PT(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(L(`ExpressionSource`)),QH=R.check(HT(0)),$H=F([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]);P([class extends NE(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:ZH,code:$H,message:z,position:B(QH)}){},class extends NE(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:ZH,message:z}){}]),P([j,cT,uT,lT,oT]);var eU=class extends Rr()(`@usine/expression/ExpressionEngine`){},tU=z.pipe(L(`InstancePath`)),nU=F([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),rU=class e extends NE(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:tU,stage:nU,expression:xE(ZH),message:z,details:$w(N(M({path:N(P([j,cT])),message:j})))}){static fromSchema(t,n){let r=Hy()(n.issue).issues.map(({path:e,message:t})=>({path:(e??[]).map(e=>Ok(e).pipe(Ak(jk,e=>e),Ak(Mk,e=>e),Ak(Nk,String),Pk(({key:e})=>String(e)))),message:t}));return new e({file:t,stage:`schema`,expression:y(),message:Yy()(n.issue),details:r})}};P([rU,class extends NE(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:tU,stage:nU,message:z}){}]);var iU=j.check(PT(/\S/u,{message:`Expected a non-blank repository label`})),aU=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),oU=class extends V(`@usine/engine/RepositoryLabel`)({name:iU,color:yE(aU),description:yE(j)}){},sU=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),cU=N(oU).check(sU),lU=class extends V(`@usine/engine/RepositoryLabelProjection`)({repository:Xk,labels:cU}){},uU=N(j),dU=Vw(uU),fU=M({repository:Xk,labels:P([lU.fields.labels,uU])}),pU=e=>dU(e)?e.map(e=>new oU({name:e,color:y(),description:y()})):e,mU=Hw(N(fU)),hU=Xw(lU.fields.labels),gU=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),_U=T(function*(){let e=yield*iN;return{get:O(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*mU(yield*e.select({repository:ez.repository,labels:ez.labelsJson}).from(ez).where(Y(ez.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?y():b(new lU({repository:n.repository,labels:pU(n.labels)}))},gU(`read repository label projection`))}}),vU=T(function*(){let e=yield*iN;return{replace:O(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*D({repository:t.repository});let n=hU(t.labels);return(yield*e.insert(ez).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:ez.repository,set:{labelsJson:n},setWhere:oM(ez.labelsJson,n)}).returning({repository:ez.repository}).execute()).length===0?(yield*A(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*A(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},gU(`write repository label projection`))}}),yU=class e extends Rr()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=Xf(e,_U)},bU=class e extends Rr()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=Xf(e,vU)},xU=`~effect/http/HttpBody`,SU=e=>pe(e,xU),CU=class{[xU];constructor(){this[xU]=xU}[gt](){return this.toJSON()}toString(){return ot(this,{ignoreToString:!0})}},wU=new class extends CU{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},TU=class extends CU{_tag=`Uint8Array`;contentType;contentLength;text;_body;constructor(e,t,n,r){super(),this._body=e,this.text=r,this.contentType=t,this.contentLength=n}get body(){return this._body??=kU(this.text)}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}},EU=(e,t)=>new TU(e,t??`application/octet-stream`,e.length),DU=new TextEncoder,OU=globalThis.Buffer,kU=OU===void 0?e=>DU.encode(e):e=>OU.from(e,`utf8`),AU=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),OU!==void 0)return new TU(void 0,t??`text/plain`,OU.byteLength(e,`utf8`),e);let n=DU.encode(e);return new TU(n,t??`text/plain`,n.length,e)},jU=(e,t)=>AU(JSON.stringify(e),t??`application/json`),MU=(e,t)=>AU(Xv(Vv(e)),t??`application/x-www-form-urlencoded`),NU=class extends CU{_tag=`FormData`;contentType=void 0;contentLength=void 0;formData;constructor(e){super(),this.formData=e}toJSON(){return{_id:`effect/HttpBody`,_tag:`FormData`,formData:this.formData}}},PU=e=>new NU(e),FU=class extends CU{_tag=`Stream`;stream;contentType;contentLength;constructor(e,t,n){super(),this.stream=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Stream`,contentType:this.contentType,contentLength:this.contentLength}}},IU=(e,t,n)=>new FU(e,t??`application/octet-stream`,n),LU=`~effect/http/HttpClientError`,RU=class extends wo(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[LU]=LU;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},zU=e=>e.endsWith(`Error`)?e.slice(0,-5):e,BU=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,VU=e=>`${e.method} ${ey(e.url)}`,HU=class extends wo(`TransportError`){get methodAndUrl(){return VU(this.request)}get message(){return BU(zU(this._tag),this.description,this.methodAndUrl)}},UU=class extends wo(`InvalidUrlError`){get methodAndUrl(){return VU(this.request)}get message(){return BU(zU(this._tag),this.description,this.methodAndUrl)}},WU=class extends wo(`StatusCodeError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},GU=class extends wo(`DecodeError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},KU=class extends wo(`EmptyBodyError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},qU=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,JU=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],YU=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?Mv(Mv(e,`content-type`),`content-length`):(e=t.contentType===void 0?Mv(e,`content-type`):kv(e,`content-type`,t.contentType),t.contentLength===void 0?Mv(e,`content-length`):kv(e,`content-length`,t.contentLength.toString())),XU=class extends wo(`UrlError`){},ZU=(e,t,n)=>Ti({try:()=>{let r=new URL(e,QU());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Iv(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new XU({cause:e})}),QU=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0){let e=location.origin+location.pathname;try{return new URL(e).href}catch{return}}},$U=`~effect/http/HttpClientRequest`,eW={[$U]:$U,...yt,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:ey(this.url),urlParams:this.urlParams,hash:this.hash,headers:tt(this.headers),body:this.body.toJSON()}},pipe(){return e(this,arguments)}};function tW(e,t,n,r,i,a){let o=Object.create(eW);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var nW=tW(`GET`,``,Kv,y(),Ev,wU),rW=e=>(t,n)=>oW(nW,{method:e,url:t,...n??void 0}),iW=rW(`GET`),aW=rW(`POST`),oW=r(2,(e,t)=>{let n=e;return t.method&&(n=sW(n,t.method)),t.url&&(n=pW(n,t.url)),t.headers&&(n=lW(n,t.headers)),t.urlParams&&(n=gW(n,t.urlParams)),t.hash&&(n=vW(n,t.hash)),t.body&&(n=yW(n,t.body)),t.accept&&(n=uW(n,t.accept)),t.acceptJson&&(n=dW(n)),n}),sW=r(2,(e,t)=>tW(t,e.url,e.urlParams,e.hash,e.headers,e.body)),cW=r(3,(e,t,n)=>tW(e.method,e.url,e.urlParams,e.hash,kv(e.headers,t,n),e.body)),lW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,Av(e.headers,t),e.body)),uW=r(2,(e,t)=>cW(e,`Accept`,t)),dW=uW(`application/json`),fW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,kv(kv(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),pW=r(2,(e,t)=>{if(typeof t==`string`)return tW(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Vv(n.searchParams),i=Sr(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,tW(e.method,n.toString(),r,i,e.headers,e.body)}),mW=r(2,(e,t)=>t===``?e:tW(e.method,hW(t,e.url),e.urlParams,e.hash,e.headers,e.body)),hW=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},gW=r(2,(e,t)=>tW(e.method,e.url,Jv(e.urlParams,t),e.hash,e.headers,e.body)),_W=r(2,(e,t)=>tW(e.method,e.url,Yv(e.urlParams,t),e.hash,e.headers,e.body)),vW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,b(t),e.headers,e.body)),yW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,YU(e.headers,t),t)),bW=r(2,(e,t)=>yW(e,jU(t))),xW=r(2,(e,t)=>yW(e,PU(t)));function SW(e){let t=ZU(e.url,e.urlParams,Tr(e.hash));return Oi(t)?b(t.success):y()}var CW=`~effect/http/HttpIncomingMessage`,wW=(e,t)=>{let n=Uw(PE(e)),r=t?.reviver===void 0?void 0:Uw(aE(PE(e),t));return e=>r===void 0?E(e.json,e=>n(e,t)):E(e.text,i=>i===``?E(e.json,e=>n(e,t)):r(i,t))},TW=(e,t)=>({...t,headers:tt(e.headers),remoteAddress:e.remoteAddress}),EW=`~effect/http/HttpClientResponse/WebSource`,DW=e=>e[EW]?.(),OW=`~effect/http/HttpClientResponse`,kW=(e,t)=>new AW(e,t),AW=class extends bt{[CW];[OW];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[CW]=CW,this[OW]=OW}toJSON(){return TW(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split(`#`)[0];let e=SW(this.request);return x(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Dv(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=lv(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return y()}[EW](){return this.source}get stream(){return this.source.body?PO({evaluate:()=>this.source.body,onError:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}):MO(new RU({reason:new KU({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return E(this.text,e=>qh({try:()=>e===``?null:JSON.parse(e),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=ng(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return E(this.text,e=>qh({try:()=>Vv(new URLSearchParams(e)),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Ih({try:()=>this.source.formData(),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}).pipe(Ig,Zg)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Ih({try:()=>this.source.arrayBuffer(),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}).pipe(Ig,Zg),this.arrayBufferBody}get upgrade(){return Uh(new RU({reason:new WU({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return e(this,arguments)}},jW=e=>Ov({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${vr(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),MW={"http:":80,"https:":443,"ws:":80,"wss:":443},NW=(e,t,n)=>{let r=ey(t.search,n).slice(1);if(e.attribute(`url.full`,ey(t.href,n)),e.attribute(`url.path`,t.pathname),r!==``&&e.attribute(`url.query`,r),e.attribute(`url.scheme`,t.protocol.slice(0,-1)),t.hostname!==``){e.attribute(`server.address`,t.hostname.startsWith(`[`)?t.hostname.slice(1,-1):t.hostname);let n=t.port===``?MW[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},PW=(e,t)=>{let n=e.params.filter(([,e])=>typeof e!=`string`).map(([e])=>e);return n.length===0?t:[...t,...new URLSearchParams(n.map(e=>[e,``])).keys()]},FW=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Pv(a,i)?`<redacted>`:n[a])},IW=`~effect/http/HttpClient`,LW=Rr(`effect/HttpClient`),RW=r(2,(e,t)=>zW(n=>t(e.postprocess(n)),e.preprocess)),zW=(e,t)=>{let n=Object.create(BW);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},BW={[IW]:IW,pipe(){return e(this,arguments)},...yt,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(JU.map(([e,t])=>[t,function(t,n){return this.execute(rW(e)(t,n))}]))},VW=e=>zW(t=>E(t,t=>Jh(n=>{let r=XW.get(t),i=r??new AbortController,a=ZU(t.url,t.urlParams,Tr(t.hash));if(Di(a))return Uh(new RU({reason:new UU({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(Bo)||n.getRef(WW)(t)){let a=e(t,o,i.signal,n);return r?a:Bg(e=>Sg(e(a),{onSuccess(e){return YW.register(e,i),w(new ZW(e,i))},onFailure(e){return nf(e)&&i.abort(),Wh(e)}}))}return Ug(n.getRef(qW)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Fv);NW(a,o,PW(t.urlParams,n.getRef(cy)));let c=n.getRef(GW);return FW(a,`request`,t.headers,c,s),t=n.getRef(KW)?lW(t,jW(a)):t,Bg(l=>l(e(t,o,i.signal,n)).pipe(Gg(a,{captureStackTrace:!1}),Sg({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),FW(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),HW(n,a,t,e)),r?w(e):(YW.register(e,i),w(new ZW(e,i)))),onFailure(e){return!r&&nf(e)&&i.abort(),Wh(e)}})))})})),w),HW=(e,t,n,r)=>{let i=St();Ct(0);let a;try{a=df(new RU({reason:new WU({request:n,response:r})}))}finally{Ct(i)}t.end(e.getRef(Ef)?e.getRef(ap).currentTimeNanosUnsafe():BigInt(0),a)},UW=r(2,(e,t)=>zW(e.postprocess,n=>ng(e.preprocess(n),t))),WW=vi(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>s}),GW=vi(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>s}),KW=vi(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:o}),qW=vi(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),JW=e=>Xf(LW)(wg(t=>ng(e,e=>RW(e,Og(e=>hi(t,e)))))),YW=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{try{e.abort()}catch{}});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new WeakMap;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),XW=new WeakMap,ZW=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[OW]=OW;[CW]=CW;applyInterrupt(e){return Rh(()=>(YW.unregister(this.original),Rg(e,()=>zh(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[EW](){let e=DW(this.original);return e!==void 0&&YW.unregister(this.original),e}get stream(){return AO(()=>(YW.unregister(this.original),WO(this.original.stream,zh(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[gt](){return this.original[gt]()}pipe(){return e(this,arguments)}},QW=vi(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),$W=class extends Rr()(`effect/http/FetchHttpClient/RequestInit`){},eG=JW(w(VW((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return Uh(new RU({reason:new HU({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(QW),a=si(r.context,$W)??{},o=a.headers?jv(Dv(a.headers),e.headers):e.headers;o[`content-length`]&&(o=Mv(o,`content-length`));let s,c=zh(()=>s?.abort()),l=r=>ng(Ih({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:typeof ReadableStream<`u`&&r instanceof ReadableStream?`half`:void 0,signal:s?AbortSignal.any([n,s.signal]):n}),catch:t=>new RU({reason:new HU({request:e,cause:t})})}),t=>{let n=kW(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>Mg(n[e],c)}])),stream:{get:()=>WO(n.stream,c)}})):n}).pipe(Ng(()=>c));switch(e.body._tag){case`Raw`:case`Uint8Array`:return l(e.body.body);case`FormData`:return l(e.body.formData);case`Stream`:{s=new AbortController;let t=AbortSignal.any([n,s.signal]),r=Vh(e=>{let n=()=>e(Lg);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),zh(()=>t.removeEventListener(`abort`,n))});return E(JO(UO(e.body.stream,r)),l)}}return l(void 0)})));function tG(e,t){let n=1;for(;t<e.length;)if(t++,e[t]===`\\`)t++;else if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t;throw TypeError(`Invalid regexp expression in "`+e+`"`)}var nG=Rr(`effect/http/HttpEffect/CurrentRequestState`),rG=e=>Jh(t=>{let n=si(t.context,nG);return n!==void 0&&(n.loggerDisabled=!0),e}),iG=Rr(`effect/http/HttpRouter`),aG=e=>e.endsWith(`/`)?e.slice(0,-1):e,oG=r(2,(e,t)=>(t=aG(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),sG=`~effect/http/HttpRouter/Middleware`,cG=function(){return arguments.length===0?lG:lG(arguments[0],arguments[1])},lG=(e,t)=>t?.global?$f(T(function*(){let t=yield*iG,n=Mh(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new fG(Mh(e)?Qf(ng(e,e=>Zr(new Map([[dG,e]])))):Yf(Zr(new Map([[dG,e]])))),uG=0,dG=`effect/http/HttpRouter/MiddlewareFn`,fG=class e{[sG]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++uG}`;this.layer=Qf(T({self:this},function*(){let e=yield*Cg(),t=[ci(e,dG)];if(this.dependencies){let n=yield*Gf,r=ui(e,Df),i=yield*Kf(this.dependencies,n,r);t.push(...mG(i))}return Zr(new Map([[n,t]]))})).pipe(rp(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?ip(this.dependencies,t.layer):t.layer)}},pG=new WeakMap,mG=e=>{let t=pG.get(e);if(t)return t;let n=pa(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=Wi(e).reverse()}return pG.set(e,t),t};cG(rG).layer;var hG={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},gG=e=>hG[e],_G=R.check(HT(1)).pipe(L(`GitHubAppId`)),vG=CE(z.check(PT(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(L(`GitHubAppPrivateKey`)),{disallowEncode:!0});V(`@usine/github/AppCredentials`)({appId:_G,privateKey:vG});var yG=class extends Rr()(`@usine/github/GitHubCredentials`){},bG=class extends NE(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:z}){},xG=new TextEncoder,SG=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),CG=(...e)=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},wG=e=>{if(e<128)return new Uint8Array([e]);let t=[];for(let n=e;n>0;n>>>=8)t.unshift(n&255);return new Uint8Array([128|t.length,...t])},TG=(e,t)=>CG(new Uint8Array([e]),wG(t.length),t),EG=e=>TG(48,CG(new Uint8Array([2,1,0]),SG,TG(4,e))),DG=e=>{let t=e.includes(`-----BEGIN RSA PRIVATE KEY-----`),n=e.replace(/-----BEGIN (?:RSA )?PRIVATE KEY-----/gu,``).replace(/-----END (?:RSA )?PRIVATE KEY-----/gu,``).replace(/\s/gu,``),r=atob(n),i=Uint8Array.from(r,e=>e.charCodeAt(0));return t?EG(i):i},OG=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},kG=e=>OG(xG.encode(JSON.stringify(e))),AG=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},jG=O(`AppJwt.import`)(function*(e){let t=yield*Ih({try:async()=>crypto.subtle.importKey(`pkcs8`,AG(DG(bv(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new bG({message:`Could not import the GitHub App private key as an RSA private key`})});return O(`AppJwt.sign`)(function*(){let n=Math.floor((yield*op)/1e3),r=`${kG({alg:`RS256`,typ:`JWT`})}.${kG({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*Fh(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,AG(xG.encode(r))));return vv(`${r}.${OG(new Uint8Array(i))}`)})}),MG=R.check(HT(1)),NG=MG.pipe(L(`GitHubInstallationId`)),PG=MG.pipe(L(`GitHubRepositoryId`)),FG=z.pipe(L(`GitHubAppSlug`)),IG=class extends V(`@usine/github/Installation`)({id:NG,accountLogin:z,appSlug:FG}){},LG=class extends H(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},RG=class extends H(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:Xk,repositoryId:PG,permissions:lA}){},zG=P([LG,RG]),BG=class extends V(`@usine/github/InstallationToken`)({value:SE(z,{disallowJsonEncode:!0}),expiresAt:_E,scope:zG}){},VG=F([`missing`,`multiple`,`suspended`]),HG=class extends NE(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:VG,message:z}){},UG={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},WG={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},GG=(e,t)=>e===t||t===`read`&&e===`write`,KG=e=>Object.entries(UG).flatMap(([t,n])=>GG(e[t],n)?[]:[`${t}:${n}`]),qG=class extends H(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:NG,repository:Xk,repositoryId:PG}){},JG=class extends NE(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:Xk,message:z}){};P([qG,JG]);var YG=(e,t,n)=>{let r=new Map(n.map(e=>[e.name.toLowerCase(),e]));return t.map(t=>{let n=r.get(t.toLowerCase());return n===void 0?new JG({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new qG({installationId:e.id,repository:t,repositoryId:n.id})})},XG=class extends NE(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:N(z).check(qT()),message:z}){},ZG=F([`create-repository-label`,`discover-installation`,`fetch-base-ref-head`,`fetch-item-labels`,`fetch-issue-snapshot`,`fetch-item-timeline`,`fetch-pull-request-snapshot`,`find-missing-issues`,`list-installation-repositories`,`list-repository-labels`,`mint-installation-token`,`mint-worker-token`,`poll-repository-changes`,`read-bot-account`,`update-item-labels`]),QG=class extends NE(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:ZG,status:B(R),message:z}){},$G=class extends NE(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:ZG,retryAt:_E,message:z}){},eK=class extends NE(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:ZG,message:z,detail:z}){},tK=class extends NE(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:ZG,item:R.check(HT(1)),message:z}){};P([HG,XG,QG,$G,eK]);var nK=`https://api.github.com`,rK=`2026-03-10`,iK=e=>lW({accept:`application/vnd.github+json`,authorization:`Bearer ${bv(e)}`,"user-agent":`usine`,"x-github-api-version":rK}),aK=(e,t)=>new QG({operation:e,status:t.response===void 0?y():b(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),oK=Ww(M({message:z})),sK=(e,t)=>t.json.pipe(ng(t=>vr(oK(t),{onNone:()=>e,onSome:({message:t})=>new QG({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),og(t=>A(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(rg(e)))),cK=(e,t)=>new eK({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),lK=e=>{if(e===void 0||!/^\d+$/u.test(e))return y();let t=Number(e);return Number.isSafeInteger(t)?b(t):y()},uK=(e,t)=>{let n=lK(e);if(S(n))return b(t+n.value*1e3);if(e===void 0)return y();let r=Date.parse(e);return Number.isFinite(r)?b(r):y()},dK=(e,t)=>{let n=lK(e[`x-ratelimit-remaining`]),r=lK(e[`x-ratelimit-reset`]);return S(n)&&n.value<=t&&S(r)?b(r.value*1e3):y()},fK=(e,t)=>Or(lK(e[`x-poll-interval`]),e=>t+e*1e3),pK=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():b(Math.max(...t))},mK=(e,t)=>pK([uK(e[`retry-after`],t),dK(e,0)]),hK=(e,t,n)=>{let r=kr(mK(t.headers,n),z_);return(t.status===403||t.status===429)&&S(r)?new $G({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new QG({operation:e,status:b(t.status),message:`GitHub returned HTTP status ${t.status}`})},gK=36e5,_K=3e5,vK=N(M({id:NG,appSlug:FG,account:M({login:z}),permissions:hT(j,j),suspendedAt:I(j)}).pipe(mT({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),yK=M({login:ON,id:kN}),bK=M({id:PG,name:Xk}).pipe(mT({name:`full_name`})),xK=M({totalCount:R.check(HT(0)),repositories:N(bK)}).pipe(mT({totalCount:`total_count`})),SK=M({token:z,expiresAt:vE,repositories:xE(N(bK))}).pipe(mT({expiresAt:`expires_at`})),CK=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:UG}}:{operation:`mint-worker-token`,body:{permissions:WG[e.permissions],repository_ids:[e.repositoryId]}},wK=class e extends Rr()(`@usine/github/GitHubApp`){static layer=Xf(e,T(function*(){let e=yield*jG(yield*yG),t=yield*LW,n=(e,n,r)=>T(function*(){let i=yield*t.execute(n).pipe(dg(t=>aK(e,t)));if(i.status<200||i.status>=300){let t=hK(e,i,yield*op);return t._tag===`GitHubRateLimitError`?yield*t:yield*yield*sK(t,i)}return yield*wW(r)(i).pipe(dg(t=>cK(e,t.message)))}),r=O(`GitHubApp.discoverInstallation`)(function*(){let t=yield*e(),[r,...i]=yield*n(`discover-installation`,iW(`${nK}/app/installations?per_page=2`).pipe(iK(t)),vK);if(r===void 0)return yield*new HG({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(i.length>0)return yield*new HG({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(r.suspendedAt!==null)return yield*new HG({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=KG(r.permissions);return a.length>0?yield*new XG({missing:a,message:`The GitHub App installation is missing permissions: ${a.join(`, `)}. Grant them in the GitHub App settings, then approve the change on the installation.`}):new IG({id:r.id,accountLogin:r.account.login,appSlug:r.appSlug})}),i=O(`GitHubApp.mintToken`)(function*(t,r){let{operation:i,body:a}=CK(r);yield*D({installationId:t,operation:i,scope:r._tag,permissions:r._tag===`SingleRepository`?r.permissions:`installation`});let o=yield*e(),s=yield*n(i,aW(`${nK}/app/installations/${t}/access_tokens`).pipe(bW(a),iK(o)),SK),c=yield*op,l=K_(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new eK({operation:i,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${J_(s.expiresAt)} is ${l}ms from now`});l>gK&&(yield*k(`Accepted GitHub token clock skew; capped the local lease`,{installationId:t,operation:i,skewMillis:l-gK}));let u=yr(s.repositories,()=>[]);return r._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===r.repositoryId))?yield*new eK({operation:i,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${r.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new BG({value:vv(s.token),expiresAt:R_(c+Math.min(l,gK)),scope:r})}),a=O(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let r=1;;r+=1){let i=yield*n(`list-installation-repositories`,iW(`${nK}/installation/repositories?per_page=100&page=${r}`).pipe(iK(e.value)),xK);if(t.push(...i.repositories),t.length>=i.totalCount)return t;if(i.repositories.length===0)return yield*new eK({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${r} was empty after ${t.length} of ${i.totalCount} repositories`})}}),o=yield*qk(y()),s=O(`GitHubApp.lease`)(()=>Yk(o,e=>T(function*(){let t=yield*op;if(S(e)&&K_(e.value.token.expiresAt)-t>_K)return[e.value,e];let n=yield*r(),a={installation:n,token:yield*i(n.id,new LG)};return[a,b(a)]}))),c=yield*qk(y()),l=O(`GitHubApp.botAccount`)(()=>Yk(c,e=>T(function*(){let{installation:t,token:r}=yield*s(),{appSlug:i}=t;if(yield*D({appSlug:i}),S(e)&&e.value.appSlug===i)return[e.value.account,e];let a=new AN(yield*n(`read-bot-account`,iW(`${nK}/users/${encodeURIComponent(`${i}[bot]`)}`).pipe(iK(r.value)),yK));return yield*k(`Read the App's bot account`,{appSlug:i,login:a.login,id:a.id}),[a,b({appSlug:i,account:a})]})));return{installation:O(`GitHubApp.installation`)(()=>ng(s(),e=>e.installation)),botAccount:l,installationToken:O(`GitHubApp.installationToken`)(()=>ng(s(),e=>e.token)),projectAccess:O(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*s();return YG(t,e,yield*a(n))}),workerToken:O(`GitHubApp.workerToken`)((e,t)=>i(e.installationId,new RG({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},TK=z.pipe(L(`GitHubEntityTag`)),EK=z.pipe(L(`GitHubBaseRefName`)),DK=class extends V(`@usine/github/BaseRefHead`)({baseRefName:EK,sha:Qk,entityTag:yE(TK)}){},OK=class e extends V(`@usine/github/PollCursor`)({entityTag:yE(TK),watermark:yE(vE)}){static empty=new e({entityTag:y(),watermark:y()})},kK=class extends H(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:R.check(HT(1)),updatedAt:_E}){},AK=class extends H(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:R.check(HT(1)),updatedAt:_E}){},jK=P([kK,AK]),MK=class extends H(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:OK,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(w(y())))}){},NK=class extends H(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:OK,items:N(jK),backlog:lT,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(w(y())))}){};P([MK,NK]);var PK=z.pipe(L(`GitHubRepositoryLabelName`)),FK=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(L(`GitHubRepositoryLabelColor`)),IK=class extends V(`@usine/github/RepositoryLabel`)({name:PK,color:FK,description:yE(j)}){},LK=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),RK=class extends V(`@usine/github/RepositoryLabelCatalog`)({entityTag:yE(TK),labels:N(IK).check(LK)}){},zK=class extends H(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};P([RK,zK]);var BK=class extends V(`@usine/github/NewRepositoryLabel`)({name:PK,color:B(FK),description:B(j)}){},VK=M({name:PK,color:FK,description:I(j)}),HK=e=>{let{name:t,owner:n}=eA(e);return`${nK}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},UK=class e extends Rr()(`@usine/github/GitHubLabelWriter`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*LW;return{create:O(`GitHubLabelWriter.create`)(function*(n,r){yield*D({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};S(r.color)&&(a.color=r.color.value),S(r.description)&&(a.description=r.description.value);let o=aW(HK(n)).pipe(bW(a),iK(i.value)),s=yield*t.execute(o).pipe(dg(e=>aK(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*hK(`create-repository-label`,s,yield*op);let c=yield*wW(VK)(s).pipe(dg(e=>cK(`create-repository-label`,e.message)));return new IK({name:c.name,color:c.color,description:Sr(c.description)})})}}))},WK=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),GK=e=>Array.isArray(e)?e.map(GK):Vw(LE)(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!WK.has(e)).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,GK(t)])):e,KK=6e4,qK=M({data:$w(aT),errors:$w(N(M({message:j,type:$w(j)})))}),JK=O(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=aW(`${nK}/graphql`).pipe(bW({query:r,variables:i}),iK(t.value)),s=yield*e.execute(o).pipe(dg(e=>aK(n,e))),c=yield*op;if(s.status!==200)return yield*hK(n,s,c);let l=yield*wW(qK)(s).pipe(dg(e=>cK(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new $G({operation:n,retryAt:R_(yr(mK(s.headers,c),()=>c+KK)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*cK(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*Hw(a)(l.data).pipe(dg(e=>cK(n,e.message)))}),YK=R.check(HT(1)),XK=R.check(HT(0)),ZK=j.check(PT(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),QK=(e,t)=>I(e).pipe(ST(e,{decode:sb(e=>e??t),encode:sb(e=>e)})),$K={totalCount:0,nodes:[]},eq=M({login:z}),tq=I(eq),nq=M({totalCount:XK,nodes:N(M({name:z}))}),rq=M({totalCount:XK,nodes:N(M({author:tq,body:j,createdAt:ZK}))}),iq=M({number:YK,title:j,body:j,url:z,state:j,stateReason:I(j),createdAt:ZK,updatedAt:ZK,closedAt:I(ZK),author:tq,issueType:I(M({name:j})),milestone:I(M({title:j})),labels:QK(nq,$K),assignees:M({totalCount:XK,nodes:N(eq)}),comments:rq,closedByPullRequestsReferences:QK(M({totalCount:XK,nodes:N(M({number:YK,state:j,isDraft:lT,url:z}))}),$K)}),aq=I(M({login:$w(z)})),oq=M({author:tq,state:j,body:j,submittedAt:I(ZK),commit:I(M({oid:z}))}),sq=M({author:tq,body:j}),cq=M({number:YK,title:j,body:j,url:z,state:j,isDraft:lT,merged:lT,createdAt:ZK,updatedAt:ZK,mergedAt:I(ZK),author:tq,baseRefName:EK,headRefName:j,headRefOid:z,additions:XK,deletions:XK,changedFiles:XK,reviewDecision:I(j),mergeable:j.pipe(DT(w(`UNKNOWN`))),mergeStateStatus:j.pipe(DT(w(`UNKNOWN`))),statusCheckRollup:I(M({state:j})),labels:QK(nq,$K),reviewRequests:QK(M({totalCount:XK,nodes:N(M({requestedReviewer:aq}))}),$K),reviews:QK(M({totalCount:XK,nodes:N(oq)}),$K),reviewThreads:M({totalCount:XK,nodes:N(M({isResolved:lT,isOutdated:lT,path:j,comments:M({totalCount:XK,nodes:N(sq)})}))}),comments:rq,closingIssuesReferences:QK(M({totalCount:XK,nodes:N(M({number:YK,state:j}))}),$K)}),lq=j.check(PT(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(L(`GitHubContentHash`)),uq=class extends H(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:iq,contentHash:lq}){},dq=class extends H(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:cq,contentHash:lq}){};P([uq,dq]);var fq=`
36
+ )`)).groupBy(J`coalesce(json_extract(${JR.envelope}, '$.payload.event.session.id'), json_extract(${JR.envelope}, '$.payload.intervention.target.sessionId'), '@parent')`,J`json_extract(${JR.envelope}, '$.payload._tag')`,J`json_extract(${JR.envelope}, '$.payload.event._tag') = 'SessionStarted'`)),TranscriptUsageQuery:({attemptId:t})=>{let n=e.select({sequence:JR.sequence,tokens:J`max(json_extract(${JR.envelope}, '$.payload.event.totalTokens'))`.as(`tokens`)}).from(JR).where(cM(Y(JR.attemptId,t),J`json_extract(${JR.envelope}, '$.payload._tag') = 'SessionEvent'`,J`json_extract(${JR.envelope}, '$.payload.event._tag') = 'SessionTokensUpdated'`)).groupBy(J`json_extract(${JR.envelope}, '$.payload.event.session.id')`).as(`highest`);return hM(JR.sequence,e.select({sequence:n.sequence}).from(n))},TranscriptAllQuery:({attemptId:e})=>Y(JR.attemptId,e),TranscriptTailQuery:({attemptId:e,after:t})=>cM(Y(JR.attemptId,e),dM(JR.sequence,t)),TranscriptPageQuery:({attemptId:e,before:t})=>vr(t,{onNone:()=>Y(JR.attemptId,e),onSome:t=>cM(Y(JR.attemptId,e),pM(JR.sequence,t))})}),r=e.select({sequence:JR.sequence,attemptId:JR.attemptId,direction:JR.direction,envelope:JR.envelope,receivedAt:JR.receivedAt}).from(JR).where(n);return(yield*cV(yield*kk(t,{TranscriptWorkerQuery:()=>r.orderBy(jM(JR.sequence)).limit(1).execute(),TranscriptSessionsQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptUsageQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptAllQuery:()=>r.orderBy(AM(JR.sequence)).execute(),TranscriptTailQuery:({limit:e})=>r.orderBy(AM(JR.sequence)).limit(e).execute(),TranscriptPageQuery:({limit:e})=>r.orderBy(jM(JR.sequence)).limit(e).execute()}),{onExcessProperty:`error`})).map(FV).sort((e,t)=>e.sequence-t.sequence)})}),JV=(e,t)=>K_(t.openedAt)-K_(e.openedAt)||t.runId.localeCompare(e.runId),YV={eventId:VR.eventId,dedupKey:VR.dedupKey,payload:VR.payloadJson,receivedAt:VR.receivedAt,itemKey:Z.itemKey,loop:Z.loopName,step:Z.stepName,approval:Z.approval,permissions:Z.permissions,cycleLimit:Z.cycleLimit,cycleGeneration:Z.cycleGeneration,repository:Z.repository,revision:Z.revision,task:Z.task,agent:Z.agentJson,parentModel:Z.parentModel},XV=YL(VR,`approval_event`),ZV={itemKey:Z.itemKey,runId:Q.runId,eventId:Q.eventId,loop:Q.loopName,state:Q.stateJson,resolvedFailureAttemptId:Q.resolvedFailureAttemptId,openedAt:Q.openedAt,closedAt:Q.closedAt,repository:Q.repository,revision:Q.revision,task:Q.task,agent:Q.agentJson,parentModel:Q.parentModel,stepName:qR.stepName,result:qR.result,approvedAt:XV.receivedAt,approvalChannel:YR.channel,approver:YR.approver,againFrom:XR.fromRunId,againRequestedBy:XR.requestedBy},QV={attemptId:$.attemptId,runId:$.runId,stepName:$.stepName,worker:$.workerName,number:$.attemptNumber,brain:$.brainJson,task:$.task,agent:$.agent,operatorIntervened:$.operatorIntervened,parentModel:$.parentModel,startedAt:$.startedAt,outcome:$.outcomeJson,endedAt:$.endedAt,salvage:$.salvageJson,start:$.startJson,failureResolution:$.failureResolutionJson,reattachedAt:$.reattachedAt,comments:$.commentsJson,outOfMemory:$.outOfMemoryJson},$V=J`json_extract(${Q.stateJson}, '$._tag')`,eH=hM($V,[...AA]),tH=hM($V,[...MA]),nH=e=>Kw(IE)(SV(e)),rH=e=>{let t=O(`RunStoreQueries.eventRouteByDedup`)(function*(t){return yield*$B(yield*e.select(YV).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(VR.dedupKey,t)).execute())}),n=O(`RunStoreQueries.eventRouteByRun`)(function*(t){return yield*$B(yield*e.select(YV).from(Q).innerJoin(VR,Y(VR.eventId,Q.eventId)).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(Q.runId,t)).execute())}),r=()=>e.select(ZV).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).innerJoin(qR,Y(qR.runId,Q.runId)).leftJoin(YR,Y(YR.runId,Q.runId)).leftJoin(XV,Y(XV.eventId,YR.eventId)).leftJoin(XR,Y(XR.eventId,Q.eventId)),i=O(`RunStoreQueries.runRows`)(function*(e){return yield*nV(yield*r().where(Y(Q.runId,e)).execute())}),a=(...t)=>T(function*(){let n=yield*e.select({attemptId:$.attemptId,worker:$.workerName,repository:Q.repository,runId:$.runId,loop:Z.loopName,itemKey:Z.itemKey,number:$.attemptNumber,permissions:Z.permissions,outcome:J`coalesce(json_extract(${$.outcomeJson}, '$._tag'), '')`,salvage:$.salvageJson}).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(_M($.leftoversDiscardedAt),...t)).execute();return(yield*Hw(N(M({attemptId:sF,worker:EN,repository:Xk,runId:HA,loop:aA,itemKey:nI,number:cF,permissions:lA,outcome:j,salvage:I($P)})))(n)).map(({number:e,outcome:t,salvage:n,...r})=>({...r,ref:ZP(r.runId,e),succeeded:t===`Succeeded`,open:t===``,rejected:n?._tag===`Rejected`?b(n):y()}))}),o=O(`RunStoreQueries.salvageCandidates`)(function*(){return yield*a()}),s=O(`RunStoreQueries.salvageCandidate`)(function*(e){return yield*D({attemptId:e}),ea(yield*a(Y($.attemptId,e)))}),c=O(`RunStoreQueries.attemptRows`)(function*(t){return yield*iV(yield*e.select(QV).from($).where(Y($.runId,t)).orderBy($.attemptNumber).execute())}),l=O(`RunStoreQueries.snapshot`)(function*(e){let[t,r,a]=yield*Nh([i(e),c(e),n(e)]),o=t[0],s=a[0];return o===void 0||s===void 0?yield*new iz({runId:e}):new IB({event:EV(s),itemKey:s.itemKey,run:kV(o),step:MV(o),attempts:r.map(NV),resolvedFailureAttemptId:Sr(o.resolvedFailureAttemptId),closedAt:Sr(o.closedAt),approval:AV(o),runAgain:jV(o),repository:o.repository,revision:o.revision,task:o.task,agent:o.agent,parentModel:Sr(o.parentModel),permissions:s.permissions})}),u=O(`RunStoreQueries.summariesWithAttempts`)(function*(t){let n=da((yield*Ph(ua(t.map(({runId:e})=>e),100),t=>e.select(QV).from($).where(hM($.runId,t)).orderBy(AM($.runId),AM($.attemptNumber)).execute().pipe(E(iV)))).flat(),({runId:e})=>e);return t.map(e=>PV(e,n[e.runId]??[]))}),d=O(`RunStoreQueries.itemRunSummaries`)(function*(e){if(e.length===0)return[];let t=(yield*Ph(ua([...new Set(e)],100),e=>r().where(hM(Z.itemKey,e)).execute().pipe(E(nV)))).flat().sort(JV);return yield*u(t)}),f=O(`RunStoreQueries.runSummaries`)(function*(e){let[t,n]=yield*Nh([r().where(eH).orderBy(jM(Q.openedAt),jM(Q.runId)).execute().pipe(E(nV)),r().where(gM($V,[...AA])).orderBy(jM(Q.openedAt),jM(Q.runId)).limit(e).execute().pipe(E(nV))]),i=[...t,...n].sort(JV);return yield*u(i)}),p=O(`RunStoreQueries.runEvents`)(function*(t){return(yield*Ph(ua([...new Set(t)],100),t=>e.select({runId:Q.runId,eventId:VR.eventId,dedupKey:VR.dedupKey,payload:VR.payloadJson,receivedAt:VR.receivedAt}).from(Q).innerJoin(VR,Y(VR.eventId,Q.eventId)).where(hM(Q.runId,t)).execute().pipe(E(rV)))).flat().map(DV)}),m=O(`RunStoreQueries.closedRunSummaries`)(function*(e){let t=yield*r().where(gM($V,[...AA])).orderBy(jM(Q.closedAt),jM(Q.runId)).limit(e).execute().pipe(E(nV));return yield*u(t)}),h=O(`RunStoreQueries.closedRunSummariesSince`)(function*(e){let t=gM($V,[...AA]),n=yield*r().where(vr(e,{onNone:()=>t,onSome:e=>cM(t,fM(Q.closedAt,uV(e)))})).orderBy(jM(Q.closedAt),jM(Q.runId)).execute().pipe(E(nV));return yield*u(n)}),g=O(`RunStoreQueries.projectionRevision`)(function*(){return Sr((yield*sV(yield*e.select({revision:rz.revision}).from(rz).where(Y(rz.singleton,1)).limit(1).execute()))[0]?.revision)}),_=O(`RunStoreQueries.updateState`)(function*(t,n,r){let i=TA(n)?null:uV(r??(yield*B_));if((yield*e.update(Q).set({stateJson:dV(n),closedAt:i}).where(Y(Q.runId,t)).returning({runId:Q.runId}).execute()).length===0)return yield*new iz({runId:t})}),v=O(`RunStoreQueries.resolveFailure`)(function*(t,n,r){yield*D({runId:t,attemptId:n}),yield*e.update($).set({failureResolutionJson:_V(r)}).where(Y($.attemptId,n)).execute(),yield*e.update(Q).set({resolvedFailureAttemptId:n}).where(Y(Q.runId,t)).execute()}),ee=O(`RunStoreQueries.addAttempt`)(function*(t){yield*e.insert($).values({attemptId:t.id,runId:t.runId,stepName:t.stepName,workerName:t.worker,attemptNumber:t.number,brainJson:CV(t.brain),task:t.task,agent:t.agent,operatorIntervened:t.operatorIntervened,parentModel:C(t.parentModel),startedAt:uV(t.startedAt),outcomeJson:null,endedAt:null,salvageJson:null,startJson:vr(t.start,{onNone:()=>null,onSome:vV})}).execute()}),te=O(`RunStoreQueries.recordReattach`)(function*(t,n){yield*D({attemptId:t}),yield*e.update($).set({reattachedAt:uV(n)}).where(Y($.attemptId,t)).execute()}),ne=O(`RunStoreQueries.nextStart`)(function*(t){return Sr((yield*yV(yield*e.select({nextStart:Q.nextStartJson}).from(Q).where(Y(Q.runId,t)).execute()))[0]?.nextStart)}),re=O(`RunStoreQueries.setNextStart`)(function*(t,n){yield*e.update(Q).set({nextStartJson:vr(n,{onNone:()=>null,onSome:vV})}).where(Y(Q.runId,t)).execute()}),ie=O(`RunStoreQueries.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.update($).set({salvageJson:pV(n)}).where(Y($.attemptId,t)).execute(),n._tag===`Retained`&&S(n.pushFailure)&&(yield*e.update($).set({outcomeJson:fV(new qP({failure:n.pushFailure.value}))}).where(cM(Y($.attemptId,t),J`json_extract(${$.outcomeJson}, '$._tag') = 'Failed'`,J`json_extract(${$.outcomeJson}, '$.failure._tag') != 'GitHubPushFailure'`)).execute())}),ae=O(`RunStoreQueries.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.update($).set({commentsJson:mV(n)}).where(Y($.attemptId,t)).execute()}),oe=O(`RunStoreQueries.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=qi(((yield*gV(yield*e.select({outOfMemory:$.outOfMemoryJson}).from($).where(Y($.attemptId,t)).execute()))[0]?.outOfMemory??[]).filter(({container:e})=>e!==n.container),n);return yield*e.update($).set({outOfMemoryJson:hV(r)}).where(Y($.attemptId,t)).execute(),gF(r)}),se=O(`RunStoreQueries.closeAttempt`)(function*(t,n,r){yield*e.update($).set({outcomeJson:fV(n),endedAt:uV(r)}).where(cM(Y($.attemptId,t),_M($.outcomeJson))).execute()}),ce=O(`RunStoreQueries.amend`)(function*(t,n){yield*D({runId:t,agent:n.agent.name}),yield*e.update(Q).set({task:n.task,agentJson:nH(n.agent),parentModel:C(n.parentModel)}).where(Y(Q.runId,t)).execute()}),le=O(`RunStoreQueries.markIntervened`)(function*(t){yield*D({attemptId:t}),yield*e.update($).set({operatorIntervened:!0}).where(Y($.attemptId,t)).execute()}),ue=O(`RunStoreQueries.updateAttemptParentModel`)(function*(t,n){yield*e.update($).set({parentModel:n}).where(Y($.attemptId,t)).execute()}),de=O(`RunStoreQueries.updateStepResult`)(function*(t,n,r){yield*e.update(qR).set({result:bV(r)}).where(cM(Y(qR.runId,t),Y(qR.stepName,n))).execute()}),fe=O(`RunStoreQueries.approvalExists`)(function*(t){return(yield*e.$count(YR,Y(YR.runId,t)).execute())>0}),pe=O(`RunStoreQueries.recordApproval`)(function*(t,n,r){yield*e.insert(VR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:lV(n.payload),receivedAt:uV(n.receivedAt)}).onConflictDoNothing().execute(),yield*e.insert(YR).values({runId:t,eventId:n.id,channel:r.channel,approver:C(r.approver)}).execute()}),me=O(`RunStoreQueries.createRun`)(function*(t,n,r){let i=YL(Z,`candidate`),a=YL(Q,`candidate_run`),o=YL(ZR,`ignored`);yield*e.insert(ZR).select(e.select({eventId:i.eventId,reason:J`'superseded'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).leftJoin(o,Y(o.eventId,i.eventId)).where(cM(Y(i.loopName,t.loop),Y(i.itemKey,t.itemKey),oM(i.eventId,n),_M(a.runId),_M(o.eventId)))).onConflictDoNothing().execute(),yield*e.insert(Q).values({runId:r,eventId:n,loopName:t.loop,stateJson:dV(new mA),openedAt:uV(t.event.receivedAt),repository:t.repository,revision:t.revision,task:t.task,agentJson:nH(t.agent),parentModel:C(t.parentModel)}).onConflictDoNothing().execute(),yield*e.insert(qR).values({runId:r,stepName:t.step,result:null}).onConflictDoNothing().execute()}),he=O(`RunStoreQueries.runForEvent`)(function*(t){return yield*aV(yield*e.select({runId:Q.runId}).from(Q).where(Y(Q.eventId,t)).execute())}),ge=O(`RunStoreQueries.ignoredEvent`)(function*(t){return yield*oV(yield*e.select({reason:ZR.reason}).from(ZR).where(Y(ZR.eventId,t)).execute())}),_e=O(`RunStoreQueries.blockingRun`)(function*(t,n){return yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n),eH)).orderBy(jM(Q.openedAt)).limit(1).execute())}),ve=O(`RunStoreQueries.newestReopening`)(function*(t){return Or(Sr((yield*eV(yield*e.select({...YV,reopening:Z.reopening}).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).where(Y(Z.reopensEventId,t)).orderBy(jM(Z.reopening)).limit(1).execute()))[0]),e=>({submission:OV(e),reopening:e.reopening}))}),ye=O(`RunStoreQueries.reopenedEvent`)(function*(t){let n=YL(VR,`reopened_event`);return Sr((yield*tV(yield*e.select({eventId:n.eventId,dedupKey:n.dedupKey}).from(Z).innerJoin(n,Y(n.eventId,Z.reopensEventId)).where(Y(Z.eventId,t)).execute()))[0])}),be=O(`RunStoreQueries.recordRunAgain`)(function*(t,n){yield*e.insert(XR).values({eventId:t,fromRunId:n.from,requestedBy:C(n.requestedBy)}).execute()}),xe=O(`RunStoreQueries.recordTriggerEvent`)(function*(n,r=y()){yield*e.insert(VR).values({eventId:n.event.id,dedupKey:n.event.dedupKey,payloadJson:lV(n.event.payload),receivedAt:uV(n.event.receivedAt)}).onConflictDoNothing().execute();let i=(yield*t(n.event.dedupKey))[0];return i===void 0?(yield*e.insert(Z).values({eventId:n.event.id,itemKey:n.itemKey,loopName:n.loop,stepName:n.step,approval:n.approval,permissions:n.permissions,cycleLimit:C(n.cycleLimit),cycleGeneration:n.cycleGeneration,repository:n.repository,revision:n.revision,task:n.task,agentJson:nH(n.agent),parentModel:C(n.parentModel),reopensEventId:C(Or(r,({eventId:e})=>e)),reopening:vr(r,{onNone:()=>0,onSome:({reopening:e})=>e})}).execute(),n):OV(i)}),Se=O(`RunStoreQueries.nextQueued`)(function*(t){let r=(yield*n(t))[0];if(r===void 0)return y();let i=yield*KV(e).suppression(r.loop,r.itemKey);if(S(i))return yield*k(`Queued Events wait while a suppression keeps the Item`,{runId:t,suppressedBy:i.value.runId,loop:r.loop,itemKey:r.itemKey}),y();let a=yield*$B(yield*e.select(YV).from(VR).innerJoin(Z,Y(Z.eventId,VR.eventId)).leftJoin(Q,Y(Q.eventId,VR.eventId)).leftJoin(ZR,Y(ZR.eventId,VR.eventId)).where(cM(Y(Z.loopName,r.loop),Y(Z.itemKey,r.itemKey),VV(e).currentEvent,_M(Q.runId),_M(ZR.eventId))).orderBy(jM(VR.receivedAt)).execute());return Sr(a[0]).pipe(Or(e=>({submission:OV(e),eventIds:a.map(e=>e.eventId)})))}),Ce=O(`RunStoreQueries.runIdsToDrive`)(function*(){return(yield*aV(yield*e.select({runId:Q.runId}).from(Q).where(cM(eH,oM($V,`Waiting`))).execute())).map(({runId:e})=>e)}),we=O(`RunStoreQueries.pendingContinuations`)(function*(){let t=yield*e.selectDistinct({loop:Z.loopName,itemKey:Z.itemKey}).from(Z).leftJoin(Q,Y(Q.eventId,Z.eventId)).leftJoin(ZR,Y(ZR.eventId,Z.eventId)).leftJoin(UR,Y(UR.itemKey,Z.itemKey)).leftJoin(HR,cM(Y(HR.loopName,Z.loopName),Y(HR.itemKey,Z.itemKey))).where(cM(_M(Q.runId),_M(ZR.eventId),_M(UR.askJson),_M(HR.suppressedByRunId),VV(e).currentEvent)).execute();return(yield*Ph(yield*Hw(N(M({loop:aA,itemKey:nI})))(t),({loop:t,itemKey:n})=>T(function*(){return(yield*_e(t,n)).length>0?[]:yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n))).orderBy(jM(Q.openedAt),jM(Q.runId)).limit(1).execute())}))).flat().map(({runId:e})=>e)}),Te=O(`RunStoreQueries.revokeQueued`)(function*(t,n,r){let i=YL(Z,`candidate`),a=YL(Q,`candidate_run`);return(yield*e.insert(ZR).select(e.select({eventId:i.eventId,reason:J`'revoked'`.as(`reason`)}).from(i).leftJoin(a,Y(a.eventId,i.eventId)).where(cM(Y(i.loopName,t),Y(i.itemKey,n),hM(i.eventId,r),_M(a.runId)))).onConflictDoNothing().returning({eventId:ZR.eventId}).execute()).length}),Ee=O(`RunStoreQueries.revokeUnstarted`)(function*(t,n){let r=yield*aV(yield*e.select({runId:Q.runId}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n),tH)).execute()),i=e.select({eventId:Z.eventId}).from(Z).where(cM(Y(Z.loopName,t),Y(Z.itemKey,n)));return yield*Te(t,n,i),r});return{salvageCandidates:o,salvageCandidate:s,cycles:VV(e),loopItems:KV(e),...qV(e),addAttempt:ee,recordReattach:te,nextStart:ne,setNextStart:re,recordSalvage:ie,recordComments:ae,recordOutOfMemory:oe,amend:ce,markIntervened:le,approvalExists:fe,blockingRun:_e,closeAttempt:se,createRun:me,eventRouteByRun:n,ignoredEvent:ge,newestReopening:ve,nextQueued:Se,reopenedEvent:ye,recordRunAgain:be,pendingContinuations:we,recordTriggerEvent:xe,runIdsToDrive:Ce,recordApproval:pe,revision:g,revokeQueued:Te,revokeUnstarted:Ee,runSummaries:f,closedRunSummaries:m,closedRunSummariesSince:h,itemRunSummaries:d,runEvents:p,runForEvent:he,snapshot:l,updateStepResult:de,updateAttemptParentModel:ue,updateState:_,resolveFailure:v}},iH=T(function*(){let e=yield*iN,t=rH(e),n=O(`RunReader.inspect`)(e=>t.snapshot(e).pipe(TV(`read run`))),r=O(`RunReader.evidence`)(function*(t){yield*D({runId:t});let n=yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t);return new RB({snapshot:r,transcript:(yield*Ph(r.attempts,({id:e})=>n.transcript(new bB({attemptId:e})))).flat().sort((e,t)=>e.sequence-t.sequence)})})).pipe(TV(`read run evidence`));return yield*A(`Run evidence read`,{runId:t,attempts:n.snapshot.attempts.length,transcriptRows:n.transcript.length}),n}),i=O(`RunReader.list`)(e=>t.runSummaries(e.closedLimit).pipe(TV(`list runs`))),a=O(`RunReader.closed`)(e=>t.closedRunSummaries(e.limit).pipe(TV(`list closed runs`))),o=O(`RunReader.closedSince`)(e=>t.closedRunSummariesSince(e).pipe(TV(`list runs closed since a time`))),s=O(`RunReader.revision`)(()=>t.revision().pipe(TV(`read projection revision`)));return{inspect:n,evidence:r,list:i,closed:a,closedSince:o,forItems:O(`RunReader.forItems`)(e=>t.itemRunSummaries(e).pipe(TV(`read item run histories`))),events:O(`RunReader.events`)(e=>t.runEvents(e).pipe(TV(`read the events of runs`))),revision:s,transcript:O(`RunReader.transcript`)(e=>t.transcript(e).pipe(TV(`read attempt transcript`))),attemptsByWorker:O(`RunReader.attemptsByWorker`)(()=>RV(e).attemptCountsByWorker().pipe(TV(`count attempts by worker`))),sightings:O(`RunReader.sightings`)(e=>t.loopItems.sightings(e).pipe(TV(`read loop sightings`)))}}),aH=class e extends Rr()(`@usine/engine/RunReader`){static layer=Xf(e,iH)},oH=class extends V(`@usine/orchestrator/UsageCostView`)({usd:TP,estimate:lT}){},sH=class extends V(`@usine/orchestrator/SessionUsageView`)({attemptId:sF,session:hP,pool:kP,tokens:dP,cost:I(oH)}){},cH=class extends V(`@usine/orchestrator/PoolUsageView`)({pool:kP,tokens:dP,cost:I(oH)}){},lH=class extends V(`@usine/orchestrator/RunUsageView`)({tokens:dP,pools:N(cH),sessions:N(sH)}){},uH=class extends V(`@usine/orchestrator/TaskPoolUsageView`)({pool:kP,tokens:dP,cost:I(oH),unpriced:lT}){},dH=class extends V(`@usine/orchestrator/TaskUsageView`)({durationMillis:R.check(HT(0)),runningSince:N(j),unmeasured:R.check(HT(0)),tokens:dP,pools:N(uH),cost:I(oH)}){},fH=[`apiKeys`,`claudePlan`,`chatgptPlan`],pH=(e,t)=>vr(t,{onNone:()=>null,onSome:t=>new oH({usd:t,estimate:e!==`apiKeys`})}),mH=({session:e,costUsd:t,breakdown:n})=>S(t)||e.brain.harness!==`codex`?t:kr(n,t=>FB(e.brain.model,t)),hH=e=>{let t=new Map;for(let{attemptId:n,envelope:r}of e){let e=r.payload;if(e._tag!==`SessionEvent`||e.event._tag!==`SessionTokensUpdated`)continue;let i=`${n} ${e.event.session.id}`,a=t.get(i);a!==void 0&&a.report.totalTokens>=e.event.totalTokens||t.set(i,{attemptId:n,report:e.event})}let n=[...t.values()].map(e=>({...e,price:mH(e.report)})),r=n.map(({attemptId:e,report:t,price:n})=>{let r=jP(t.session);return new sH({attemptId:e,session:t.session,pool:r,tokens:t.totalTokens,cost:pH(r,n)})}),i=new Set(n.flatMap(({report:e,price:t})=>x(t)&&e.session.brain.harness===`codex`&&S(e.breakdown)?[e.session.brain.model]:[])),a=fH.flatMap(e=>{let t=r.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new cH({pool:e,tokens:dP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:pH(e,n.length===t.length?b(TP.make(n.reduce((e,t)=>e+t,0))):y())})]});return{view:new lH({tokens:dP.make(r.reduce((e,{tokens:t})=>e+t,0)),pools:a,sessions:r}),unknownModels:i}},gH=(e,t)=>{let n=0,r=0,i=[];for(let{attempts:t}of e)for(let{startedAt:e,endedAt:a,outcome:o}of t)o===null?i.push(e):a===null?r+=1:n+=Math.max(0,Date.parse(a)-Date.parse(e));let a=e.flatMap(({id:e})=>t.get(e)?.sessions??[]),o=fH.flatMap(e=>{let t=a.filter(t=>t.pool===e);if(t.length===0)return[];let n=t.flatMap(({cost:e})=>e===null?[]:[e.usd]);return[new uH({pool:e,tokens:dP.make(t.reduce((e,{tokens:t})=>e+t,0)),cost:pH(e,n.length===0?y():b(TP.make(n.reduce((e,t)=>e+t,0)))),unpriced:n.length<t.length})]}),s=o.flatMap(({cost:e})=>e===null?[]:[e]);return new dH({durationMillis:Math.round(n),runningSince:i,unmeasured:r,tokens:dP.make(a.reduce((e,{tokens:t})=>e+t,0)),pools:o,cost:s.length===0?null:new oH({usd:TP.make(s.reduce((e,{usd:t})=>e+t,0)),estimate:s.some(({estimate:e})=>e)})})},_H=T(function*(){let e=yield*aH,t=yield*zh(()=>new Map),n=yield*zh(()=>new Set),r=O(`RunUsageReader.attemptReports`)(function*(n){let r=t.get(n.id);if(r!==void 0)return{reports:r,read:!1};let i=yield*e.transcript(new CB({attemptId:n.id}));return S(n.outcome)&&t.set(n.id,i),{reports:i,read:!0}});return{read:O(`RunUsageReader.read`)(function*(e){yield*D({runId:e.run.id});let t=yield*Ph(e.attempts,r,{concurrency:4}),{view:i,unknownModels:a}=hH(t.flatMap(({reports:e})=>e));for(let t of a)n.has(t)||(n.add(t),yield*e_(`The OpenAI price table has no rates for a Codex model, so its sessions have no cost`,{model:t,runId:e.run.id}));return yield*A(`Read Run usage`,{runId:e.run.id,sessions:i.sessions.length,tokens:i.tokens,attemptsRead:t.filter(({read:e})=>e).length,attemptsCached:t.filter(({read:e})=>!e).length}),i})}});(class e extends Rr()(`@usine/orchestrator/RunUsageReader`){static layer=Xf(e,_H)});var vH=F(jA),yH=I(j),bH=class extends V(`@usine/orchestrator/EditAndRetry`)({task:lF,agent:fN}){},xH=class extends V(`@usine/orchestrator/SessionIntervention`)({attemptId:sF,target:WF.pipe(DT(w({_tag:`Parent`}))),action:BF}){};NE(`@usine/orchestrator/RosterAgentNotFoundError`)(`RosterAgentNotFoundError`,{agent:fN,message:j}),NE(`@usine/orchestrator/LoopNotFoundError`)(`LoopNotFoundError`,{loop:aA,message:j});var SH=class extends V(`@usine/orchestrator/ApprovalView`)({approvedAt:j,source:I(pI)}){},CH=class extends V(`@usine/orchestrator/RunView`)({id:HA,itemKey:nI,loop:aA,repository:Xk,agent:fN,agentBrain:dN,state:vH,loopPaused:lT,openedAt:j,closedAt:I(j),task:j,attempts:N(Kz),approval:I(SH),runAgain:I(Dz),resultMessage:yH,pullRequestUrl:yH,canApprove:lT,canRetry:lT,canResolveFailure:lT,canCancel:lT,canRunAgain:lT}){},wH=R.check(HT(0)),TH=R.check(HT(0)),EH=class extends V(`@usine/orchestrator/RunDurationView`)({endedMillis:wH,runningSince:I(j),unmeasured:TH}){},DH=class extends V(`@usine/orchestrator/UnconfirmedStopView`)({runId:HA,attemptNumber:cF,worker:EN}){},OH=class extends V(`@usine/orchestrator/RunDetailView`)({run:CH,agentDefinitionChanged:lT,eventDedupKey:j,eventPayload:IE,transcript:N(OB),sessionState:N(OB),earlierTranscript:N(kB),worker:I(EN).pipe(TT(w(null))),settledItemState:I(xz).pipe(TT(w(null))),duration:EH.pipe(TT(w(new EH({endedMillis:0,runningSince:null,unmeasured:0})))),usage:lH.pipe(TT(w(new lH({tokens:dP.make(0),pools:[],sessions:[]})))),unconfirmedStop:I(DH).pipe(TT(w(null))),machine:I(aB).pipe(TT(w(null)))}){},kH=z.pipe(L(`BoardLaneId`)),AH=F([`authored`,`proposed`,`fallback`]),jH=class extends V(`@usine/orchestrator/BoardItemLink`)({itemKey:nI,kind:F([`issue`,`pr`]),number:rI,title:j,url:z,state:bz}){},MH=class extends V(`@usine/orchestrator/BoardPullRequestView`)({number:rI,url:z,state:F([`pr-open`,`pr-merged`])}){},NH=class extends V(`@usine/orchestrator/BoardTaskView`)({...jH.fields,labels:N(fz),items:N(jH).check(qT()),pullRequest:I(MH),runs:N(CH),run:I(CH),needsYou:lT,conflicting:lT,loops:N(aA),usage:dH}){},PH={id:kH,name:yz,sources:N(Tz),origin:AH,items:N(NH)},FH=class extends H(`@usine/orchestrator/WritableBoardLaneView`)(`WritableBoardLane`,{...PH,origin:rT(`authored`),labels:N(fz).check(qT())}){},IH=class extends H(`@usine/orchestrator/ReadOnlyBoardLaneView`)(`ReadOnlyBoardLane`,PH){},LH=P([FH,IH]),RH=class extends NE(`@usine/orchestrator/BoardProjectionError`)(`BoardProjectionError`,{repository:Xk,itemKey:nI,message:z}){},zH=class extends V(`@usine/orchestrator/BoardView`)({lanes:N(LH),failures:N(RH)}){},BH=class extends V(`@usine/orchestrator/LabelView`)({name:fz,color:I(j),description:I(j)}){};V(`@usine/orchestrator/BoardMove`)({repository:Xk,item:rI,toLane:kH});var VH=class extends NE(`@usine/orchestrator/BoardProjectNotFoundError`)(`BoardProjectNotFoundError`,{repository:Xk}){},HH=class extends NE(`@usine/orchestrator/BoardItemNotFoundError`)(`BoardItemNotFoundError`,{repository:Xk,item:rI}){};NE(`@usine/orchestrator/BoardLaneNotFoundError`)(`BoardLaneNotFoundError`,{repository:Xk,lane:kH}),NE(`@usine/orchestrator/BoardLaneReadOnlyError`)(`BoardLaneReadOnlyError`,{repository:Xk,lane:kH});var UH=j.check(PT(/^(?:[A-Za-z_][A-Za-z0-9_.]*|list<[A-Za-z_][A-Za-z0-9_.]*>|map<[A-Za-z_][A-Za-z0-9_.]*,[A-Za-z_][A-Za-z0-9_.]*>)$/u,{message:`Expected a CEL type reference`})).pipe(L(`CelTypeReference`)),WH=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected a CEL identifier`})),GH=j.check(PT(/^[A-Za-z_][A-Za-z0-9_.]*$/u,{message:`Expected a CEL object-type name`})),KH=e=>NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:e}),qH=class extends V(`@usine/expression/ObjectField`)({name:WH,type:UH,nullable:lT.pipe(TT(w(!1)))}){},JH=class extends V(`@usine/expression/ObjectType`)({name:GH,fields:N(qH).check(KH(`Expected unique CEL object-field names`))}){},YH=class extends V(`@usine/expression/Variable`)({name:WH,type:UH}){},XH=class extends V(`@usine/expression/Environment`)({types:N(JH).check(KH(`Expected unique CEL object-type names`)),variables:N(YH).check(KH(`Expected unique CEL variable names`))}){},ZH=j.check(PT(/\S/u,{message:`Expected a non-blank CEL expression`})).pipe(L(`ExpressionSource`)),QH=R.check(HT(0)),$H=F([`check_failed`,`parse_error`,`type_error`,`unexpected_result_type`]);P([class extends NE(`@usine/expression/ExpressionCheckError`)(`ExpressionCheckError`,{source:ZH,code:$H,message:z,position:B(QH)}){},class extends NE(`@usine/expression/ExpressionEvaluationError`)(`ExpressionEvaluationError`,{source:ZH,message:z}){}]),P([j,cT,uT,lT,oT]);var eU=class extends Rr()(`@usine/expression/ExpressionEngine`){},tU=z.pipe(L(`InstancePath`)),nU=F([`expression`,`frontmatter`,`read`,`reference`,`schema`,`yaml`]),rU=class e extends NE(`@usine/config/ConfigFileError`)(`ConfigFileError`,{file:tU,stage:nU,expression:xE(ZH),message:z,details:$w(N(M({path:N(P([j,cT])),message:j})))}){static fromSchema(t,n){let r=Hy()(n.issue).issues.map(({path:e,message:t})=>({path:(e??[]).map(e=>Ok(e).pipe(Ak(jk,e=>e),Ak(Mk,e=>e),Ak(Nk,String),Pk(({key:e})=>String(e)))),message:t}));return new e({file:t,stage:`schema`,expression:y(),message:Yy()(n.issue),details:r})}};P([rU,class extends NE(`@usine/config/FactoryConfigError`)(`FactoryConfigError`,{file:tU,stage:nU,message:z}){}]);var iU=j.check(PT(/\S/u,{message:`Expected a non-blank repository label`})),aU=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})),oU=class extends V(`@usine/engine/RepositoryLabel`)({name:iU,color:yE(aU),description:yE(j)}){},sU=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),cU=N(oU).check(sU),lU=class extends V(`@usine/engine/RepositoryLabelProjection`)({repository:Xk,labels:cU}){},uU=N(j),dU=Vw(uU),fU=M({repository:Xk,labels:P([lU.fields.labels,uU])}),pU=e=>dU(e)?e.map(e=>new oU({name:e,color:y(),description:y()})):e,mU=Hw(N(fU)),hU=Xw(lU.fields.labels),gU=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),_U=T(function*(){let e=yield*iN;return{get:O(`RepositoryLabelProjectionReader.get`)(function*(t){let n=(yield*mU(yield*e.select({repository:ez.repository,labels:ez.labelsJson}).from(ez).where(Y(ez.repository,t)).limit(1).execute(),{onExcessProperty:`error`}))[0];return n===void 0?y():b(new lU({repository:n.repository,labels:pU(n.labels)}))},gU(`read repository label projection`))}}),vU=T(function*(){let e=yield*iN;return{replace:O(`RepositoryLabelProjectionWriter.replace`)(function*(t){yield*D({repository:t.repository});let n=hU(t.labels);return(yield*e.insert(ez).values({repository:t.repository,labelsJson:n}).onConflictDoUpdate({target:ez.repository,set:{labelsJson:n},setWhere:oM(ez.labelsJson,n)}).returning({repository:ez.repository}).execute()).length===0?(yield*A(`Repository label projection already matched GitHub`,{repository:t.repository,labels:t.labels.length}),!1):(yield*A(`Repository label projection updated from trigger polling`,{repository:t.repository,labels:t.labels.length}),!0)},gU(`write repository label projection`))}}),yU=class e extends Rr()(`@usine/engine/RepositoryLabelProjectionReader`){static layer=Xf(e,_U)},bU=class e extends Rr()(`@usine/engine/RepositoryLabelProjectionWriter`){static layer=Xf(e,vU)},xU=`~effect/http/HttpBody`,SU=e=>pe(e,xU),CU=class{[xU];constructor(){this[xU]=xU}[gt](){return this.toJSON()}toString(){return ot(this,{ignoreToString:!0})}},wU=new class extends CU{_tag=`Empty`;toJSON(){return{_id:`effect/HttpBody`,_tag:`Empty`}}},TU=class extends CU{_tag=`Uint8Array`;contentType;contentLength;text;_body;constructor(e,t,n,r){super(),this._body=e,this.text=r,this.contentType=t,this.contentLength=n}get body(){return this._body??=kU(this.text)}toJSON(){return{_id:`effect/HttpBody`,_tag:`Uint8Array`,body:this.contentType.startsWith(`text/`)||this.contentType.endsWith(`json`)?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}},EU=(e,t)=>new TU(e,t??`application/octet-stream`,e.length),DU=new TextEncoder,OU=globalThis.Buffer,kU=OU===void 0?e=>DU.encode(e):e=>OU.from(e,`utf8`),AU=(e,t)=>{if(typeof e!=`string`&&(e=e===void 0?``:String(e)),OU!==void 0)return new TU(void 0,t??`text/plain`,OU.byteLength(e,`utf8`),e);let n=DU.encode(e);return new TU(n,t??`text/plain`,n.length,e)},jU=(e,t)=>AU(JSON.stringify(e),t??`application/json`),MU=(e,t)=>AU(Xv(Vv(e)),t??`application/x-www-form-urlencoded`),NU=class extends CU{_tag=`FormData`;contentType=void 0;contentLength=void 0;formData;constructor(e){super(),this.formData=e}toJSON(){return{_id:`effect/HttpBody`,_tag:`FormData`,formData:this.formData}}},PU=e=>new NU(e),FU=class extends CU{_tag=`Stream`;stream;contentType;contentLength;constructor(e,t,n){super(),this.stream=e,this.contentType=t,this.contentLength=n}toJSON(){return{_id:`effect/HttpBody`,_tag:`Stream`,contentType:this.contentType,contentLength:this.contentLength}}},IU=(e,t,n)=>new FU(e,t??`application/octet-stream`,n),LU=`~effect/http/HttpClientError`,RU=class extends wo(`HttpClientError`){constructor(e){`cause`in e.reason?super({...e,cause:e.reason.cause}):super(e)}[LU]=LU;get request(){return this.reason.request}get response(){return`response`in this.reason?this.reason.response:void 0}get message(){return this.reason.message}},zU=e=>e.endsWith(`Error`)?e.slice(0,-5):e,BU=(e,t,n)=>t?`${e}: ${t} (${n})`:`${e} error (${n})`,VU=e=>`${e.method} ${ey(e.url)}`,HU=class extends wo(`TransportError`){get methodAndUrl(){return VU(this.request)}get message(){return BU(zU(this._tag),this.description,this.methodAndUrl)}},UU=class extends wo(`InvalidUrlError`){get methodAndUrl(){return VU(this.request)}get message(){return BU(zU(this._tag),this.description,this.methodAndUrl)}},WU=class extends wo(`StatusCodeError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},GU=class extends wo(`DecodeError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},KU=class extends wo(`EmptyBodyError`){get methodAndUrl(){return VU(this.request)}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return BU(zU(this._tag),this.description,e)}},qU=e=>e!==`GET`&&e!==`HEAD`&&e!==`OPTIONS`&&e!==`TRACE`,JU=[[`GET`,`get`],[`POST`,`post`],[`PUT`,`put`],[`DELETE`,`del`],[`PATCH`,`patch`],[`HEAD`,`head`],[`OPTIONS`,`options`],[`TRACE`,`trace`],[`QUERY`,`query`]],YU=(e,t)=>t._tag===`Empty`||t._tag===`FormData`?Mv(Mv(e,`content-type`),`content-length`):(e=t.contentType===void 0?Mv(e,`content-type`):kv(e,`content-type`,t.contentType),t.contentLength===void 0?Mv(e,`content-length`):kv(e,`content-length`,t.contentLength.toString())),XU=class extends wo(`UrlError`){},ZU=(e,t,n)=>Ti({try:()=>{let r=new URL(e,QU());for(let e=0;e<t.params.length;e++){let[n,i]=t.params[e];i!==void 0&&r.searchParams.append(n,Iv(i))}return n!==void 0&&(r.hash=n),r},catch:e=>new XU({cause:e})}),QU=()=>{if(`location`in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0){let e=location.origin+location.pathname;try{return new URL(e).href}catch{return}}},$U=`~effect/http/HttpClientRequest`,eW={[$U]:$U,...yt,toJSON(){return{_id:`HttpClientRequest`,method:this.method,url:ey(this.url),urlParams:this.urlParams,hash:this.hash,headers:tt(this.headers),body:this.body.toJSON()}},pipe(){return e(this,arguments)}};function tW(e,t,n,r,i,a){let o=Object.create(eW);return o.method=e,o.url=t,o.urlParams=n,o.hash=r,o.headers=i,o.body=a,o}var nW=tW(`GET`,``,Kv,y(),Ev,wU),rW=e=>(t,n)=>oW(nW,{method:e,url:t,...n??void 0}),iW=rW(`GET`),aW=rW(`POST`),oW=r(2,(e,t)=>{let n=e;return t.method&&(n=sW(n,t.method)),t.url&&(n=pW(n,t.url)),t.headers&&(n=lW(n,t.headers)),t.urlParams&&(n=gW(n,t.urlParams)),t.hash&&(n=vW(n,t.hash)),t.body&&(n=yW(n,t.body)),t.accept&&(n=uW(n,t.accept)),t.acceptJson&&(n=dW(n)),n}),sW=r(2,(e,t)=>tW(t,e.url,e.urlParams,e.hash,e.headers,e.body)),cW=r(3,(e,t,n)=>tW(e.method,e.url,e.urlParams,e.hash,kv(e.headers,t,n),e.body)),lW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,Av(e.headers,t),e.body)),uW=r(2,(e,t)=>cW(e,`Accept`,t)),dW=uW(`application/json`),fW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,kv(kv(e.headers,`connection`,`Upgrade`),`upgrade`,t),e.body)),pW=r(2,(e,t)=>{if(typeof t==`string`)return tW(e.method,t,e.urlParams,e.hash,e.headers,e.body);let n=new URL(t.toString()),r=Vv(n.searchParams),i=Sr(n.hash===``?void 0:n.hash.slice(1));return n.search=``,n.hash=``,tW(e.method,n.toString(),r,i,e.headers,e.body)}),mW=r(2,(e,t)=>t===``?e:tW(e.method,hW(t,e.url),e.urlParams,e.hash,e.headers,e.body)),hW=(e,t)=>{let n=e.endsWith(`/`),r=t.startsWith(`/`);return n&&r?e+t.slice(1):!n&&!r?e+`/`+t:e+t},gW=r(2,(e,t)=>tW(e.method,e.url,Jv(e.urlParams,t),e.hash,e.headers,e.body)),_W=r(2,(e,t)=>tW(e.method,e.url,Yv(e.urlParams,t),e.hash,e.headers,e.body)),vW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,b(t),e.headers,e.body)),yW=r(2,(e,t)=>tW(e.method,e.url,e.urlParams,e.hash,YU(e.headers,t),t)),bW=r(2,(e,t)=>yW(e,jU(t))),xW=r(2,(e,t)=>yW(e,PU(t)));function SW(e){let t=ZU(e.url,e.urlParams,Tr(e.hash));return Oi(t)?b(t.success):y()}var CW=`~effect/http/HttpIncomingMessage`,wW=(e,t)=>{let n=Uw(PE(e)),r=t?.reviver===void 0?void 0:Uw(aE(PE(e),t));return e=>r===void 0?E(e.json,e=>n(e,t)):E(e.text,i=>i===``?E(e.json,e=>n(e,t)):r(i,t))},TW=(e,t)=>({...t,headers:tt(e.headers),remoteAddress:e.remoteAddress}),EW=`~effect/http/HttpClientResponse/WebSource`,DW=e=>e[EW]?.(),OW=`~effect/http/HttpClientResponse`,kW=(e,t)=>new AW(e,t),AW=class extends bt{[CW];[OW];request;source;constructor(e,t){super(),this.request=e,this.source=t,this[CW]=CW,this[OW]=OW}toJSON(){return TW(this,{_id:`HttpClientResponse`,request:this.request.toJSON(),status:this.status})}get status(){return this.source.status}get url(){if(this.source.url)return this.source.url.split(`#`)[0];let e=SW(this.request);return x(e)?``:(e.value.hash=``,e.value.href)}get headers(){return Dv(this.source.headers)}cachedCookies;get cookies(){return this.cachedCookies?this.cachedCookies:this.cachedCookies=lv(this.source.headers.getSetCookie?.()??[])}get remoteAddress(){return y()}[EW](){return this.source}get stream(){return this.source.body?PO({evaluate:()=>this.source.body,onError:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}):MO(new RU({reason:new KU({request:this.request,response:this,description:`can not create stream from empty body`})}))}get json(){return E(this.text,e=>qh({try:()=>e===``?null:JSON.parse(e),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}))}textBody;get text(){return this.textBody??=ng(this.arrayBuffer,e=>new TextDecoder().decode(e))}get urlParamsBody(){return E(this.text,e=>qh({try:()=>Vv(new URLSearchParams(e)),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}))}formDataBody;get formData(){return this.formDataBody??=Ih({try:()=>this.source.formData(),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}).pipe(Ig,Zg)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody||=Ih({try:()=>this.source.arrayBuffer(),catch:e=>new RU({reason:new GU({request:this.request,response:this,cause:e})})}).pipe(Ig,Zg),this.arrayBufferBody}get upgrade(){return Uh(new RU({reason:new WU({request:this.request,response:this,description:`fetch cannot hand over the connection of an HTTP upgrade`})}))}pipe(){return e(this,arguments)}},jW=e=>Ov({b3:`${e.traceId}-${e.spanId}-${e.sampled?`1`:`0`}${vr(e.parent,{onNone:()=>``,onSome:e=>`-${e.spanId}`})}`,traceparent:`00-${e.traceId.padStart(32,`0`)}-${e.spanId}-${e.sampled?`01`:`00`}`}),MW={"http:":80,"https:":443,"ws:":80,"wss:":443},NW=(e,t,n)=>{let r=ey(t.search,n).slice(1);if(e.attribute(`url.full`,ey(t.href,n)),e.attribute(`url.path`,t.pathname),r!==``&&e.attribute(`url.query`,r),e.attribute(`url.scheme`,t.protocol.slice(0,-1)),t.hostname!==``){e.attribute(`server.address`,t.hostname.startsWith(`[`)?t.hostname.slice(1,-1):t.hostname);let n=t.port===``?MW[t.protocol]:Number(t.port);n!==void 0&&e.attribute(`server.port`,n)}},PW=(e,t)=>{let n=e.params.filter(([,e])=>typeof e!=`string`).map(([e])=>e);return n.length===0?t:[...t,...new URLSearchParams(n.map(e=>[e,``])).keys()]},FW=(e,t,n,r,i)=>{for(let a in n)r(a,t)&&e.attribute(`http.${t}.header.${a}`,Pv(a,i)?`<redacted>`:n[a])},IW=`~effect/http/HttpClient`,LW=Rr(`effect/HttpClient`),RW=r(2,(e,t)=>zW(n=>t(e.postprocess(n)),e.preprocess)),zW=(e,t)=>{let n=Object.create(BW);return n.preprocess=t,n.postprocess=e,n.execute=function(n){return e(t(n))},n},BW={[IW]:IW,pipe(){return e(this,arguments)},...yt,toJSON(){return{_id:`effect/HttpClient`}},...Object.fromEntries(JU.map(([e,t])=>[t,function(t,n){return this.execute(rW(e)(t,n))}]))},VW=e=>zW(t=>E(t,t=>Jh(n=>{let r=XW.get(t),i=r??new AbortController,a=ZU(t.url,t.urlParams,Tr(t.hash));if(Di(a))return Uh(new RU({reason:new UU({request:t,cause:a.failure})}));let o=a.success;if(n.getRef(Bo)||n.getRef(WW)(t)){let a=e(t,o,i.signal,n);return r?a:Bg(e=>Sg(e(a),{onSuccess(e){return YW.register(e,i),w(new ZW(e,i))},onFailure(e){return nf(e)&&i.abort(),Wh(e)}}))}return Ug(n.getRef(qW)(t),{kind:`client`},a=>{a.attribute(`http.request.method`,t.method);let s=n.getRef(Fv);NW(a,o,PW(t.urlParams,n.getRef(cy)));let c=n.getRef(GW);return FW(a,`request`,t.headers,c,s),t=n.getRef(KW)?lW(t,jW(a)):t,Bg(l=>l(e(t,o,i.signal,n)).pipe(Gg(a,{captureStackTrace:!1}),Sg({onSuccess:e=>(a.attribute(`http.response.status_code`,e.status),FW(a,`response`,e.headers,c,s),e.status>=400&&e.status<600&&(a.attribute(`error.type`,String(e.status)),HW(n,a,t,e)),r?w(e):(YW.register(e,i),w(new ZW(e,i)))),onFailure(e){return!r&&nf(e)&&i.abort(),Wh(e)}})))})})),w),HW=(e,t,n,r)=>{let i=St();Ct(0);let a;try{a=df(new RU({reason:new WU({request:n,response:r})}))}finally{Ct(i)}t.end(e.getRef(Ef)?e.getRef(ap).currentTimeNanosUnsafe():BigInt(0),a)},UW=r(2,(e,t)=>zW(e.postprocess,n=>ng(e.preprocess(n),t))),WW=vi(`effect/http/HttpClient/TracerDisabledWhen`,{defaultValue:()=>s}),GW=vi(`effect/http/HttpClient/TracerHeaderFilter`,{defaultValue:()=>s}),KW=vi(`effect/http/HttpClient/TracerPropagationEnabled`,{defaultValue:o}),qW=vi(`effect/http/HttpClient/SpanNameGenerator`,{defaultValue:()=>e=>e.method}),JW=e=>Xf(LW)(wg(t=>ng(e,e=>RW(e,Og(e=>hi(t,e)))))),YW=(()=>{if(`FinalizationRegistry`in globalThis&&globalThis.FinalizationRegistry){let e=new FinalizationRegistry(e=>{try{e.abort()}catch{}});return{register(t,n){e.register(t,n,t)},unregister(t){e.unregister(t)}}}let e=new WeakMap;return{register(t,n){e.set(t,setTimeout(()=>n.abort(),5e3))},unregister(t){let n=e.get(t);n!==void 0&&(clearTimeout(n),e.delete(t))}}})(),XW=new WeakMap,ZW=class{original;controller;constructor(e,t){this.original=e,this.controller=t}[OW]=OW;[CW]=CW;applyInterrupt(e){return Rh(()=>(YW.unregister(this.original),Rg(e,()=>zh(()=>{this.controller.abort()}))))}get request(){return this.original.request}get url(){return this.original.url}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get upgrade(){return this.applyInterrupt(this.original.upgrade)}[EW](){let e=DW(this.original);return e!==void 0&&YW.unregister(this.original),e}get stream(){return AO(()=>(YW.unregister(this.original),WO(this.original.stream,zh(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[gt](){return this.original[gt]()}pipe(){return e(this,arguments)}},QW=vi(`effect/http/FetchHttpClient/Fetch`,{defaultValue:()=>globalThis.fetch}),$W=class extends Rr()(`effect/http/FetchHttpClient/RequestInit`){},eG=JW(w(VW((e,t,n,r)=>{if(e.headers.upgrade!==void 0)return Uh(new RU({reason:new HU({request:e,description:`fetch cannot send an HTTP upgrade request`})}));let i=r.getRef(QW),a=si(r.context,$W)??{},o=a.headers?jv(Dv(a.headers),e.headers):e.headers;o[`content-length`]&&(o=Mv(o,`content-length`));let s,c=zh(()=>s?.abort()),l=r=>ng(Ih({try:()=>i(t,{...a,method:e.method,headers:o,body:r,duplex:typeof ReadableStream<`u`&&r instanceof ReadableStream?`half`:void 0,signal:s?AbortSignal.any([n,s.signal]):n}),catch:t=>new RU({reason:new HU({request:e,cause:t})})}),t=>{let n=kW(e,t);return s?(t.body===null&&s.abort(),Object.create(n,{...Object.fromEntries([`arrayBuffer`,`text`,`json`,`formData`,`urlParamsBody`].map(e=>[e,{get:()=>Mg(n[e],c)}])),stream:{get:()=>WO(n.stream,c)}})):n}).pipe(Ng(()=>c));switch(e.body._tag){case`Raw`:case`Uint8Array`:return l(e.body.body);case`FormData`:return l(e.body.formData);case`Stream`:{s=new AbortController;let t=AbortSignal.any([n,s.signal]),r=Vh(e=>{let n=()=>e(Lg);if(t.aborted)n();else return t.addEventListener(`abort`,n,{once:!0}),zh(()=>t.removeEventListener(`abort`,n))});return E(JO(UO(e.body.stream,r)),l)}}return l(void 0)})));function tG(e,t){let n=1;for(;t<e.length;)if(t++,e[t]===`\\`)t++;else if(e[t]===`)`?n--:e[t]===`(`&&n++,!n)return t;throw TypeError(`Invalid regexp expression in "`+e+`"`)}var nG=Rr(`effect/http/HttpEffect/CurrentRequestState`),rG=e=>Jh(t=>{let n=si(t.context,nG);return n!==void 0&&(n.loggerDisabled=!0),e}),iG=Rr(`effect/http/HttpRouter`),aG=e=>e.endsWith(`/`)?e.slice(0,-1):e,oG=r(2,(e,t)=>(t=aG(t),e===`*`?`${t}/*`:e===`/`?t:t+e)),sG=`~effect/http/HttpRouter/Middleware`,cG=function(){return arguments.length===0?lG:lG(arguments[0],arguments[1])},lG=(e,t)=>t?.global?$f(T(function*(){let t=yield*iG,n=Mh(e)?yield*e:e;yield*t.addGlobalMiddleware(n)})):new fG(Mh(e)?Qf(ng(e,e=>Zr(new Map([[dG,e]])))):Yf(Zr(new Map([[dG,e]])))),uG=0,dG=`effect/http/HttpRouter/MiddlewareFn`,fG=class e{[sG]={};layerFn;dependencies;constructor(e,t){this.layerFn=e,this.dependencies=t;let n=`effect/http/HttpRouter/Middleware-${++uG}`;this.layer=Qf(T({self:this},function*(){let e=yield*Cg(),t=[ci(e,dG)];if(this.dependencies){let n=yield*Gf,r=ui(e,Df),i=yield*Kf(this.dependencies,n,r);t.push(...mG(i))}return Zr(new Map([[n,t]]))})).pipe(rp(this.layerFn))}layer;combine(t){return new e(this.layerFn,this.dependencies?ip(this.dependencies,t.layer):t.layer)}},pG=new WeakMap,mG=e=>{let t=pG.get(e);if(t)return t;let n=pa(),r=0;for(let[t,i]of e.mapUnsafe)t.startsWith(`effect/http/HttpRouter/Middleware-`)&&(n.push(i),i.length>r&&(r=i.length));if(n.length===0)t=[];else{let e=new Set;for(let t=r-1;t>=0;t--)for(let r of n)t<r.length&&e.add(r[t]);t=Wi(e).reverse()}return pG.set(e,t),t};cG(rG).layer;var hG={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,OK:200,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511},gG=e=>hG[e],_G=R.check(HT(1)).pipe(L(`GitHubAppId`)),vG=CE(z.check(PT(/^-----BEGIN (?:RSA )?PRIVATE KEY-----[\s\S]+-----END (?:RSA )?PRIVATE KEY-----\s*$/u,{message:`Expected a PEM-encoded RSA private key`})).pipe(L(`GitHubAppPrivateKey`)),{disallowEncode:!0});V(`@usine/github/AppCredentials`)({appId:_G,privateKey:vG});var yG=class extends Rr()(`@usine/github/GitHubCredentials`){},bG=class extends NE(`@usine/github/AppAuthenticationError`)(`AppAuthenticationError`,{message:z}){},xG=new TextEncoder,SG=new Uint8Array([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]),CG=(...e)=>{let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t},wG=e=>{if(e<128)return new Uint8Array([e]);let t=[];for(let n=e;n>0;n>>>=8)t.unshift(n&255);return new Uint8Array([128|t.length,...t])},TG=(e,t)=>CG(new Uint8Array([e]),wG(t.length),t),EG=e=>TG(48,CG(new Uint8Array([2,1,0]),SG,TG(4,e))),DG=e=>{let t=e.includes(`-----BEGIN RSA PRIVATE KEY-----`),n=e.replace(/-----BEGIN (?:RSA )?PRIVATE KEY-----/gu,``).replace(/-----END (?:RSA )?PRIVATE KEY-----/gu,``).replace(/\s/gu,``),r=atob(n),i=Uint8Array.from(r,e=>e.charCodeAt(0));return t?EG(i):i},OG=e=>{let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/=/gu,``).replace(/\+/gu,`-`).replace(/\//gu,`_`)},kG=e=>OG(xG.encode(JSON.stringify(e))),AG=e=>{let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t},jG=O(`AppJwt.import`)(function*(e){let t=yield*Ih({try:async()=>crypto.subtle.importKey(`pkcs8`,AG(DG(bv(e.privateKey))),{name:`RSASSA-PKCS1-v1_5`,hash:`SHA-256`},!1,[`sign`]),catch:()=>new bG({message:`Could not import the GitHub App private key as an RSA private key`})});return O(`AppJwt.sign`)(function*(){let n=Math.floor((yield*op)/1e3),r=`${kG({alg:`RS256`,typ:`JWT`})}.${kG({iat:n-60,exp:n+540,iss:e.appId})}`,i=yield*Fh(()=>crypto.subtle.sign(`RSASSA-PKCS1-v1_5`,t,AG(xG.encode(r))));return vv(`${r}.${OG(new Uint8Array(i))}`)})}),MG=R.check(HT(1)),NG=MG.pipe(L(`GitHubInstallationId`)),PG=MG.pipe(L(`GitHubRepositoryId`)),FG=z.pipe(L(`GitHubAppSlug`)),IG=class extends V(`@usine/github/Installation`)({id:NG,accountLogin:z,appSlug:FG}){},LG=class extends H(`@usine/github/TokenScope/InstallationWide`)(`InstallationWide`,{}){},RG=class extends H(`@usine/github/TokenScope/SingleRepository`)(`SingleRepository`,{repository:Xk,repositoryId:PG,permissions:lA}){},zG=P([LG,RG]),BG=class extends V(`@usine/github/InstallationToken`)({value:SE(z,{disallowJsonEncode:!0}),expiresAt:_E,scope:zG}){},VG=F([`missing`,`multiple`,`suspended`]),HG=class extends NE(`@usine/github/InstallationDiscoveryError`)(`InstallationDiscoveryError`,{reason:VG,message:z}){},UG={checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},WG={write:{checks:`read`,contents:`write`,issues:`write`,metadata:`read`,pull_requests:`write`},read:{checks:`read`,contents:`read`,issues:`write`,metadata:`read`,pull_requests:`write`}},GG=(e,t)=>e===t||t===`read`&&e===`write`,KG=e=>Object.entries(UG).flatMap(([t,n])=>GG(e[t],n)?[]:[`${t}:${n}`]),qG=class extends H(`@usine/github/ProjectAccess/CoveredProject`)(`CoveredProject`,{installationId:NG,repository:Xk,repositoryId:PG}){},JG=class extends NE(`@usine/github/ProjectNotInstalledError`)(`ProjectNotInstalledError`,{repository:Xk,message:z}){};P([qG,JG]);var YG=(e,t,n)=>{let r=new Map(n.map(e=>[e.name.toLowerCase(),e]));return t.map(t=>{let n=r.get(t.toLowerCase());return n===void 0?new JG({repository:t,message:`The GitHub App installation has no access to "${t}"`}):new qG({installationId:e.id,repository:t,repositoryId:n.id})})},XG=class extends NE(`@usine/github/AppPermissionError`)(`AppPermissionError`,{missing:N(z).check(qT()),message:z}){},ZG=F([`create-repository-label`,`discover-installation`,`fetch-base-ref-head`,`fetch-item-labels`,`fetch-issue-snapshot`,`fetch-item-timeline`,`fetch-pull-request-snapshot`,`find-missing-issues`,`list-installation-repositories`,`list-repository-labels`,`mint-installation-token`,`mint-worker-token`,`poll-repository-changes`,`read-bot-account`,`update-item-labels`]),QG=class extends NE(`@usine/github/GitHubApiError`)(`GitHubApiError`,{operation:ZG,status:B(R),message:z}){},$G=class extends NE(`@usine/github/GitHubRateLimitError`)(`GitHubRateLimitError`,{operation:ZG,retryAt:_E,message:z}){},eK=class extends NE(`@usine/github/InvalidGitHubResponseError`)(`InvalidGitHubResponseError`,{operation:ZG,message:z,detail:z}){},tK=class extends NE(`@usine/github/GitHubItemNotFoundError`)(`GitHubItemNotFoundError`,{operation:ZG,item:R.check(HT(1)),message:z}){};P([HG,XG,QG,$G,eK]);var nK=`https://api.github.com`,rK=`2026-03-10`,iK=e=>lW({accept:`application/vnd.github+json`,authorization:`Bearer ${bv(e)}`,"user-agent":`usine`,"x-github-api-version":rK}),aK=(e,t)=>new QG({operation:e,status:t.response===void 0?y():b(t.response.status),message:t.response===void 0?`Could not send the request to GitHub`:`GitHub returned HTTP status ${t.response.status}`}),oK=Ww(M({message:z})),sK=(e,t)=>t.json.pipe(ng(t=>vr(oK(t),{onNone:()=>e,onSome:({message:t})=>new QG({operation:e.operation,status:e.status,message:`${e.message}: ${t}`})})),og(t=>A(`GitHub's error response has no JSON body to read a reason from`,{operation:e.operation,message:t.message}).pipe(rg(e)))),cK=(e,t)=>new eK({operation:e,message:`GitHub returned a response in an unexpected format`,detail:t}),lK=e=>{if(e===void 0||!/^\d+$/u.test(e))return y();let t=Number(e);return Number.isSafeInteger(t)?b(t):y()},uK=(e,t)=>{let n=lK(e);if(S(n))return b(t+n.value*1e3);if(e===void 0)return y();let r=Date.parse(e);return Number.isFinite(r)?b(r):y()},dK=(e,t)=>{let n=lK(e[`x-ratelimit-remaining`]),r=lK(e[`x-ratelimit-reset`]);return S(n)&&n.value<=t&&S(r)?b(r.value*1e3):y()},fK=(e,t)=>Or(lK(e[`x-poll-interval`]),e=>t+e*1e3),pK=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[e]}));return t.length===0?y():b(Math.max(...t))},mK=(e,t)=>pK([uK(e[`retry-after`],t),dK(e,0)]),hK=(e,t,n)=>{let r=kr(mK(t.headers,n),z_);return(t.status===403||t.status===429)&&S(r)?new $G({operation:e,retryAt:r.value,message:`GitHub API rate limit exceeded`}):new QG({operation:e,status:b(t.status),message:`GitHub returned HTTP status ${t.status}`})},gK=36e5,_K=3e5,vK=N(M({id:NG,appSlug:FG,account:M({login:z}),permissions:hT(j,j),suspendedAt:I(j)}).pipe(mT({appSlug:`app_slug`,suspendedAt:`suspended_at`}))),yK=M({login:ON,id:kN}),bK=M({id:PG,name:Xk}).pipe(mT({name:`full_name`})),xK=M({totalCount:R.check(HT(0)),repositories:N(bK)}).pipe(mT({totalCount:`total_count`})),SK=M({token:z,expiresAt:vE,repositories:xE(N(bK))}).pipe(mT({expiresAt:`expires_at`})),CK=e=>e._tag===`InstallationWide`?{operation:`mint-installation-token`,body:{permissions:UG}}:{operation:`mint-worker-token`,body:{permissions:WG[e.permissions],repository_ids:[e.repositoryId]}},wK=class e extends Rr()(`@usine/github/GitHubApp`){static layer=Xf(e,T(function*(){let e=yield*jG(yield*yG),t=yield*LW,n=(e,n,r)=>T(function*(){let i=yield*t.execute(n).pipe(dg(t=>aK(e,t)));if(i.status<200||i.status>=300){let t=hK(e,i,yield*op);return t._tag===`GitHubRateLimitError`?yield*t:yield*yield*sK(t,i)}return yield*wW(r)(i).pipe(dg(t=>cK(e,t.message)))}),r=O(`GitHubApp.discoverInstallation`)(function*(){let t=yield*e(),[r,...i]=yield*n(`discover-installation`,iW(`${nK}/app/installations?per_page=2`).pipe(iK(t)),vK);if(r===void 0)return yield*new HG({reason:`missing`,message:`The GitHub App is not installed on any account. Install it on the account that owns the repositories.`});if(i.length>0)return yield*new HG({reason:`multiple`,message:`The GitHub App has more than one installation. Uninstall it from every account except one.`});if(r.suspendedAt!==null)return yield*new HG({reason:`suspended`,message:`The GitHub App installation is suspended. Unsuspend it in the installation settings on GitHub.`});let a=KG(r.permissions);return a.length>0?yield*new XG({missing:a,message:`The GitHub App installation is missing permissions: ${a.join(`, `)}. Grant them in the GitHub App settings, then approve the change on the installation.`}):new IG({id:r.id,accountLogin:r.account.login,appSlug:r.appSlug})}),i=O(`GitHubApp.mintToken`)(function*(t,r){let{operation:i,body:a}=CK(r);yield*D({installationId:t,operation:i,scope:r._tag,permissions:r._tag===`SingleRepository`?r.permissions:`installation`});let o=yield*e(),s=yield*n(i,aW(`${nK}/app/installations/${t}/access_tokens`).pipe(bW(a),iK(o)),SK),c=yield*op,l=K_(s.expiresAt)-c;if(l<=0||l>378e4)return yield*new eK({operation:i,message:`GitHub returned an installation token that is expired or exceeds the one-hour lifetime limit`,detail:`expires_at ${J_(s.expiresAt)} is ${l}ms from now`});l>gK&&(yield*k(`Accepted GitHub token clock skew; capped the local lease`,{installationId:t,operation:i,skewMillis:l-gK}));let u=yr(s.repositories,()=>[]);return r._tag===`SingleRepository`&&!(u.length===1&&u.every(e=>e.id===r.repositoryId))?yield*new eK({operation:i,message:`GitHub did not confirm that the worker token is scoped to exactly one repository`,detail:`expected repository ID ${r.repositoryId}, got [${u.map(e=>e.id).join(`, `)}]`}):new BG({value:vv(s.token),expiresAt:R_(c+Math.min(l,gK)),scope:r})}),a=O(`GitHubApp.installedRepositories`)(function*(e){let t=[];for(let r=1;;r+=1){let i=yield*n(`list-installation-repositories`,iW(`${nK}/installation/repositories?per_page=100&page=${r}`).pipe(iK(e.value)),xK);if(t.push(...i.repositories),t.length>=i.totalCount)return t;if(i.repositories.length===0)return yield*new eK({operation:`list-installation-repositories`,message:`GitHub returned an empty page before it listed total_count repositories`,detail:`page ${r} was empty after ${t.length} of ${i.totalCount} repositories`})}}),o=yield*qk(y()),s=O(`GitHubApp.lease`)(()=>Yk(o,e=>T(function*(){let t=yield*op;if(S(e)&&K_(e.value.token.expiresAt)-t>_K)return[e.value,e];let n=yield*r(),a={installation:n,token:yield*i(n.id,new LG)};return[a,b(a)]}))),c=yield*qk(y()),l=O(`GitHubApp.botAccount`)(()=>Yk(c,e=>T(function*(){let{installation:t,token:r}=yield*s(),{appSlug:i}=t;if(yield*D({appSlug:i}),S(e)&&e.value.appSlug===i)return[e.value.account,e];let a=new AN(yield*n(`read-bot-account`,iW(`${nK}/users/${encodeURIComponent(`${i}[bot]`)}`).pipe(iK(r.value)),yK));return yield*k(`Read the App's bot account`,{appSlug:i,login:a.login,id:a.id}),[a,b({appSlug:i,account:a})]})));return{repositories:O(`GitHubApp.repositories`)(function*(){let{token:e,installation:t}=yield*s();yield*D({installationId:t.id});let n=yield*a(e);return yield*A(`Listed installation repositories`,{count:n.length}),n.map(({name:e})=>e)}),installation:O(`GitHubApp.installation`)(()=>ng(s(),e=>e.installation)),botAccount:l,installationToken:O(`GitHubApp.installationToken`)(()=>ng(s(),e=>e.token)),projectAccess:O(`GitHubApp.projectAccess`)(function*(e){let{installation:t,token:n}=yield*s();return YG(t,e,yield*a(n))}),workerToken:O(`GitHubApp.workerToken`)((e,t)=>i(e.installationId,new RG({repository:e.repository,repositoryId:e.repositoryId,permissions:t})))}}))},TK=z.pipe(L(`GitHubEntityTag`)),EK=z.pipe(L(`GitHubBaseRefName`)),DK=class extends V(`@usine/github/BaseRefHead`)({baseRefName:EK,sha:Qk,entityTag:yE(TK)}){},OK=class e extends V(`@usine/github/PollCursor`)({entityTag:yE(TK),watermark:yE(vE)}){static empty=new e({entityTag:y(),watermark:y()})},kK=class extends H(`@usine/github/ChangedIssue`)(`ChangedIssue`,{number:R.check(HT(1)),updatedAt:_E}){},AK=class extends H(`@usine/github/ChangedPullRequest`)(`ChangedPullRequest`,{number:R.check(HT(1)),updatedAt:_E}){},jK=P([kK,AK]),MK=class extends H(`@usine/github/RepositoryNotModified`)(`RepositoryNotModified`,{cursor:OK,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(w(y())))}){},NK=class extends H(`@usine/github/RepositoryChanges`)(`RepositoryChanges`,{cursor:OK,items:N(jK),backlog:lT,nextPollAt:B(_E),backoffUntil:B(_E).pipe(TT(w(y())))}){};P([MK,NK]);var PK=z.pipe(L(`GitHubRepositoryLabelName`)),FK=j.check(PT(/^[0-9a-fA-F]{6}$/u,{message:`Expected a six-digit hex label color`})).pipe(L(`GitHubRepositoryLabelColor`)),IK=class extends V(`@usine/github/RepositoryLabel`)({name:PK,color:FK,description:yE(j)}){},LK=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique label names`}),RK=class extends V(`@usine/github/RepositoryLabelCatalog`)({entityTag:yE(TK),labels:N(IK).check(LK)}){},zK=class extends H(`@usine/github/RepositoryLabelsNotModified`)(`RepositoryLabelsNotModified`,{}){};P([RK,zK]);var BK=class extends V(`@usine/github/NewRepositoryLabel`)({name:PK,color:B(FK),description:B(j)}){},VK=M({name:PK,color:FK,description:I(j)}),HK=e=>{let{name:t,owner:n}=eA(e);return`${nK}/repos/${encodeURIComponent(n)}/${encodeURIComponent(t)}/labels`},UK=class e extends Rr()(`@usine/github/GitHubLabelWriter`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*LW;return{create:O(`GitHubLabelWriter.create`)(function*(n,r){yield*D({repository:n,label:r.name});let i=yield*e.installationToken(),a={name:r.name};S(r.color)&&(a.color=r.color.value),S(r.description)&&(a.description=r.description.value);let o=aW(HK(n)).pipe(bW(a),iK(i.value)),s=yield*t.execute(o).pipe(dg(e=>aK(`create-repository-label`,e)));if(s.status<200||s.status>=300)return yield*hK(`create-repository-label`,s,yield*op);let c=yield*wW(VK)(s).pipe(dg(e=>cK(`create-repository-label`,e.message)));return new IK({name:c.name,color:c.color,description:Sr(c.description)})})}}))},WK=new Set([`closedAt`,`createdAt`,`mergedAt`,`submittedAt`,`updatedAt`]),GK=e=>Array.isArray(e)?e.map(GK):Vw(LE)(e)?Object.fromEntries(Object.entries(e).filter(([e])=>!WK.has(e)).sort(([e],[t])=>e<t?-1:+(e>t)).map(([e,t])=>[e,GK(t)])):e,KK=6e4,qK=M({data:$w(aT),errors:$w(N(M({message:j,type:$w(j)})))}),JK=O(`GitHub.queryGraphql`)(function*(e,t,n,r,i,a){let o=aW(`${nK}/graphql`).pipe(bW({query:r,variables:i}),iK(t.value)),s=yield*e.execute(o).pipe(dg(e=>aK(n,e))),c=yield*op;if(s.status!==200)return yield*hK(n,s,c);let l=yield*wW(qK)(s).pipe(dg(e=>cK(n,e.message)));if(l.errors!==void 0&&l.errors.length>0){if(l.errors.some(e=>e.type===`RATE_LIMITED`))return yield*new $G({operation:n,retryAt:R_(yr(mK(s.headers,c),()=>c+KK)),message:`GitHub GraphQL API rate limit exceeded`});if(!l.errors.every(e=>e.type===`NOT_FOUND`))return yield*cK(n,`GraphQL errors: ${l.errors.map(e=>e.message).join(`; `)}`)}return yield*Hw(a)(l.data).pipe(dg(e=>cK(n,e.message)))}),YK=R.check(HT(1)),XK=R.check(HT(0)),ZK=j.check(PT(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/u,{message:`Expected a GitHub UTC timestamp`})),QK=(e,t)=>I(e).pipe(ST(e,{decode:sb(e=>e??t),encode:sb(e=>e)})),$K={totalCount:0,nodes:[]},eq=M({login:z}),tq=I(eq),nq=M({totalCount:XK,nodes:N(M({name:z}))}),rq=M({totalCount:XK,nodes:N(M({author:tq,body:j,createdAt:ZK}))}),iq=M({number:YK,title:j,body:j,url:z,state:j,stateReason:I(j),createdAt:ZK,updatedAt:ZK,closedAt:I(ZK),author:tq,issueType:I(M({name:j})),milestone:I(M({title:j})),labels:QK(nq,$K),assignees:M({totalCount:XK,nodes:N(eq)}),comments:rq,closedByPullRequestsReferences:QK(M({totalCount:XK,nodes:N(M({number:YK,state:j,isDraft:lT,url:z}))}),$K)}),aq=I(M({login:$w(z)})),oq=M({author:tq,state:j,body:j,submittedAt:I(ZK),commit:I(M({oid:z}))}),sq=M({author:tq,body:j}),cq=M({number:YK,title:j,body:j,url:z,state:j,isDraft:lT,merged:lT,createdAt:ZK,updatedAt:ZK,mergedAt:I(ZK),author:tq,baseRefName:EK,headRefName:j,headRefOid:z,additions:XK,deletions:XK,changedFiles:XK,reviewDecision:I(j),mergeable:j.pipe(DT(w(`UNKNOWN`))),mergeStateStatus:j.pipe(DT(w(`UNKNOWN`))),statusCheckRollup:I(M({state:j})),labels:QK(nq,$K),reviewRequests:QK(M({totalCount:XK,nodes:N(M({requestedReviewer:aq}))}),$K),reviews:QK(M({totalCount:XK,nodes:N(oq)}),$K),reviewThreads:M({totalCount:XK,nodes:N(M({isResolved:lT,isOutdated:lT,path:j,comments:M({totalCount:XK,nodes:N(sq)})}))}),comments:rq,closingIssuesReferences:QK(M({totalCount:XK,nodes:N(M({number:YK,state:j}))}),$K)}),lq=j.check(PT(/^[a-f0-9]{64}$/u,{message:`Expected a SHA-256 content hash`})).pipe(L(`GitHubContentHash`)),uq=class extends H(`@usine/github/IssueSnapshot`)(`IssueSnapshot`,{payload:iq,contentHash:lq}){},dq=class extends H(`@usine/github/PullRequestSnapshot`)(`PullRequestSnapshot`,{payload:cq,contentHash:lq}){};P([uq,dq]);var fq=`
37
37
  query UsineIssuePayload($owner: String!, $name: String!, $number: Int!) {
38
38
  repository(owner: $owner, name: $name) {
39
39
  issue(number: $number) {
@@ -168,57 +168,57 @@ var e=(e,t)=>{switch(t.length){case 0:return e;case 1:return t[0](e);case 2:retu
168
168
  `)?`\r
169
169
  `:t.startsWith(`---
170
170
  `)?`
171
- `:void 0;if(n===void 0)return new rU({file:e,stage:`frontmatter`,expression:y(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=Kq(t,n,r);if(a<0)return new rU({file:e,stage:`frontmatter`,expression:y(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return w({yaml:t.slice(r,a),body:t.slice(s),newline:n})},Jq=class extends V(`@usine/config/AgentFile`)({name:fN,harness:lN,model:cN,effort:uN,parentModel:B(cN),parentEffort:B(uN),persona:pN}){get agent(){return new mN({name:this.name,persona:this.persona,brain:new dN({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},Yq=class extends V(`@usine/config/InvalidAgent`)({file:tU,error:rU}){},Xq=F([`latest`,`next`]),Zq=F([`off`,`propose`,`automatic`]),Qq=j.check(PT(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u)).pipe(L(`ReleaseVersion`)),$q=F([`idle`,`now`]),eJ={previous:Qq,target:Qq},tJ=P([class extends V(`@usine/core/UpgradeInstalling`)({...eJ,status:rT(`installing`)}){},class extends V(`@usine/core/UpgradeGood`)({...eJ,status:rT(`good`)}){},class extends V(`@usine/core/UpgradeRolledBack`)({...eJ,status:rT(`rolled-back`),reason:z,failureStage:F([`install`,`health-check`,`unknown`]).pipe(DT(w(`unknown`)))}){},class extends V(`@usine/core/UpgradeFailed`)({...eJ,status:rT(`failed`),reason:z}){}]),nJ=_z(`Expected a non-blank registry tag`).pipe(L(`RegistryTag`)),rJ=R.check(HT(1)),iJ=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),aJ=e=>`label`in e?`label:${pz(e.label)}`:`state:${e.state}`,oJ=NT(e=>{let t=e.flatMap(({sources:e})=>e.map(aJ));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),sJ=N(Ez).check(iJ,oJ),cJ=NT(e=>new Set(e.map(({name:e})=>pz(e))).size===e.length,{message:`Expected unique GitHub label names`}),lJ=N(gz).check(cJ),uJ=class extends V(`@usine/config/ManagedRepo`)({name:Xk,tags:N(nJ).check(XT()).pipe(DT(w([]))),lanes:sJ.pipe(DT(w([])))}){},dJ=rJ.pipe(DT(w(1))),fJ=class extends V(`@usine/config/LocalWorker`)({name:EN,kind:rT(`local`),maxConcurrentAttempts:dJ}){},pJ=class extends V(`@usine/config/ExeDevWorker`)({name:EN,kind:rT(`exe.dev`),maxConcurrentAttempts:dJ}){},mJ=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(L(`EnvironmentVariableName`)),hJ=class extends V(`@usine/config/WorkerGateway`)({domain:FN,destination:jN,adminPort:IN.pipe(DT(w(7070))),adminTokenEnv:mJ,llmProviders:N(LN).check(XT()).pipe(DT(w([])))}){},gJ=class extends V(`@usine/config/WorkerContainer`)({image:xE(zN),cpus:xE(VN),memoryMib:xE(HN),pids:xE(UN)}){},_J=class extends V(`@usine/config/ProviderApiKeys`)({anthropic:xE(mJ),openai:xE(mJ)}){}.pipe(DT(w({}))),vJ=lP.pipe(mT({sshWait:`ssh_wait`,creationBackoffMin:`creation_backoff_min`,creationBackoffMax:`creation_backoff_max`,machineCheckInterval:`machine_check_interval`}),DT(w({}))),yJ=class extends V(`@usine/config/HetznerProvisioner`)({provider:rT(`hetzner`),tokenEnv:mJ,serverType:ZN,location:QN,image:$N,network:xE(eP),firewall:xE(eP),sshKey:eP,sshUser:rP.pipe(DT(w(`usine`))),labels:nP.pipe(DT(w({}))),apiKeys:_J,timings:vJ}){},bJ=class extends V(`@usine/config/BoatTailnet`)({gatewayAddress:oP,clientIdEnv:mJ,clientSecretEnv:mJ}){},xJ=class extends V(`@usine/config/BoatProvisioner`)({provider:rT(`boat`),tokenEnv:mJ,size:iP.pipe(DT(w(`default`))),snapshot:xE(aP),tailnet:xE(bJ.pipe(mT({gatewayAddress:`gateway_address`,clientIdEnv:`client_id_env`,clientSecretEnv:`client_secret_env`}))),apiKeys:_J,timings:vJ}){};P([yJ,xJ]);var SJ=P([yJ.pipe(mT({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),xJ.pipe(mT({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),CJ=class extends V(`@usine/config/SshWorker`)({name:EN,kind:rT(`ssh`),maxConcurrentAttempts:dJ,destination:xE(jN),provisioner:xE(SJ),identityFile:xE(NN),port:xE(MN),root:PN,gateway:xE(hJ.pipe(mT({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:gJ.pipe(mT({memoryMib:`memory_mib`}),DT(w({})))}){},wJ=e=>{let t=Tr(e.provisioner);if(t===void 0)return x(e.destination)?`SSH worker "${e.name}" needs a destination or a provisioner`:void 0;if(S(e.destination))return`SSH worker "${e.name}" sets both destination and provisioner; a provisioned worker creates its machines, so remove destination`;if(S(e.port))return`SSH worker "${e.name}" sets port, which a provisioned worker takes from its provider`;switch(t.provider){case`hetzner`:return S(e.gateway)&&x(t.network)?`SSH worker "${e.name}" has a gateway, so its provisioner needs the gateway's private network in network`:void 0;case`boat`:return S(e.gateway)&&(x(t.tailnet)||x(t.snapshot))?`SSH worker "${e.name}" needs provisioner.tailnet and provisioner.snapshot to use a Boat gateway`:S(t.tailnet)&&x(e.gateway)?`SSH worker "${e.name}" sets provisioner.tailnet without a gateway`:x(e.identityFile)?`SSH worker "${e.name}" has a Boat provisioner and needs identity_file, whose .pub file usine adds to each sandbox`:void 0}},TJ=rE.check(NT(e=>e.protocol===`https:`,{message:`Expected an https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),EJ=class extends V(`@usine/config/CloudflareLlmProviderKey`)({provider:JN,apiKeyEnv:mJ}){},DJ=NT(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),OJ=class extends V(`@usine/config/CloudflareWorker`)({name:EN,kind:rT(`cloudflare`),maxConcurrentAttempts:dJ,workerUrl:TJ,accessClientIdEnv:mJ,accessClientSecretEnv:mJ,image:qN,instanceType:KN.pipe(DT(w(`standard-4`))),llmProviders:N(EJ.pipe(mT({apiKeyEnv:`api_key_env`}))).check(DJ).pipe(DT(w([])))}){};P([fJ,pJ,CJ,OJ]);var kJ=class extends V(`@usine/config/Settings`)({upgradeChannel:Xq.pipe(DT(w(`latest`))),upgradeMode:Zq.pipe(DT(w(`propose`))),pollInterval:rJ.pipe(DT(w(60))),maxChildren:pP.pipe(DT(w(4))),maxAttemptMinutes:xE(rJ),maxAttemptTokens:xE(rJ),parentModel:xE(cN),parentEffort:xE(uN)}){},AJ=P([M({mode:rT(`off`)}),M({mode:rT(`deliveries`)}),M({mode:rT(`endpoint`),publicUrl:rE}).pipe(mT({publicUrl:`public_url`}))]),jJ=rE.check(NT(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``,{message:`Expected a URL without a username, password, or query string; authenticate in a collector next to usine up`})),MJ=class extends V(`@usine/config/Tracing`)({otlpUrl:jJ,serviceName:_z(`Expected a non-blank service name`).pipe(DT(w(`usine`)))}){},NJ=kJ.pipe(mT({upgradeChannel:`upgrade_channel`,upgradeMode:`upgrade_mode`,pollInterval:`poll_interval`,maxChildren:`max_children`,maxAttemptMinutes:`max_attempt_minutes`,maxAttemptTokens:`max_attempt_tokens`,parentModel:`parent_model`,parentEffort:`parent_effort`})),PJ=P([fJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`})),pJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`})),CJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(NT(e=>wJ(e)??!0)),OJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),FJ=N(uJ).check(vz(e=>e.name)),IJ=N(PJ).check(qT(),iJ),LJ=class extends V(`@usine/config/UsineConfig`)({version:rT(1),labels:lJ.pipe(DT(w([]))),repos:FJ,settings:NJ.pipe(DT(w({}))),workers:IJ.pipe(DT(w([{name:`local`,kind:`local`}]))),webhooks:AJ.pipe(DT(w({mode:`off`}))),operator:xE(aN),tracing:xE(MJ.pipe(mT({otlpUrl:`otlp_url`,serviceName:`service_name`})))}){},RJ=class extends V(`@usine/config/Selector`)({repos:xE(N(Xk).check(qT(),vz(e=>e))),tags:xE(N(nJ).check(qT(),XT()))}){}.check(NT(e=>S(e.repos)||S(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),zJ=(e,t)=>vr(e,{onNone:()=>!0,onSome:e=>{let n=vr(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>tA(e)===tA(t.name))}),r=vr(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),BJ=j.check(NT(e=>e.trim().split(/\s+/u).length===5&&Oi(Dm(e)),{message:`Expected a valid five-field cron expression`})).pipe(L(`Cron`)),VJ=j.check(NT(e=>S(H_(e)),{message:`Expected an IANA time-zone name`})).pipe(L(`TimeZone`)),HJ=class extends V(`@usine/config/IssueTrigger`)({on:rT(`issue`),if:ZH}){},UJ=class extends V(`@usine/config/PullRequestTrigger`)({on:rT(`pr`),if:ZH}){},WJ=class extends V(`@usine/config/ScheduleTrigger`)({on:rT(`schedule`),if:ZH,cron:BJ,tz:VJ.pipe(DT(w(`UTC`)))}){},GJ=P([HJ,UJ,WJ]),KJ=PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case file name`}),qJ=aA.check(KJ),JJ=_z(`Expected a non-blank Markdown prompt`).pipe(L(`PromptTemplate`)),YJ=R.check(HT(1,{message:`Expected a priority of at least 1`})).pipe(L(`LoopPriority`)),XJ=class extends V(`@usine/config/LoopFile`)({name:qJ,trigger:GJ,selector:B(RJ),approval:sA,maxCycles:iI.pipe(DT(w(oI)),TT(w(oI))),permissions:lA.pipe(DT(w(`write`)),TT(w(`write`))),priority:B(YJ).pipe(TT(w(y()))),step:wN,agent:fN,body:JJ}){},ZJ=class extends V(`@usine/config/QuarantinedLoop`)({file:tU,error:rU}){},QJ=e=>tU.make(`loops/${e}.md`),$J=class extends H(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:Xk,lane:yz,label:fz}){},eY=class extends H(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:XJ.fields.name,label:fz}){},tY=P([$J,eY]),nY=Kw(UH),rY=(e,t)=>new JH({name:e,fields:t.map(([e,t,n])=>new qH({name:e,type:nY(t),nullable:n===`nullable`}))}),iY=rY(`Actor`,[[`login`,`string`]]),aY=rY(`Label`,[[`name`,`string`]]),oY=rY(`Milestone`,[[`title`,`string`]]),sY=rY(`IssueType`,[[`name`,`string`]]),cY=rY(`Commit`,[[`oid`,`string`]]),lY=rY(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),uY=rY(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),dY=rY(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),fY=rY(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),pY=rY(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),mY=rY(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),hY=rY(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),gY=rY(`IssuePayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`stateReason`,`string`,`nullable`],[`createdAt`,`string`],[`updatedAt`,`string`],[`closedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`issueType`,`IssueType`,`nullable`],[`milestone`,`Milestone`,`nullable`],[`labels`,`Labels`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),_Y=rY(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),vY=rY(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),yY=rY(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),bY=rY(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),xY=rY(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),SY=rY(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),CY=rY(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),wY=rY(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),TY=rY(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),EY=rY(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),DY=rY(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),OY=rY(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),kY=rY(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),AY=rY(`StatusCheckRollup`,[[`state`,`string`]]),jY=rY(`PullRequestPayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`isDraft`,`bool`],[`merged`,`bool`],[`createdAt`,`string`],[`updatedAt`,`string`],[`mergedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`baseRefName`,`string`],[`headRefName`,`string`],[`headRefOid`,`string`],[`additions`,`int`],[`deletions`,`int`],[`changedFiles`,`int`],[`reviewDecision`,`string`,`nullable`],[`mergeable`,`string`],[`mergeStateStatus`,`string`],[`statusCheckRollup`,`StatusCheckRollup`,`nullable`],[`labels`,`Labels`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),MY=rY(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),NY=rY(`SchedulePayload`,[[`tick`,`Tick`]]),PY=(e,t)=>new XH({types:[lY,...e],variables:[new YH({name:`repo`,type:nY(`RepoContext`)}),new YH({name:`item`,type:nY(t)})]}),FY=PY([iY,aY,oY,sY,uY,dY,fY,pY,mY,hY,gY],`IssuePayload`),IY=PY([iY,aY,cY,uY,_Y,vY,yY,bY,xY,SY,CY,wY,TY,EY,DY,OY,kY,AY,jY],`PullRequestPayload`),LY=PY([MY,NY],`SchedulePayload`),RY=e=>{switch(e){case`issue`:return FY;case`pr`:return IY;case`schedule`:return LY}},zY=e=>{let{owner:t}=eA(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},BY=Symbol.for(`yaml.alias`),VY=Symbol.for(`yaml.document`),HY=Symbol.for(`yaml.map`),UY=Symbol.for(`yaml.pair`),WY=Symbol.for(`yaml.scalar`),GY=Symbol.for(`yaml.seq`),KY=Symbol.for(`yaml.node.type`),qY=e=>!!e&&typeof e==`object`&&e[KY]===BY,JY=e=>!!e&&typeof e==`object`&&e[KY]===VY,YY=e=>!!e&&typeof e==`object`&&e[KY]===HY,XY=e=>!!e&&typeof e==`object`&&e[KY]===UY,ZY=e=>!!e&&typeof e==`object`&&e[KY]===WY,QY=e=>!!e&&typeof e==`object`&&e[KY]===GY;function $Y(e){if(e&&typeof e==`object`)switch(e[KY]){case HY:case GY:return!0}return!1}function eX(e){if(e&&typeof e==`object`)switch(e[KY]){case BY:case HY:case WY:case GY:return!0}return!1}var tX=e=>(ZY(e)||$Y(e))&&!!e.anchor,nX=Symbol(`break visit`),rX=Symbol(`skip children`),iX=Symbol(`remove node`);function aX(e,t){let n=sX(t);JY(e)?oX(null,e.contents,n,Object.freeze([e]))===iX&&(e.contents=null):oX(null,e,n,Object.freeze([]))}aX.BREAK=nX,aX.SKIP=rX,aX.REMOVE=iX;function oX(e,t,n,r){let i=cX(e,t,n,r);if(eX(i)||XY(i))return lX(e,r,i),oX(e,i,n,r);if(typeof i!=`symbol`){if($Y(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=oX(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===nX)return nX;else i===iX&&(t.items.splice(e,1),--e)}}else if(XY(t)){r=Object.freeze(r.concat(t));let e=oX(`key`,t.key,n,r);if(e===nX)return nX;e===iX&&(t.key=null);let i=oX(`value`,t.value,n,r);if(i===nX)return nX;i===iX&&(t.value=null)}}return i}function sX(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function cX(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(YY(t))return n.Map?.(e,t,r);if(QY(t))return n.Seq?.(e,t,r);if(XY(t))return n.Pair?.(e,t,r);if(ZY(t))return n.Scalar?.(e,t,r);if(qY(t))return n.Alias?.(e,t,r)}function lX(e,t,n){let r=t[t.length-1];if($Y(r))r.items[e]=n;else if(XY(r))e===`key`?r.key=n:r.value=n;else if(JY(r))r.contents=n;else{let e=qY(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var uX={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},dX=e=>e.replace(/[!,[\]{}]/g,e=>uX[e]),fX=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+dX(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&eX(e.contents)){let t={};aX(e.contents,(e,n)=>{eX(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
172
- `)}};fX.defaultYaml={explicit:!1,version:`1.2`},fX.defaultTags={"!!":`tag:yaml.org,2002:`};function pX(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function mX(e){let t=new Set;return aX(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function hX(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function gX(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=mX(e);let a=hX(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(ZY(t.node)||$Y(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function _X(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=_X(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=_X(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=_X(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=_X(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function vX(e,t,n){if(Array.isArray(e))return e.map((e,t)=>vX(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!tX(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var yX=class{constructor(e){Object.defineProperty(this,KY,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!JY(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=vX(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?_X(i,{"":o},``,o):o}},bX=class extends yX{constructor(e){super(BY),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],aX(e,{Node:(e,t)=>{(qY(t)||tX(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(vX(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=xX(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(pX(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function xX(e,t,n){if(qY(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if($Y(t)){let r=0;for(let i of t.items){let t=xX(e,i,n);t>r&&(r=t)}return r}if(XY(t)){let r=xX(e,t.key,n),i=xX(e,t.value,n);return Math.max(r,i)}return 1}var SX=e=>!e||typeof e!=`function`&&typeof e!=`object`,CX=class extends yX{constructor(e){super(WY),this.value=e}toJSON(e,t){return t?.keep?this.value:vX(this.value,e,t)}toString(){return String(this.value)}};CX.BLOCK_FOLDED=`BLOCK_FOLDED`,CX.BLOCK_LITERAL=`BLOCK_LITERAL`,CX.PLAIN=`PLAIN`,CX.QUOTE_DOUBLE=`QUOTE_DOUBLE`,CX.QUOTE_SINGLE=`QUOTE_SINGLE`;var wX=`tag:yaml.org,2002:`;function TX(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function EX(e,t,n){if(JY(e)&&(e=e.contents),eX(e))return e;if(XY(e)){let t=n.schema[HY].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new bX(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=wX+t.slice(2));let l=TX(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new CX(e);return c&&(c.node=t),t}l=e instanceof Map?o[HY]:Symbol.iterator in Object(e)?o[GY]:o[HY]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new CX(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function DX(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return EX(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var OX=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,kX=class extends yX{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>eX(t)||XY(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(OX(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if($Y(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,DX(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if($Y(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&ZY(i)?i.value:i:$Y(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!XY(t))return!1;let n=t.value;return n==null||e&&ZY(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return $Y(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if($Y(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,DX(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},AX=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function jX(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var MX=(e,t,n)=>e.endsWith(`
173
- `)?jX(n,t):n.includes(`
171
+ `:void 0;if(n===void 0)return new rU({file:e,stage:`frontmatter`,expression:y(),message:`Expected the file to start with a YAML frontmatter delimiter (---)`});let r=3+n.length,i=`${n}---`,a=Kq(t,n,r);if(a<0)return new rU({file:e,stage:`frontmatter`,expression:y(),message:`Expected a closing YAML frontmatter delimiter (---)`});let o=a+i.length,s=t.startsWith(n,o)?o+n.length:o;return w({yaml:t.slice(r,a),body:t.slice(s),newline:n})},Jq=class extends V(`@usine/config/AgentFile`)({name:fN,harness:lN,model:cN,effort:uN,parentModel:B(cN),parentEffort:B(uN),persona:pN}){get agent(){return new mN({name:this.name,persona:this.persona,brain:new dN({harness:this.harness,model:this.model,effort:this.effort}),parentModel:this.parentModel,parentEffort:this.parentEffort})}},Yq=class extends V(`@usine/config/InvalidAgent`)({file:tU,error:rU}){},Xq=F([`latest`,`next`]),Zq=F([`off`,`propose`,`automatic`]),Qq=j.check(PT(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u)).pipe(L(`ReleaseVersion`)),$q=F([`idle`,`now`]),eJ={previous:Qq,target:Qq},tJ=P([class extends V(`@usine/core/UpgradeInstalling`)({...eJ,status:rT(`installing`)}){},class extends V(`@usine/core/UpgradeGood`)({...eJ,status:rT(`good`)}){},class extends V(`@usine/core/UpgradeRolledBack`)({...eJ,status:rT(`rolled-back`),reason:z,failureStage:F([`install`,`health-check`,`unknown`]).pipe(DT(w(`unknown`)))}){},class extends V(`@usine/core/UpgradeFailed`)({...eJ,status:rT(`failed`),reason:z}){}]),nJ=_z(`Expected a non-blank registry tag`).pipe(L(`RegistryTag`)),rJ=R.check(HT(1)),iJ=NT(e=>new Set(e.map(({name:e})=>e)).size===e.length,{message:`Expected unique names`}),aJ=e=>`label`in e?`label:${pz(e.label)}`:`state:${e.state}`,oJ=NT(e=>{let t=e.flatMap(({sources:e})=>e.map(aJ));return new Set(t).size===t.length},{message:`Expected each lane source in only one lane`}),sJ=N(Ez).check(iJ,oJ),cJ=NT(e=>new Set(e.map(({name:e})=>pz(e))).size===e.length,{message:`Expected unique GitHub label names`}),lJ=N(gz).check(cJ),uJ=class extends V(`@usine/config/ManagedRepo`)({name:Xk,tags:N(nJ).check(XT()).pipe(DT(w([]))),lanes:sJ.pipe(DT(w([])))}){},dJ=rJ.pipe(DT(w(1))),fJ=class extends V(`@usine/config/LocalWorker`)({name:EN,kind:rT(`local`),maxConcurrentAttempts:dJ}){},pJ=class extends V(`@usine/config/ExeDevWorker`)({name:EN,kind:rT(`exe.dev`),maxConcurrentAttempts:dJ}){},mJ=j.check(PT(/^[A-Za-z_][A-Za-z0-9_]*$/u,{message:`Expected an environment variable name`})).pipe(L(`EnvironmentVariableName`)),hJ=class extends V(`@usine/config/WorkerGateway`)({domain:FN,destination:jN,adminPort:IN.pipe(DT(w(7070))),adminTokenEnv:mJ,llmProviders:N(LN).check(XT()).pipe(DT(w([])))}){},gJ=class extends V(`@usine/config/WorkerContainer`)({image:xE(zN),cpus:xE(VN),memoryMib:xE(HN),pids:xE(UN)}){},_J=class extends V(`@usine/config/ProviderApiKeys`)({anthropic:xE(mJ),openai:xE(mJ)}){}.pipe(DT(w({}))),vJ=lP.pipe(mT({sshWait:`ssh_wait`,creationBackoffMin:`creation_backoff_min`,creationBackoffMax:`creation_backoff_max`,machineCheckInterval:`machine_check_interval`}),DT(w({}))),yJ=class extends V(`@usine/config/HetznerProvisioner`)({provider:rT(`hetzner`),tokenEnv:mJ,serverType:ZN,location:QN,image:$N,network:xE(eP),firewall:xE(eP),sshKey:eP,sshUser:rP.pipe(DT(w(`usine`))),labels:nP.pipe(DT(w({}))),apiKeys:_J,timings:vJ}){},bJ=class extends V(`@usine/config/BoatTailnet`)({gatewayAddress:oP,clientIdEnv:mJ,clientSecretEnv:mJ}){},xJ=class extends V(`@usine/config/BoatProvisioner`)({provider:rT(`boat`),tokenEnv:mJ,size:iP.pipe(DT(w(`default`))),snapshot:xE(aP),tailnet:xE(bJ.pipe(mT({gatewayAddress:`gateway_address`,clientIdEnv:`client_id_env`,clientSecretEnv:`client_secret_env`}))),apiKeys:_J,timings:vJ}){};P([yJ,xJ]);var SJ=P([yJ.pipe(mT({tokenEnv:`token_env`,serverType:`server_type`,sshKey:`ssh_key`,sshUser:`ssh_user`,apiKeys:`api_keys`})),xJ.pipe(mT({tokenEnv:`token_env`,apiKeys:`api_keys`}))]),CJ=class extends V(`@usine/config/SshWorker`)({name:EN,kind:rT(`ssh`),maxConcurrentAttempts:dJ,destination:xE(jN),provisioner:xE(SJ),identityFile:xE(NN),port:xE(MN),root:PN,gateway:xE(hJ.pipe(mT({adminPort:`admin_port`,adminTokenEnv:`admin_token_env`,llmProviders:`llm_providers`}))),container:gJ.pipe(mT({memoryMib:`memory_mib`}),DT(w({})))}){},wJ=e=>{let t=Tr(e.provisioner);if(t===void 0)return x(e.destination)?`SSH worker "${e.name}" needs a destination or a provisioner`:void 0;if(S(e.destination))return`SSH worker "${e.name}" sets both destination and provisioner; a provisioned worker creates its machines, so remove destination`;if(S(e.port))return`SSH worker "${e.name}" sets port, which a provisioned worker takes from its provider`;switch(t.provider){case`hetzner`:return S(e.gateway)&&x(t.network)?`SSH worker "${e.name}" has a gateway, so its provisioner needs the gateway's private network in network`:void 0;case`boat`:return S(e.gateway)&&(x(t.tailnet)||x(t.snapshot))?`SSH worker "${e.name}" needs provisioner.tailnet and provisioner.snapshot to use a Boat gateway`:S(t.tailnet)&&x(e.gateway)?`SSH worker "${e.name}" sets provisioner.tailnet without a gateway`:x(e.identityFile)?`SSH worker "${e.name}" has a Boat provisioner and needs identity_file, whose .pub file usine adds to each sandbox`:void 0}},TJ=rE.check(NT(e=>e.protocol===`https:`,{message:`Expected an https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``&&e.hash===``&&e.pathname===`/`,{message:`Expected the Worker's origin, without a path, credentials, or query string`})),EJ=class extends V(`@usine/config/CloudflareLlmProviderKey`)({provider:JN,apiKeyEnv:mJ}){},DJ=NT(e=>new Set(e.map(({provider:e})=>e)).size===e.length,{message:`Expected each provider once`}),OJ=class extends V(`@usine/config/CloudflareWorker`)({name:EN,kind:rT(`cloudflare`),maxConcurrentAttempts:dJ,workerUrl:TJ,accessClientIdEnv:mJ,accessClientSecretEnv:mJ,image:qN,instanceType:KN.pipe(DT(w(`standard-4`))),llmProviders:N(EJ.pipe(mT({apiKeyEnv:`api_key_env`}))).check(DJ).pipe(DT(w([])))}){},kJ=P([fJ,pJ,CJ,OJ]),AJ=class extends V(`@usine/config/Settings`)({upgradeChannel:Xq.pipe(DT(w(`latest`))),upgradeMode:Zq.pipe(DT(w(`propose`))),pollInterval:rJ.pipe(DT(w(60))),maxChildren:pP.pipe(DT(w(4))),maxAttemptMinutes:xE(rJ),maxAttemptTokens:xE(rJ),parentModel:xE(cN),parentEffort:xE(uN)}){},jJ=P([M({mode:rT(`off`)}),M({mode:rT(`deliveries`)}),M({mode:rT(`endpoint`),publicUrl:rE}).pipe(mT({publicUrl:`public_url`}))]),MJ=rE.check(NT(e=>e.protocol===`http:`||e.protocol===`https:`,{message:`Expected an http or https URL`}),NT(e=>e.username===``&&e.password===``&&e.search===``,{message:`Expected a URL without a username, password, or query string; authenticate in a collector next to usine up`})),NJ=class extends V(`@usine/config/Tracing`)({otlpUrl:MJ,serviceName:_z(`Expected a non-blank service name`).pipe(DT(w(`usine`)))}){},PJ=AJ.pipe(mT({upgradeChannel:`upgrade_channel`,upgradeMode:`upgrade_mode`,pollInterval:`poll_interval`,maxChildren:`max_children`,maxAttemptMinutes:`max_attempt_minutes`,maxAttemptTokens:`max_attempt_tokens`,parentModel:`parent_model`,parentEffort:`parent_effort`})),FJ=P([fJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`})),pJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`})),CJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`,identityFile:`identity_file`})).check(NT(e=>wJ(e)??!0)),OJ.pipe(mT({maxConcurrentAttempts:`max_concurrent_attempts`,workerUrl:`worker_url`,accessClientIdEnv:`access_client_id_env`,accessClientSecretEnv:`access_client_secret_env`,instanceType:`instance_type`,llmProviders:`llm_providers`}))]),IJ=N(uJ).check(vz(e=>e.name)),LJ=N(FJ).check(qT(),iJ),RJ=class extends V(`@usine/config/UsineConfig`)({version:rT(1),labels:lJ.pipe(DT(w([]))),repos:IJ,settings:PJ.pipe(DT(w({}))),workers:LJ.pipe(DT(w([{name:`local`,kind:`local`}]))),webhooks:jJ.pipe(DT(w({mode:`off`}))),operator:xE(aN),tracing:xE(NJ.pipe(mT({otlpUrl:`otlp_url`,serviceName:`service_name`})))}){},zJ=class extends V(`@usine/config/Selector`)({repos:xE(N(Xk).check(qT(),vz(e=>e))),tags:xE(N(nJ).check(qT(),XT()))}){}.check(NT(e=>S(e.repos)||S(e.tags),{message:`Expected selector.repos, selector.tags, or both`})),BJ=(e,t)=>vr(e,{onNone:()=>!0,onSome:e=>{let n=vr(e.repos,{onNone:()=>!0,onSome:e=>e.some(e=>tA(e)===tA(t.name))}),r=vr(e.tags,{onNone:()=>!0,onSome:e=>e.some(e=>t.tags.includes(e))});return n&&r}}),VJ=j.check(NT(e=>e.trim().split(/\s+/u).length===5&&Oi(Dm(e)),{message:`Expected a valid five-field cron expression`})).pipe(L(`Cron`)),HJ=j.check(NT(e=>S(H_(e)),{message:`Expected an IANA time-zone name`})).pipe(L(`TimeZone`)),UJ=class extends V(`@usine/config/IssueTrigger`)({on:rT(`issue`),if:ZH}){},WJ=class extends V(`@usine/config/PullRequestTrigger`)({on:rT(`pr`),if:ZH}){},GJ=class extends V(`@usine/config/ScheduleTrigger`)({on:rT(`schedule`),if:ZH,cron:VJ,tz:HJ.pipe(DT(w(`UTC`)))}){},KJ=P([UJ,WJ,GJ]),qJ=PT(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,{message:`Expected a kebab-case file name`}),JJ=aA.check(qJ),YJ=_z(`Expected a non-blank Markdown prompt`).pipe(L(`PromptTemplate`)),XJ=R.check(HT(1,{message:`Expected a priority of at least 1`})).pipe(L(`LoopPriority`)),ZJ=class extends V(`@usine/config/LoopFile`)({name:JJ,trigger:KJ,selector:B(zJ),approval:sA,maxCycles:iI.pipe(DT(w(oI)),TT(w(oI))),permissions:lA.pipe(DT(w(`write`)),TT(w(`write`))),priority:B(XJ).pipe(TT(w(y()))),step:wN,agent:fN,body:YJ}){},QJ=class extends V(`@usine/config/QuarantinedLoop`)({file:tU,error:rU}){},$J=e=>tU.make(`loops/${e}.md`),eY=class extends H(`@usine/config/UndeclaredLaneLabelWarning`)(`UndeclaredLaneLabelWarning`,{repository:Xk,lane:yz,label:fz}){},tY=class extends H(`@usine/config/UndeclaredTriggerLabelWarning`)(`UndeclaredTriggerLabelWarning`,{loop:ZJ.fields.name,label:fz}){},nY=P([eY,tY]),rY=Kw(UH),iY=(e,t)=>new JH({name:e,fields:t.map(([e,t,n])=>new qH({name:e,type:rY(t),nullable:n===`nullable`}))}),aY=iY(`Actor`,[[`login`,`string`]]),oY=iY(`Label`,[[`name`,`string`]]),sY=iY(`Milestone`,[[`title`,`string`]]),cY=iY(`IssueType`,[[`name`,`string`]]),lY=iY(`Commit`,[[`oid`,`string`]]),uY=iY(`RepoContext`,[[`name`,`string`],[`owner`,`string`],[`url`,`string`]]),dY=iY(`Labels`,[[`totalCount`,`int`],[`nodes`,`list<Label>`]]),fY=iY(`Assignees`,[[`totalCount`,`int`],[`nodes`,`list<Actor>`]]),pY=iY(`IssueComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),mY=iY(`IssueComments`,[[`totalCount`,`int`],[`nodes`,`list<IssueComment>`]]),hY=iY(`PullRequestReference`,[[`number`,`int`],[`state`,`string`],[`isDraft`,`bool`],[`url`,`string`]]),gY=iY(`PullRequestReferences`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestReference>`]]),_Y=iY(`IssuePayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`stateReason`,`string`,`nullable`],[`createdAt`,`string`],[`updatedAt`,`string`],[`closedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`issueType`,`IssueType`,`nullable`],[`milestone`,`Milestone`,`nullable`],[`labels`,`Labels`],[`assignees`,`Assignees`],[`comments`,`IssueComments`],[`closedByPullRequestsReferences`,`PullRequestReferences`]]),vY=iY(`RequestedReviewer`,[[`login`,`string`,`nullable`]]),yY=iY(`ReviewRequest`,[[`requestedReviewer`,`RequestedReviewer`,`nullable`]]),bY=iY(`ReviewRequests`,[[`totalCount`,`int`],[`nodes`,`list<ReviewRequest>`]]),xY=iY(`Review`,[[`author`,`Actor`,`nullable`],[`state`,`string`],[`body`,`string`],[`submittedAt`,`string`,`nullable`],[`commit`,`Commit`,`nullable`]]),SY=iY(`Reviews`,[[`totalCount`,`int`],[`nodes`,`list<Review>`]]),CY=iY(`ReviewThreadComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`]]),wY=iY(`ReviewThreadComments`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThreadComment>`]]),TY=iY(`ReviewThread`,[[`isResolved`,`bool`],[`isOutdated`,`bool`],[`path`,`string`],[`comments`,`ReviewThreadComments`]]),EY=iY(`ReviewThreads`,[[`totalCount`,`int`],[`nodes`,`list<ReviewThread>`]]),DY=iY(`PullRequestComment`,[[`author`,`Actor`,`nullable`],[`body`,`string`],[`createdAt`,`string`]]),OY=iY(`PullRequestComments`,[[`totalCount`,`int`],[`nodes`,`list<PullRequestComment>`]]),kY=iY(`ClosingIssueReference`,[[`number`,`int`],[`state`,`string`]]),AY=iY(`ClosingIssueReferences`,[[`totalCount`,`int`],[`nodes`,`list<ClosingIssueReference>`]]),jY=iY(`StatusCheckRollup`,[[`state`,`string`]]),MY=iY(`PullRequestPayload`,[[`number`,`int`],[`title`,`string`],[`body`,`string`],[`url`,`string`],[`state`,`string`],[`isDraft`,`bool`],[`merged`,`bool`],[`createdAt`,`string`],[`updatedAt`,`string`],[`mergedAt`,`string`,`nullable`],[`author`,`Actor`,`nullable`],[`baseRefName`,`string`],[`headRefName`,`string`],[`headRefOid`,`string`],[`additions`,`int`],[`deletions`,`int`],[`changedFiles`,`int`],[`reviewDecision`,`string`,`nullable`],[`mergeable`,`string`],[`mergeStateStatus`,`string`],[`statusCheckRollup`,`StatusCheckRollup`,`nullable`],[`labels`,`Labels`],[`reviewRequests`,`ReviewRequests`],[`reviews`,`Reviews`],[`reviewThreads`,`ReviewThreads`],[`comments`,`PullRequestComments`],[`closingIssuesReferences`,`ClosingIssueReferences`]]),NY=iY(`Tick`,[[`scheduledAt`,`string`],[`scheduledAtLocal`,`string`],[`cron`,`string`],[`tz`,`string`]]),PY=iY(`SchedulePayload`,[[`tick`,`Tick`]]),FY=(e,t)=>new XH({types:[uY,...e],variables:[new YH({name:`repo`,type:rY(`RepoContext`)}),new YH({name:`item`,type:rY(t)})]}),IY=FY([aY,oY,sY,cY,dY,fY,pY,mY,hY,gY,_Y],`IssuePayload`),LY=FY([aY,oY,lY,dY,vY,yY,bY,xY,SY,CY,wY,TY,EY,DY,OY,kY,AY,jY,MY],`PullRequestPayload`),RY=FY([NY,PY],`SchedulePayload`),zY=e=>{switch(e){case`issue`:return IY;case`pr`:return LY;case`schedule`:return RY}},BY=e=>{let{owner:t}=eA(e.name);return{name:e.name,owner:t,url:`https://github.com/${e.name}`}},VY=Symbol.for(`yaml.alias`),HY=Symbol.for(`yaml.document`),UY=Symbol.for(`yaml.map`),WY=Symbol.for(`yaml.pair`),GY=Symbol.for(`yaml.scalar`),KY=Symbol.for(`yaml.seq`),qY=Symbol.for(`yaml.node.type`),JY=e=>!!e&&typeof e==`object`&&e[qY]===VY,YY=e=>!!e&&typeof e==`object`&&e[qY]===HY,XY=e=>!!e&&typeof e==`object`&&e[qY]===UY,ZY=e=>!!e&&typeof e==`object`&&e[qY]===WY,QY=e=>!!e&&typeof e==`object`&&e[qY]===GY,$Y=e=>!!e&&typeof e==`object`&&e[qY]===KY;function eX(e){if(e&&typeof e==`object`)switch(e[qY]){case UY:case KY:return!0}return!1}function tX(e){if(e&&typeof e==`object`)switch(e[qY]){case VY:case UY:case GY:case KY:return!0}return!1}var nX=e=>(QY(e)||eX(e))&&!!e.anchor,rX=Symbol(`break visit`),iX=Symbol(`skip children`),aX=Symbol(`remove node`);function oX(e,t){let n=cX(t);YY(e)?sX(null,e.contents,n,Object.freeze([e]))===aX&&(e.contents=null):sX(null,e,n,Object.freeze([]))}oX.BREAK=rX,oX.SKIP=iX,oX.REMOVE=aX;function sX(e,t,n,r){let i=lX(e,t,n,r);if(tX(i)||ZY(i))return uX(e,r,i),sX(e,i,n,r);if(typeof i!=`symbol`){if(eX(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=sX(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===rX)return rX;else i===aX&&(t.items.splice(e,1),--e)}}else if(ZY(t)){r=Object.freeze(r.concat(t));let e=sX(`key`,t.key,n,r);if(e===rX)return rX;e===aX&&(t.key=null);let i=sX(`value`,t.value,n,r);if(i===rX)return rX;i===aX&&(t.value=null)}}return i}function cX(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function lX(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(XY(t))return n.Map?.(e,t,r);if($Y(t))return n.Seq?.(e,t,r);if(ZY(t))return n.Pair?.(e,t,r);if(QY(t))return n.Scalar?.(e,t,r);if(JY(t))return n.Alias?.(e,t,r)}function uX(e,t,n){let r=t[t.length-1];if(eX(r))r.items[e]=n;else if(ZY(r))e===`key`?r.key=n:r.value=n;else if(YY(r))r.contents=n;else{let e=JY(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var dX={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},fX=e=>e.replace(/[!,[\]{}]/g,e=>dX[e]),pX=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+fX(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&tX(e.contents)){let t={};oX(e.contents,(e,n)=>{tX(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
172
+ `)}};pX.defaultYaml={explicit:!1,version:`1.2`},pX.defaultTags={"!!":`tag:yaml.org,2002:`};function mX(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function hX(e){let t=new Set;return oX(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function gX(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function _X(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=hX(e);let a=gX(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(QY(t.node)||eX(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}function vX(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=vX(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=vX(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=vX(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=vX(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}function yX(e,t,n){if(Array.isArray(e))return e.map((e,t)=>yX(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!nX(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var bX=class{constructor(e){Object.defineProperty(this,qY,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!YY(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=yX(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?vX(i,{"":o},``,o):o}},xX=class extends bX{constructor(e){super(VY),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],oX(e,{Node:(e,t)=>{(JY(t)||nX(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}if(r&&t){let{anchors:e,doc:n,maxAliasCount:i}=t,a=e.get(r);if(a||=(yX(r,null,t),e.get(r)),a?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=SX(n,r,e)),a.count*a.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return r}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,t,n){let r=`*${this.source}`;if(e){if(mX(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}};function SX(e,t,n){if(JY(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(eX(t)){let r=0;for(let i of t.items){let t=SX(e,i,n);t>r&&(r=t)}return r}if(ZY(t)){let r=SX(e,t.key,n),i=SX(e,t.value,n);return Math.max(r,i)}return 1}var CX=e=>!e||typeof e!=`function`&&typeof e!=`object`,wX=class extends bX{constructor(e){super(GY),this.value=e}toJSON(e,t){return t?.keep?this.value:yX(this.value,e,t)}toString(){return String(this.value)}};wX.BLOCK_FOLDED=`BLOCK_FOLDED`,wX.BLOCK_LITERAL=`BLOCK_LITERAL`,wX.PLAIN=`PLAIN`,wX.QUOTE_DOUBLE=`QUOTE_DOUBLE`,wX.QUOTE_SINGLE=`QUOTE_SINGLE`;var TX=`tag:yaml.org,2002:`;function EX(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function DX(e,t,n){if(YY(e)&&(e=e.contents),tX(e))return e;if(ZY(e)){let t=n.schema[UY].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new xX(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=TX+t.slice(2));let l=EX(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new wX(e);return c&&(c.node=t),t}l=e instanceof Map?o[UY]:Symbol.iterator in Object(e)?o[KY]:o[UY]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new wX(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}function OX(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return DX(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var kX=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,AX=class extends bX{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>tX(t)||ZY(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(kX(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(eX(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,OX(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(eX(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&QY(i)?i.value:i:eX(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ZY(t))return!1;let n=t.value;return n==null||e&&QY(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return eX(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(eX(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,OX(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}},jX=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function MX(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var NX=(e,t,n)=>e.endsWith(`
173
+ `)?MX(n,t):n.includes(`
174
174
  `)?`
175
- `+jX(n,t):(e.endsWith(` `)?``:` `)+n,NX=`flow`,PX=`block`,FX=`quoted`;function IX(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=LX(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
176
- `)n===`block`&&(h=LX(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
175
+ `+MX(n,t):(e.endsWith(` `)?``:` `)+n,PX=`flow`,FX=`block`,IX=`quoted`;function LX(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=RX(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
176
+ `)n===`block`&&(h=RX(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
177
177
  `&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
178
- `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function LX(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
179
- `);r=t,i=t+1,a=e[i]}return r}var RX=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),zX=e=>/^(%|---|\.\.\.)/m.test(e);function BX(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
180
- `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function VX(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(zX(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
178
+ `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function RX(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
179
+ `);r=t,i=t+1,a=e[i]}return r}var zX=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),BX=e=>/^(%|---|\.\.\.)/m.test(e);function VX(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
180
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function HX(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(BX(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
181
181
 
182
182
  `;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
183
- `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:IX(o,a,FX,RX(t,!1))}function HX(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
184
- `)||/[ \t]\n|\n[ \t]/.test(e))return VX(e,t);let n=t.indent||(zX(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:IX(r,n,NX,RX(t,!1))}function UX(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=VX;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?HX:i&&!t?VX:n?HX:VX}return r(e,t)}var WX;try{WX=RegExp(`(^|(?<!
183
+ `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:LX(o,a,IX,zX(t,!1))}function UX(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
184
+ `)||/[ \t]\n|\n[ \t]/.test(e))return HX(e,t);let n=t.indent||(BX(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:LX(r,n,PX,zX(t,!1))}function WX(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=HX;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?UX:i&&!t?HX:n?UX:HX}return r(e,t)}var GX;try{GX=RegExp(`(^|(?<!
185
185
  ))
186
186
  +(?!
187
- |$)`,`g`)}catch{WX=/\n+(?!\n|$)/g}function GX({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return UX(n,r);let l=r.indent||(r.forceBlockIndent||zX(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===CX.BLOCK_FOLDED?!1:t===CX.BLOCK_LITERAL||!BX(n,c,l.length);if(!n)return u?`|
187
+ |$)`,`g`)}catch{GX=/\n+(?!\n|$)/g}function KX({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return WX(n,r);let l=r.indent||(r.forceBlockIndent||BX(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===wX.BLOCK_FOLDED?!1:t===wX.BLOCK_LITERAL||!VX(n,c,l.length);if(!n)return u?`|
188
188
  `:`>
189
189
  `;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
190
190
  `&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
191
191
  `);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
192
- `&&(p=p.slice(0,-1)),p.replace(WX,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
192
+ `&&(p=p.slice(0,-1)),p.replace(GX,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
193
193
  `)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let ee=(h?l?`2`:`1`:``)+d;if(e&&(ee+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
194
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=RX(r,!0);o!==`folded`&&t!==CX.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=IX(`${v}${e}${p}`,l,PX,a);if(!i)return`>${ee}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${ee}\n${l}${v}${n}${p}`}function KX(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
195
- `)||u&&/[[\]{},]/.test(a))return UX(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
196
- `)?UX(a,t):GX(e,t,n,r);if(!s&&!u&&i!==CX.PLAIN&&a.includes(`
197
- `))return GX(e,t,n,r);if(zX(a)){if(c===``)return t.forceBlockIndent=!0,GX(e,t,n,r);if(s&&c===l)return UX(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return UX(a,t)}return s?d:IX(d,c,NX,RX(t,!1))}function qX(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==CX.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=CX.QUOTE_DOUBLE);let c=e=>{switch(e){case CX.BLOCK_FOLDED:case CX.BLOCK_LITERAL:return i||a?UX(o.value,t):GX(o,t,n,r);case CX.QUOTE_DOUBLE:return VX(o.value,t);case CX.QUOTE_SINGLE:return HX(o.value,t);case CX.PLAIN:return KX(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function JX(e,t){let n=Object.assign({blockQuote:!0,commentString:AX,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function YX(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(ZY(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function XX(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(ZY(e)||$Y(e))&&e.anchor;a&&pX(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function ZX(e,t,n,r){if(XY(e))return e.toString(t,n,r);if(qY(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=eX(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=YX(t.doc.schema.tags,a);let o=XX(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):ZY(a)?qX(a,t,n,r):a.toString(t,n,r);return o?ZY(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function QX({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=eX(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if($Y(e)||!eX(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||$Y(e)||(ZY(e)?e.type===CX.BLOCK_FOLDED||e.type===CX.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=ZX(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=MX(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=MX(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=MX(g,n.indent,l(f))));let _,v,ee;eX(t)?(_=!!t.spaceBefore,v=t.commentBefore,ee=t.comment):(_=!1,v=null,ee=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&ZY(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&QY(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let te=!1,ne=ZX(t,n,()=>te=!0,()=>h=!0),re=` `;if(f||_||v){if(re=_?`
198
- `:``,v){let e=l(v);re+=`\n${jX(e,n.indent)}`}ne===``&&!n.inFlow?re===`
194
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=zX(r,!0);o!==`folded`&&t!==wX.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=LX(`${v}${e}${p}`,l,FX,a);if(!i)return`>${ee}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${ee}\n${l}${v}${n}${p}`}function qX(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
195
+ `)||u&&/[[\]{},]/.test(a))return WX(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
196
+ `)?WX(a,t):KX(e,t,n,r);if(!s&&!u&&i!==wX.PLAIN&&a.includes(`
197
+ `))return KX(e,t,n,r);if(BX(a)){if(c===``)return t.forceBlockIndent=!0,KX(e,t,n,r);if(s&&c===l)return WX(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return WX(a,t)}return s?d:LX(d,c,PX,zX(t,!1))}function JX(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==wX.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=wX.QUOTE_DOUBLE);let c=e=>{switch(e){case wX.BLOCK_FOLDED:case wX.BLOCK_LITERAL:return i||a?WX(o.value,t):KX(o,t,n,r);case wX.QUOTE_DOUBLE:return HX(o.value,t);case wX.QUOTE_SINGLE:return UX(o.value,t);case wX.PLAIN:return qX(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}function YX(e,t){let n=Object.assign({blockQuote:!0,commentString:jX,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function XX(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(QY(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function ZX(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(QY(e)||eX(e))&&e.anchor;a&&mX(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function QX(e,t,n,r){if(ZY(e))return e.toString(t,n,r);if(JY(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=tX(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=XX(t.doc.schema.tags,a);let o=ZX(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):QY(a)?JX(a,t,n,r):a.toString(t,n,r);return o?QY(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}function $X({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=tX(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(eX(e)||!tX(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||eX(e)||(QY(e)?e.type===wX.BLOCK_FOLDED||e.type===wX.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=QX(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=NX(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=NX(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=NX(g,n.indent,l(f))));let _,v,ee;tX(t)?(_=!!t.spaceBefore,v=t.commentBefore,ee=t.comment):(_=!1,v=null,ee=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&QY(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&$Y(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let te=!1,ne=QX(t,n,()=>te=!0,()=>h=!0),re=` `;if(f||_||v){if(re=_?`
198
+ `:``,v){let e=l(v);re+=`\n${MX(e,n.indent)}`}ne===``&&!n.inFlow?re===`
199
199
  `&&ee&&(re=`
200
200
 
201
- `):re+=`\n${n.indent}`}else if(!p&&$Y(t)){let e=ne[0],r=ne.indexOf(`
201
+ `):re+=`\n${n.indent}`}else if(!p&&eX(t)){let e=ne[0],r=ne.indexOf(`
202
202
  `),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=ne.indexOf(` `);e===`&`&&n!==-1&&n<r&&ne[n+1]===`!`&&(n=ne.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(re=`\n${n.indent}`)}}else(ne===``||ne[0]===`
203
- `)&&(re=``);return g+=re+ne,n.inFlow?te&&r&&r():ee&&!te?g+=MX(g,n.indent,l(ee)):h&&i&&i(),g}function $X(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var eZ=`<<`,tZ={identify:e=>e===eZ||typeof e==`symbol`&&e.description===eZ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new CX(Symbol(eZ)),{addToJSMap:rZ}),stringify:()=>eZ},nZ=(e,t)=>(tZ.identify(t)||ZY(t)&&(!t.type||t.type===CX.PLAIN)&&tZ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===tZ.tag&&e.default);function rZ(e,t,n){let r=aZ(e,n);if(QY(r))for(let n of r.items)iZ(e,t,n);else if(Array.isArray(r))for(let n of r)iZ(e,t,n);else iZ(e,t,r)}function iZ(e,t,n){let r=aZ(e,n);if(!YY(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function aZ(e,t){return e&&qY(t)?t.resolve(e.doc,e):t}function oZ(e,t,{key:n,value:r}){if(eX(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(nZ(e,n))rZ(e,t,r);else{let i=vX(n,``,e);if(t instanceof Map)t.set(i,vX(r,i,e));else if(t instanceof Set)t.add(i);else{let a=sZ(n,i,e),o=vX(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function sZ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(eX(e)&&n?.doc){let t=JX(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),$X(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function cZ(e,t,n){return new lZ(EX(e,void 0,n),EX(t,void 0,n))}var lZ=class e{constructor(e,t=null){Object.defineProperty(this,KY,{value:UY}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return eX(n)&&(n=n.clone(t)),eX(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return oZ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?QX(this,e,t,n):JSON.stringify(this)}};function uZ(e,t,n){return(t.inFlow??e.flow?fZ:dZ)(e,t,n)}function dZ({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(eX(i))!d&&i.spaceBefore&&f.push(``),pZ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(XY(i)){let e=eX(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),pZ(n,f,e.commentBefore,d))}d=!1;let s=ZX(i,u,()=>o=null,()=>d=!0);o&&(s+=MX(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
203
+ `)&&(re=``);return g+=re+ne,n.inFlow?te&&r&&r():ee&&!te?g+=NX(g,n.indent,l(ee)):h&&i&&i(),g}function eZ(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var tZ=`<<`,nZ={identify:e=>e===tZ||typeof e==`symbol`&&e.description===tZ,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new wX(Symbol(tZ)),{addToJSMap:iZ}),stringify:()=>tZ},rZ=(e,t)=>(nZ.identify(t)||QY(t)&&(!t.type||t.type===wX.PLAIN)&&nZ.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===nZ.tag&&e.default);function iZ(e,t,n){let r=oZ(e,n);if($Y(r))for(let n of r.items)aZ(e,t,n);else if(Array.isArray(r))for(let n of r)aZ(e,t,n);else aZ(e,t,r)}function aZ(e,t,n){let r=oZ(e,n);if(!XY(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function oZ(e,t){return e&&JY(t)?t.resolve(e.doc,e):t}function sZ(e,t,{key:n,value:r}){if(tX(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(rZ(e,n))iZ(e,t,r);else{let i=yX(n,``,e);if(t instanceof Map)t.set(i,yX(r,i,e));else if(t instanceof Set)t.add(i);else{let a=cZ(n,i,e),o=yX(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function cZ(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(tX(e)&&n?.doc){let t=YX(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),eZ(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}function lZ(e,t,n){return new uZ(DX(e,void 0,n),DX(t,void 0,n))}var uZ=class e{constructor(e,t=null){Object.defineProperty(this,qY,{value:WY}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return tX(n)&&(n=n.clone(t)),tX(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return sZ(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?$X(this,e,t,n):JSON.stringify(this)}};function dZ(e,t,n){return(t.inFlow??e.flow?pZ:fZ)(e,t,n)}function fZ({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(tX(i))!d&&i.spaceBefore&&f.push(``),mZ(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(ZY(i)){let e=tX(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),mZ(n,f,e.commentBefore,d))}d=!1;let s=QX(i,u,()=>o=null,()=>d=!0);o&&(s+=NX(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
204
204
  `}}return e?(p+=`
205
- `+jX(l(e),c),s&&s()):d&&o&&o(),p}function fZ({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(eX(i))i.spaceBefore&&d.push(``),pZ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(XY(i)){let e=eX(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),pZ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=eX(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=ZX(i,c,()=>a=null);l||=d.length>u||o.includes(`
206
- `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=MX(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
207
- `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function pZ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=jX(t(r),e);n.push(i.trimStart())}}function mZ(e,t){let n=ZY(t)?t.value:t;for(let r of e)if(XY(r)&&(r.key===t||r.key===n||ZY(r.key)&&r.key.value===n))return r}var hZ=class extends kX{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(HY,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(cZ(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=XY(e)?e:!e||typeof e!=`object`||!(`key`in e)?new lZ(e,e?.value):new lZ(e.key,e.value);let r=mZ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);ZY(r.value)&&SX(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=mZ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=mZ(this.items,e)?.value;return(!t&&ZY(n)?n.value:n)??void 0}has(e){return!!mZ(this.items,e)}set(e,t){this.add(new lZ(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)oZ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!XY(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),uZ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},gZ={collection:`map`,default:!0,nodeClass:hZ,tag:`tag:yaml.org,2002:map`,resolve(e,t){return YY(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>hZ.from(e,t,n)},_Z=class extends kX{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(GY,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=vZ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=vZ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&ZY(r)?r.value:r}has(e){let t=vZ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=vZ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];ZY(r)&&SX(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(vX(e,String(r++),t));return n}toString(e,t,n){return e?uZ(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(EX(a,void 0,n))}}return i}};function vZ(e){let t=ZY(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var yZ={collection:`seq`,default:!0,nodeClass:_Z,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return QY(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>_Z.from(e,t,n)},bZ={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),qX(e,t,n,r)}},xZ={identify:e=>e==null,createNode:()=>new CX(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new CX(null),stringify:({source:e},t)=>typeof e==`string`&&xZ.test.test(e)?e:t.options.nullStr},SZ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new CX(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&SZ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function CZ({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var wZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:CZ},TZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():CZ(e)}},EZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new CX(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:CZ},DZ=e=>typeof e==`bigint`||Number.isInteger(e),OZ=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function kZ(e,t,n){let{value:r}=e;return DZ(r)&&r>=0?n+r.toString(t):CZ(e)}var AZ={identify:e=>DZ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>OZ(e,2,8,n),stringify:e=>kZ(e,8,`0o`)},jZ={identify:DZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>OZ(e,0,10,n),stringify:CZ},MZ={identify:e=>DZ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>OZ(e,2,16,n),stringify:e=>kZ(e,16,`0x`)},NZ=[gZ,yZ,bZ,xZ,SZ,AZ,jZ,MZ,wZ,TZ,EZ];function PZ(e){return typeof e==`bigint`||Number.isInteger(e)}var FZ=({value:e})=>JSON.stringify(e),IZ=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:FZ},{identify:e=>e==null,createNode:()=>new CX(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:FZ},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:FZ},{identify:PZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>PZ(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:FZ}],LZ=[gZ,yZ].concat(IZ,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),RZ={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=CX.BLOCK_LITERAL,t!==CX.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===CX.BLOCK_LITERAL?`
208
- `:` `)}return qX({comment:e,type:t,value:s},r,i,a)}};function zZ(e,t){if(QY(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!XY(r)){if(YY(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new lZ(new CX(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=XY(r)?r:new lZ(r)}}else t(`Expected a sequence for this tag`);return e}function BZ(e,t,n){let{replacer:r}=n,i=new _Z(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(cZ(o,s,n))}return i}var VZ={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:zZ,createNode:BZ},HZ=class e extends _Z{constructor(){super(),this.add=hZ.prototype.add.bind(this),this.delete=hZ.prototype.delete.bind(this),this.get=hZ.prototype.get.bind(this),this.has=hZ.prototype.has.bind(this),this.set=hZ.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(XY(e)?(r=vX(e.key,``,t),i=vX(e.value,r,t)):r=vX(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=BZ(e,t,n),i=new this;return i.items=r.items,i}};HZ.tag=`tag:yaml.org,2002:omap`;var UZ={collection:`seq`,identify:e=>e instanceof Map,nodeClass:HZ,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=zZ(e,t),r=[];for(let{key:e}of n.items)ZY(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new HZ,n)},createNode:(e,t,n)=>HZ.from(e,t,n)};function WZ({value:e,source:t},n){return t&&(e?GZ:KZ).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var GZ={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new CX(!0),stringify:WZ},KZ={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new CX(!1),stringify:WZ},qZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:CZ},JZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():CZ(e)}},YZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new CX(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:CZ},XZ=e=>typeof e==`bigint`||Number.isInteger(e);function ZZ(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function QZ(e,t,n){let{value:r}=e;if(XZ(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return CZ(e)}var $Z={identify:XZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>ZZ(e,2,2,n),stringify:e=>QZ(e,2,`0b`)},eQ={identify:XZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>ZZ(e,1,8,n),stringify:e=>QZ(e,8,`0`)},tQ={identify:XZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>ZZ(e,0,10,n),stringify:CZ},nQ={identify:XZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>ZZ(e,2,16,n),stringify:e=>QZ(e,16,`0x`)},rQ=class e extends hZ{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=XY(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new lZ(e.key,null):new lZ(e,null),mZ(this.items,t.key)||this.items.push(t)}get(e,t){let n=mZ(this.items,e);return!t&&XY(n)?ZY(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=mZ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new lZ(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(cZ(e,null,n));return i}};rQ.tag=`tag:yaml.org,2002:set`;var iQ={collection:`map`,identify:e=>e instanceof Set,nodeClass:rQ,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>rQ.from(e,t,n),resolve(e,t){if(YY(e)){if(e.hasAllNullValues(!0))return Object.assign(new rQ,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function aQ(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function oQ(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return CZ(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var sQ={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>aQ(e,n),stringify:oQ},cQ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>aQ(e,!1),stringify:oQ},lQ={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(lQ.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=aQ(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``},uQ=[gZ,yZ,bZ,xZ,GZ,KZ,$Z,eQ,tQ,nQ,qZ,JZ,YZ,RZ,tZ,UZ,VZ,iQ,sQ,cQ,lQ],dQ=new Map([[`core`,NZ],[`failsafe`,[gZ,yZ,bZ]],[`json`,LZ],[`yaml11`,uQ],[`yaml-1.1`,uQ]]),fQ={binary:RZ,bool:SZ,float:EZ,floatExp:TZ,floatNaN:wZ,floatTime:cQ,int:jZ,intHex:MZ,intOct:AZ,intTime:sQ,map:gZ,merge:tZ,null:xZ,omap:UZ,pairs:VZ,seq:yZ,set:iQ,timestamp:lQ},pQ={"tag:yaml.org,2002:binary":RZ,"tag:yaml.org,2002:merge":tZ,"tag:yaml.org,2002:omap":UZ,"tag:yaml.org,2002:pairs":VZ,"tag:yaml.org,2002:set":iQ,"tag:yaml.org,2002:timestamp":lQ};function mQ(e,t,n){let r=dQ.get(t);if(r&&!e)return n&&!r.includes(tZ)?r.concat(tZ):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(dQ.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(tZ)),i.reduce((e,t)=>{let n=typeof t==`string`?fQ[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(fQ).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var hQ=(e,t)=>e.key<t.key?-1:+(e.key>t.key),gQ=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?mQ(e,`compat`):e?mQ(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?pQ:{},this.tags=mQ(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,HY,{value:gZ}),Object.defineProperty(this,WY,{value:bZ}),Object.defineProperty(this,GY,{value:yZ}),this.sortMapEntries=typeof a==`function`?a:a===!0?hQ:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function _Q(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=JX(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(jX(t,``))}let o=!1,s=null;if(e.contents){if(eX(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(jX(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=ZX(e.contents,i,()=>s=null,t);s&&(c+=MX(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(ZX(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
209
- `)?(n.push(`...`),n.push(jX(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(jX(a(t),``)))}return n.join(`
205
+ `+MX(l(e),c),s&&s()):d&&o&&o(),p}function pZ({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(tX(i))i.spaceBefore&&d.push(``),mZ(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(ZY(i)){let e=tX(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),mZ(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=tX(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=QX(i,c,()=>a=null);l||=d.length>u||o.includes(`
206
+ `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=NX(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
207
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function mZ({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=MX(t(r),e);n.push(i.trimStart())}}function hZ(e,t){let n=QY(t)?t.value:t;for(let r of e)if(ZY(r)&&(r.key===t||r.key===n||QY(r.key)&&r.key.value===n))return r}var gZ=class extends AX{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(UY,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(lZ(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=ZY(e)?e:!e||typeof e!=`object`||!(`key`in e)?new uZ(e,e?.value):new uZ(e.key,e.value);let r=hZ(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);QY(r.value)&&CX(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=hZ(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=hZ(this.items,e)?.value;return(!t&&QY(n)?n.value:n)??void 0}has(e){return!!hZ(this.items,e)}set(e,t){this.add(new uZ(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)sZ(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!ZY(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),dZ(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}},_Z={collection:`map`,default:!0,nodeClass:gZ,tag:`tag:yaml.org,2002:map`,resolve(e,t){return XY(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>gZ.from(e,t,n)},vZ=class extends AX{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(KY,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=yZ(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=yZ(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&QY(r)?r.value:r}has(e){let t=yZ(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=yZ(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];QY(r)&&CX(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(yX(e,String(r++),t));return n}toString(e,t,n){return e?dZ(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(DX(a,void 0,n))}}return i}};function yZ(e){let t=QY(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var bZ={collection:`seq`,default:!0,nodeClass:vZ,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return $Y(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>vZ.from(e,t,n)},xZ={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),JX(e,t,n,r)}},SZ={identify:e=>e==null,createNode:()=>new wX(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new wX(null),stringify:({source:e},t)=>typeof e==`string`&&SZ.test.test(e)?e:t.options.nullStr},CZ={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new wX(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&CZ.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}};function wZ({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var TZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:wZ},EZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():wZ(e)}},DZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new wX(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:wZ},OZ=e=>typeof e==`bigint`||Number.isInteger(e),kZ=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function AZ(e,t,n){let{value:r}=e;return OZ(r)&&r>=0?n+r.toString(t):wZ(e)}var jZ={identify:e=>OZ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>kZ(e,2,8,n),stringify:e=>AZ(e,8,`0o`)},MZ={identify:OZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>kZ(e,0,10,n),stringify:wZ},NZ={identify:e=>OZ(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>kZ(e,2,16,n),stringify:e=>AZ(e,16,`0x`)},PZ=[_Z,bZ,xZ,SZ,CZ,jZ,MZ,NZ,TZ,EZ,DZ];function FZ(e){return typeof e==`bigint`||Number.isInteger(e)}var IZ=({value:e})=>JSON.stringify(e),LZ=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:IZ},{identify:e=>e==null,createNode:()=>new wX(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:IZ},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:IZ},{identify:FZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>FZ(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:IZ}],RZ=[_Z,bZ].concat(LZ,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}}),zZ={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=wX.BLOCK_LITERAL,t!==wX.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===wX.BLOCK_LITERAL?`
208
+ `:` `)}return JX({comment:e,type:t,value:s},r,i,a)}};function BZ(e,t){if($Y(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!ZY(r)){if(XY(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new uZ(new wX(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=ZY(r)?r:new uZ(r)}}else t(`Expected a sequence for this tag`);return e}function VZ(e,t,n){let{replacer:r}=n,i=new vZ(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(lZ(o,s,n))}return i}var HZ={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:BZ,createNode:VZ},UZ=class e extends vZ{constructor(){super(),this.add=gZ.prototype.add.bind(this),this.delete=gZ.prototype.delete.bind(this),this.get=gZ.prototype.get.bind(this),this.has=gZ.prototype.has.bind(this),this.set=gZ.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(ZY(e)?(r=yX(e.key,``,t),i=yX(e.value,r,t)):r=yX(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=VZ(e,t,n),i=new this;return i.items=r.items,i}};UZ.tag=`tag:yaml.org,2002:omap`;var WZ={collection:`seq`,identify:e=>e instanceof Map,nodeClass:UZ,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=BZ(e,t),r=[];for(let{key:e}of n.items)QY(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new UZ,n)},createNode:(e,t,n)=>UZ.from(e,t,n)};function GZ({value:e,source:t},n){return t&&(e?KZ:qZ).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var KZ={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new wX(!0),stringify:GZ},qZ={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new wX(!1),stringify:GZ},JZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:wZ},YZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():wZ(e)}},XZ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new wX(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:wZ},ZZ=e=>typeof e==`bigint`||Number.isInteger(e);function QZ(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function $Z(e,t,n){let{value:r}=e;if(ZZ(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return wZ(e)}var eQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>QZ(e,2,2,n),stringify:e=>$Z(e,2,`0b`)},tQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>QZ(e,1,8,n),stringify:e=>$Z(e,8,`0`)},nQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>QZ(e,0,10,n),stringify:wZ},rQ={identify:ZZ,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>QZ(e,2,16,n),stringify:e=>$Z(e,16,`0x`)},iQ=class e extends gZ{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=ZY(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new uZ(e.key,null):new uZ(e,null),hZ(this.items,t.key)||this.items.push(t)}get(e,t){let n=hZ(this.items,e);return!t&&ZY(n)?QY(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=hZ(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new uZ(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(lZ(e,null,n));return i}};iQ.tag=`tag:yaml.org,2002:set`;var aQ={collection:`map`,identify:e=>e instanceof Set,nodeClass:iQ,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>iQ.from(e,t,n),resolve(e,t){if(XY(e)){if(e.hasAllNullValues(!0))return Object.assign(new iQ,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}};function oQ(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function sQ(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return wZ(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var cQ={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>oQ(e,n),stringify:sQ},lQ={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>oQ(e,!1),stringify:sQ},uQ={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(uQ.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=oQ(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``},dQ=[_Z,bZ,xZ,SZ,KZ,qZ,eQ,tQ,nQ,rQ,JZ,YZ,XZ,zZ,nZ,WZ,HZ,aQ,cQ,lQ,uQ],fQ=new Map([[`core`,PZ],[`failsafe`,[_Z,bZ,xZ]],[`json`,RZ],[`yaml11`,dQ],[`yaml-1.1`,dQ]]),pQ={binary:zZ,bool:CZ,float:DZ,floatExp:EZ,floatNaN:TZ,floatTime:lQ,int:MZ,intHex:NZ,intOct:jZ,intTime:cQ,map:_Z,merge:nZ,null:SZ,omap:WZ,pairs:HZ,seq:bZ,set:aQ,timestamp:uQ},mQ={"tag:yaml.org,2002:binary":zZ,"tag:yaml.org,2002:merge":nZ,"tag:yaml.org,2002:omap":WZ,"tag:yaml.org,2002:pairs":HZ,"tag:yaml.org,2002:set":aQ,"tag:yaml.org,2002:timestamp":uQ};function hQ(e,t,n){let r=fQ.get(t);if(r&&!e)return n&&!r.includes(nZ)?r.concat(nZ):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(fQ.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(nZ)),i.reduce((e,t)=>{let n=typeof t==`string`?pQ[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(pQ).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var gQ=(e,t)=>e.key<t.key?-1:+(e.key>t.key),_Q=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?hQ(e,`compat`):e?hQ(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?mQ:{},this.tags=hQ(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,UY,{value:_Z}),Object.defineProperty(this,GY,{value:xZ}),Object.defineProperty(this,KY,{value:bZ}),this.sortMapEntries=typeof a==`function`?a:a===!0?gQ:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}};function vQ(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=YX(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(MX(t,``))}let o=!1,s=null;if(e.contents){if(tX(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(MX(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=QX(e.contents,i,()=>s=null,t);s&&(c+=NX(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(QX(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
209
+ `)?(n.push(`...`),n.push(MX(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(MX(a(t),``)))}return n.join(`
210
210
  `)+`
211
- `}var vQ=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,KY,{value:VY});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new fX({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[KY]:{value:VY}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=eX(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){yQ(this.contents)&&this.contents.add(e)}addIn(e,t){yQ(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=mX(this);e.anchor=!t||n.has(t)?hX(t||`a`,n):t}return new bX(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=gX(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=EX(e,l,p);return o&&$Y(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new lZ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return yQ(this.contents)?this.contents.delete(e):!1}deleteIn(e){return OX(e)?this.contents!=null&&(this.contents=null,!0):yQ(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return $Y(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return OX(e)?!t&&ZY(this.contents)?this.contents.value:this.contents:$Y(this.contents)?this.contents.getIn(e,t):void 0}has(e){return $Y(this.contents)?this.contents.has(e):!1}hasIn(e){return OX(e)?this.contents!==void 0:$Y(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=DX(this.schema,[e],t):yQ(this.contents)&&this.contents.set(e,t)}setIn(e,t){OX(e)?this.contents=t:this.contents==null?this.contents=DX(this.schema,Array.from(e),t):yQ(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new fX({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new fX({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new gQ(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=vX(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?_X(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return _Q(this,e)}};function yQ(e){if($Y(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var bQ=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},xQ=class extends bQ{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},SQ=class extends bQ{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},CQ=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
212
- `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function wQ(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,ee=null,te=null,ne=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!te||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),te&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),te=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){ee&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),ee=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let re=e[e.length-1],ie=re?re.offset+re.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:ee,found:te,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:ie,start:ne??ie}}function TQ(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
213
- `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(TQ(t.key)||TQ(t.value))return!0}return!1;default:return!0}}function EQ(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&TQ(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function DQ(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||ZY(e)&&ZY(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var OQ=`All mapping items must start at the same column`;function kQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??hZ)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=wQ(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,OQ)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
214
- `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||TQ(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,OQ);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&EQ(r.indent,u,i),n.atKey=!1,DQ(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=wQ(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&EQ(r.indent,f,i),s=c.range[2];let l=new lZ(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
215
- `+_.comment:g.comment=_.comment);let e=new lZ(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function AQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??_Z)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=wQ(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&EQ(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function jQ(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var MQ=`Block collections are not allowed within flow collections`,NQ=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function PQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?hZ:_Z))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=wQ(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
216
- `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&TQ(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];XY(t)&&(t=t.value??t.key),t.comment?t.comment+=`
217
- `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],NQ(m)&&i(r.range,`BLOCK_IN_FLOW`,MQ)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);NQ(f)&&i(g.range,`BLOCK_IN_FLOW`,MQ),n.atKey=!1;let _=wQ(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?NQ(m)&&i(v.range,`BLOCK_IN_FLOW`,MQ):_.comment&&(g.comment?g.comment+=`
218
- `+_.comment:g.comment=_.comment);let ee=new lZ(g,v);if(n.options.keepSourceTokens&&(ee.srcToken=l),o){let e=c;DQ(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(ee)}else{let e=new hZ(n.schema);e.flow=!0,e.items.push(ee);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=jQ(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
219
- `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function FQ(e,t,n,r,i,a){let o=n.type===`block-map`?kQ(e,t,n,r,a):n.type===`block-seq`?AQ(e,t,n,r,a):PQ(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function IQ(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===hZ.tagName&&s===`map`||o===_Z.tagName&&s===`seq`)return FQ(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),FQ(e,t,n,i,o)}let l=FQ(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=eX(u)?u:new CX(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function LQ(e,t,n){let r=t.offset,i=RQ(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?CX.BLOCK_FOLDED:CX.BLOCK_LITERAL,o=t.source?zQ(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
211
+ `}var yQ=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,qY,{value:HY});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new pX({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[qY]:{value:HY}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=tX(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){bQ(this.contents)&&this.contents.add(e)}addIn(e,t){bQ(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=hX(this);e.anchor=!t||n.has(t)?gX(t||`a`,n):t}return new xX(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=_X(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=DX(e,l,p);return o&&eX(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){return new uZ(this.createNode(e,null,n),this.createNode(t,null,n))}delete(e){return bQ(this.contents)?this.contents.delete(e):!1}deleteIn(e){return kX(e)?this.contents!=null&&(this.contents=null,!0):bQ(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return eX(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return kX(e)?!t&&QY(this.contents)?this.contents.value:this.contents:eX(this.contents)?this.contents.getIn(e,t):void 0}has(e){return eX(this.contents)?this.contents.has(e):!1}hasIn(e){return kX(e)?this.contents!==void 0:eX(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=OX(this.schema,[e],t):bQ(this.contents)&&this.contents.set(e,t)}setIn(e,t){kX(e)?this.contents=t:this.contents==null?this.contents=OX(this.schema,Array.from(e),t):bQ(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new pX({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new pX({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new _Q(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=yX(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?vX(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return vQ(this,e)}};function bQ(e){if(eX(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var xQ=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},SQ=class extends xQ{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},CQ=class extends xQ{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},wQ=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
212
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}};function TQ(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,ee=null,te=null,ne=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!te||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,ne??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),te&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),te=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){ee&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),ee=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let re=e[e.length-1],ie=re?re.offset+re.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:ee,found:te,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:ie,start:ne??ie}}function EQ(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
213
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(EQ(t.key)||EQ(t.value))return!0}return!1;default:return!0}}function DQ(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&EQ(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}function OQ(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||QY(e)&&QY(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var kQ=`All mapping items must start at the same column`;function AQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??gZ)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=TQ(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,kQ)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
214
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||EQ(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,kQ);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&DQ(r.indent,u,i),n.atKey=!1,OQ(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=TQ(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&DQ(r.indent,f,i),s=c.range[2];let l=new uZ(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
215
+ `+_.comment:g.comment=_.comment);let e=new uZ(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}function jQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??vZ)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=TQ(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&DQ(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}function MQ(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var NQ=`Block collections are not allowed within flow collections`,PQ=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function FQ({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?gZ:vZ))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=TQ(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
216
+ `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&EQ(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];ZY(t)&&(t=t.value??t.key),t.comment?t.comment+=`
217
+ `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],PQ(m)&&i(r.range,`BLOCK_IN_FLOW`,NQ)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);PQ(f)&&i(g.range,`BLOCK_IN_FLOW`,NQ),n.atKey=!1;let _=TQ(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?PQ(m)&&i(v.range,`BLOCK_IN_FLOW`,NQ):_.comment&&(g.comment?g.comment+=`
218
+ `+_.comment:g.comment=_.comment);let ee=new uZ(g,v);if(n.options.keepSourceTokens&&(ee.srcToken=l),o){let e=c;OQ(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(ee)}else{let e=new gZ(n.schema);e.flow=!0,e.items.push(ee);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=MQ(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
219
+ `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}function IQ(e,t,n,r,i,a){let o=n.type===`block-map`?AQ(e,t,n,r,a):n.type===`block-seq`?jQ(e,t,n,r,a):FQ(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function LQ(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===gZ.tagName&&s===`map`||o===vZ.tagName&&s===`seq`)return IQ(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),IQ(e,t,n,i,o)}let l=IQ(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=tX(u)?u:new wX(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function RQ(e,t,n){let r=t.offset,i=zQ(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?wX.BLOCK_FOLDED:wX.BLOCK_LITERAL,o=t.source?BQ(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
220
220
  `.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
221
- `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===CX.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
221
+ `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===wX.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
222
222
  `):t.length>c||r[0]===` `?(f===` `?f=`
223
223
  `:!p&&f===`
224
224
  `&&(f=`
@@ -231,67 +231,75 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
231
231
  `+o[e][0].slice(c);d[d.length-1]!==`
232
232
  `&&(d+=`
233
233
  `);break;default:d+=`
234
- `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function RQ({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function zQ(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function BQ(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=CX.PLAIN,c=VQ(a,l);break;case`single-quoted-scalar`:s=CX.QUOTE_SINGLE,c=HQ(a,l);break;case`double-quoted-scalar`:s=CX.QUOTE_DOUBLE,c=WQ(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=jQ(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function VQ(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),UQ(e)}function HQ(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),UQ(e.slice(1,-1)).replace(/''/g,`'`)}function UQ(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
234
+ `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function zQ({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function BQ(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}function VQ(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=wX.PLAIN,c=HQ(a,l);break;case`single-quoted-scalar`:s=wX.QUOTE_SINGLE,c=UQ(a,l);break;case`double-quoted-scalar`:s=wX.QUOTE_DOUBLE,c=GQ(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=MQ(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function HQ(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),WQ(e)}function UQ(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),WQ(e.slice(1,-1)).replace(/''/g,`'`)}function WQ(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
235
235
  `?a+=o:o=`
236
- `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function WQ(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
236
+ `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function GQ(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
237
237
  `){if(i===`
238
- `){let{fold:t,offset:i}=GQ(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=KQ[i];if(a)n+=a;else if(i===`
238
+ `){let{fold:t,offset:i}=KQ(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=qQ[i];if(a)n+=a;else if(i===`
239
239
  `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
240
- `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=qQ(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
240
+ `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=JQ(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
241
241
  `&&(a!==`\r`||e[r+2]!==`
242
- `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function GQ(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
242
+ `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function KQ(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
243
243
  `||r===`\r`)&&(r!==`\r`||e[t+2]===`
244
244
  `);)r===`
245
245
  `&&(n+=`
246
- `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var KQ={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
247
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function qQ(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function JQ(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?LQ(e,t,r):BQ(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[WY]:c?YQ(e.schema,i,c,n,r):t.type===`scalar`?XQ(e,i,t,r):e.schema[WY];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=ZY(a)?a:new CX(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new CX(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function YQ(e,t,n,r,i){if(n===`!`)return e[WY];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[WY])}function XQ({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[WY];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[WY];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function ZQ(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var QQ={composeNode:$Q,composeEmptyNode:e$};function $Q(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=t$(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=JQ(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=IQ(QQ,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=e$(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!ZY(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function e$(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=JQ(e,{type:`scalar`,offset:ZQ(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function t$({options:e},{offset:t,source:n,end:r},i){let a=new bX(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=jQ(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function n$(e,t,{offset:n,start:r,value:i,end:a},o){let s=new vQ(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=wQ(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?$Q(c,i,l,o):e$(c,l.end,r,null,l,o);let u=s.contents.range[2],d=jQ(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function r$(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function i$(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
246
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}var qQ={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
247
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function JQ(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}function YQ(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?RQ(e,t,r):VQ(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[GY]:c?XQ(e.schema,i,c,n,r):t.type===`scalar`?ZQ(e,i,t,r):e.schema[GY];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=QY(a)?a:new wX(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new wX(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function XQ(e,t,n,r,i){if(n===`!`)return e[GY];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[GY])}function ZQ({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[GY];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[GY];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}function QQ(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var $Q={composeNode:e$,composeEmptyNode:t$};function e$(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=n$(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=YQ(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=LQ($Q,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=t$(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!QY(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function t$(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=YQ(e,{type:`scalar`,offset:QQ(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function n$({options:e},{offset:t,source:n,end:r},i){let a=new xX(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=MQ(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}function r$(e,t,{offset:n,start:r,value:i,end:a},o){let s=new yQ(void 0,Object.assign({_directives:t},e)),c={atKey:!1,atRoot:!0,directives:s.directives,options:s.options,schema:s.schema},l=TQ(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});l.found&&(s.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!l.hasNewline&&o(l.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),s.contents=i?e$(c,i,l,o):t$(c,l.end,r,null,l,o);let u=s.contents.range[2],d=MQ(a,u,!1,o);return d.comment&&(s.comment=d.comment),s.range=[n,u,d.offset],s}function i$(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function a$(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
248
248
 
249
249
  `:`
250
- `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var a$=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=r$(e);r?this.warnings.push(new SQ(i,t,n)):this.errors.push(new xQ(i,t,n))},this.directives=new fX({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=i$(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if($Y(i)&&!i.flow&&i.items.length>0){let e=i.items[0];XY(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:i$(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=r$(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=n$(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new xQ(r$(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new xQ(r$(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=jQ(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new xQ(r$(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new vQ(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},o$=Symbol(`break visit`),s$=Symbol(`skip children`),c$=Symbol(`remove item`);function l$(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),u$(Object.freeze([]),e,t)}l$.BREAK=o$,l$.SKIP=s$,l$.REMOVE=c$,l$.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},l$.parentCollection=(e,t)=>{let n=l$.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function u$(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=u$(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===o$)return o$;else r===c$&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function d$(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
250
+ `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var o$=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=i$(e);r?this.warnings.push(new CQ(i,t,n)):this.errors.push(new SQ(i,t,n))},this.directives=new pX({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=a$(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(eX(i)&&!i.flow&&i.items.length>0){let e=i.items[0];ZY(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:a$(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=i$(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=r$(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new SQ(i$(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new SQ(i$(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=MQ(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new SQ(i$(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=new yQ(void 0,Object.assign({_directives:this.directives},this.options));this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),e.range=[0,t,t],this.decorate(e,!1),yield e}}},s$=Symbol(`break visit`),c$=Symbol(`skip children`),l$=Symbol(`remove item`);function u$(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),d$(Object.freeze([]),e,t)}u$.BREAK=s$,u$.SKIP=c$,u$.REMOVE=l$,u$.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},u$.parentCollection=(e,t)=>{let n=u$.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function d$(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=d$(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===s$)return s$;else r===l$&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}function f$(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
251
251
  `:case`\r
252
- `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function f$(e){switch(e){case void 0:case` `:case`
253
- `:case`\r`:case` `:return!0;default:return!1}}var p$=new Set(`0123456789ABCDEFabcdef`),m$=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),h$=new Set(`,[]{}`),g$=new Set(` ,[]{}
254
- \r `),_$=e=>!e||g$.has(e),v$=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
252
+ `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}function p$(e){switch(e){case void 0:case` `:case`
253
+ `:case`\r`:case` `:return!0;default:return!1}}var m$=new Set(`0123456789ABCDEFabcdef`),h$=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),g$=new Set(`,[]{}`),_$=new Set(` ,[]{}
254
+ \r `),v$=e=>!e||_$.has(e),y$=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
255
255
  `||t===`\r`&&this.buffer[e+1]===`
256
256
  `}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
257
257
  `||!t&&!this.atEnd)return e+n+1}return t===`
258
- `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&f$(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
259
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&f$(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!f$(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&f$(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(_$),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&f$(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(_$),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||f$(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
258
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&p$(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
259
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&p$(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!p$(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&p$(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(v$),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&p$(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(v$),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||p$(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
260
260
  `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
261
- `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>f$(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
261
+ `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>p$(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
262
262
  `:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
263
263
  `)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
264
264
  `,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
265
265
  `;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
266
- `&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(f$(r)||e&&h$.has(r))break;t=n}else if(f$(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
266
+ `&&n>=this.pos&&n+1+t>i)e=n;else break}while(1);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(p$(r)||e&&g$.has(r))break;t=n}else if(p$(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
267
267
  `?(n+=1,r=`
268
- `,i=this.buffer[n+1]):t=n),i===`#`||e&&h$.has(i))break;if(r===`
269
- `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&h$.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(_$),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(f$(n)||t&&h$.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!f$(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(m$.has(t))t=this.buffer[++e];else if(t===`%`&&p$.has(this.buffer[e+1])&&p$.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
268
+ `,i=this.buffer[n+1]):t=n),i===`#`||e&&g$.has(i))break;if(r===`
269
+ `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&g$.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(v$),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(p$(n)||t&&g$.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!p$(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(h$.has(t))t=this.buffer[++e];else if(t===`%`&&m$.has(this.buffer[e+1])&&m$.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
270
270
  `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
271
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},y$=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function b$(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function x$(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function S$(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function C$(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function w$(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function T$(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function E$(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!b$(t.start,`explicit-key-ind`)&&!b$(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,S$(t.value)?t.value.end?T$(t.value.end,t.sep):t.value.end=t.sep:T$(t.start,t.sep),delete t.sep)}var D$=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new v$,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=d$(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&E$(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&x$(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:x$(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=w$(C$(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
271
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}},b$=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};function x$(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function S$(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function C$(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function w$(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function T$(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function E$(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function D$(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!x$(t.start,`explicit-key-ind`)&&!x$(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,C$(t.value)?t.value.end?E$(t.value.end,t.sep):t.value.end=t.sep:E$(t.start,t.sep),delete t.sep)}var O$=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new y$,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=f$(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source})}else{if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&D$(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&S$(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:S$(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=T$(w$(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
272
272
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
273
- `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){T$(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(b$(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=w$(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(b$(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(S$(t.key)&&!b$(t.sep,`newline`)){let e=w$(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):b$(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!b$(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){T$(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||b$(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=w$(C$(t));E$(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
273
+ `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){E$(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(x$(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=T$(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(x$(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(C$(t.key)&&!x$(t.sep,`newline`)){let e=T$(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):x$(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!x$(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){E$(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||x$(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=T$(w$(t));D$(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
274
274
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
275
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=w$(C$(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=w$(C$(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function O$(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new y$||null,prettyErrors:t}}function k$(e,t={}){let{lineCounter:n,prettyErrors:r}=O$(t),i=new D$(n?.addNewLine),a=new a$(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new xQ(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(CQ(e,n)),o.warnings.forEach(CQ(e,n))),o}var A$=e=>vr(Ww(M({message:z}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),j$=(e,t)=>T(function*(){let n=yield*qh({try:()=>k$(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new rU({file:e,stage:`yaml`,expression:y(),message:A$(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new rU({file:e,stage:`yaml`,expression:y(),message:r.message})}),M$=Yy(),N$=P([j,lT]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(ST(ZH,{decode:sb(e=>String(e)),encode:sb(e=>e)})),P$=P([HJ.mapFields(Tw({if:N$})).pipe(ST(HJ)),UJ.mapFields(Tw({if:N$})).pipe(ST(UJ)),WJ.mapFields(Tw({if:N$})).pipe(ST(WJ))]),F$=class extends V(`@usine/config/LoopFrontmatter`)({trigger:P$,selector:xE(RJ),approval:sA.pipe(DT(w(`none`))),step:wN.pipe(DT(w(`run`))),agent:fN,maxCycles:XJ.fields.maxCycles,permissions:XJ.fields.permissions,priority:xE(YJ)}){}.pipe(mT({maxCycles:`max_cycles`})),I$=class extends V(`@usine/config/AgentFrontmatter`)({harness:lN,model:cN,effort:uN,parentModel:xE(cN),parentEffort:xE(uN)}){}.pipe(mT({parentModel:`parent_model`,parentEffort:`parent_effort`})),L$=(e,t)=>rU.fromSchema(e,t),R$=Hw(IE),z$=(e,t)=>T(function*(){return yield*R$((yield*j$(e,t)).toJS()).pipe(dg(t=>new rU({file:e,stage:`yaml`,expression:y(),message:M$(t.issue)})))}),B$=(e,t,n)=>new rU({file:e,stage:`expression`,expression:b(t.source),message:t.message,details:[{path:n,message:t.message}]}),V$=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?w(t.slice(0,-3)):new rU({file:e,stage:`schema`,expression:y(),message:`Expected a .md filename`})},H$=e=>V$(e).pipe(E(t=>Hw(XJ.fields.name)(t).pipe(dg(t=>L$(e,t))))),U$=e=>V$(e).pipe(E(t=>Hw(fN)(t).pipe(dg(t=>L$(e,t))))),W$=(e,t)=>T(function*(){let n=[],r=0;for(;r<t.length;){let i=t.indexOf(`{{`,r);if(i<0)break;let a=t.indexOf(`}}`,i+2);if(a<0)return yield*new rU({file:e,stage:`expression`,expression:y(),message:`The prompt has an unclosed {{ at character ${i}. Close it with }}.`});let o=t.slice(i+2,a).trim(),s=yield*Hw(ZH)(o).pipe(dg(t=>L$(e,t)));n.push({source:s,start:i,end:a+2}),r=a+2}return n}),G$=(e,t,n)=>{let r=QJ(t.name),i=RY(t.trigger.on);return T(function*(){let a=yield*Ph(yield*W$(r,t.body),t=>e.evaluateScalar(t.source,i,n).pipe(dg(e=>B$(r,e,[`body`])),ng(e=>({expression:t,value:e})))),o=``,s=0;for(let{expression:e,value:n}of a)o+=t.body.slice(s,e.start),o+=String(n),s=e.end;return o+t.body.slice(s)})},K$=O(`ConfigParser.parseUsineYaml`)((e,t)=>T(function*(){let n=yield*z$(e,t);return yield*Hw(LJ)(n,{onExcessProperty:`error`,errors:`all`}).pipe(dg(t=>L$(e,t)))})),q$=O(`ConfigParser.parseAgentFile`)((e,t)=>T(function*(){let n=yield*U$(e),r=yield*qq(e,t),i=yield*z$(e,r.yaml),a=yield*Hw(I$)(i,{onExcessProperty:`error`,errors:`all`}).pipe(dg(t=>L$(e,t))),o=yield*Hw(pN)(r.body).pipe(dg(t=>L$(e,t)));return new Jq({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),J$=e=>O(`ConfigParser.parseLoopFile`)((t,n)=>T(function*(){let r=yield*H$(t),i=yield*qq(t,n),a=yield*z$(t,i.yaml),o=yield*Hw(F$)(a,{onExcessProperty:`error`,errors:`all`}).pipe(dg(e=>L$(t,e))),s=yield*Hw(JJ)(i.body).pipe(dg(e=>L$(t,e))),c=RY(o.trigger.on),l=[],u=yield*e.checkBoolean(o.trigger.if,c).pipe(dg(e=>B$(t,e,[`trigger`,`if`])),$h);Di(u)&&l.push(u.failure);let d=yield*W$(t,s).pipe($h);if(Di(d))l.push(d.failure);else{let n=yield*Ph(d.success,({source:n})=>e.checkScalar(n,c).pipe(dg(e=>B$(t,e,[`body`])),$h));for(let e of n)Di(e)&&l.push(e.failure)}return Yi(l)?yield*new rU({file:t,stage:`expression`,expression:l[0].expression,message:l.map(({message:e})=>e).join(`
276
- `),details:l.flatMap(e=>e.details??[{path:[`body`],message:e.message}])}):new XJ({name:r,trigger:o.trigger,selector:o.selector,approval:o.approval,maxCycles:o.maxCycles,permissions:o.permissions,priority:o.priority,step:o.step,agent:o.agent,body:s})})),Y$=Ww(fz),X$=e=>O(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>pz(e))),i=[];for(let e of t.repos)for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(pz(n.label))&&i.push(new $J({repository:e.name,lane:t.name,label:n.label}));for(let t of n){let n=yield*e.relatedStringLiterals(t.trigger.if,[`item`,`labels`]);for(let e of n){let n=Y$(e);S(n)&&!r.has(pz(n.value))&&i.push(new eY({loop:t.name,label:n.value}))}}return i}),Z$=class e extends Rr()(`@usine/config/ConfigParser`){static layer=Xf(e,T(function*(){return Q$(yield*eU)}))},Q$=e=>({configWarnings:X$(e),parseUsineYaml:K$,parseAgentFile:q$,parseLoopFile:J$(e),renderPrompt:O(`ConfigParser.renderPrompt`)((t,n)=>G$(e,t,n))}),$$=z.pipe(L(`CursorKey`)),e1=Hw(N(M({value:IE}))),t1=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),n1=class e extends Rr()(`@usine/engine/CursorStore`){static layer=Xf(e,T(function*(){let e=yield*iN;return{read:O(`CursorStore.read`)(function*(t,n){let r=Sr((yield*T(function*(){return yield*e1(yield*e.select({value:QR.valueJson}).from(QR).where(Y(QR.cursorKey,t)).limit(1).execute())}).pipe(t1(`read runtime cursor`)))[0]);return x(r)?y():yield*Hw(n)(r.value.value,{onExcessProperty:`error`}).pipe(ng(b),og(e=>e_(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(rg(y()))))}),write:O(`CursorStore.write`)(function*(t,n,r){let i=yield*Jw(n)(r).pipe(t1(`encode runtime cursor`));yield*e.insert(QR).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:QR.cursorKey,set:{valueJson:i}}).execute().pipe(ag,t1(`write runtime cursor`))})}}))},r1=e=>e.pipe(dg(e=>e instanceof QL?e:new sz({operation:`update cycle budget`,cause:e}))),i1=class e extends Rr()(`@usine/engine/CycleBudgets`){static layer=Xf(e,T(function*(){let e=yield*iN,t=VV(e);return{generation:O(`CycleBudgets.generation`)(function*(e){return yield*D({itemKey:e}),vr(yield*t.get(e).pipe(dg(e=>new sz({operation:`read cycle generation`,cause:e}))),{onNone:()=>aI.make(0),onSome:e=>e.generation})}),asks:O(`CycleBudgets.asks`)(()=>t.asks().pipe(dg(e=>new sz({operation:`read cycle asks`,cause:e})))),reset:O(`CycleBudgets.reset`)(function*(t,n){yield*D({askId:t,eventId:n.id}),yield*e.transaction(e=>T(function*(){if((yield*e.select().from(GR).where(Y(GR.askId,t)).execute())[0]?.eventId===n.id){yield*k(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*VV(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new QL({askId:t});let i=yield*VV(e).get(r.itemKey);if(x(i))return yield*Kh(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(VR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:lV(n.payload),receivedAt:uV(n.receivedAt)}).execute(),yield*e.insert(GR).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(UR).set({generation:a,askJson:null,resetPending:!0}).where(Y(UR.itemKey,r.itemKey)).execute(),yield*e.update(WR).set({generation:a}).where(cM(Y(WR.itemKey,r.itemKey),hM(WR.runId,e.select({runId:Q.runId}).from(Q).where(hM(J`json_extract(${Q.stateJson}, '$._tag')`,[...MA]))))).execute(),yield*k(`Operator reset Item cycle budget`,{askId:t,eventId:n.id,itemKey:r.itemKey,repository:r.repository,generation:a,completedCycles:r.completedCycles,counts:r.counts})})).pipe(r1)}),close:O(`CycleBudgets.close`)(function*(t,n){yield*D({askId:t,reason:n});let r=uV(yield*B_);return yield*e.transaction(e=>T(function*(){let i=(yield*VV(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*k(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=Xw(uI)(i);return yield*e.insert(KR).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:KR.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(UR).set({askJson:null}).where(Y(UR.itemKey,i.itemKey)).execute(),yield*k(`Closed cycle-budget Ask without a reset`,{askId:t,reason:n,itemKey:i.itemKey,repository:i.repository,loop:i.loop,completedCycles:i.completedCycles,counts:i.counts}),!0})).pipe(dg(e=>new sz({operation:`close cycle ask`,cause:e})))}),pendingResets:O(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(ng(e=>e.map(e=>new ZL(e))),dg(e=>new sz({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:O(`CycleBudgets.acknowledgeReset`)(function*(t){yield*D({itemKey:t.itemKey,generation:t.generation}),yield*e.update(UR).set({resetPending:!1}).where(cM(Y(UR.itemKey,t.itemKey),Y(UR.generation,t.generation))).execute().pipe(dg(e=>new sz({operation:`acknowledge cycle reset`,cause:e}))),yield*k(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},a1=new class extends V(`@usine/engine/RetryRequest`)({requestedBy:B(aN),amendment:B(dF)}){}({requestedBy:y(),amendment:y()});V(`@usine/engine/RunAgainRequest`)({step:wN,approval:sA,cycleLimit:B(iI),permissions:lA,context:dF,requestedBy:B(aN)});var o1=P([NR,zR]),s1=(e,t,n)=>{let r=rA.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new kR({event:new iA({id:nA.make(r),dedupKey:r,payload:e.event.payload,receivedAt:n.receivedAt}),itemKey:e.itemKey,loop:e.run.loop,step:t.step,approval:t.approval,permissions:t.permissions,cycleLimit:t.cycleLimit,cycleGeneration:n.generation,repository:e.repository,revision:e.revision,task:t.context.task,agent:t.context.agent,parentModel:t.context.parentModel})},c1=class extends V(`@usine/engine/StepExecution`)({attempt:_F,event:iA,run:UA,step:TN,repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:B(cN),permissions:lA,resume:B(QP),reattach:lT.pipe(TT(w(!1)))}){},l1=class extends Rr()(`@usine/engine/StepExecutor`){},u1=e=>({attemptWindows:O(`RunStoreQueries.attemptWindows`)(function*(t){yield*D({attemptId:t});let[n]=yield*e.select(QV).from($).where(Y($.attemptId,t)).execute().pipe(E(iV));if(n===void 0)return yield*Kh(Error(`No attempt ${t} recorded`));let r=yF(NV(n));if(x(r))return yield*A(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new wF({own:r,overlapping:[]});let i=e.select({itemKey:Z.itemKey}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Y(Q.runId,n.runId));return new wF({own:r,overlapping:(yield*e.select(QV).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(hM(Z.itemKey,i),Y($.agent,n.agent),oM($.attemptId,t))).orderBy($.startedAt).execute().pipe(E(iV))).flatMap(e=>Mr(yF(NV(e)))).filter(e=>CF(r.value,e))})})}),d1=cF.make(3),f1=e=>Sr(e.attempts.at(-1)).pipe(Nr(e=>x(e.outcome))),p1=e=>kr(e.salvage,e=>e._tag===`Retained`?e.pushFailure:y()),m1=(e,t,n)=>{let r=new qP({failure:n});return TF({failure:n,number:t.number,maxAutoAttempts:d1})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:LA(e)}},h1=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=f1(e);if(x(r))return{_tag:`Unchanged`,reason:`NoOpenAttempt`};if(r.value.id!==t)return{_tag:`Unchanged`,reason:`AttemptReplaced`};let i=vr(p1(r.value),{onNone:()=>n,onSome:e=>Ci(e)});return Di(i)?m1(e.run.state,r.value,i.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new KP,state:IA(e.run.state),result:i.success}},g1=e=>kk(e,{Pushed:e=>b(e),PartlyPushed:({ref:e,commit:t})=>b(new QP({ref:e,commit:t})),Retained:()=>y(),Rejected:()=>y()}),_1=e=>ra(e,e=>kr(e.salvage,g1)),v1=(e,t,n,r)=>{let i=e.run.state;if(!DA(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=y(),o=f1(e);if(i._tag===`Running`&&S(o)){if(Fr(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:_1(e.attempts)};let r=m1(i,o.value,yr(p1(o.value),()=>t));if(r._tag===`RunFailed`)return r;a=b(r)}let s=S(a)?new iF:yr(r,()=>e.attempts.length===0?new eF:new rF);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:FA(i),number:cF.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:_1(e.attempts)}},y1=e=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:TA(e.run.state)?{_tag:`Canceled`,state:zA(e.run.state),attempt:e.run.state._tag===`Running`?Or(f1(e),e=>({id:e.id,worker:e.worker,outcome:new JP})):y()}:{_tag:`CancelRejected`},b1=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:RA(t)}:t._tag===`Running`&&x(f1(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},x1=(e,t)=>vr(e,{onNone:()=>!1,onSome:e=>!Fr(e,t)}),S1=(e,t)=>e._tag===`Owned`?e.run.state._tag===`Canceled`&&t?{_tag:`ReopenEvent`}:{_tag:`JoinRun`,run:e.run}:e.reason===`revoked`&&t?{_tag:`ReopenEvent`}:{_tag:`StayIgnored`,reason:e.reason},C1=(e,t)=>{if(e._tag!==`RunFailed`||Oi(t))return y();switch(t.failure._tag){case`QuestionFailure`:return b(`question`);case`BlockedFailure`:return b(`blocker`);default:return y()}},w1=(e,t)=>vr(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),T1=(e,t)=>{if(x(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:EA(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:BA(n.state,t)}:{_tag:`OpenRun`}},E1=B(HA).pipe(TT(w(y()))),D1=class extends V(`@usine/engine/internal/Claim`)({result:BR,openedRun:E1,supersededRun:E1}){},O1=class extends H(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:c1}){},k1=class extends H(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},A1=class extends H(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},j1=T(function*(){let e=yield*iN,t=yield*YO,n=rH(e),r=O(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return S(r)?new zR({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new NR({eventId:t.event.id,runId:n}))}),i=O(`RunStore.openRun`)(function*(e,t,n,i=y()){let a=yield*r(e,t,n);return new D1({result:a,openedRun:a._tag===`Claimed`?b(n):y(),supersededRun:i})}),a=e=>jR(e).pipe(kg(YO,t)),o=O(`RunStore.settlementOf`)(function*(e,t){let n=(yield*e.runForEvent(t))[0];if(n!==void 0){let t=(yield*e.snapshot(n.runId)).run;return b({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?y():b({_tag:`Ignored`,reason:r.reason})}),s=O(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new D1({result:new LR({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(S(r)){let n=w1(r.value,t.event.id),i={eventId:t.event.id,suppressedBy:r.value.runId,loop:t.loop,itemKey:t.itemKey};switch(n._tag){case`SuppressFrom`:return yield*e.loopItems.suppressFrom(t.loop,t.itemKey,t.event.id),yield*k(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new D1({result:new RR({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*k(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new D1({result:new RR({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*k(`Item changed after the Agent stopped for the operator; the Loop acts on its new state`,i)}}let a=(yield*e.blockingRun(t.loop,t.itemKey))[0],o=T1(a===void 0?y():b((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*k(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new D1({result:new PR({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,b(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=O(`RunStore.recordAndClaim`)(function*(t,n){return yield*D({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>T(function*(){let r=rH(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=yr(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(x(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=S1(d.value,x1(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*k(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new D1({result:new NR({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*k(`Event remains ignored`,{eventId:u,reason:f.reason}),new D1({result:new LR({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(MR(t,i.event.dedupKey,e),b({eventId:i.event.id,reopening:e}));return yield*k(`The Item came back to the state of an Event no Attempt worked on; it opens again`,{eventId:u,settled:d.value._tag,reopenedEventId:n.event.id,reopening:e}),yield*s(r,n,yield*a(n))}}}))},TV(`submit event`)),l=O(`RunStore.parkForApproval`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=NA(r.run.state);return yield*n.updateState(t,i),i}))},TV(`park run for approval`)),u=O(`RunStore.applyFinish`)(function*(e,t,n){if(yield*D({runId:t}),n._tag===`Unchanged`){yield*k(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*D({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*k(`Attempt completion decided`,kk(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*B_;yield*e.closeAttempt(r.id,i,o),n._tag!==`RetryAttempt`&&(n._tag===`RunSucceeded`&&(yield*e.updateStepResult(t,r.stepName,n.result)),yield*e.updateState(t,n.state,o))}),d=O(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Or(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*k(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:yr(i,()=>`none yet`)}):yield*k(`Agent stopped for the operator, but nothing is suppressed; the Loop last saw the Item not matching`,a)}),f=(e,{attempt:t,state:n,resume:r,reattach:i})=>new c1({attempt:t,event:e.event,run:new UA({id:e.run.id,eventId:e.run.eventId,loop:e.run.loop,state:n,openedAt:e.run.openedAt}),step:e.step,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel,permissions:e.permissions,resume:r,reattach:i}),p=O(`RunStore.beginAttempt`)(function*(t,n,r){return yield*D({runId:t,worker:n}),yield*e.transaction(e=>T(function*(){let i=rH(e),a=yield*i.snapshot(t),o=new RP({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=v1(a,o,r,s);if(c._tag===`RunClosed`)return yield*k(`Attempt start skipped`,{runId:t,state:c.state._tag}),new A1;if(c._tag===`RunFailed`)return yield*u(i,t,c),new k1;if(c._tag===`ReattachAttempt`){let e=yield*B_,r=new _F({...c.attempt,reattachedAt:b(e)});return yield*i.recordReattach(r.id,e),yield*D({attemptId:r.id}),yield*k(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*t_(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new O1({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}S(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=sF.make(`${t}/${a.step.name}/${c.number}`),d=yield*B_,p=new _F({id:l,runId:t,stepName:a.step.name,worker:n,number:c.number,brain:a.agent.brain,task:a.task,agent:a.agent.name,operatorIntervened:!1,parentModel:a.parentModel,startedAt:d,outcome:y(),endedAt:y(),salvage:y(),start:b(c.start),reattachedAt:y()});return yield*i.addAttempt(p),S(s)&&(yield*i.setNextStart(t,y())),yield*k(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Or(c.resume,({ref:e})=>e)}),new O1({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},TV(`begin attempt`)),m=O(`RunStore.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>rH(e).recordSalvage(t,n)),yield*k(`Attempt salvage recorded`,kk(n,{Pushed:({ref:e,commit:n})=>({attemptId:t,ref:e,commit:n}),PartlyPushed:({ref:e,commit:n,path:r})=>({attemptId:t,ref:e,commit:n,path:r}),Retained:({path:e,commit:n,pushFailure:r})=>({attemptId:t,path:e,commit:n,pushFailure:Or(r,({message:e})=>e)}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},TV(`record attempt salvage`)),h=O(`RunStore.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.transaction(e=>rH(e).recordComments(t,n)),yield*k(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},TV(`record attempt comments`)),g=O(`RunStore.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>rH(e).recordOutOfMemory(t,n));yield*k(`Recorded the processes the kernel killed in the Attempt's container`,{attemptId:t,container:n.container,kills:n.kills,memoryMib:n.memoryMib,attemptKills:r.kills})},TV(`record attempt out-of-memory kills`)),_=O(`RunStore.attemptWindows`)(function*(t){yield*D({attemptId:t});let n=yield*u1(e).attemptWindows(t);return yield*A(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:S(n.own),ended:Ir(n.own,({endedAt:e})=>S(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},TV(`read attempt windows`)),v=O(`RunStore.discardLeftovers`)(function*(t){yield*D({worker:t});let n=yield*B_;return yield*e.transaction(e=>RV(e).discardLeftovers(t,n))},TV(`discard attempt leftovers`)),ee=O(`RunStore.openAttempts`)(function*(t){return yield*D({worker:t}),yield*RV(e).openAttempts(t)},TV(`count open attempts`)),te=O(`RunStore.finishAttempt`)(function*(t,n){return yield*D({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>T(function*(){let r=rH(e),i=yield*r.snapshot(t.runId),a=h1(i,t.id,n);yield*u(r,t.runId,a);let o=C1(a,n);return S(o)&&(yield*d(r,i,o.value)),a}))},TV(`finish attempt`)),ne=O(`RunStore.resolveFailure`)(function*(t,n,r){return yield*D({runId:t,attemptId:n}),yield*e.transaction(e=>T(function*(){let i=rH(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!OA(a.run.state).canResolveFailure||o?.id!==n)return yield*k(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new az({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(Fr(a.resolvedFailureAttemptId,n))return yield*k(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new fF({resolvedAt:yield*B_,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*k(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:J_(s.resolvedAt),operator:C(r)}),c}))},TV(`resolve run failure`)),re=O(`RunStore.approve`)(function*(t,n,r){return yield*D({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>T(function*(){let i=rH(e);if(yield*i.approvalExists(t))return!1;let a=yield*i.snapshot(t);return a.run.state._tag===`Waiting`?(yield*i.recordApproval(t,n,r),yield*i.updateState(t,PA(a.run.state)),!0):yield*new az({runId:t,operation:`approve`,state:a.run.state._tag})}))},TV(`approve run`)),ie=O(`RunStore.retry`)(function*(t,n=a1){let{amendment:r,requestedBy:i}=n;return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),a=yield*n.snapshot(t),o=b1(a);if(yield*k(`Operator retry decided`,{runId:t,state:a.run.state._tag,decision:o._tag}),o._tag===`Resume`){let e=(yield*n.blockingRun(a.run.loop,a.itemKey))[0];return e===void 0?(S(r)&&(yield*n.amend(t,r.value),yield*k(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*k(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,b(S(r)?new nF({operator:i}):new tF({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*k(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new oz({runId:t,openRunId:e.runId,message:`Cannot retry run ${t}: run ${e.runId} of loop "${a.run.loop}" is open on the same item. Cancel run ${e.runId}, or try again after it closes.`}))}return o._tag===`ResumePending`&&x(r)?!1:yield*new az({runId:t,operation:`retry`,state:a.run.state._tag})}))},TV(`retry run`)),ae=O(`RunStore.runAgain`)(function*(t,n){yield*D({runId:t,agent:n.context.agent.name});let i=yield*B_;return yield*e.transaction(e=>T(function*(){let o=rH(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!OA(s.run.state).canRunAgain)return yield*k(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new az({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*k(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new oz({runId:t,openRunId:u.runId,message:`Run ${t} cannot run again: run ${u.runId} of loop "${c}" is open on the same item. Cancel run ${u.runId}, or try again after it closes.`});let d=yr(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=vr(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=vr(yield*o.cycles.get(l),{onNone:()=>aI.make(0),onSome:e=>e.generation}),m=s1(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,b({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new Dz({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*k(`Run again decided`,kk(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:yr(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:yr(n.requestedBy,()=>`none`)})})),g}))},TV(`run again`)),oe=O(`RunStore.cancel`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t),i=y1(r);if(yield*k(`Operator cancellation decided`,{runId:t,state:r.run.state._tag,decision:i._tag}),i._tag===`AlreadyClosed`)return i;if(i._tag===`CancelRejected`)return yield*new az({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*B_;if(S(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Or(i.attempt,({id:e,worker:t})=>({id:e,worker:t})),loop:r.run.loop,itemKey:r.itemKey}}))},TV(`cancel run`)),se=O(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=rH(e);yield*r.loopItems.unmatched(t,n);let i=yield*r.revokeUnstarted(t,n);for(let e of i){let t=yield*r.snapshot(e.runId);EA(t.run.state)&&(yield*r.updateState(e.runId,VA(t.run.state)))}return i.map(e=>e.runId)}))},TV(`revoke run`)),ce=O(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*D({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},TV(`revoke queued events`)),le=O(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=rH(e),a=yield*r.runForEvent(t.event.id);return a[0]===void 0?(yield*r.ignoredEvent(t.event.id)).length>0||(yield*r.blockingRun(t.loop,t.itemKey)).length>0||S(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?y():(yield*i(r,t,n)).openedRun:(yield*k(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),y())}))},TV(`claim queued event`)),ue=O(`RunStore.appendTranscript`)(function*(t,n){let r=yield*B_;yield*e.transaction(e=>T(function*(){let i=rH(e);t===`outbound`&&n.payload._tag===`Started`&&(yield*i.updateAttemptParentModel(n.attemptId,n.payload.parentModel)),t===`outbound`&&n.payload._tag===`InterventionApplied`&&(yield*i.markIntervened(n.attemptId)),(yield*i.appendTranscript(t,n,r))||(yield*A(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},TV(`append attempt transcript`)),de=O(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},TV(`read attempt transcript`));return{approve:re,appendTranscript:ue,beginAttempt:p,cancel:oe,claimQueued:le,finishAttempt:te,nextQueued:e=>n.nextQueued(e).pipe(TV(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(TV(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(TV(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(TV(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(TV(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:v,openAttempts:ee,submission:e=>n.eventRouteByRun(e).pipe(E(t=>t[0]===void 0?Uh(new iz({runId:e})):w(OV(t[0]))),TV(`read run submission`)),resolveFailure:ne,retry:ie,revoke:se,revokeQueued:ce,runAgain:ae,snapshot:e=>n.snapshot(e).pipe(TV(`read run`)),transcript:de}}),M1=class e extends Rr()(`@usine/engine/internal/RunStore`){static layer=Xf(e,j1)},N1=z.pipe(L(`ItemProjectionSource`)),P1=z.pipe(L(`ItemContentHash`)),F1=class extends V(`@usine/engine/ItemProjection`)({itemKey:nI,repository:Xk,source:N1,number:rI,contentHash:P1,payload:LE,goneAt:yE(vE).pipe(DT(w(null)),TT(w(y())))}){},I1=M({itemKey:F1.fields.itemKey,repository:Xk,source:N1,number:rI,contentHash:P1,payload:LE,goneAt:F1.fields.goneAt}),L1=Hw(N(I1)),R1=Hw(N(rI)),z1=Xw(LE),B1=Xw(I1.fields.goneAt),V1=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),H1={itemKey:$R.itemKey,repository:$R.repository,source:$R.source,number:$R.itemNumber,contentHash:$R.contentHash,payload:$R.payloadJson,goneAt:$R.goneAt},U1=T(function*(){let e=yield*iN;return{get:O(`ItemProjectionReader.get`)(function*(t){yield*D({itemKey:t});let[n]=yield*L1(yield*e.select(H1).from($R).where(Y($R.itemKey,t)).execute(),{onExcessProperty:`error`});return Or(Sr(n),e=>new F1(e))},V1(`read item projection`)),list:O(`ItemProjectionReader.list`)(function*(t,n){return yield*D({repository:t,limit:n.limit}),(yield*L1(yield*e.select(H1).from($R).where(Y($R.repository,t)).orderBy(jM($R.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new F1(e))},V1(`list item projections`)),openIssues:O(`ItemProjectionReader.openIssues`)(function*(t){return yield*D({repository:t}),yield*R1((yield*e.select({number:$R.itemNumber}).from($R).where(cM(Y($R.repository,t),Y($R.source,`issue`),_M($R.goneAt),J`json_extract(${$R.payloadJson}, '$.state') = 'OPEN'`)).orderBy(AM($R.itemNumber)).execute()).map(({number:e})=>e))},V1(`list open issue projections`))}}),W1=T(function*(){let e=yield*iN;return{upsert:O(`ItemProjectionWriter.upsert`)(function*(t){yield*D({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=B1(t.goneAt);return(yield*e.insert($R).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:z1(t.payload),goneAt:n}).onConflictDoUpdate({target:$R.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:z1(t.payload),goneAt:n},setWhere:J`${$R.contentHash} != ${t.contentHash} OR ${$R.goneAt} IS NOT ${n}`}).returning({itemKey:$R.itemKey}).execute()).length===0?(yield*A(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*A(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},V1(`write item projection`)),markGone:O(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*D({itemKey:t}),(yield*e.update($R).set({goneAt:B1(b(n))}).where(cM(Y($R.itemKey,t),_M($R.goneAt))).returning({itemKey:$R.itemKey}).execute()).length===0?(yield*A(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*k(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:J_(n)}),!0)},V1(`mark item projection gone`))}}),G1=class e extends Rr()(`@usine/engine/ItemProjectionReader`){static layer=Xf(e,U1)},K1=class e extends Rr()(`@usine/engine/ItemProjectionWriter`){static layer=Xf(e,W1)},q1=class extends Rr()(`@usine/engine/TriggerCondition`){},J1=class extends V(`@usine/engine/LoopRuntimeState`)({loop:aA,paused:lT}){},Y1=e=>t=>t.pipe(dg(t=>new sz({operation:e,cause:t}))),X1=T(function*(){let e=yield*iN,t=O(`LoopControl.stateFor`)(function*(t){yield*D({loop:t});let n=(yield*e.select({loop:nz.loopName,paused:nz.paused}).from(nz).where(Y(nz.loopName,t)).limit(1).execute())[0];return n===void 0?new J1({loop:t,paused:!1}):new J1(n)},Y1(`read loop runtime state`)),n=O(`LoopControl.states`)(function*(){return(yield*e.select({loop:nz.loopName,paused:nz.paused}).from(nz).orderBy(AM(nz.loopName)).execute()).map(e=>new J1(e))},Y1(`list loop runtime states`)),r=O(`LoopControl.write`)(function*(n){yield*D({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*A(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(nz).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:nz.loopName,set:{paused:n.paused}}).execute().pipe(Y1(`write loop runtime state`)),yield*k(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:O(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:O(`LoopControl.pause`)(e=>r(new J1({loop:e,paused:!0}))),states:n(),unpause:O(`LoopControl.unpause`)(e=>r(new J1({loop:e,paused:!1})))}}),Z1=class e extends Rr()(`@usine/engine/LoopControl`){static layer=Xf(e,X1)},Q1=N(z),$1=class extends V(`@usine/engine/BoardMoveRecord`)({repository:Xk,itemKey:nI,at:_E,fromLane:z,toLane:z,added:Q1.check(qT()),removed:Q1}){},e0=Hw(N(M({repository:$1.fields.repository,itemKey:$1.fields.itemKey,at:vE,fromLane:$1.fields.fromLane,toLane:$1.fields.toLane,added:$1.fields.added,removed:$1.fields.removed}))),t0=Xw($1.fields.added),n0=Xw($1.fields.removed),r0=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),i0=T(function*(){let e=yield*iN;return{record:O(`BoardMoves.record`)(function*(t){yield*D({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(tz).values({repository:t.repository,itemKey:t.itemKey,movedAt:uV(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:t0(t.added),removedJson:n0(t.removed)}).execute(),yield*A(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:uV(t.at),fromLane:t.fromLane,toLane:t.toLane})},r0(`record board move`)),onItem:O(`BoardMoves.onItem`)(function*(t,n){return yield*D({itemKey:t}),(yield*e0(yield*e.select({repository:tz.repository,itemKey:tz.itemKey,at:tz.movedAt,fromLane:tz.fromLane,toLane:tz.toLane,added:tz.addedJson,removed:tz.removedJson}).from(tz).where(cM(Y(tz.itemKey,t),fM(tz.movedAt,uV(n)))).orderBy(AM(tz.movedAt),AM(tz.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new $1(e))},r0(`read board moves`))}}),a0=class e extends Rr()(`@usine/engine/BoardMoves`){static layer=Xf(e,i0)},o0=class extends Rr()(`@usine/engine/RunEngineShutdown`){},s0=class e extends Rr()(`@usine/engine/AttemptAdmission`){static layer=Xf(e,T(function*(){let e=yield*Dg(o0),t=S(e)?e.value:yield*vf(),n=yield*Lk(new Set),r=yield*vf(),i=O(`AttemptAdmission.enter`)(function*(e){yield*D({runId:e});let r=yield*Bk(n,n=>Sf(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*k(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=O(`AttemptAdmission.leave`)(function*(e){yield*D({runId:e});let i=yield*Hk(n,t=>new Set([...t].filter(t=>t!==e)));(yield*xf(t))&&(yield*k(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*Cf(r,void 0)))});return{withAttempt:O(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*D({runId:e}),yield*jg(i(e),e=>e?t:Hh,t=>t?a(e):Bh)}),drain:O(`AttemptAdmission.drain`)(function*(){yield*Cf(t,void 0);let e=yield*Rk(n);yield*k(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*Cf(r,void 0)),yield*yf(r),yield*k(`Engine drain completed; all admitted Attempts settled`)})}}))},c0=class extends NE(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:sF,worker:EN,cause:eE()}){},l0=(e,t)=>{let n=new Map(e);return n.delete(t),n},u0=O(`CheckoutRecovery.for`)(function*(e,t){let n=yield*Lk(new Map),r=n=>t.recover(n,{salvage:t=>e.recordSalvage(n.attemptId,t),comments:t=>e.recordComments(n.attemptId,t),windows:e.attemptWindows(n.attemptId)}).pipe(pg(e=>t_(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),gg),i=O(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(E(e=>Ig(e.release).pipe(ng(t=>({worker:e.worker,release:t,checkoutKept:!0})))),E(t=>Vk(n,n=>new Map(n).set(e.attemptId,t))),zg)}),a=O(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*D(n);let a=yield*t.isLive(e.attemptId).pipe($h);if(Oi(a)&&!a.success)return yield*r(e);Di(a)?yield*e_(`Could not read whether an open Attempt's parent task is live; its checkout stays for its Run to decide`,{...n,errorTag:a.failure._tag,message:a.failure.message}):yield*k(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*k(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=O(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*D(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe($h);return Oi(a)?(yield*r(e),y()):(yield*e_(`Could not confirm that the parent task of a closed Attempt stopped; its checkout and a slot of its Worker stay kept, and no Attempt starts on its Item, until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),b(e))}),s=O(`CheckoutRecovery.atStartup`)(function*(){let n=new Set(yield*t.workers),r=yield*e.salvageCandidates,i=r.filter(({worker:e})=>n.has(e)),s=r.filter(({worker:e})=>!n.has(e));return s.length>0&&(yield*e_(`Attempts recorded on Workers that are not configured were not reconciled; their checkouts stay until those Workers are configured again or their leftovers are discarded`,{attempts:s.length,workers:[...new Set(s.map(({worker:e})=>e))].sort().join(`,`)})),ga(yield*Ph(i,e=>e.open?a(e).pipe(rg(y())):o(e)))}),c=O(`CheckoutRecovery.reattachSlot`)(function*(e){return Or(Nr(Cr((yield*Rk(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:Rk(n).pipe(E(n=>n.get(e)===t?k(`The slot startup occupied stays kept with the checkout no execution acquired, until the Attempt's parent task is confirmed stopped`,{attemptId:e,worker:t.worker}):t.release))}))}),l=O(`CheckoutRecovery.acquired`)(function*(e){(yield*Bk(n,t=>t.get(e)?.checkoutKept===!0?[!0,l0(t,e)]:[!1,t]))&&(yield*k(`The reattached Attempt's execution acquired the checkout startup kept; its executor releases the checkout from here, and its Run the slot once the Attempt ends`,{attemptId:e}))}),u=O(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*D(r);let i=yield*Ig(t.release);(yield*Bk(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*k(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*A(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},zg),d=O(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*D(i);let a=yield*t.interrupt(e,r).pipe($h);if(Oi(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?e_(`Could not confirm that the parent task of an Attempt its Run does not reattach stopped; its checkout and its Worker's slot stay, and the Run starts no next Attempt until the stop is confirmed`,o):e_(`Could not confirm that the parent task of a closed Attempt stopped; its Worker's slot stays taken, and no Attempt starts on its Item, until a reconcile confirms the stop`,o),yield*new c0({attemptId:e,worker:n.worker,cause:a.failure})}),f=O(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe($h);if(Di(i)){yield*t_(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:i.failure._tag});return}if(x(i.success)){yield*e_(`The leftovers of the Attempt whose checkout startup kept were discarded; the checkout stays`,{attemptId:n});return}let a=i.success.value,o={attemptId:n,worker:a.worker,open:a.open};yield*D(o),(yield*t.workers).includes(a.worker)?(yield*k(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*e_(`The Worker of the Attempt whose checkout startup kept is no longer configured; the checkout stays until it is configured again or its leftovers are discarded`,o)});return{atStartup:s,reattachSlot:c,acquired:l,hold:u,reconcile:O(`CheckoutRecovery.reconcile`)(function*(e,t){yield*D({attemptId:e,reason:t});let r=(yield*Rk(n)).get(e);r===void 0?yield*A(`No slot kept for the Attempt awaits its parent task's stop`,{attemptId:e}):(yield*d(e,r,t),r.checkoutKept&&(yield*f(e)),yield*Vk(n,t=>l0(t,e)).pipe(Zh(r.release),zg),yield*k(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),d0=class extends V(`@usine/engine/UnconfirmedStop`)({attemptId:sF,runId:HA,loop:aA,itemKey:nI,worker:EN,reason:uF}){},f0=class e extends Rr()(`@usine/engine/UnconfirmedStops`){static empty=Jf(e)({list:w([])})},p0=e=>cg(e,{EnginePersistenceError:e=>new RP({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>Kh(e),RunOperationRejectedError:e=>Kh(e),RunRetryBlockedError:e=>Kh(e)}),m0=4,h0=`100 millis`,g0=(e,t)=>n=>n.pipe(pg(n=>n._tag===`EnginePersistenceError`?e_(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):Bh),hg({schedule:dh(h0),times:m0,while:e=>e._tag===`EnginePersistenceError`})),_0=e=>kr(e,e=>e._tag===`Live`?b(e.attempt):y()),v0=class e extends Rr()(`@usine/engine/internal/RunDriver`){static layer=Xf(e,T(function*(){let e=yield*M1,t=yield*l1,n=yield*s0,r=yield*q1,i=yield*K1,a=yield*YO,o=yield*ek(),s=yield*u0(e,t),c=yield*Lk(new Map),l=yield*Lk(new Map),u=(e,t)=>Bk(l,n=>n.get(e)===t?[!0,l0(n,e)]:[!1,n]).pipe(E(n=>n?t.release:A(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=O(`RunDriver.launch`)(function*(e){if(yield*D({runId:e}),yield*sk(o,e)){yield*A(`The Run's fiber already runs in this process`,{runId:e});return}yield*A(`Starting the Run's fiber`,{runId:e});let t=yield*eg(Hg);yield*uk(o,e,ee(e).pipe(mg(t=>Qd(t)?Bh:t_(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),Wg(`RunDriver.drive`,{root:!0,links:Mr(Or(t,e=>({span:e,attributes:{}})))}),lg(e=>Qd(e)?Wh(e):Bh)),{onlyIfMissing:!0})}),f=O(`RunDriver.resume`)(function*(e){yield*D({runId:e});let t=yield*ak(o,e);S(t)&&(yield*A(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*RE(t.value)),yield*d(e)}),p=O(`RunDriver.stop`)(function*(e){yield*D({runId:e}),(yield*sk(o,e))?(yield*ck(o,e),yield*k(`The closed Run's fiber stopped`,{runId:e})):yield*A(`The closed Run has no fiber in this process`,{runId:e})}),m=O(`RunDriver.markItemGone`)(function*(e,t){return yield*D({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*B_).pipe(g0(e,`mark the item's projection gone`),og(n=>e_(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(rg(!1))))}),h=O(`RunDriver.continueWithNewest`)(function*(t){yield*D({runId:t});let n=yield*e.nextQueued(t).pipe(g0(t,`read the queued events`));if(x(n))return;let i=n.value.submission,o={completedRunId:t,eventId:i.event.id,loop:i.loop,itemKey:i.itemKey},s=yield*r.recheck(i);if(s!==`matches`){let r=yield*e.revokeQueued(n.value).pipe(g0(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*k(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*k(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*jR(i).pipe(kg(YO,a)),l=yield*e.claimQueued(i,c).pipe(g0(t,`claim the queued event`));x(l)?yield*k(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*k(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=O(`RunDriver.openAttempt`)(function*(n){yield*D({runId:n});let r=yield*e.snapshot(n).pipe(g0(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||S(i.outcome))return y();let a={runId:n,attemptId:i.id,worker:i.worker};yield*D({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe($h);if(Di(o))return yield*e_(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),b({_tag:`Interrupted`,attempt:i});if(o.success)return yield*k(`The open Attempt's parent task is live; reattaching it`,a),b({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe($h);if(Di(s))return yield*e_(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),b({_tag:`Interrupted`,attempt:i});if(x(s.success))return yield*k(`The open Attempt's parent task is gone; the Run does not reattach it`,a),b({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*k(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:Ai(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),b({_tag:`Finished`,attempt:i,result:c})}),_=O(`RunDriver.slot`)(function*(e,n,r,i){yield*D({runId:e});let a=w(r),o=_0(r);if(S(o)){let t=yield*s.reattachSlot(o.value.id);if(S(t))return yield*k(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(e,n,Or(o,({worker:e})=>e))),open:S(o)?g(e):a}}),v=O(`RunDriver.attempt`)(function*(n,r,i,a){yield*D({runId:n,worker:i});let o=yield*a;if(x(_0(o))&&S(yield*ie(r)))return yield*k(`Run waits for an unconfirmed stop after reserving a worker slot`,{runId:n,worker:i,itemKey:r.itemKey}),`WaitingForStop`;if(S(o)&&o.value._tag===`Finished`){let t=yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(g0(n,`finish the attempt`));if(t._tag!==`RetryAttempt`)return t._tag}let c=yield*e.beginAttempt(n,i,Or(_0(o),({id:e})=>e)).pipe(g0(n,`begin the attempt`));if(c._tag===`AttemptRecoveryFailed`)return`RunFailed`;if(c._tag===`RunClosed`)return`Unchanged`;let l=yield*t.execute(c.execution,{append:(t,n)=>e.appendTranscript(t,n).pipe(p0),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(p0),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(p0),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(p0),windows:e.attemptWindows(c.execution.attempt.id).pipe(g0(n,`read the attempt windows`),p0),transcript:e.transcript(new bB({attemptId:c.execution.attempt.id})).pipe(g0(n,`read the attempt transcript`),p0,ng(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(ug(e=>t_(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(Zh(new zP({message:`The step executor crashed with an unexpected error`,cause:e})))),$h);return c.execution.reattach&&Di(l)&&(yield*ae(new d0({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,worker:i,reason:`failed`}))),Di(l)&&(yield*re({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,reason:`failed`,worker:i})),(yield*e.finishAttempt(c.execution.attempt,l).pipe(g0(n,`finish the attempt`)))._tag}),ee=$g(function*(t){let r=yield*e.submission(t).pipe(g0(t,`read the run's submission`));if(yield*D({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(g0(t,`park the run for approval`)))._tag===`Waiting`){yield*k(`Run waits for its approval`,{runId:t});return}let i;do{let e=yield*g(t);if(S(e)&&e.value._tag!==`Live`&&(yield*ae(new d0({attemptId:e.value.attempt.id,runId:t,loop:r.loop,itemKey:r.itemKey,worker:e.value.attempt.worker,reason:`startup`}))),x(_0(e))){let e=yield*ie(r);if(S(e)){yield*k(`The Run starts no Attempt while the parent task of an earlier Attempt on its Item is not confirmed stopped; each reconcile tries that stop again, then drives the Run`,{runId:t,loop:r.loop,itemKey:r.itemKey,unstoppedAttemptId:e.value.attemptId,unstoppedRunId:e.value.runId,worker:e.value.worker,reason:e.value.reason});return}}i=yield*Bg(i=>_(t,r,e,i).pipe(Qh(({lease:e})=>Vk(l,n=>new Map(n).set(t,e))),E(({lease:e,open:a})=>i(n.withAttempt(t,v(t,r,e.worker,a))).pipe(Mg(u(t,e))))))}while(i===`RetryAttempt`);i!==`WaitingForStop`&&(i===`Unchanged`?yield*k(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t))}),te=O(`RunDriver.holdSlot`)(function*(e){let{runId:t,attemptId:n}=e;yield*D({runId:t,attemptId:n}),yield*ne(new d0(e));let r=yield*Bk(l,e=>[Cr(e.get(t)),l0(e,t)]);x(r)?yield*A(`The Run's fiber holds no slot in this process; no slot moves to its Attempt`,{runId:t,attemptId:n}):yield*s.hold(n,r.value)},zg),ne=e=>Vk(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),re=O(`RunDriver.confirmStopAfterFailure`)(function*(e){let{attemptId:n,runId:r,worker:i}=e,a={runId:r,attemptId:n,worker:i,reason:e.reason};yield*D(a),yield*ne(new d0(e));let o=yield*t.interrupt(n,e.reason).pipe($h);Oi(o)?(yield*Vk(c,e=>l0(e,n)),yield*A(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a)):(yield*e_(`Could not confirm that the parent task of the failed Attempt stopped; the Attempt keeps its Run's slot, no Attempt starts on its Item, and each reconcile tries the stop again`,{...a,errorTag:o.failure._tag,message:o.failure.message}),yield*te(e))}),ie=e=>Rk(c).pipe(ng(t=>Cr([...t.values()].find(({itemKey:t})=>t===e.itemKey)))),ae=O(`RunDriver.reconcileKept`)(function*(e){yield*D({...e}),yield*ne(e),yield*s.reconcile(e.attemptId,e.reason),yield*Vk(c,t=>l0(t,e.attemptId)),yield*k(`Parent stop confirmed; runs on the item can start attempts again`,{...e})}),oe=O(`RunDriver.releaseKept`)(function*(e){yield*D({...e}),yield*ae(e).pipe(sg(`ParentStopUnconfirmedError`,t=>e_(`Parent stop unconfirmed; the worker slot and checkout stay reserved until reconciliation succeeds`,{...e,errorTag:t._tag})))}),se=O(`RunDriver.recoverWorkspaces`)(function*(){yield*Ph(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>ne(new d0({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:O(`RunDriver.reconcile`)(function*(){let n=[...(yield*Rk(c)).values()];yield*Ph(n,e=>sk(o,e.runId).pipe(E(t=>t?Bh:oe(e))),{discard:!0});let r=yield*e.pendingContinuations;yield*Ph(r,e=>h(e).pipe(pg(t=>t_(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),gg),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*bg(i,e=>ng(sk(o,e),e=>!e));yield*Ph(a,d,{discard:!0}),yield*t.sweep;let s={continuedAfterRunIds:r,startedRunIds:a,drivenRunIds:i.length,retriedStopAttemptIds:n.map(({attemptId:e})=>e)};r.length===0&&a.length===0&&n.length===0?yield*A(`Every Run to drive already has its fiber`,s):yield*k(`Runs recovered from the run tables`,s)}),recoverWorkspaces:se,holdSlot:te,releaseKept:oe,unconfirmedStops:Rk(c).pipe(ng(e=>[...e.values()]))}}))},y0=vi(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});T(function*(){let e=yield*M1,t=yield*v0,n=yield*s0,r=yield*l1,i=yield*YO,a=O(`RunEngine.submit`)(function*(n){let r=yield*jR(n).pipe(kg(YO,i)),a=yield*e.recordAndClaim(n,r);return S(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),S(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},zg),o=O(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*k(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:yr(i.approver,()=>`none`)}),yield*t.resume(n)):yield*A(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},zg),s=O(`RunEngine.retry`)(function*(n,r=a1){(yield*e.retry(n,r))?yield*t.resume(n):yield*A(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},zg),c=O(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},zg),l=O(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*A(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*k(`Run canceled`,{runId:n,openAttempt:vr(i.openAttempt,{onNone:()=>`none`,onSome:({id:e})=>e})}),S(i.openAttempt)&&(yield*t.holdSlot({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`}));let a=S(i.openAttempt)?yield*r.interrupt(i.openAttempt.value.id,`cancel`).pipe($h):Si(void 0);if(yield*t.stop(n),S(i.openAttempt)&&(yield*t.releaseKept({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`})),yield*t.continueWithNewest(n),S(i.openAttempt)&&Di(a))return yield*new cz({attemptId:i.openAttempt.value.id,cause:a.failure})},zg),u=O(`RunEngine.intervene`)(function*(t,n,i){yield*D({runId:t,attemptId:n,action:i.action._tag});let a=yield*e.snapshot(t),o=a.attempts.at(-1);if(a.run.state._tag!==`Running`||o?.id!==n||S(o.outcome))return yield*k(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new uz({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(dg(e=>new uz({runId:t,attemptId:n,message:kk(e,{RunawayFailure:()=>`The attempt reached its runaway limit`,ChildSessionBudgetFailure:()=>`The attempt reached its child-session budget`,QuestionFailure:()=>`The attempt ended with a question for the operator`,BlockedFailure:({message:e})=>e,GitHubPushFailure:({message:e})=>e,InfraFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),pg(e=>e_(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=O(`RunEngine.resolveFailure`)(function*(n,r,i){yield*D({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*k(`The operator resolved the Agent's question or blocker; the Item's queued Events get their turn`,{runId:n,attemptId:r}),yield*t.continueWithNewest(n))},zg),f=O(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*Ph(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},zg),p=O(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=O(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=O(`RunEngine.discardLeftovers`)(function*(t){if(yield*D({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*k(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new dz({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*k(`Discarded the leftovers of the Attempts on a Worker that is not configured; startup no longer reconciles them`,{worker:t,attempts:n.length}),yield*r.discard(t,n),n.length});return yield*t.recoverWorkspaces(),yield*t.reconcile(),yield*_g(yield*y0).pipe(Zh(t.reconcile()),pg(e=>t_(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),gg,Vg,qg),{approve:o,cancel:l,discardLeftovers:h,drain:n.drain,inspect:p,intervene:u,reconcile:t.reconcile,retry:s,resolveFailure:d,revoke:f,runAgain:c,submit:a,transcript:m}});var b0=class extends Rr()(`@usine/engine/RunEngine`){},x0=(e,t)=>e.changes.pipe(RO(e=>e!==t),KO,E(vr({onNone:()=>Hh,onSome:e=>w(e)}))),S0=Zk.make(`HEAD`),C0=class extends NE(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:aA,agent:fN,message:z}){},w0=O(`TriggerRouting.resolveLoop`)(function*(e,t){yield*D({loop:t.name,agent:t.agent});let n=new Map(e.agents.map(e=>[e.name,e])).get(t.agent);if(n===void 0)return yield*new C0({loop:t.name,agent:t.agent,message:`Loop "${t.name}" references agent "${t.agent}", which is not in the roster`});let r=n.agent;return{agent:r,loop:t,parentModel:hN(r,e.config.settings.parentModel)}}),T0=O(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*$h(w0(e,n));Oi(r)?t.push(r.success):yield*t_(`Loaded loop lost its rostered Agent; skipping the loop`,{loop:r.failure.loop,agent:r.failure.agent,errorTag:r.failure._tag,message:r.failure.message})}return t}),E0=e=>e.trigger.on===`schedule`?y():b(e.maxCycles),D0=e=>new kR({event:new iA({id:nA.make(e.dedupKey),dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),itemKey:e.itemKey,cycleGeneration:e.cycleGeneration,loop:e.loop.name,step:e.loop.step,approval:e.loop.approval,permissions:e.loop.permissions,cycleLimit:E0(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),O0=e=>kk(e,{Claimed:({runId:e})=>({runId:e}),Queued:()=>({}),Suppressed:({runId:e})=>({suppressedBy:e}),Ignored:({reason:e})=>({reason:e}),CycleBlocked:({ask:e})=>({askId:e.id,reason:`cycle-budget-exhausted`})}),k0=e=>vr(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),A0=class extends V(`@usine/orchestrator/RepositoryPollFailure`)({repository:Xk,errorTag:z,message:j}){},j0=class extends V(`@usine/orchestrator/RepositoryPoll`)({repository:Xk,completedAt:_E}){},M0=class extends V(`@usine/orchestrator/PollCycle`)({repositoryPolls:N(j0).pipe(TT(w([]))),repositories:R.check(HT(0)),changedItems:R.check(HT(0)),submissions:N(BR),revokedRuns:R.check(HT(0)),failures:N(A0),preflightFindings:N(Hq),nextPollAt:B(_E)}){},N0=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...k0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},P0=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[K_(e)]}));return t.length===0?y():z_(Math.max(...t))},F0=class extends V(`@usine/orchestrator/LoopEvaluationFailure`)({loop:aA,stage:F([`if`,`prompt`]),expression:yE(ZH),errorTag:z,message:j}){},I0=class extends V(`@usine/orchestrator/FailingItem`)({stream:F([`issue`,`pr`]),number:rI,updatedAt:vE,contentHash:P1,failures:yT(F0)}){},L0=e=>e.stream===`issue`?new kK({number:e.number,updatedAt:e.updatedAt}):new AK({number:e.number,updatedAt:e.updatedAt}),R0=(e,t,n)=>{let[r,...i]=n;return r===void 0?y():b(new I0({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:rI.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},z0=e=>e.stage===`if`?`if:`:vr(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),B0=(e,t)=>t.failures.map(n=>new A0({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${z0(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),V0=e=>vr(e,{onNone:()=>[],onSome:({failures:e})=>e}),H0=(e,t)=>e.loop===t.loop&&e.stage===t.stage,U0=O(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*D({repository:e,item:t});for(let i of Mr(r)){let r=vr(n,{onNone:()=>[],onSome:e=>e.contentHash===i.contentHash?e.failures:[]});for(let n of i.failures){let a={repository:e,item:t,contentHash:i.contentHash,loop:n.loop,stage:n.stage,expression:C(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>H0(e,n))?yield*A(`Loop evaluation still fails on unchanged Item content`,a):yield*t_(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=V0(r);for(let r of V0(n))i.some(e=>H0(e,r))||(yield*k(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),W0=Hw(N(fz)),G0=M({labels:iq.fields.labels}),K0=M({labels:cq.fields.labels}),q0=(e,t)=>Hw(e===`issue`?G0:K0)(t).pipe(E(({labels:e})=>W0(e.nodes.map(({name:e})=>e)))),J0=(e,t)=>new RH({repository:e.repository,itemKey:e.itemKey,message:t}),Y0=e=>T(function*(){let t=S(e.goneAt);if(e.source===`issue`){let n=yield*Hw(iq)(e.payload).pipe(dg(t=>J0(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:rI.make(e.number),title:n.title,url:n.url,state:n.state===`OPEN`&&!t?`issue-open`:`issue-closed`,linkedPullRequests:n.closedByPullRequestsReferences.nodes.map(({url:e})=>e),labels:yield*W0(n.labels.nodes.map(({name:e})=>e)).pipe(dg(t=>J0(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*Hw(cq)(e.payload).pipe(dg(t=>J0(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:rI.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*W0(n.labels.nodes.map(({name:e})=>e)).pipe(dg(t=>J0(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*J0(e,`Unsupported item projection source: ${e.source}`)}),X0=O(`settledItemState`)(function*(e){yield*D({itemKey:e});let t=yield*(yield*G1).get(e);if(x(t))return y();let n=yield*$h(Y0(t.value));if(Di(n))return yield*A(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),y();let{state:r}=n.success;return Cz(r)?b(r):y()}),Z0=(e,t)=>e.canApprove||e.canResolveFailure&&!t,Q0=O(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*D({repository:e});let t=yield*i1,n=(yield*t.asks()).filter(t=>tA(t.repository)===tA(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*X0(e.itemKey);x(r)?yield*A(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*k(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),$0=tT(nI).pipe(ST(aE(vT([rT(`github`),Xk,rI])))),e2=Xw($0),t2=(e,t)=>e2([`github`,Xk.make(tA(e)),rI.make(t)]),n2={labels:[],findings:[],catalogChanged:!1,nextPollAt:y()},r2=O(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*D({repository:e});let r=yield*yU,i=yield*bU,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:y(),failures:[],nextPollAt:y()};if(Di(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*e_(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:J_(t.retryAt)}),{...a,nextPollAt:b(t.retryAt)}):(yield*t_(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...N0(t)}),{...a,failures:[new A0({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof RK)){let t=yield*r.get(e);return x(t)?(yield*e_(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:y(),entityTagChanged:!0}):(yield*A(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:b(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new oU({name:e,color:b(t),description:n}));return yield*i.replace(new lU({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:b(s)}}),i2=O(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*D({repository:e});let r=yield*Bq,i=yield*Gq,a=yield*bU,o=yield*r2(e,n,yield*$h(r.labels(e,n))),s=yield*vr(o.confirmedLabels,{onNone:()=>w(n2),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?y():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:P0([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new lU({repository:e,labels:s.labels})).pipe(dg(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),a2=O(`PollingTriggers.observeItem`)(function*(e,t){yield*D({repository:e,item:t.number});let n=yield*Bq,r=yield*K1,i=yield*i1,a=t2(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new F1({itemKey:a,repository:e,source:N1.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:rI.make(t.number),contentHash:P1.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*A(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),o2=O(`PollingTriggers.markItemGone`)(function*(e,t){return yield*D({repository:e,item:t}),yield*(yield*K1).markGone(t2(e,t),yield*B_)}),s2=(e,t,{projection:n,cycleGeneration:r})=>rA.make(JSON.stringify([e.name,tA(t.name),n.number,n.contentHash,...r===0?[]:[r]])),c2=(e,t,n)=>T(function*(){return yield*(yield*eU).evaluateBoolean(e.trigger.if,RY(e.trigger.on),{repo:zY(t),item:n})}),l2=(e,t,n)=>T(function*(){let r=yield*eU,i=zY(t);return yield*r.evaluateBooleanEach(e.trigger.if,RY(e.trigger.on),n.map(e=>({repo:i,item:e})))}),u2=O(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*D({repository:e.name,item:r.number});let a=yield*Z$,o=yield*b0,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:zY(e),item:c};if(s.length===0)return yield*A(`Item projected without any matching repository Loop`,{repository:e.name,item:r.number,stream:r.source}),{submissions:[],revokedRuns:0,failures:[]};let u=[],d=r.source===`pr`?Zk.make(yield*Hw(Qk)(c.headRefOid).pipe(dg(()=>new eK({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):S0,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*D({loop:m.name,agent:t.name});let s=yield*$h(c2(m,e,c));if(Di(s)){f.push(new F0({loop:m.name,stage:`if`,expression:b(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*A(`Item did not match its loop expression`,{repository:e.name,loop:m.name,agent:t.name,item:r.number});let n=yield*o.revoke(m.name,r.itemKey);p+=n.length,n.length>0&&(yield*k(`Item stopped matching; revoked its unstarted runs`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,runIds:n.join(`, `)}));continue}let g=s2(m,e,n),_=yield*B_,v=yield*$h(a.renderPrompt(m,l));if(Di(v)){f.push(new F0({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let ee=yield*o.submit(D0({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:lF.make(v.success),agent:t,parentModel:h}));yield*k(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:ee._tag,...O0(ee)}),u.push(ee)}return{submissions:u,revokedRuns:p,failures:f}}),d2=O(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*D({repository:e.name,item:r});let i=yield*b0,a=t2(e.name,r),o=0;for(let{agent:s,loop:c}of t.filter(({loop:e})=>e.trigger.on===n)){let t=yield*i.revoke(c.name,a);o+=t.length,t.length>0&&(yield*k(`Item is gone from GitHub; revoked its unstarted runs`,{repository:e.name,loop:c.name,agent:s.name,item:r,runIds:t.join(`, `)}))}return o}),f2=T(function*(){let e=new Set,t=yield*sD({capacity:128,strategy:`dropping`}),n=yield*Lk(0),r=({repository:e,item:t})=>`${tA(e)}:${t.number}`,i=e=>vr(e,{onNone:()=>Bh,onSome:e=>Vk(n,t=>Math.max(t,K_(e)))});return{offer:O(`PollingTriggers.hint`)(function*(n,a,o=y()){yield*D({repository:n,item:a.number}),yield*i(o);let s={repository:n,item:a},c=r(s);e.has(c)?yield*A(`Self-write Hint coalesced with a pending Item fetch`,{repository:n,item:a.number}):(e.add(c),(yield*lD(t,s))?yield*A(`Self-write Hint queued`,{repository:n,item:a.number}):(e.delete(c),yield*e_(`Self-write Hint queue full; the normal poll will refresh the Item`,{repository:n,item:a.number})))},zg),take:Bg(n=>n(hD(t)).pipe(Qh(t=>zh(()=>e.delete(r(t)))))),defer:i,awaitBackoff:T(function*(){for(;;){let e=yield*Rk(n),t=yield*op;if(e<=t)return;yield*k(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*_g(eo(e-t))}})}}),p2=class e extends Rr()(`@usine/orchestrator/ItemHints`){static layer=Xf(e,f2)},m2=no(10),h2={revokedRuns:0,failures:[],nextPollAt:y()},g2=O(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*D({repository:e.name});let n=yield*G1,r=yield*Bq,i=yield*n.openIssues(e.name);if(i.length===0)return yield*A(`No open issues to check against GitHub`,{repository:e.name}),h2;let a=yield*$h(r.missingIssues(e.name,i));if(Di(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*e_(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:J_(t.retryAt)}),{...h2,nextPollAt:b(t.retryAt)}):(yield*t_(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...N0(t)}),{...h2,failures:[new A0({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*d2(e,t,`issue`,n),i=yield*o2(e.name,n);o+=r,yield*k(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*A(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...h2,revokedRuns:o}}),_2=4,v2=class extends V(`@usine/orchestrator/OpenPullRequest`)({number:AK.fields.number,updatedAt:vE,baseRefName:xE(EK),mergeable:j.pipe(DT(w(`UNKNOWN`))),checksUnsettled:lT.pipe(DT(w(!0)))}){},y2=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?b(new v2({number:e.number,updatedAt:e.updatedAt,baseRefName:b(t.payload.baseRefName),mergeable:t.payload.mergeable,checksUnsettled:t.payload.statusCheckRollup?.state===`PENDING`||t.payload.statusCheckRollup?.state===`EXPECTED`||t.payload.statusCheckRollup===null&&t.payload.mergeStateStatus===`BLOCKED`})):y(),b2=O(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*D({repository:e,baseRefName:t});let i=yield*$h((yield*Bq).baseRefHead(e,t,n));if(Di(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*e_(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...N0(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return x(n)?(yield*k(`Base branch head recorded; refreshing its open pull requests once`,{repository:e,baseRefName:t,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a}):n.value.sha===a.sha?{_tag:`Unchanged`,head:a}:(yield*k(`Base branch head moved; refreshing its open pull requests`,{repository:e,baseRefName:t,previousHead:n.value.sha,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a})}),x2=(e,t)=>{if(x(e.baseRefName))return b(`baseUnrecorded`);let n=t.get(e.baseRefName.value);return n?._tag===`Moved`?b(`baseMoved`):n?._tag===`Unreadable`?b(`baseUnreadable`):e.mergeable===`UNKNOWN`?b(`mergeableUnknown`):e.checksUnsettled?b(`checksUnsettled`):y()},S2=O(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*D({repository:e}),t.length===0)return{refreshed:[],baseRefHeads:[]};let i=new Map;for(let{number:e,baseRefName:n}of t){if(x(n))continue;let t=i.get(n.value)??[];t.push(e),i.set(n.value,t)}let a=new Map(yield*Ph(i,([t,r])=>b2(e,t,Sr(n.find(e=>e.baseRefName===t)),r).pipe(ng(e=>[t,e])),{concurrency:_2})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>Mr(Or(x2(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*A(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=da(s,({reason:e})=>e);yield*k(`Refreshing open pull requests`,{repository:e,baseRefReads:a.size,refreshed:s.length,skipped:o.length-s.length,...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.map(({pullRequest:e})=>e.number).join(`, `)]))})}return{refreshed:s.map(({pullRequest:e})=>e),baseRefHeads:[...a.values()].flatMap(e=>e._tag===`Unreadable`?Mr(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),C2=4,w2=4,T2=z.pipe(L(`GitHubPollWatchKey`)),E2=class extends V(`@usine/orchestrator/StoredPollCursor`)({boardVersion:rT(5),openPullRequests:N(v2),baseRefHeads:N(DK).pipe(DT(w([]))),cursor:OK,labelEntityTag:yE(TK),watches:N(T2).check(XT()),failingItems:N(I0).pipe(DT(w([])))}){},D2=e=>$$.make(`github-poll:${tA(e.name)}`),O2=({loop:e})=>T2.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),k2=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:e})=>e.trigger.on!==`schedule`&&zJ(e.selector,n));return{repository:n,declaredLabels:e.config.labels,loops:r,watches:r.map(O2).sort()}}),A2=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),j2=class e extends Rr()(`@usine/orchestrator/PollingTriggers`){static layer=Xf(e,T(function*(){let e=yield*n1,t=yield*i1,n=yield*Bq,r=yield*Z1,i=yield*Lk(y()),a=yield*Lk(new Map),o=yield*p2,s=yield*ID(1),c=yield*Lk({instance:y(),repositories:new Set}),l=yield*Lk(new Map),u=e=>new E2({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:OK.empty,labelEntityTag:y(),watches:e,failingItems:[]}),d=O(`PollingTriggers.readCursor`)(function*(t){yield*D({repository:t.repository.name});let n=yield*e.read(D2(t.repository),E2);return x(n)?u(t.watches):A2(n.value.watches,t.watches)?n.value:(yield*k(`Watched loops changed; re-polling the repository from scratch`,{repository:t.repository.name,previousWatches:n.value.watches.length,currentWatches:t.watches.length}),u(t.watches))}),f=O(`PollingTriggers.writeCursor`)(function*(t,n){yield*D({repository:t.repository.name}),yield*e.write(D2(t.repository),E2,n)}),p=O(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*D({repository:e.repository.name});let t=D2(e.repository),n=yield*op,r=(yield*Rk(l)).get(t);return r!==void 0&&n-r<ro(m2)?(yield*A(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:J_(R_(r))}),h2):(yield*Vk(l,e=>new Map(e).set(t,n)),yield*g2(e.repository,e.loops))}),m=O(`PollingTriggers.pollRepository`)(function*(e){yield*D({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>tA(t)===tA(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*k(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*i2(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*T(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*Rk(c)).repositories.has(D2(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*S2(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,L0(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new AK({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*k(`Repository changed`,{repository:e.repository.name,changedItems:s.items.length,backlog:s.backlog}));let g=new Set([...m.refreshed,...l].map(({number:e})=>e).filter(e=>!d.has(e)));l.length>0&&(yield*k(`Evaluating Items whose Loops failed before this process started or the instance was reloaded`,{repository:e.repository.name,items:l.map(({number:e})=>e).join(`, `)}));let _=P0([s.nextPollAt,a.nextPollAt]);yield*A(`Refreshing detected Items and open pull requests`,{repository:e.repository.name,detection:s._tag,openPullRequests:i.openPullRequests.length,refreshedPullRequests:m.refreshed.length,items:h.size});let v=new Map(i.failingItems.map(e=>[e.number,e])),ee=yield*Ph(h.values(),t=>T(function*(){let n=yield*a2(e.repository.name,t),r=yield*u2(e.repository,e.loops,n),i=R0(t,n.projection.contentHash,r.failures);return yield*U0(e.repository.name,t.number,Sr(v.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(sg(`GitHubItemNotFoundError`,n=>T(function*(){if(!g.has(t.number))return yield*n;let r=yield*d2(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*o2(e.repository.name,t.number);return yield*e_(`GitHub no longer has an Item the poll cursor kept; it is dropped from the cursor`,{repository:e.repository.name,item:t.number,openPullRequest:i.openPullRequests.some(({number:e})=>e===t.number),revokedRuns:r,projectionMarkedGone:a,errorTag:n._tag,message:n.message}),{_tag:`Missing`,revokedRuns:r}}))),{concurrency:w2}),te=ee.flatMap(e=>e._tag===`Evaluated`?[e]:[]),ne=ee.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),re=te.map(({cycle:e})=>e),ie=yield*p(e);yield*o.defer(ie.nextPollAt),yield*Q0(e.repository.name);let ae=[...i.failingItems.filter(({number:e})=>!h.has(e)),...te.flatMap(({failing:e})=>Mr(e))].sort((e,t)=>e.number-t.number),oe=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...te.flatMap(({item:e,observation:t})=>Mr(y2(e,t.snapshot)))],se=m.baseRefHeads.filter(({baseRefName:e})=>oe.some(t=>Fr(t.baseRefName,e))),ce=new E2({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:oe,baseRefHeads:se,failingItems:ae});return(s._tag===`RepositoryChanges`||h.size>0||a.entityTagChanged||!Le(se,i.baseRefHeads))&&(yield*f(e,ce)),yield*Vk(c,t=>({...t,repositories:new Set([...t.repositories,D2(e.repository)])})),yield*Ph(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:re.flatMap(({submissions:e})=>e),revokedRuns:re.reduce((e,t)=>e+t.revokedRuns,ne+ie.revokedRuns),failures:[...a.failures,...ie.failures,...ae.flatMap(t=>B0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:P0([_,ie.nextPollAt])}}).pipe(dg(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>B0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*Cg()).pipe(_i(Z$,i1,eU,Bq,G1,K1,Gq,yU,bU,b0)),g=O(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*Vk(c,t=>Fr(t.instance,e)?t:{instance:b(e),repositories:new Set});let t=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let n of e.loops)n.trigger.on!==`schedule`&&t.has(n.name)&&(yield*A(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=k2(e,(yield*T0(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*Ph(n,e=>$h(m(e)).pipe(ng(t=>({repository:e,result:t}))),{concurrency:C2}),l=[],u=[],d=[],f=[],p=yield*B_;for(let{repository:e,result:t}of s){if(Oi(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*Vk(a,t=>new Map(t).set(tA(e.repository.name),new j0({repository:e.repository.name,completedAt:p})));continue}let n=t.failure._tag===`InterruptedRepositoryCycle`,r=n?t.failure.error:t.failure;n&&(u.push(...t.failure.failures),f.push(...t.failure.preflightFindings),d.push(t.failure.nextPollAt),yield*o.defer(t.failure.nextPollAt)),r._tag===`GitHubRateLimitError`?(yield*e_(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:J_(r.retryAt)}),d.push(b(r.retryAt)),yield*o.defer(b(r.retryAt))):(yield*t_(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...N0(r)}),u.push(new A0({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*Rk(a),g=new M0({repositoryPolls:n.flatMap(({repository:e})=>Mr(Sr(h.get(tA(e.name))))),repositories:n.length,changedItems:l.reduce((e,t)=>e+t.changedItems,0),submissions:l.flatMap(({submissions:e})=>e),revokedRuns:l.reduce((e,t)=>e+t.revokedRuns,0),failures:[...l.flatMap(({failures:e})=>e),...u],preflightFindings:f,nextPollAt:P0([...l.map(({nextPollAt:e})=>e),...d])});return yield*zk(i,b(g)),g},Eg(h),s.withPermits(1)),_=O(`PollingTriggers.refreshHint`)(function*(e,t){yield*D({repository:t.repository,item:t.item.number}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=k2(e,(yield*T0(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>tA(e.name)===tA(t.repository));if(i===void 0){yield*k(`Self-write Hint ignored for an unmanaged repository`,{repository:t.repository,item:t.item.number});return}let a=yield*a2(i.repository.name,t.item),s=yield*u2(i.repository,i.loops,a);for(let e of s.failures)yield*e_(`Self-write Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:t.item.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*k(`Self-write Hint refreshed the Item`,{repository:t.repository,item:t.item.number,submissions:s.submissions.length,revokedRuns:s.revokedRuns,failures:s.failures.length})},Eg(h),(e,t,n)=>e.pipe(og(e=>T(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(b(e.retryAt))),yield*e_(`Self-write Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:n.item.number,...N0(e)})})),s.withPermits(1))),v=(e,t,n,r)=>T(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*op);if(t<=0)return;let n=yield*vg([_g(eo(t)).pipe(ng(()=>({_tag:`Due`}))),o.take.pipe(ng(e=>({_tag:`Hint`,hint:e}))),x0(e,a).pipe(ng(e=>({_tag:`Reloaded`,instance:e})))]);if(n._tag===`Due`)return;if(n._tag===`Hint`){yield*_(yield*e.get,n.hint);continue}a=n.instance,i=r;let s=r-(yield*op);s>0?yield*k(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*k(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:Rk(i),poll:g,run:e=>T(function*(){let t=yield*e.get,n=yield*op,r=yield*$h(g(t));if(Di(r)){let e=t.config.settings.pollInterval*1e3;yield*t_(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*_g(eo(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=vr(i.nextPollAt,{onNone:()=>0,onSome:K_}),s=yield*op,c=Math.max(0,Math.max(a,o)-s);yield*k(`Poll cycle complete`,{repositories:i.repositories,changedItems:i.changedItems,submissions:i.submissions.length,revokedRuns:i.revokedRuns,failures:i.failures.length,preflightFindings:i.preflightFindings.length,sleepMs:c}),yield*v(e,t,a,o)}).pipe(Vg),hint:o.offer}})).pipe(rp(p2.layer))},M2=4,N2=6e4,P2=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...k0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},F2=class extends H(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:aA,agent:fN,message:j}){},I2=class extends H(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:aA,repository:Xk,scheduledAt:_E,errorTag:z,message:j}){},L2=class extends H(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:aA,cron:j,tz:j,message:j}){},R2=P([F2,L2,I2]),z2=class extends V(`@usine/orchestrator/ScheduleCycle`)({loops:R.check(HT(0)),fanout:R.check(HT(0)),submissions:N(BR),skipped:R.check(HT(0)),alreadyFired:R.check(HT(0)),failures:N(R2),nextTickAt:B(_E)}){},B2=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(e=>zJ(t.selector,e)),trigger:n}]:[]}),V2=(e,t)=>{let n=W_(t);return n.setUTCSeconds(0,0),L_(km(e,n)?n:Mm(e,n))},H2=(e,t)=>L_(jm(e,W_(t))),U2=(e,t)=>vr(U_(e,t),{onNone:()=>J_(e),onSome:Y_}),W2=e=>e.length===0?y():z_(Math.min(...e.map(K_))),G2=e=>nI.make(JSON.stringify([`github`,tA(e.name)])),K2=(e,t,n)=>rA.make(JSON.stringify([e.name,tA(t.name),J_(n)])),q2=e=>({tick:{scheduledAt:J_(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends Rr()(`@usine/orchestrator/ScheduleTriggers`){static layer=Xf(e,T(function*(){let e=yield*Z$,t=yield*eU,n=yield*b0,r=yield*Z1,i=yield*Lk(y()),a=yield*Lk({instance:y(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=Om(e.cron,e.tz);return o.set(e,n),n},c=O(`ScheduleTriggers.submitTick`)(function*(r,i){yield*D({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt)});let a=q2(r),o={repo:zY(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,RY(`schedule`),o)))return yield*A(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt)}),y();let s=K2(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(D0({cycleGeneration:aI.make(0),agent:r.agent,dedupKey:s,itemKey:G2(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:S0,task:lF.make(c),parentModel:r.parentModel}));return yield*k(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...O0(l)}),b(l)}),l=O(`ScheduleTriggers.tick`)(function*(e){let t=yield*B_,n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let t of e.loops)t.trigger.on===`schedule`&&n.has(t.name)&&(yield*A(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=B2(e).filter(({loop:e})=>!n.has(e.name)),l=yield*Bk(a,t=>{let n=Fr(t.instance,e)?t:{instance:b(e),ticks:new Map};return[n.ticks,n]}),u=[],d=[],f=[],p=new Map,m=[],h=0;for(let n of o){n.repositories.length===0&&(yield*e_(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*qh({try:()=>{let e=s(n.trigger),r=V2(e,t);return{latest:r,latestLocal:U2(r,n.trigger.tz),next:H2(e,t)}},catch:e=>e}).pipe($h);if(Di(r)){yield*t_(`Schedule cron boundaries could not be computed`,{loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}),f.push(new L2({loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}));continue}let i=r.success;m.push(i.next);let a=K_(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*A(`Tick already fired`,{loop:n.loop.name,scheduledAt:J_(i.latest)});continue}let c=yield*$h(w0(e,n.loop));if(Di(c)){let e=c.failure;yield*t_(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new F2({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*k(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:J_(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:J_(i.next)});for(let e of n.repositories)u.push({agent:c.success.agent,loop:n.loop,parentModel:c.success.parentModel,repository:e,scheduledAt:i.latest,scheduledAtLocal:i.latestLocal,trigger:n.trigger})}}yield*D({schedules:o.length,fanout:u.length});let g=yield*Ph(u,e=>$h(c(e,t)).pipe(ng(t=>({candidate:e,result:t}))),{concurrency:M2}),_=[],v=[],ee=new Set,te=new Set,ne=0;for(let{candidate:e,result:t}of g){if(Oi(t)){S(t.success)?(_.push(t.success.value),ee.add(e.loop.name)):ne+=1;continue}let n=t.failure;te.add(e.loop.name),yield*t_(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:J_(e.scheduledAt),...P2(n)}),v.push(new I2({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*Vk(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)ee.has(e)&&!te.has(e)&&t.set(e,n);return{...e,ticks:t}});let re=new z2({loops:o.length,fanout:u.length,submissions:_,skipped:ne,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:W2(m)});return yield*zk(i,b(re)),re}),u=(e,t,n)=>yg(_g(eo(n)),x0(e,t).pipe(Zh(k(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:Rk(i),run:e=>T(function*(){let t=yield*e.get,n=yield*$h(l(t));if(Di(n)){yield*t_(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:N2}),yield*u(e,t,N2);return}let r=n.success,i=yield*op,a=vr(r.nextTickAt,{onNone:()=>i+N2,onSome:K_}),o=Math.min(N2,Math.max(0,a-i)),s={loops:r.loops,fanout:r.fanout,submissions:r.submissions.length,skipped:r.skipped,alreadyFired:r.alreadyFired,failures:r.failures.length,nextTickAt:vr(r.nextTickAt,{onNone:()=>`none`,onSome:J_}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*A(`Schedule cycle complete`,s):yield*k(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(Vg),tick:l}}))});var J2=class extends H(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:j,repository:Xk,runId:HA,loop:aA,item:I(jH)}){},Y2=class extends H(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:j,repository:Xk,runId:HA,loop:aA,failure:Iz}){},X2=class extends H(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:j,failure:A0}){},Z2=class extends H(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:j,finding:Hq}){},Q2=class extends H(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:j,failure:RH}){},$2=class extends H(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:j,failure:R2}){},e4=class extends H(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:j,kind:F([`loop`,`agent`]),error:rU}){},t4=class extends H(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,M({id:j,worker:EN,attempts:R.check(HT(1)),running:R.check(HT(0))}).check(NT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},n4=class extends H(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:j,repository:Xk,runId:HA,loop:aA,attemptNumber:cF,worker:EN}){},r4=class extends H(`@usine/orchestrator/UnresponsiveWorkerNeed`)(`UnresponsiveWorkerNeed`,{id:j,worker:EN,lastAnsweredAt:j,attempts:N(M({attemptId:sF,attemptNumber:cF,runId:HA,repository:Xk,loop:aA})).check(GT(1))}){},i4=P([class extends H(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:j,ask:uI,itemLabel:j,itemUrl:I(j)}){},J2,Q2,Y2,X2,Z2,$2,e4,t4,n4,r4,class extends H(`@usine/orchestrator/WorkerPreflightNeed`)(`WorkerPreflightNeed`,{id:j,worker:EN,message:j}){}]),a4=F([`clear`,`active`,`needs-you`]),o4=class extends V(`@usine/orchestrator/ProjectView`)({repository:Xk,status:a4,runs:N(CH),board:zH,labels:N(BH),preflightFindings:N(Hq)}){},s4=class extends V(`@usine/orchestrator/LoopView`)({name:aA,trigger:j,agent:fN,paused:lT}){},c4=class extends H(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:N(o4),loops:N(s4),needsYou:N(i4),dismissedNeeds:N(i4).pipe(TT(w([])))}){},l4=class extends H(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:z,projects:N(o4),loops:N(s4),needsYou:N(i4),dismissedNeeds:N(i4).pipe(TT(w([])))}){},u4=P([c4,l4]),d4=500,f4=500,p4=e=>kk(e,{GitHubPushFailure:({message:e})=>new Oz({message:e}),InfraFailure:({message:e})=>new kz({message:e}),DefectFailure:({message:e})=>new Az({message:e}),AgentFailure:({message:e})=>new jz({message:e}),BlockedFailure:({message:e})=>new Mz({message:e}),QuestionFailure:({question:e})=>new Nz({question:e}),RunawayFailure:({ceiling:e})=>new Pz({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new Fz({attemptedChildren:e,maxChildren:t})}),m4=e=>kk(e,{Succeeded:()=>new Lz,Failed:({failure:e})=>new Rz({failure:p4(e)}),Canceled:()=>new zz}),h4=e=>{switch(e.kind){case`local`:return new Vz;case`ssh`:return vr(e.provisioner,{onSome:({provider:e})=>new Uz({provider:e}),onNone:()=>new Hz({destination:yr(e.destination,()=>jN.make(e.name)),port:C(e.port)})});case`exe.dev`:return new Hz({destination:jN.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new Wz}},g4=e=>new Map(e.map(e=>[e.name,h4(e)])),_4=(e,t)=>new Kz({id:e.id,number:e.number,worker:e.worker,workerAccess:t.get(e.worker)??null,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,startedAt:J_(e.startedAt),outcome:vr(e.outcome,{onNone:()=>null,onSome:m4}),endedAt:vr(e.endedAt,{onNone:()=>null,onSome:J_}),salvage:C(e.salvage),start:C(e.start),reattachedAt:vr(e.reattachedAt,{onNone:()=>null,onSome:J_}),outOfMemory:C(e.outOfMemory)});O(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*Ph(t.attempts.filter(e=>S(e.outcome)&&x(e.endedAt)),t=>e.transcript(new TB({attemptId:t.id,before:y(),limit:1})).pipe(ng(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var v4=O(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*A(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),y4=(e,t,n)=>{let r=OA(e.run.state),i=C(e.step.result),a=i?.facts.find(e=>e._tag===`PullRequest`);return new CH({id:e.run.id,itemKey:e.itemKey,loop:e.run.loop,repository:e.repository,agent:e.agent.name,agentBrain:e.agent.brain,state:e.run.state._tag,loopPaused:t.has(e.run.loop),openedAt:J_(e.run.openedAt),closedAt:vr(e.closedAt,{onNone:()=>null,onSome:J_}),task:e.task,attempts:e.attempts.map(e=>_4(e,n)),approval:vr(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new SH({approvedAt:J_(e),source:C(t)})}),runAgain:C(e.runAgain),resultMessage:i?.message??null,pullRequestUrl:a?.url.toString()??null,...r,canResolveFailure:r.canResolveFailure&&!Fr(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},b4=e=>kk(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new EB({failure:p4(e)}),Interrupted:e=>e,Steer:e=>e,Interrupt:e=>e,OperatorMessage:e=>e,Release:e=>e,Cancel:e=>e,InterventionApplied:e=>e,InterventionRejected:e=>e,WorkerUnresponsive:e=>e,WorkerResponsive:e=>e}),x4=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:J_(e.receivedAt),direction:e.direction,payload:b4(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new OB({...t,target:e.envelope.target,operator:e.envelope.operator}):new OB(t)},S4=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(x4),C4=O(`Operator.readTranscriptPage`)(function*(e,t,n){yield*D({attemptId:t,before:C(n)});let r=yield*e.transcript(new TB({attemptId:t,before:n,limit:501})),i=r.length>d4,a=i?r.slice(1):r,o=a[0];return yield*A(`Read operator transcript page`,{attemptId:t,before:C(n),returned:a.length,hasEarlier:i}),{events:S4(a),earlier:i&&o!==void 0?[new kB({attemptId:t,before:o.sequence})]:[]}});O(`Operator.readTranscript`)(function*(e,t,n){yield*D({runId:t.run.id,request:n._tag});let r=yield*kk(n,{ColdTranscriptRequest:()=>Ph(t.attempts,t=>C4(e,t.id,y()),{concurrency:4}).pipe(ng(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>Ph(t.attempts,t=>e.transcript(new wB({attemptId:t.id,after:n,limit:f4})),{concurrency:4}).pipe(ng(e=>({events:S4(e.flat()).slice(0,f4),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?C4(e,n,b(r)):new NB({runId:t.run.id,attemptId:n})});return yield*A(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var w4=Ww(rE),T4=e=>new jH({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),E4=(e,t,n,r,i,a)=>{let o=da(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${tA(e)}/pull/`,l=new Map(s.filter(({item:e})=>e.kind===`pr`).map(e=>[`${c}${e.item.number}`,e])),u=new Set(r);for(let e of s){if(e.item.kind!==`issue`)continue;let t=[...e.item.linkedPullRequests,...e.runs.flatMap(({pullRequestUrl:e})=>e===null?[]:[e])];for(let n of t){let t=w4(n);if(x(t)||t.value.protocol!==`https:`||t.value.host!==`github.com`)continue;let r=l.get(t.value.pathname.toLowerCase());r!==void 0&&(e.related.add(r),r.related.add(e))}}let d=new Set,f=[];for(let e of s){if(d.has(e))continue;d.add(e);let t=[e];for(let e of t)for(let n of e.related)d.has(n)||(d.add(n),t.push(n));let n=ia(t,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||lr(e.number,t.number)),r=n[0],o=t.flatMap(({item:e,runs:t})=>t.map(t=>({item:e,run:t}))).sort(({run:e},{run:t})=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),s=o.find(({run:e})=>e.canCancel),c=t.filter(({item:e})=>e.kind===`pr`).sort(({item:e},{item:t})=>Number(t.state===`pr-open`)-Number(e.state===`pr-open`)||t.number-e.number),l=s?.item??c[0]?.item??r.item,[p=null]=c.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new MH({number:e,url:t,state:n})]:[]),m=o.find(({item:e,run:t})=>Z0(t,Cz(e.state)))??s??o[0],h=o.map(({run:e})=>e).reverse(),g=new NH({...T4(l),title:r.item.title,labels:l.labels,items:n.map(({item:e})=>T4(e)),pullRequest:p,runs:h,run:m?.run??null,needsYou:o.some(({item:e,run:t})=>Z0(t,Cz(e.state)))||t.some(({item:e})=>u.has(e.itemKey)),conflicting:l.conflicting,loops:[...new Set(n.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:gH(h,a)});f.push({view:g,running:s?.run.state===`Running`?s.run:void 0})}return f},D4=e=>e.flatMap(e=>`label`in e?[e.label]:[]),O4=e=>e.flatMap(e=>`state`in e?[e.state]:[]),k4=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>fz.make(e)).map(e=>({lane:new Ez({name:yz.make(e),sources:[new wz({label:e})]}),origin:`proposed`})),A4=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):k4(t),j4=e=>kH.make(`${e.origin}:${e.lane.name}`),M4=(e,t)=>{let n=new Set(e.labels.map(pz));return t.find(({lane:e})=>D4(e.sources).some(e=>n.has(pz(e))))},N4=(e,t)=>t.find(({lane:t})=>O4(t.sources).includes(e.state)),P4=(e,t)=>Cz(e.state)?N4(e,t):M4(e,t)??N4(e,t),F4=O(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*D(a),Cz(t.state))return;let o=M4(t,r);if(o!==void 0)return yield*A(`Placing the running card in the lane its Item's labels match`,{...a,lane:o.lane.name}),o;let s=i.get(n.id);if(s===void 0){yield*A(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*q0(t.kind,s.payload).pipe(ng(b),og(e=>e_(`The running Run's Event has no labels to read; placing its card by its Item's state`,{...a,eventId:s.id,errorTag:e._tag,message:e.message}).pipe(rg(y()))));if(x(c))return;let l=M4({labels:c.value},r);return yield*A(l===void 0?`No lane label when the card's running Run was triggered; placing it by its Item's state`:`Keeping the card in the lane its running Run was triggered from`,{...a,lane:l?.lane.name??`none`}),l}),I4=O(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>T(function*(){yield*D({repository:e.name});let c=yield*Ph(n,e=>Y0(e).pipe($h)),l=[],u=[];for(let e of c)Oi(e)?l.push(e.success):(u.push(e.failure),yield*t_(`Item projection quarantined from Board; siblings continue`,{repository:e.failure.repository,itemKey:e.failure.itemKey,errorTag:e.failure._tag,message:e.failure.message}));let d=A4(e,t),f=E4(e.name,l,r,i,a,o);yield*A(`Projected Task cards from linked Items`,{repository:e.name,items:l.length,tasks:f.length,runs:r.length,watchedTasks:f.filter(({view:e})=>e.loops.length>0).length,runningTasks:f.filter(({running:e})=>e!==void 0).length});let p=new Map;for(let e of d)p.set(j4(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*F4(e,t,n,d,s))??P4(t,d);r===void 0?m.push(t):p.get(j4(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new zH({failures:u,lanes:[...d.map(e=>{let t=D4(e.lane.sources),n={id:j4(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(j4(e))??[])};return e.origin===`authored`&&t.length>0?new FH({...n,origin:e.origin,labels:t}):new IH(n)}),new IH({id:kH.make(`fallback:unmapped`),name:yz.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),L4=class e extends Rr()(`@usine/orchestrator/LoopMatches`){static layer=Xf(e,T(function*(){let e=yield*eU;return{matching:O(`LoopMatches.matching`)(function*(e,t,n){yield*D({repository:t.name,items:n.length});let r=e.loops.filter(e=>e.trigger.on!==`schedule`&&zJ(e.selector,t)),i=n.filter(({goneAt:e})=>x(e)),a=new Map,o=0;for(let e of r){let n=i.filter(({source:t})=>t===e.trigger.on);if(n.length===0)continue;let r=yield*$h(l2(e,t,n.map(({payload:e})=>e)));if(Di(r)){o+=n.length,yield*A(`Loop trigger could not be checked; it matches no stored Item`,{repository:t.name,loop:e.name,items:n.length,errorTag:r.failure._tag,message:r.failure.message});continue}let s=new Set;for(let[i,a]of aa(n,r.success))Oi(a)?a.success&&s.add(i):(o+=1,yield*A(`Loop trigger could not be evaluated on a stored Item`,{repository:t.name,loop:e.name,item:i.number,errorTag:a.failure._tag,message:a.failure.message}));a.set(e,s)}let s=[];for(let e of i)for(let t of r)a.get(t)?.has(e)===!0&&s.push({loop:t,item:e});return yield*A(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},kg(eU,e))}}))},R4=10,z4=class extends H(`@usine/github/LabelAdded`)(`LabelAdded`,{at:_E,label:IK}){},B4=class extends H(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:_E,label:IK}){},V4=class extends H(`@usine/github/Commented`)(`Commented`,{at:_E,url:z}){},H4=F([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),U4=class extends H(`@usine/github/Reviewed`)(`Reviewed`,{at:_E,url:z,state:H4}){};P([z4,B4,V4,U4]);var W4=`
275
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=T$(w$(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=T$(w$(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}};function k$(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new b$||null,prettyErrors:t}}function A$(e,t={}){let{lineCounter:n,prettyErrors:r}=k$(t),i=new O$(n?.addNewLine),a=new o$(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new SQ(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(wQ(e,n)),o.warnings.forEach(wQ(e,n))),o}function j$(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return YY(e)&&!r?e.toString(n):new yQ(e,r,n).toString(n)}var M$=e=>vr(Ww(M({message:z}))(e),{onNone:()=>`The YAML parser failed without an error message`,onSome:({message:e})=>e}),N$=(e,t)=>T(function*(){let n=yield*qh({try:()=>A$(t,{keepSourceTokens:!0,prettyErrors:!0,strict:!0,uniqueKeys:!0}),catch:t=>new rU({file:e,stage:`yaml`,expression:y(),message:M$(t)})}),r=n.errors[0]??n.warnings[0];return r===void 0?n:yield*new rU({file:e,stage:`yaml`,expression:y(),message:r.message})}),P$=e=>j$(e);V(`@usine/config/YamlEdit`)({path:N(z).check(qT()),value:IE});var F$=(e,t)=>{let n=e.replaceAll(`\r
276
+ `,`
277
+ `);return t===`\r
278
+ `?n.replaceAll(`
279
+ `,`\r
280
+ `):n},I$=O(`YamlWriter.updateYaml`)((e,t,n)=>T(function*(){let r=yield*N$(e,t);return r.setIn(n.path,n.value),F$(r.toString(),t.includes(`\r
281
+ `)?`\r
282
+ `:`
283
+ `)}));O(`YamlWriter.updateFrontmatter`)((e,t,n)=>T(function*(){let r=yield*qq(e,t),i=F$(yield*I$(e,r.yaml,n),r.newline),a=i.endsWith(r.newline)?i.slice(0,-r.newline.length):i;return`---${r.newline}${a}${r.newline}---${r.newline}${r.body}`}));var L$=Yy(),R$=P([j,lT]).annotate({message:`Expected a CEL expression. Quote the value so that YAML reads it as a string.`}).pipe(ST(ZH,{decode:sb(e=>String(e)),encode:sb(e=>e)})),z$=P([UJ.mapFields(Tw({if:R$})).pipe(ST(UJ)),WJ.mapFields(Tw({if:R$})).pipe(ST(WJ)),GJ.mapFields(Tw({if:R$})).pipe(ST(GJ))]),B$=class extends V(`@usine/config/LoopFrontmatter`)({trigger:z$,selector:xE(zJ),approval:sA.pipe(DT(w(`none`))),step:wN.pipe(DT(w(`run`))),agent:fN,maxCycles:ZJ.fields.maxCycles,permissions:ZJ.fields.permissions,priority:xE(XJ)}){},V$=B$.pipe(mT({maxCycles:`max_cycles`})),H$=class extends V(`@usine/config/AgentFrontmatter`)({harness:lN,model:cN,effort:uN,parentModel:xE(cN),parentEffort:xE(uN)}){},U$=H$.pipe(mT({parentModel:`parent_model`,parentEffort:`parent_effort`})),W$=e=>`---\n${P$(Xw(U$)(new H$(e)))}---\n${e.persona}`,G$=e=>`---\n${P$(Xw(V$)(new B$(e)))}---\n${e.body}`,K$=(e,t)=>rU.fromSchema(e,t),q$=Hw(IE),J$=(e,t)=>T(function*(){return yield*q$((yield*N$(e,t)).toJS()).pipe(dg(t=>new rU({file:e,stage:`yaml`,expression:y(),message:L$(t.issue)})))}),Y$=(e,t,n)=>new rU({file:e,stage:`expression`,expression:b(t.source),message:t.message,details:[{path:n,message:t.message}]}),X$=e=>{let t=e.slice(e.lastIndexOf(`/`)+1);return t.endsWith(`.md`)?w(t.slice(0,-3)):new rU({file:e,stage:`schema`,expression:y(),message:`Expected a .md filename`})},Z$=e=>X$(e).pipe(E(t=>Hw(ZJ.fields.name)(t).pipe(dg(t=>K$(e,t))))),Q$=e=>X$(e).pipe(E(t=>Hw(fN)(t).pipe(dg(t=>K$(e,t))))),$$=(e,t)=>T(function*(){let n=[],r=0;for(;r<t.length;){let i=t.indexOf(`{{`,r);if(i<0)break;let a=t.indexOf(`}}`,i+2);if(a<0)return yield*new rU({file:e,stage:`expression`,expression:y(),message:`The prompt has an unclosed {{ at character ${i}. Close it with }}.`});let o=t.slice(i+2,a).trim(),s=yield*Hw(ZH)(o).pipe(dg(t=>K$(e,t)));n.push({source:s,start:i,end:a+2}),r=a+2}return n}),e1=(e,t,n)=>{let r=$J(t.name),i=zY(t.trigger.on);return T(function*(){let a=yield*Ph(yield*$$(r,t.body),t=>e.evaluateScalar(t.source,i,n).pipe(dg(e=>Y$(r,e,[`body`])),ng(e=>({expression:t,value:e})))),o=``,s=0;for(let{expression:e,value:n}of a)o+=t.body.slice(s,e.start),o+=String(n),s=e.end;return o+t.body.slice(s)})},t1=O(`ConfigParser.parseUsineYaml`)((e,t)=>T(function*(){let n=yield*J$(e,t);return yield*Hw(RJ)(n,{onExcessProperty:`error`,errors:`all`}).pipe(dg(t=>K$(e,t)))})),n1=O(`ConfigParser.parseAgentFile`)((e,t)=>T(function*(){let n=yield*Q$(e),r=yield*qq(e,t),i=yield*J$(e,r.yaml),a=yield*Hw(U$)(i,{onExcessProperty:`error`,errors:`all`}).pipe(dg(t=>K$(e,t))),o=yield*Hw(pN)(r.body).pipe(dg(t=>K$(e,t)));return new Jq({name:n,harness:a.harness,model:a.model,effort:a.effort,parentModel:a.parentModel,parentEffort:a.parentEffort,persona:o})})),r1=e=>O(`ConfigParser.parseLoopFile`)((t,n)=>T(function*(){let r=yield*Z$(t),i=yield*qq(t,n),a=yield*J$(t,i.yaml),o=yield*Hw(V$)(a,{onExcessProperty:`error`,errors:`all`}).pipe(dg(e=>K$(t,e))),s=yield*Hw(YJ)(i.body).pipe(dg(e=>K$(t,e))),c=zY(o.trigger.on),l=[],u=yield*e.checkBoolean(o.trigger.if,c).pipe(dg(e=>Y$(t,e,[`trigger`,`if`])),$h);Di(u)&&l.push(u.failure);let d=yield*$$(t,s).pipe($h);if(Di(d))l.push(d.failure);else{let n=yield*Ph(d.success,({source:n})=>e.checkScalar(n,c).pipe(dg(e=>Y$(t,e,[`body`])),$h));for(let e of n)Di(e)&&l.push(e.failure)}return Yi(l)?yield*new rU({file:t,stage:`expression`,expression:l[0].expression,message:l.map(({message:e})=>e).join(`
284
+ `),details:l.flatMap(e=>e.details??[{path:[`body`],message:e.message}])}):new ZJ({name:r,trigger:o.trigger,selector:o.selector,approval:o.approval,maxCycles:o.maxCycles,permissions:o.permissions,priority:o.priority,step:o.step,agent:o.agent,body:s})})),i1=Ww(fz),a1=e=>O(`ConfigParser.configWarnings`)(function*(t,n){let r=new Set(t.labels.map(({name:e})=>pz(e))),i=[];for(let e of t.repos)for(let t of e.lanes)for(let n of t.sources)`label`in n&&!r.has(pz(n.label))&&i.push(new eY({repository:e.name,lane:t.name,label:n.label}));for(let t of n){let n=yield*e.relatedStringLiterals(t.trigger.if,[`item`,`labels`]);for(let e of n){let n=i1(e);S(n)&&!r.has(pz(n.value))&&i.push(new tY({loop:t.name,label:n.value}))}}return i}),o1=class e extends Rr()(`@usine/config/ConfigParser`){static layer=Xf(e,T(function*(){return s1(yield*eU)}))},s1=e=>({configWarnings:a1(e),parseUsineYaml:t1,parseAgentFile:n1,parseLoopFile:r1(e),renderPrompt:O(`ConfigParser.renderPrompt`)((t,n)=>e1(e,t,n))}),c1=z.pipe(L(`CursorKey`)),l1=Hw(N(M({value:IE}))),u1=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),d1=class e extends Rr()(`@usine/engine/CursorStore`){static layer=Xf(e,T(function*(){let e=yield*iN;return{read:O(`CursorStore.read`)(function*(t,n){let r=Sr((yield*T(function*(){return yield*l1(yield*e.select({value:QR.valueJson}).from(QR).where(Y(QR.cursorKey,t)).limit(1).execute())}).pipe(u1(`read runtime cursor`)))[0]);return x(r)?y():yield*Hw(n)(r.value.value,{onExcessProperty:`error`}).pipe(ng(b),og(e=>e_(`Stored cursor no longer decodes; treating it as absent`,{key:t,detail:e.message}).pipe(rg(y()))))}),write:O(`CursorStore.write`)(function*(t,n,r){let i=yield*Jw(n)(r).pipe(u1(`encode runtime cursor`));yield*e.insert(QR).values({cursorKey:t,valueJson:i}).onConflictDoUpdate({target:QR.cursorKey,set:{valueJson:i}}).execute().pipe(ag,u1(`write runtime cursor`))})}}))},f1=e=>e.pipe(dg(e=>e instanceof QL?e:new sz({operation:`update cycle budget`,cause:e}))),p1=class e extends Rr()(`@usine/engine/CycleBudgets`){static layer=Xf(e,T(function*(){let e=yield*iN,t=VV(e);return{generation:O(`CycleBudgets.generation`)(function*(e){return yield*D({itemKey:e}),vr(yield*t.get(e).pipe(dg(e=>new sz({operation:`read cycle generation`,cause:e}))),{onNone:()=>aI.make(0),onSome:e=>e.generation})}),asks:O(`CycleBudgets.asks`)(()=>t.asks().pipe(dg(e=>new sz({operation:`read cycle asks`,cause:e})))),reset:O(`CycleBudgets.reset`)(function*(t,n){yield*D({askId:t,eventId:n.id}),yield*e.transaction(e=>T(function*(){if((yield*e.select().from(GR).where(Y(GR.askId,t)).execute())[0]?.eventId===n.id){yield*k(`Cycle budget reset answer already recorded`,{askId:t,eventId:n.id});return}let r=(yield*VV(e).asks()).find(({id:e})=>e===t);if(r===void 0)return yield*new QL({askId:t});let i=yield*VV(e).get(r.itemKey);if(x(i))return yield*Kh(Error(`Open cycle ask has no budget`));let a=i.value.generation+1;yield*e.insert(VR).values({eventId:n.id,dedupKey:n.dedupKey,payloadJson:lV(n.payload),receivedAt:uV(n.receivedAt)}).execute(),yield*e.insert(GR).values({askId:t,eventId:n.id,itemKey:r.itemKey}).execute(),yield*e.update(UR).set({generation:a,askJson:null,resetPending:!0}).where(Y(UR.itemKey,r.itemKey)).execute(),yield*e.update(WR).set({generation:a}).where(cM(Y(WR.itemKey,r.itemKey),hM(WR.runId,e.select({runId:Q.runId}).from(Q).where(hM(J`json_extract(${Q.stateJson}, '$._tag')`,[...MA]))))).execute(),yield*k(`Operator reset Item cycle budget`,{askId:t,eventId:n.id,itemKey:r.itemKey,repository:r.repository,generation:a,completedCycles:r.completedCycles,counts:r.counts})})).pipe(f1)}),close:O(`CycleBudgets.close`)(function*(t,n){yield*D({askId:t,reason:n});let r=uV(yield*B_);return yield*e.transaction(e=>T(function*(){let i=(yield*VV(e).asks()).find(({id:e})=>e===t);if(i===void 0)return yield*k(`Cycle-budget Ask is no longer open; nothing to close`,{askId:t,reason:n}),!1;let a=Xw(uI)(i);return yield*e.insert(KR).values({askId:t,itemKey:i.itemKey,reason:n,askJson:a,closedAt:r}).onConflictDoUpdate({target:KR.askId,set:{reason:n,askJson:a,closedAt:r}}).execute(),yield*e.update(UR).set({askJson:null}).where(Y(UR.itemKey,i.itemKey)).execute(),yield*k(`Closed cycle-budget Ask without a reset`,{askId:t,reason:n,itemKey:i.itemKey,repository:i.repository,loop:i.loop,completedCycles:i.completedCycles,counts:i.counts}),!0})).pipe(dg(e=>new sz({operation:`close cycle ask`,cause:e})))}),pendingResets:O(`CycleBudgets.pendingResets`)(()=>t.pendingResets().pipe(ng(e=>e.map(e=>new ZL(e))),dg(e=>new sz({operation:`read pending cycle resets`,cause:e})))),acknowledgeReset:O(`CycleBudgets.acknowledgeReset`)(function*(t){yield*D({itemKey:t.itemKey,generation:t.generation}),yield*e.update(UR).set({resetPending:!1}).where(cM(Y(UR.itemKey,t.itemKey),Y(UR.generation,t.generation))).execute().pipe(dg(e=>new sz({operation:`acknowledge cycle reset`,cause:e}))),yield*k(`Cycle reset trigger refresh recorded`,{itemKey:t.itemKey,generation:t.generation})})}}))},m1=new class extends V(`@usine/engine/RetryRequest`)({requestedBy:B(aN),amendment:B(dF)}){}({requestedBy:y(),amendment:y()});V(`@usine/engine/RunAgainRequest`)({step:wN,approval:sA,cycleLimit:B(iI),permissions:lA,context:dF,requestedBy:B(aN)});var h1=P([NR,zR]),g1=(e,t,n)=>{let r=rA.make(JSON.stringify([`operator-run-again`,n.reopening,n.trigger]));return new kR({event:new iA({id:nA.make(r),dedupKey:r,payload:e.event.payload,receivedAt:n.receivedAt}),itemKey:e.itemKey,loop:e.run.loop,step:t.step,approval:t.approval,permissions:t.permissions,cycleLimit:t.cycleLimit,cycleGeneration:n.generation,repository:e.repository,revision:e.revision,task:t.context.task,agent:t.context.agent,parentModel:t.context.parentModel})},_1=class extends V(`@usine/engine/StepExecution`)({attempt:_F,event:iA,run:UA,step:TN,repository:Xk,revision:Zk,task:lF,agent:mN,parentModel:B(cN),permissions:lA,resume:B(QP),reattach:lT.pipe(TT(w(!1)))}){},v1=class extends Rr()(`@usine/engine/StepExecutor`){},y1=e=>({attemptWindows:O(`RunStoreQueries.attemptWindows`)(function*(t){yield*D({attemptId:t});let[n]=yield*e.select(QV).from($).where(Y($.attemptId,t)).execute().pipe(E(iV));if(n===void 0)return yield*Kh(Error(`No attempt ${t} recorded`));let r=yF(NV(n));if(x(r))return yield*A(`The Attempt ended before end times were recorded, so it has no window and none overlaps it`,{attemptId:t}),new wF({own:r,overlapping:[]});let i=e.select({itemKey:Z.itemKey}).from(Q).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(Y(Q.runId,n.runId));return new wF({own:r,overlapping:(yield*e.select(QV).from($).innerJoin(Q,Y(Q.runId,$.runId)).innerJoin(Z,Y(Z.eventId,Q.eventId)).where(cM(hM(Z.itemKey,i),Y($.agent,n.agent),oM($.attemptId,t))).orderBy($.startedAt).execute().pipe(E(iV))).flatMap(e=>Mr(yF(NV(e)))).filter(e=>CF(r.value,e))})})}),b1=cF.make(3),x1=e=>Sr(e.attempts.at(-1)).pipe(Nr(e=>x(e.outcome))),S1=e=>kr(e.salvage,e=>e._tag===`Retained`?e.pushFailure:y()),C1=(e,t,n)=>{let r=new qP({failure:n});return TF({failure:n,number:t.number,maxAutoAttempts:b1})?{_tag:`RetryAttempt`,attempt:t,outcome:r}:{_tag:`RunFailed`,attempt:t,outcome:r,state:LA(e)}},w1=(e,t,n)=>{if(e.run.state._tag!==`Running`)return{_tag:`Unchanged`,reason:`RunNotRunning`};let r=x1(e);if(x(r))return{_tag:`Unchanged`,reason:`NoOpenAttempt`};if(r.value.id!==t)return{_tag:`Unchanged`,reason:`AttemptReplaced`};let i=vr(S1(r.value),{onNone:()=>n,onSome:e=>Ci(e)});return Di(i)?C1(e.run.state,r.value,i.failure):{_tag:`RunSucceeded`,attempt:r.value,outcome:new KP,state:IA(e.run.state),result:i.success}},T1=e=>kk(e,{Pushed:e=>b(e),PartlyPushed:({ref:e,commit:t})=>b(new QP({ref:e,commit:t})),Retained:()=>y(),Rejected:()=>y()}),E1=e=>ra(e,e=>kr(e.salvage,T1)),D1=(e,t,n,r)=>{let i=e.run.state;if(!DA(i)&&i._tag!==`Running`)return{_tag:`RunClosed`,state:i};let a=y(),o=x1(e);if(i._tag===`Running`&&S(o)){if(Fr(n,o.value.id))return{_tag:`ReattachAttempt`,state:i,attempt:o.value,resume:E1(e.attempts)};let r=C1(i,o.value,yr(S1(o.value),()=>t));if(r._tag===`RunFailed`)return r;a=b(r)}let s=S(a)?new iF:yr(r,()=>e.attempts.length===0?new eF:new rF);return{_tag:`StartAttempt`,state:i._tag===`Running`?i:FA(i),number:cF.make((e.attempts.at(-1)?.number??0)+1),start:s,interrupted:a,resume:E1(e.attempts)}},O1=e=>e.run.state._tag===`Canceled`?{_tag:`AlreadyClosed`}:TA(e.run.state)?{_tag:`Canceled`,state:zA(e.run.state),attempt:e.run.state._tag===`Running`?Or(x1(e),e=>({id:e.id,worker:e.worker,outcome:new JP})):y()}:{_tag:`CancelRejected`},k1=e=>{let t=e.run.state;return t._tag===`Failed`?{_tag:`Resume`,state:RA(t)}:t._tag===`Running`&&x(x1(e))?{_tag:`ResumePending`}:{_tag:`RetryRejected`}},A1=(e,t)=>vr(e,{onNone:()=>!1,onSome:e=>!Fr(e,t)}),j1=(e,t)=>e._tag===`Owned`?e.run.state._tag===`Canceled`&&t?{_tag:`ReopenEvent`}:{_tag:`JoinRun`,run:e.run}:e.reason===`revoked`&&t?{_tag:`ReopenEvent`}:{_tag:`StayIgnored`,reason:e.reason},M1=(e,t)=>{if(e._tag!==`RunFailed`||Oi(t))return y();switch(t.failure._tag){case`QuestionFailure`:return b(`question`);case`BlockedFailure`:return b(`blocker`);default:return y()}},N1=(e,t)=>vr(e.suppressedEventId,{onNone:()=>({_tag:`SuppressFrom`}),onSome:e=>e===t?{_tag:`Suppress`}:{_tag:`Lift`}}),P1=(e,t)=>{if(x(e))return{_tag:`OpenRun`};let n=e.value;return n.state._tag===`Running`?{_tag:`QueueEvent`}:EA(n.state)?{_tag:`SupersedeRun`,runId:n.id,state:BA(n.state,t)}:{_tag:`OpenRun`}},F1=B(HA).pipe(TT(w(y()))),I1=class extends V(`@usine/engine/internal/Claim`)({result:BR,openedRun:F1,supersededRun:F1}){},L1=class extends H(`@usine/engine/internal/AttemptStarted`)(`AttemptStarted`,{execution:_1}){},R1=class extends H(`@usine/engine/internal/AttemptRecoveryFailed`)(`AttemptRecoveryFailed`,{}){},z1=class extends H(`@usine/engine/internal/RunClosed`)(`RunClosed`,{}){},B1=T(function*(){let e=yield*iN,t=yield*YO,n=rH(e),r=O(`RunStore.admitRun`)(function*(e,t,n){let r=yield*e.cycles.admit(t);return S(r)?new zR({eventId:t.event.id,ask:r.value}):(yield*e.createRun(t,t.event.id,n),yield*e.cycles.reserve(t,n),new NR({eventId:t.event.id,runId:n}))}),i=O(`RunStore.openRun`)(function*(e,t,n,i=y()){let a=yield*r(e,t,n);return new I1({result:a,openedRun:a._tag===`Claimed`?b(n):y(),supersededRun:i})}),a=e=>jR(e).pipe(kg(YO,t)),o=O(`RunStore.settlementOf`)(function*(e,t){let n=(yield*e.runForEvent(t))[0];if(n!==void 0){let t=(yield*e.snapshot(n.runId)).run;return b({_tag:`Owned`,run:t})}let r=(yield*e.ignoredEvent(t))[0];return r===void 0?y():b({_tag:`Ignored`,reason:r.reason})}),s=O(`RunStore.claimEvent`)(function*(e,t,n){if(!(yield*e.cycles.isCurrentEvent(t)))return new I1({result:new LR({eventId:t.event.id,reason:`superseded`})});let r=yield*e.loopItems.suppression(t.loop,t.itemKey);if(S(r)){let n=N1(r.value,t.event.id),i={eventId:t.event.id,suppressedBy:r.value.runId,loop:t.loop,itemKey:t.itemKey};switch(n._tag){case`SuppressFrom`:return yield*e.loopItems.suppressFrom(t.loop,t.itemKey,t.event.id),yield*k(`First Item state after the Agent stopped for the operator; it waits for the operator`,i),new I1({result:new RR({eventId:t.event.id,runId:r.value.runId})});case`Suppress`:return yield*k(`Item unchanged since the Agent stopped for the operator; no Run opens`,i),new I1({result:new RR({eventId:t.event.id,runId:r.value.runId})});case`Lift`:yield*e.loopItems.lift(t.loop,t.itemKey),yield*k(`Item changed after the Agent stopped for the operator; the Loop acts on its new state`,i)}}let a=(yield*e.blockingRun(t.loop,t.itemKey))[0],o=P1(a===void 0?y():b((yield*e.snapshot(a.runId)).run),t.event.id);switch(yield*k(`Event claim decided`,{eventId:t.event.id,decision:o._tag}),o._tag){case`QueueEvent`:return new I1({result:new PR({eventId:t.event.id})});case`SupersedeRun`:return yield*e.updateState(o.runId,o.state),yield*i(e,t,n,b(o.runId));case`OpenRun`:return yield*i(e,t,n)}}),c=O(`RunStore.recordAndClaim`)(function*(t,n){return yield*D({eventId:t.event.id,runId:n,loop:t.loop,itemKey:t.itemKey}),yield*e.transaction(e=>T(function*(){let r=rH(e),i=yield*r.recordTriggerEvent(t),c=yield*r.loopItems.sighted(i.loop,i.itemKey,i.event.id),l=yr(yield*r.newestReopening(i.event.id),()=>({submission:i,reopening:0})),u=l.submission.event.id,d=yield*o(r,u);if(x(d))return yield*s(r,l.submission,l.reopening===0?n:yield*a(l.submission));let f=j1(d.value,A1(c,i.event.id));switch(f._tag){case`JoinRun`:return yield*k(`Event joined its existing Run`,{eventId:u,runId:f.run.id,state:f.run.state._tag}),new I1({result:new NR({eventId:u,runId:f.run.id})});case`StayIgnored`:return yield*k(`Event remains ignored`,{eventId:u,reason:f.reason}),new I1({result:new LR({eventId:u,reason:f.reason})});case`ReopenEvent`:{let e=l.reopening+1,n=yield*r.recordTriggerEvent(MR(t,i.event.dedupKey,e),b({eventId:i.event.id,reopening:e}));return yield*k(`The Item came back to the state of an Event no Attempt worked on; it opens again`,{eventId:u,settled:d.value._tag,reopenedEventId:n.event.id,reopening:e}),yield*s(r,n,yield*a(n))}}}))},TV(`submit event`)),l=O(`RunStore.parkForApproval`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t);if(r.run.state._tag!==`Pending`)return r.run.state;let i=NA(r.run.state);return yield*n.updateState(t,i),i}))},TV(`park run for approval`)),u=O(`RunStore.applyFinish`)(function*(e,t,n){if(yield*D({runId:t}),n._tag===`Unchanged`){yield*k(`Attempt completion ignored`,{runId:t,reason:n.reason});return}let{attempt:r,outcome:i}=n;yield*D({attemptId:r.id});let a={runId:t,attemptId:r.id,number:r.number,decision:n._tag};yield*k(`Attempt completion decided`,kk(i,{Failed:({failure:e})=>({...a,failure:e._tag}),Succeeded:()=>a}));let o=yield*B_;yield*e.closeAttempt(r.id,i,o),n._tag!==`RetryAttempt`&&(n._tag===`RunSucceeded`&&(yield*e.updateStepResult(t,r.stepName,n.result)),yield*e.updateState(t,n.state,o))}),d=O(`RunStore.suppressForOperator`)(function*(e,t,n){let r=t.run.id,i=Or(yield*e.nextQueued(r),({submission:e})=>e.event.id),a={runId:r,loop:t.run.loop,itemKey:t.itemKey,stop:n};(yield*e.loopItems.startSuppression(t.run.loop,t.itemKey,r,t.event.id,i))?yield*k(`Agent stopped for the operator; its Loop suppresses the Item`,{...a,suppressedEventId:yr(i,()=>`none yet`)}):yield*k(`Agent stopped for the operator, but nothing is suppressed; the Loop last saw the Item not matching`,a)}),f=(e,{attempt:t,state:n,resume:r,reattach:i})=>new _1({attempt:t,event:e.event,run:new UA({id:e.run.id,eventId:e.run.eventId,loop:e.run.loop,state:n,openedAt:e.run.openedAt}),step:e.step,repository:e.repository,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel,permissions:e.permissions,resume:r,reattach:i}),p=O(`RunStore.beginAttempt`)(function*(t,n,r){return yield*D({runId:t,worker:n}),yield*e.transaction(e=>T(function*(){let i=rH(e),a=yield*i.snapshot(t),o=new RP({message:`The orchestrator stopped during the attempt`,cause:Error(`attempt interrupted by orchestrator restart`)}),s=yield*i.nextStart(t),c=D1(a,o,r,s);if(c._tag===`RunClosed`)return yield*k(`Attempt start skipped`,{runId:t,state:c.state._tag}),new z1;if(c._tag===`RunFailed`)return yield*u(i,t,c),new R1;if(c._tag===`ReattachAttempt`){let e=yield*B_,r=new _F({...c.attempt,reattachedAt:b(e)});return yield*i.recordReattach(r.id,e),yield*D({attemptId:r.id}),yield*k(`Attempt reattached after an orchestrator restart`,{runId:t,attemptId:r.id,number:r.number,worker:r.worker}),r.worker!==n&&(yield*t_(`Reattached Attempt keeps its own Worker, not the reserved one`,{runId:t,attemptId:r.id,worker:r.worker,reservedWorker:n})),new L1({execution:f(a,{attempt:r,state:c.state,resume:c.resume,reattach:!0})})}S(c.interrupted)&&(yield*u(i,t,c.interrupted.value)),a.run.state._tag!==c.state._tag&&(yield*i.updateState(t,c.state));let l=sF.make(`${t}/${a.step.name}/${c.number}`),d=yield*B_,p=new _F({id:l,runId:t,stepName:a.step.name,worker:n,number:c.number,brain:a.agent.brain,task:a.task,agent:a.agent.name,operatorIntervened:!1,parentModel:a.parentModel,startedAt:d,outcome:y(),endedAt:y(),salvage:y(),start:b(c.start),reattachedAt:y()});return yield*i.addAttempt(p),S(s)&&(yield*i.setNextStart(t,y())),yield*k(`Attempt started`,{runId:t,attemptId:l,number:c.number,worker:n,start:c.start._tag,resumesFrom:Or(c.resume,({ref:e})=>e)}),new L1({execution:f(a,{attempt:p,state:c.state,resume:c.resume,reattach:!1})})}))},TV(`begin attempt`)),m=O(`RunStore.recordSalvage`)(function*(t,n){yield*D({attemptId:t,salvage:n._tag}),yield*e.transaction(e=>rH(e).recordSalvage(t,n)),yield*k(`Attempt salvage recorded`,kk(n,{Pushed:({ref:e,commit:n})=>({attemptId:t,ref:e,commit:n}),PartlyPushed:({ref:e,commit:n,path:r})=>({attemptId:t,ref:e,commit:n,path:r}),Retained:({path:e,commit:n,pushFailure:r})=>({attemptId:t,path:e,commit:n,pushFailure:Or(r,({message:e})=>e)}),Rejected:({path:e,commit:n})=>({attemptId:t,path:e,commit:n})}))},TV(`record attempt salvage`)),h=O(`RunStore.recordComments`)(function*(t,n){yield*D({attemptId:t,comments:n.length}),yield*e.transaction(e=>rH(e).recordComments(t,n)),yield*k(`Recorded the comments an Attempt posted before it ended without success`,{attemptId:t,comments:n.map(({kind:e,url:t})=>`${e} ${t.href}`)})},TV(`record attempt comments`)),g=O(`RunStore.recordOutOfMemory`)(function*(t,n){yield*D({attemptId:t,container:n.container,kills:n.kills});let r=yield*e.transaction(e=>rH(e).recordOutOfMemory(t,n));yield*k(`Recorded the processes the kernel killed in the Attempt's container`,{attemptId:t,container:n.container,kills:n.kills,memoryMib:n.memoryMib,attemptKills:r.kills})},TV(`record attempt out-of-memory kills`)),_=O(`RunStore.attemptWindows`)(function*(t){yield*D({attemptId:t});let n=yield*y1(e).attemptWindows(t);return yield*A(`Read the Attempt's window and the Attempts of the same Agent that overlap it on its Item`,{attemptId:t,recorded:S(n.own),ended:Ir(n.own,({endedAt:e})=>S(e)),overlapping:n.overlapping.map(e=>e.attemptId)}),n},TV(`read attempt windows`)),v=O(`RunStore.discardLeftovers`)(function*(t){yield*D({worker:t});let n=yield*B_;return yield*e.transaction(e=>RV(e).discardLeftovers(t,n))},TV(`discard attempt leftovers`)),ee=O(`RunStore.openAttempts`)(function*(t){return yield*D({worker:t}),yield*RV(e).openAttempts(t)},TV(`count open attempts`)),te=O(`RunStore.finishAttempt`)(function*(t,n){return yield*D({runId:t.runId,attemptId:t.id}),yield*e.transaction(e=>T(function*(){let r=rH(e),i=yield*r.snapshot(t.runId),a=w1(i,t.id,n);yield*u(r,t.runId,a);let o=M1(a,n);return S(o)&&(yield*d(r,i,o.value)),a}))},TV(`finish attempt`)),ne=O(`RunStore.resolveFailure`)(function*(t,n,r){return yield*D({runId:t,attemptId:n}),yield*e.transaction(e=>T(function*(){let i=rH(e),a=yield*i.snapshot(t),o=a.attempts.at(-1);if(!OA(a.run.state).canResolveFailure||o?.id!==n)return yield*k(`Failure resolution rejected; Run or Attempt changed`,{runId:t,attemptId:n,state:a.run.state._tag,latestAttemptId:o?.id}),yield*new az({runId:t,operation:`resolveFailure`,state:a.run.state._tag});if(Fr(a.resolvedFailureAttemptId,n))return yield*k(`Run failure already resolved`,{runId:t,attemptId:n}),!1;let s=new fF({resolvedAt:yield*B_,operator:r});yield*i.resolveFailure(t,n,s);let c=yield*i.loopItems.liftRun(t);return yield*k(`Run failure resolved`,{runId:t,attemptId:n,liftedSuppression:c,resolvedAt:J_(s.resolvedAt),operator:C(r)}),c}))},TV(`resolve run failure`)),re=O(`RunStore.approve`)(function*(t,n,r){return yield*D({runId:t,eventId:n.id,channel:r.channel}),yield*e.transaction(e=>T(function*(){let i=rH(e);if(yield*i.approvalExists(t))return!1;let a=yield*i.snapshot(t);return a.run.state._tag===`Waiting`?(yield*i.recordApproval(t,n,r),yield*i.updateState(t,PA(a.run.state)),!0):yield*new az({runId:t,operation:`approve`,state:a.run.state._tag})}))},TV(`approve run`)),ie=O(`RunStore.retry`)(function*(t,n=m1){let{amendment:r,requestedBy:i}=n;return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),a=yield*n.snapshot(t),o=k1(a);if(yield*k(`Operator retry decided`,{runId:t,state:a.run.state._tag,decision:o._tag}),o._tag===`Resume`){let e=(yield*n.blockingRun(a.run.loop,a.itemKey))[0];return e===void 0?(S(r)&&(yield*n.amend(t,r.value),yield*k(`Run effective task and Agent amended`,{runId:t,agent:r.value.agent.name})),(yield*n.loopItems.liftRun(t))&&(yield*k(`Operator retry lifts the suppression of the Item`,{runId:t})),yield*n.setNextStart(t,b(S(r)?new nF({operator:i}):new tF({operator:i}))),yield*n.updateState(t,o.state),!0):(yield*k(`Operator retry rejected; another Run is open on the Item`,{runId:t,openRunId:e.runId,loop:a.run.loop,itemKey:a.itemKey}),yield*new oz({runId:t,openRunId:e.runId,message:`Cannot retry run ${t}: run ${e.runId} of loop "${a.run.loop}" is open on the same item. Cancel run ${e.runId}, or try again after it closes.`}))}return o._tag===`ResumePending`&&x(r)?!1:yield*new az({runId:t,operation:`retry`,state:a.run.state._tag})}))},TV(`retry run`)),ae=O(`RunStore.runAgain`)(function*(t,n){yield*D({runId:t,agent:n.context.agent.name});let i=yield*B_;return yield*e.transaction(e=>T(function*(){let o=rH(e),s=yield*o.snapshot(t),{loop:c}=s.run,{itemKey:l}=s;if(!OA(s.run.state).canRunAgain)return yield*k(`Run again rejected; only a succeeded or canceled Run runs again`,{runId:t,state:s.run.state._tag}),yield*new az({runId:t,operation:`runAgain`,state:s.run.state._tag});let u=(yield*o.blockingRun(c,l))[0];if(u!==void 0)return yield*k(`Run again rejected; another Run is open on the Item`,{runId:t,openRunId:u.runId,loop:c,itemKey:l}),yield*new oz({runId:t,openRunId:u.runId,message:`Run ${t} cannot run again: run ${u.runId} of loop "${c}" is open on the same item. Cancel run ${u.runId}, or try again after it closes.`});let d=yr(yield*o.reopenedEvent(s.event.id),()=>({eventId:s.event.id,dedupKey:s.event.dedupKey})),f=vr(yield*o.newestReopening(d.eventId),{onNone:()=>1,onSome:e=>e.reopening+1}),p=vr(yield*o.cycles.get(l),{onNone:()=>aI.make(0),onSome:e=>e.generation}),m=g1(s,n,{trigger:d.dedupKey,reopening:f,generation:p,receivedAt:i}),h=yield*o.recordTriggerEvent(m,b({eventId:d.eventId,reopening:f}));yield*o.recordRunAgain(h.event.id,new Dz({from:t,requestedBy:n.requestedBy}));let g=yield*r(o,h,yield*a(h));return yield*k(`Run again decided`,kk(g,{Claimed:({runId:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`OpenRun`,openedRunId:e,requestedBy:yr(n.requestedBy,()=>`none`)}),CycleBlocked:({ask:e})=>({runId:t,eventId:h.event.id,reopening:f,decision:`CycleBlocked`,askId:e.id,requestedBy:yr(n.requestedBy,()=>`none`)})})),g}))},TV(`run again`)),oe=O(`RunStore.cancel`)(function*(t){return yield*D({runId:t}),yield*e.transaction(e=>T(function*(){let n=rH(e),r=yield*n.snapshot(t),i=O1(r);if(yield*k(`Operator cancellation decided`,{runId:t,state:r.run.state._tag,decision:i._tag}),i._tag===`AlreadyClosed`)return i;if(i._tag===`CancelRejected`)return yield*new az({runId:t,operation:`cancel`,state:r.run.state._tag});let a=yield*B_;if(S(i.attempt)){let{id:e,outcome:t}=i.attempt.value;yield*n.closeAttempt(e,t,a)}return yield*n.updateState(t,i.state,a),{_tag:`Canceled`,openAttempt:Or(i.attempt,({id:e,worker:t})=>({id:e,worker:t})),loop:r.run.loop,itemKey:r.itemKey}}))},TV(`cancel run`)),se=O(`RunStore.revoke`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=rH(e);yield*r.loopItems.unmatched(t,n);let i=yield*r.revokeUnstarted(t,n);for(let e of i){let t=yield*r.snapshot(e.runId);EA(t.run.state)&&(yield*r.updateState(e.runId,VA(t.run.state)))}return i.map(e=>e.runId)}))},TV(`revoke run`)),ce=O(`RunStore.revokeQueued`)(function*(e){let{loop:t,itemKey:r,event:i}=e.submission;return yield*D({loop:t,itemKey:r,eventId:i.id}),yield*n.revokeQueued(t,r,e.eventIds)},TV(`revoke queued events`)),le=O(`RunStore.claimQueued`)(function*(t,n){return yield*e.transaction(e=>T(function*(){let r=rH(e),a=yield*r.runForEvent(t.event.id);return a[0]===void 0?(yield*r.ignoredEvent(t.event.id)).length>0||(yield*r.blockingRun(t.loop,t.itemKey)).length>0||S(yield*r.loopItems.suppression(t.loop,t.itemKey))||!(yield*r.cycles.isCurrentEvent(t))?y():(yield*i(r,t,n)).openedRun:(yield*k(`Queued Event already opened its Run`,{eventId:t.event.id,runId:a[0].runId}),y())}))},TV(`claim queued event`)),ue=O(`RunStore.appendTranscript`)(function*(t,n){let r=yield*B_;yield*e.transaction(e=>T(function*(){let i=rH(e);t===`outbound`&&n.payload._tag===`Started`&&(yield*i.updateAttemptParentModel(n.attemptId,n.payload.parentModel)),t===`outbound`&&n.payload._tag===`InterventionApplied`&&(yield*i.markIntervened(n.attemptId)),(yield*i.appendTranscript(t,n,r))||(yield*A(`Transcript envelope already recorded; keeping the first copy`,{attemptId:n.attemptId,direction:t,sequence:n.sequence}))}))},TV(`append attempt transcript`)),de=O(`RunStore.transcript`)(function*(e){return yield*n.transcript(e)},TV(`read attempt transcript`));return{approve:re,appendTranscript:ue,beginAttempt:p,cancel:oe,claimQueued:le,finishAttempt:te,nextQueued:e=>n.nextQueued(e).pipe(TV(`find queued event`)),parkForApproval:l,pendingContinuations:n.pendingContinuations().pipe(TV(`list pending continuations`)),runIdsToDrive:n.runIdsToDrive().pipe(TV(`list the runs to drive`)),recordAndClaim:c,salvageCandidates:n.salvageCandidates().pipe(TV(`list salvage candidates`)),salvageCandidate:e=>n.salvageCandidate(e).pipe(TV(`read a salvage candidate`)),recordSalvage:m,recordComments:h,recordOutOfMemory:g,attemptWindows:_,discardLeftovers:v,openAttempts:ee,submission:e=>n.eventRouteByRun(e).pipe(E(t=>t[0]===void 0?Uh(new iz({runId:e})):w(OV(t[0]))),TV(`read run submission`)),resolveFailure:ne,retry:ie,revoke:se,revokeQueued:ce,runAgain:ae,snapshot:e=>n.snapshot(e).pipe(TV(`read run`)),transcript:de}}),V1=class e extends Rr()(`@usine/engine/internal/RunStore`){static layer=Xf(e,B1)},H1=z.pipe(L(`ItemProjectionSource`)),U1=z.pipe(L(`ItemContentHash`)),W1=class extends V(`@usine/engine/ItemProjection`)({itemKey:nI,repository:Xk,source:H1,number:rI,contentHash:U1,payload:LE,goneAt:yE(vE).pipe(DT(w(null)),TT(w(y())))}){},G1=M({itemKey:W1.fields.itemKey,repository:Xk,source:H1,number:rI,contentHash:U1,payload:LE,goneAt:W1.fields.goneAt}),K1=Hw(N(G1)),q1=Hw(N(rI)),J1=Xw(LE),Y1=Xw(G1.fields.goneAt),X1=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),Z1={itemKey:$R.itemKey,repository:$R.repository,source:$R.source,number:$R.itemNumber,contentHash:$R.contentHash,payload:$R.payloadJson,goneAt:$R.goneAt},Q1=T(function*(){let e=yield*iN;return{get:O(`ItemProjectionReader.get`)(function*(t){yield*D({itemKey:t});let[n]=yield*K1(yield*e.select(Z1).from($R).where(Y($R.itemKey,t)).execute(),{onExcessProperty:`error`});return Or(Sr(n),e=>new W1(e))},X1(`read item projection`)),list:O(`ItemProjectionReader.list`)(function*(t,n){return yield*D({repository:t,limit:n.limit}),(yield*K1(yield*e.select(Z1).from($R).where(Y($R.repository,t)).orderBy(jM($R.itemNumber)).limit(n.limit).execute(),{onExcessProperty:`error`})).map(e=>new W1(e))},X1(`list item projections`)),openIssues:O(`ItemProjectionReader.openIssues`)(function*(t){return yield*D({repository:t}),yield*q1((yield*e.select({number:$R.itemNumber}).from($R).where(cM(Y($R.repository,t),Y($R.source,`issue`),_M($R.goneAt),J`json_extract(${$R.payloadJson}, '$.state') = 'OPEN'`)).orderBy(AM($R.itemNumber)).execute()).map(({number:e})=>e))},X1(`list open issue projections`))}}),$1=T(function*(){let e=yield*iN;return{upsert:O(`ItemProjectionWriter.upsert`)(function*(t){yield*D({repository:t.repository,item:t.number,itemKey:t.itemKey});let n=Y1(t.goneAt);return(yield*e.insert($R).values({itemKey:t.itemKey,repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:J1(t.payload),goneAt:n}).onConflictDoUpdate({target:$R.itemKey,set:{repository:t.repository,source:t.source,itemNumber:t.number,contentHash:t.contentHash,payloadJson:J1(t.payload),goneAt:n},setWhere:J`${$R.contentHash} != ${t.contentHash} OR ${$R.goneAt} IS NOT ${n}`}).returning({itemKey:$R.itemKey}).execute()).length===0?(yield*A(`Item projection already matched the observed snapshot`,{repository:t.repository,item:t.number,contentHash:t.contentHash}),!1):(yield*A(`Item projection updated from trigger polling`,{repository:t.repository,item:t.number,source:t.source,contentHash:t.contentHash}),!0)},X1(`write item projection`)),markGone:O(`ItemProjectionWriter.markGone`)(function*(t,n){return yield*D({itemKey:t}),(yield*e.update($R).set({goneAt:Y1(b(n))}).where(cM(Y($R.itemKey,t),_M($R.goneAt))).returning({itemKey:$R.itemKey}).execute()).length===0?(yield*A(`Item projection already gone or never stored`,{itemKey:t}),!1):(yield*k(`Item projection marked gone from GitHub`,{itemKey:t,goneAt:J_(n)}),!0)},X1(`mark item projection gone`))}}),e0=class e extends Rr()(`@usine/engine/ItemProjectionReader`){static layer=Xf(e,Q1)},t0=class e extends Rr()(`@usine/engine/ItemProjectionWriter`){static layer=Xf(e,$1)},n0=class extends Rr()(`@usine/engine/TriggerCondition`){},r0=class extends V(`@usine/engine/LoopRuntimeState`)({loop:aA,paused:lT}){},i0=e=>t=>t.pipe(dg(t=>new sz({operation:e,cause:t}))),a0=T(function*(){let e=yield*iN,t=O(`LoopControl.stateFor`)(function*(t){yield*D({loop:t});let n=(yield*e.select({loop:nz.loopName,paused:nz.paused}).from(nz).where(Y(nz.loopName,t)).limit(1).execute())[0];return n===void 0?new r0({loop:t,paused:!1}):new r0(n)},i0(`read loop runtime state`)),n=O(`LoopControl.states`)(function*(){return(yield*e.select({loop:nz.loopName,paused:nz.paused}).from(nz).orderBy(AM(nz.loopName)).execute()).map(e=>new r0(e))},i0(`list loop runtime states`)),r=O(`LoopControl.write`)(function*(n){yield*D({loop:n.loop});let r=yield*t(n.loop);return r.paused===n.paused?(yield*A(`Loop runtime state was already set`,{loop:n.loop,paused:n.paused}),r):(yield*e.insert(nz).values({loopName:n.loop,paused:n.paused}).onConflictDoUpdate({target:nz.loopName,set:{paused:n.paused}}).execute().pipe(i0(`write loop runtime state`)),yield*k(n.paused?`Loop paused`:`Loop unpaused`,{loop:n.loop,paused:n.paused}),n)});return{isPaused:O(`LoopControl.isPaused`)(function*(e){return(yield*t(e)).paused}),pause:O(`LoopControl.pause`)(e=>r(new r0({loop:e,paused:!0}))),states:n(),unpause:O(`LoopControl.unpause`)(e=>r(new r0({loop:e,paused:!1})))}}),o0=class e extends Rr()(`@usine/engine/LoopControl`){static layer=Xf(e,a0)},s0=N(z),c0=class extends V(`@usine/engine/BoardMoveRecord`)({repository:Xk,itemKey:nI,at:_E,fromLane:z,toLane:z,added:s0.check(qT()),removed:s0}){},l0=Hw(N(M({repository:c0.fields.repository,itemKey:c0.fields.itemKey,at:vE,fromLane:c0.fields.fromLane,toLane:c0.fields.toLane,added:c0.fields.added,removed:c0.fields.removed}))),u0=Xw(c0.fields.added),d0=Xw(c0.fields.removed),f0=e=>t=>dg(t,t=>new sz({operation:e,cause:t})),p0=T(function*(){let e=yield*iN;return{record:O(`BoardMoves.record`)(function*(t){yield*D({repository:t.repository,itemKey:t.itemKey}),yield*e.insert(tz).values({repository:t.repository,itemKey:t.itemKey,movedAt:uV(t.at),fromLane:t.fromLane,toLane:t.toLane,addedJson:u0(t.added),removedJson:d0(t.removed)}).execute(),yield*A(`Recorded a Board move before writing its labels`,{repository:t.repository,itemKey:t.itemKey,at:uV(t.at),fromLane:t.fromLane,toLane:t.toLane})},f0(`record board move`)),onItem:O(`BoardMoves.onItem`)(function*(t,n){return yield*D({itemKey:t}),(yield*l0(yield*e.select({repository:tz.repository,itemKey:tz.itemKey,at:tz.movedAt,fromLane:tz.fromLane,toLane:tz.toLane,added:tz.addedJson,removed:tz.removedJson}).from(tz).where(cM(Y(tz.itemKey,t),fM(tz.movedAt,uV(n)))).orderBy(AM(tz.movedAt),AM(tz.moveId)).execute(),{onExcessProperty:`error`})).map(e=>new c0(e))},f0(`read board moves`))}}),m0=class e extends Rr()(`@usine/engine/BoardMoves`){static layer=Xf(e,p0)},h0=class extends Rr()(`@usine/engine/RunEngineShutdown`){},g0=class e extends Rr()(`@usine/engine/AttemptAdmission`){static layer=Xf(e,T(function*(){let e=yield*Dg(h0),t=S(e)?e.value:yield*vf(),n=yield*Lk(new Set),r=yield*vf(),i=O(`AttemptAdmission.enter`)(function*(e){yield*D({runId:e});let r=yield*Bk(n,n=>Sf(t)?[!1,n]:[!0,new Set([...n,e])]);return r||(yield*k(`Attempt deferred until restart; the engine is draining`,{runId:e})),r}),a=O(`AttemptAdmission.leave`)(function*(e){yield*D({runId:e});let i=yield*Hk(n,t=>new Set([...t].filter(t=>t!==e)));(yield*xf(t))&&(yield*k(`Attempt settled during drain`,{runId:e,remainingRunIds:[...i]}),i.size===0&&(yield*Cf(r,void 0)))});return{withAttempt:O(`AttemptAdmission.withAttempt`)(function*(e,t){return yield*D({runId:e}),yield*jg(i(e),e=>e?t:Hh,t=>t?a(e):Bh)}),drain:O(`AttemptAdmission.drain`)(function*(){yield*Cf(t,void 0);let e=yield*Rk(n);yield*k(`Engine drain started; no further Attempts will be admitted`,{activeRunIds:[...e]}),e.size===0&&(yield*Cf(r,void 0)),yield*yf(r),yield*k(`Engine drain completed; all admitted Attempts settled`)})}}))},_0=class extends NE(`@usine/engine/internal/ParentStopUnconfirmedError`)(`ParentStopUnconfirmedError`,{attemptId:sF,worker:EN,cause:eE()}){},v0=(e,t)=>{let n=new Map(e);return n.delete(t),n},y0=O(`CheckoutRecovery.for`)(function*(e,t){let n=yield*Lk(new Map),r=n=>t.recover(n,{salvage:t=>e.recordSalvage(n.attemptId,t),comments:t=>e.recordComments(n.attemptId,t),windows:e.attemptWindows(n.attemptId)}).pipe(pg(e=>t_(`Attempt salvage reconciliation failed; work retained`,{attemptId:n.attemptId,worker:n.worker,message:String(e)})),gg),i=O(`CheckoutRecovery.keep`)(function*(e){yield*t.occupy(e.worker,e.attemptId).pipe(E(e=>Ig(e.release).pipe(ng(t=>({worker:e.worker,release:t,checkoutKept:!0})))),E(t=>Vk(n,n=>new Map(n).set(e.attemptId,t))),zg)}),a=O(`CheckoutRecovery.recoverOpen`)(function*(e){let n={attemptId:e.attemptId,worker:e.worker};yield*D(n);let a=yield*t.isLive(e.attemptId).pipe($h);if(Oi(a)&&!a.success)return yield*r(e);Di(a)?yield*e_(`Could not read whether an open Attempt's parent task is live; its checkout stays for its Run to decide`,{...n,errorTag:a.failure._tag,message:a.failure.message}):yield*k(`Leaving the checkout of an open Attempt whose parent task is live for its Run to reattach`,n),yield*i(e),yield*k(`Occupied a slot on the Worker of an open Attempt kept for its Run to reattach`,n)}),o=O(`CheckoutRecovery.recoverClosed`)(function*(e){let n={attemptId:e.attemptId,runId:e.runId,worker:e.worker};yield*D(n);let a=yield*t.interrupt(e.attemptId,`startup`).pipe($h);return Oi(a)?(yield*r(e),y()):(yield*e_(`Could not confirm that the parent task of a closed Attempt stopped; its checkout and a slot of its Worker stay kept, and no Attempt starts on its Item, until a reconcile confirms the stop`,{...n,errorTag:a.failure._tag,message:a.failure.message}),yield*i(e),b(e))}),s=O(`CheckoutRecovery.atStartup`)(function*(){let n=new Set(yield*t.workers),r=yield*e.salvageCandidates,i=r.filter(({worker:e})=>n.has(e)),s=r.filter(({worker:e})=>!n.has(e));return s.length>0&&(yield*e_(`Attempts recorded on Workers that are not configured were not reconciled; their checkouts stay until those Workers are configured again or their leftovers are discarded`,{attempts:s.length,workers:[...new Set(s.map(({worker:e})=>e))].sort().join(`,`)})),ga(yield*Ph(i,e=>e.open?a(e).pipe(rg(y())):o(e)))}),c=O(`CheckoutRecovery.reattachSlot`)(function*(e){return Or(Nr(Cr((yield*Rk(n)).get(e)),({checkoutKept:e})=>e),t=>({worker:t.worker,release:Rk(n).pipe(E(n=>n.get(e)===t?k(`The slot startup occupied stays kept with the checkout no execution acquired, until the Attempt's parent task is confirmed stopped`,{attemptId:e,worker:t.worker}):t.release))}))}),l=O(`CheckoutRecovery.acquired`)(function*(e){(yield*Bk(n,t=>t.get(e)?.checkoutKept===!0?[!0,v0(t,e)]:[!1,t]))&&(yield*k(`The reattached Attempt's execution acquired the checkout startup kept; its executor releases the checkout from here, and its Run the slot once the Attempt ends`,{attemptId:e}))}),u=O(`CheckoutRecovery.hold`)(function*(e,t){let r={attemptId:e,worker:t.worker};yield*D(r);let i=yield*Ig(t.release);(yield*Bk(n,n=>n.has(e)?[!1,n]:[!0,new Map(n).set(e,{worker:t.worker,release:i,checkoutKept:!1})]))?yield*k(`The Attempt keeps its Run's slot until its parent task is confirmed stopped`,r):(yield*A(`The Attempt already has a slot kept until its parent task is confirmed stopped; releasing its Run's lease`,r),yield*i)},zg),d=O(`CheckoutRecovery.confirmStop`)(function*(e,n,r){let i={attemptId:e,worker:n.worker,checkoutKept:n.checkoutKept,reason:r};yield*D(i);let a=yield*t.interrupt(e,r).pipe($h);if(Oi(a))return;let o={...i,errorTag:a.failure._tag,message:a.failure.message};return yield*n.checkoutKept?e_(`Could not confirm that the parent task of an Attempt its Run does not reattach stopped; its checkout and its Worker's slot stay, and the Run starts no next Attempt until the stop is confirmed`,o):e_(`Could not confirm that the parent task of a closed Attempt stopped; its Worker's slot stays taken, and no Attempt starts on its Item, until a reconcile confirms the stop`,o),yield*new _0({attemptId:e,worker:n.worker,cause:a.failure})}),f=O(`CheckoutRecovery.recoverKept`)(function*(n){let i=yield*e.salvageCandidate(n).pipe($h);if(Di(i)){yield*t_(`Could not read the Attempt whose checkout startup kept; the checkout stays until the next startup`,{attemptId:n,errorTag:i.failure._tag});return}if(x(i.success)){yield*e_(`The leftovers of the Attempt whose checkout startup kept were discarded; the checkout stays`,{attemptId:n});return}let a=i.success.value,o={attemptId:n,worker:a.worker,open:a.open};yield*D(o),(yield*t.workers).includes(a.worker)?(yield*k(`Reconciling the checkout startup kept for an Attempt that was not reattached`,o),yield*r(a)):yield*e_(`The Worker of the Attempt whose checkout startup kept is no longer configured; the checkout stays until it is configured again or its leftovers are discarded`,o)});return{atStartup:s,reattachSlot:c,acquired:l,hold:u,reconcile:O(`CheckoutRecovery.reconcile`)(function*(e,t){yield*D({attemptId:e,reason:t});let r=(yield*Rk(n)).get(e);r===void 0?yield*A(`No slot kept for the Attempt awaits its parent task's stop`,{attemptId:e}):(yield*d(e,r,t),r.checkoutKept&&(yield*f(e)),yield*Vk(n,t=>v0(t,e)).pipe(Zh(r.release),zg),yield*k(`Released the slot kept for an Attempt whose parent task is confirmed stopped`,{attemptId:e,worker:r.worker,checkoutKept:r.checkoutKept}))})}}),b0=class extends V(`@usine/engine/UnconfirmedStop`)({attemptId:sF,runId:HA,loop:aA,itemKey:nI,worker:EN,reason:uF}){},x0=class e extends Rr()(`@usine/engine/UnconfirmedStops`){static empty=Jf(e)({list:w([])})},S0=e=>cg(e,{EnginePersistenceError:e=>new RP({message:`Runtime store error: could not ${e.operation}`,cause:e}),RunNotFoundError:e=>Kh(e),RunOperationRejectedError:e=>Kh(e),RunRetryBlockedError:e=>Kh(e)}),C0=4,w0=`100 millis`,T0=(e,t)=>n=>n.pipe(pg(n=>n._tag===`EnginePersistenceError`?e_(`A Run store operation failed to persist`,{runId:e,operation:t,cause:n.cause}):Bh),hg({schedule:dh(w0),times:C0,while:e=>e._tag===`EnginePersistenceError`})),E0=e=>kr(e,e=>e._tag===`Live`?b(e.attempt):y()),D0=class e extends Rr()(`@usine/engine/internal/RunDriver`){static layer=Xf(e,T(function*(){let e=yield*V1,t=yield*v1,n=yield*g0,r=yield*n0,i=yield*t0,a=yield*YO,o=yield*ek(),s=yield*y0(e,t),c=yield*Lk(new Map),l=yield*Lk(new Map),u=(e,t)=>Bk(l,n=>n.get(e)===t?[!0,v0(n,e)]:[!1,n]).pipe(E(n=>n?t.release:A(`The Run's slot stays with its Attempt until the parent task is confirmed stopped`,{runId:e,worker:t.worker}))),d=O(`RunDriver.launch`)(function*(e){if(yield*D({runId:e}),yield*sk(o,e)){yield*A(`The Run's fiber already runs in this process`,{runId:e});return}yield*A(`Starting the Run's fiber`,{runId:e});let t=yield*eg(Hg);yield*uk(o,e,ee(e).pipe(mg(t=>Qd(t)?Bh:t_(`The Run's fiber stopped on an engine failure; the next reconcile or a restart resumes it`,{runId:e,cause:t})),Wg(`RunDriver.drive`,{root:!0,links:Mr(Or(t,e=>({span:e,attributes:{}})))}),lg(e=>Qd(e)?Wh(e):Bh)),{onlyIfMissing:!0})}),f=O(`RunDriver.resume`)(function*(e){yield*D({runId:e});let t=yield*ak(o,e);S(t)&&(yield*A(`Waiting for the Run's previous fiber to end`,{runId:e}),yield*RE(t.value)),yield*d(e)}),p=O(`RunDriver.stop`)(function*(e){yield*D({runId:e}),(yield*sk(o,e))?(yield*ck(o,e),yield*k(`The closed Run's fiber stopped`,{runId:e})):yield*A(`The closed Run has no fiber in this process`,{runId:e})}),m=O(`RunDriver.markItemGone`)(function*(e,t){return yield*D({runId:e,itemKey:t.itemKey}),yield*i.markGone(t.itemKey,yield*B_).pipe(T0(e,`mark the item's projection gone`),og(n=>e_(`Could not mark the gone Item's projection; its Board card stays in place`,{completedRunId:e,itemKey:t.itemKey,errorTag:n._tag}).pipe(rg(!1))))}),h=O(`RunDriver.continueWithNewest`)(function*(t){yield*D({runId:t});let n=yield*e.nextQueued(t).pipe(T0(t,`read the queued events`));if(x(n))return;let i=n.value.submission,o={completedRunId:t,eventId:i.event.id,loop:i.loop,itemKey:i.itemKey},s=yield*r.recheck(i);if(s!==`matches`){let r=yield*e.revokeQueued(n.value).pipe(T0(t,`revoke the queued events`));if(s===`no-longer-matches`){yield*k(`Queued Event no longer matches its trigger; revoked`,{...o,revokedEvents:r});return}let a=yield*m(t,i);yield*k(`Queued Event's Item is gone from its source; revoked its queued Events`,{...o,revokedEvents:r,projectionMarkedGone:a});return}let c=yield*jR(i).pipe(kg(YO,a)),l=yield*e.claimQueued(i,c).pipe(T0(t,`claim the queued event`));x(l)?yield*k(`Queued Event still matches its trigger but could no longer be claimed; no Run opened`,o):(yield*k(`Queued Event still matches its trigger; opening its Run`,{...o,runId:l.value}),yield*d(l.value))}),g=O(`RunDriver.openAttempt`)(function*(n){yield*D({runId:n});let r=yield*e.snapshot(n).pipe(T0(n,`read the run`)),i=r.attempts.at(-1);if(r.run.state._tag!==`Running`||i===void 0||S(i.outcome))return y();let a={runId:n,attemptId:i.id,worker:i.worker};yield*D({attemptId:i.id,worker:i.worker});let o=yield*t.isLive(i.id).pipe($h);if(Di(o))return yield*e_(`Could not read whether the open Attempt is live; the Run does not reattach it`,{...a,errorTag:o.failure._tag,message:o.failure.message}),b({_tag:`Interrupted`,attempt:i});if(o.success)return yield*k(`The open Attempt's parent task is live; reattaching it`,a),b({_tag:`Live`,attempt:i});let s=yield*t.outcome(i.id).pipe($h);if(Di(s))return yield*e_(`Could not read the open Attempt's stored outcome; the Run does not reattach it`,{...a,errorTag:s.failure._tag,message:s.failure.message}),b({_tag:`Interrupted`,attempt:i});if(x(s.success))return yield*k(`The open Attempt's parent task is gone; the Run does not reattach it`,a),b({_tag:`Interrupted`,attempt:i});let c=s.success.value;return yield*k(`The open Attempt's parent task finished before this process recorded it; finishing the Attempt with its stored result`,{...a,outcome:Ai(c,{onSuccess:()=>`Succeeded`,onFailure:({_tag:e})=>e})}),b({_tag:`Finished`,attempt:i,result:c})}),_=O(`RunDriver.slot`)(function*(e,n,r,i){yield*D({runId:e});let a=w(r),o=E0(r);if(S(o)){let t=yield*s.reattachSlot(o.value.id);if(S(t))return yield*k(`The Run reattaches its open Attempt in the slot startup occupied on its Worker`,{runId:e,attemptId:o.value.id,worker:t.value.worker}),{lease:t.value,open:a}}return{lease:yield*i(t.reserve(e,n,Or(o,({worker:e})=>e))),open:S(o)?g(e):a}}),v=O(`RunDriver.attempt`)(function*(n,r,i,a){yield*D({runId:n,worker:i});let o=yield*a;if(x(E0(o))&&S(yield*ie(r)))return yield*k(`Run waits for an unconfirmed stop after reserving a worker slot`,{runId:n,worker:i,itemKey:r.itemKey}),`WaitingForStop`;if(S(o)&&o.value._tag===`Finished`){let t=yield*e.finishAttempt(o.value.attempt,o.value.result).pipe(T0(n,`finish the attempt`));if(t._tag!==`RetryAttempt`)return t._tag}let c=yield*e.beginAttempt(n,i,Or(E0(o),({id:e})=>e)).pipe(T0(n,`begin the attempt`));if(c._tag===`AttemptRecoveryFailed`)return`RunFailed`;if(c._tag===`RunClosed`)return`Unchanged`;let l=yield*t.execute(c.execution,{append:(t,n)=>e.appendTranscript(t,n).pipe(S0),salvage:t=>e.recordSalvage(c.execution.attempt.id,t).pipe(S0),comments:t=>e.recordComments(c.execution.attempt.id,t).pipe(S0),outOfMemory:t=>e.recordOutOfMemory(c.execution.attempt.id,t).pipe(S0),windows:e.attemptWindows(c.execution.attempt.id).pipe(T0(n,`read the attempt windows`),S0),transcript:e.transcript(new bB({attemptId:c.execution.attempt.id})).pipe(T0(n,`read the attempt transcript`),S0,ng(e=>e.flatMap(({envelope:e})=>e.version===7?[e]:[]))),checkoutAcquired:s.acquired(c.execution.attempt.id)}).pipe(ug(e=>t_(`Step executor defect; operator intervention required`,{runId:n,attemptId:c.execution.attempt.id,defect:e instanceof Error?e.message:String(e)}).pipe(Zh(new zP({message:`The step executor crashed with an unexpected error`,cause:e})))),$h);return c.execution.reattach&&Di(l)&&(yield*ae(new b0({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,worker:i,reason:`failed`}))),Di(l)&&(yield*re({attemptId:c.execution.attempt.id,runId:n,loop:r.loop,itemKey:r.itemKey,reason:`failed`,worker:i})),(yield*e.finishAttempt(c.execution.attempt,l).pipe(T0(n,`finish the attempt`)))._tag}),ee=$g(function*(t){let r=yield*e.submission(t).pipe(T0(t,`read the run's submission`));if(yield*D({runId:t,loop:r.loop,itemKey:r.itemKey}),r.approval===`required`&&(yield*e.parkForApproval(t).pipe(T0(t,`park the run for approval`)))._tag===`Waiting`){yield*k(`Run waits for its approval`,{runId:t});return}let i;do{let e=yield*g(t);if(S(e)&&e.value._tag!==`Live`&&(yield*ae(new b0({attemptId:e.value.attempt.id,runId:t,loop:r.loop,itemKey:r.itemKey,worker:e.value.attempt.worker,reason:`startup`}))),x(E0(e))){let e=yield*ie(r);if(S(e)){yield*k(`The Run starts no Attempt while the parent task of an earlier Attempt on its Item is not confirmed stopped; each reconcile tries that stop again, then drives the Run`,{runId:t,loop:r.loop,itemKey:r.itemKey,unstoppedAttemptId:e.value.attemptId,unstoppedRunId:e.value.runId,worker:e.value.worker,reason:e.value.reason});return}}i=yield*Bg(i=>_(t,r,e,i).pipe(Qh(({lease:e})=>Vk(l,n=>new Map(n).set(t,e))),E(({lease:e,open:a})=>i(n.withAttempt(t,v(t,r,e.worker,a))).pipe(Mg(u(t,e))))))}while(i===`RetryAttempt`);i!==`WaitingForStop`&&(i===`Unchanged`?yield*k(`Run closed by another operation; its fiber ends`,{runId:t}):yield*h(t))}),te=O(`RunDriver.holdSlot`)(function*(e){let{runId:t,attemptId:n}=e;yield*D({runId:t,attemptId:n}),yield*ne(new b0(e));let r=yield*Bk(l,e=>[Cr(e.get(t)),v0(e,t)]);x(r)?yield*A(`The Run's fiber holds no slot in this process; no slot moves to its Attempt`,{runId:t,attemptId:n}):yield*s.hold(n,r.value)},zg),ne=e=>Vk(c,t=>t.has(e.attemptId)?t:new Map(t).set(e.attemptId,e)),re=O(`RunDriver.confirmStopAfterFailure`)(function*(e){let{attemptId:n,runId:r,worker:i}=e,a={runId:r,attemptId:n,worker:i,reason:e.reason};yield*D(a),yield*ne(new b0(e));let o=yield*t.interrupt(n,e.reason).pipe($h);Oi(o)?(yield*Vk(c,e=>v0(e,n)),yield*A(`The parent task of the failed Attempt is confirmed stopped; the Run's slot is freed`,a)):(yield*e_(`Could not confirm that the parent task of the failed Attempt stopped; the Attempt keeps its Run's slot, no Attempt starts on its Item, and each reconcile tries the stop again`,{...a,errorTag:o.failure._tag,message:o.failure.message}),yield*te(e))}),ie=e=>Rk(c).pipe(ng(t=>Cr([...t.values()].find(({itemKey:t})=>t===e.itemKey)))),ae=O(`RunDriver.reconcileKept`)(function*(e){yield*D({...e}),yield*ne(e),yield*s.reconcile(e.attemptId,e.reason),yield*Vk(c,t=>v0(t,e.attemptId)),yield*k(`Parent stop confirmed; runs on the item can start attempts again`,{...e})}),oe=O(`RunDriver.releaseKept`)(function*(e){yield*D({...e}),yield*ae(e).pipe(sg(`ParentStopUnconfirmedError`,t=>e_(`Parent stop unconfirmed; the worker slot and checkout stay reserved until reconciliation succeeds`,{...e,errorTag:t._tag})))}),se=O(`RunDriver.recoverWorkspaces`)(function*(){yield*Ph(yield*s.atStartup(),({attemptId:e,runId:t,loop:n,itemKey:r,worker:i})=>ne(new b0({attemptId:e,runId:t,loop:n,itemKey:r,worker:i,reason:`startup`})),{discard:!0})});return{launch:d,resume:f,stop:p,continueWithNewest:h,reconcile:O(`RunDriver.reconcile`)(function*(){let n=[...(yield*Rk(c)).values()];yield*Ph(n,e=>sk(o,e.runId).pipe(E(t=>t?Bh:oe(e))),{discard:!0});let r=yield*e.pendingContinuations;yield*Ph(r,e=>h(e).pipe(pg(t=>t_(`Could not continue the queued Events behind a closed Run`,{runId:e,errorTag:t._tag})),gg),{discard:!0});let i=yield*e.runIdsToDrive,a=yield*bg(i,e=>ng(sk(o,e),e=>!e));yield*Ph(a,d,{discard:!0}),yield*t.sweep;let s={continuedAfterRunIds:r,startedRunIds:a,drivenRunIds:i.length,retriedStopAttemptIds:n.map(({attemptId:e})=>e)};r.length===0&&a.length===0&&n.length===0?yield*A(`Every Run to drive already has its fiber`,s):yield*k(`Runs recovered from the run tables`,s)}),recoverWorkspaces:se,holdSlot:te,releaseKept:oe,unconfirmedStops:Rk(c).pipe(ng(e=>[...e.values()]))}}))},O0=vi(`@usine/engine/ReconcileInterval`,{defaultValue:()=>`3 minutes`});T(function*(){let e=yield*V1,t=yield*D0,n=yield*g0,r=yield*v1,i=yield*YO,a=O(`RunEngine.submit`)(function*(n){let r=yield*jR(n).pipe(kg(YO,i)),a=yield*e.recordAndClaim(n,r);return S(a.supersededRun)&&(yield*t.stop(a.supersededRun.value)),S(a.openedRun)&&(yield*t.launch(a.openedRun.value)),a.result},zg),o=O(`RunEngine.approve`)(function*(n,r,i){(yield*e.approve(n,r,i))?(yield*k(`Run approved`,{runId:n,eventId:r.id,channel:i.channel,approver:yr(i.approver,()=>`none`)}),yield*t.resume(n)):yield*A(`Approval was already recorded; the Run is unchanged`,{runId:n,eventId:r.id})},zg),s=O(`RunEngine.retry`)(function*(n,r=m1){(yield*e.retry(n,r))?yield*t.resume(n):yield*A(`Retry changed nothing; the Run already waits for its next Attempt`,{runId:n})},zg),c=O(`RunEngine.runAgain`)(function*(n,r){let i=yield*e.runAgain(n,r);return i._tag===`Claimed`&&(yield*t.launch(i.runId)),i},zg),l=O(`RunEngine.cancel`)(function*(n){let i=yield*e.cancel(n);if(i._tag===`AlreadyClosed`){yield*A(`Cancel was a no-op; the run was already closed`,{runId:n});return}yield*k(`Run canceled`,{runId:n,openAttempt:vr(i.openAttempt,{onNone:()=>`none`,onSome:({id:e})=>e})}),S(i.openAttempt)&&(yield*t.holdSlot({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`}));let a=S(i.openAttempt)?yield*r.interrupt(i.openAttempt.value.id,`cancel`).pipe($h):Si(void 0);if(yield*t.stop(n),S(i.openAttempt)&&(yield*t.releaseKept({attemptId:i.openAttempt.value.id,worker:i.openAttempt.value.worker,runId:n,loop:i.loop,itemKey:i.itemKey,reason:`cancel`})),yield*t.continueWithNewest(n),S(i.openAttempt)&&Di(a))return yield*new cz({attemptId:i.openAttempt.value.id,cause:a.failure})},zg),u=O(`RunEngine.intervene`)(function*(t,n,i){yield*D({runId:t,attemptId:n,action:i.action._tag});let a=yield*e.snapshot(t),o=a.attempts.at(-1);if(a.run.state._tag!==`Running`||o?.id!==n||S(o.outcome))return yield*k(`Operator input rejected for an inactive Attempt`,{runId:t,attemptId:n}),yield*new uz({runId:t,attemptId:n,message:`This attempt is no longer running`});yield*r.intervene(n,i).pipe(dg(e=>new uz({runId:t,attemptId:n,message:kk(e,{RunawayFailure:()=>`The attempt reached its runaway limit`,ChildSessionBudgetFailure:()=>`The attempt reached its child-session budget`,QuestionFailure:()=>`The attempt ended with a question for the operator`,BlockedFailure:({message:e})=>e,GitHubPushFailure:({message:e})=>e,InfraFailure:({message:e})=>e,DefectFailure:({message:e})=>e,AgentFailure:({message:e})=>e})})),pg(e=>e_(`Operator input delivery failed`,{runId:t,attemptId:n,message:e.message})))}),d=O(`RunEngine.resolveFailure`)(function*(n,r,i){yield*D({runId:n,attemptId:r}),(yield*e.resolveFailure(n,r,i))&&(yield*k(`The operator resolved the Agent's question or blocker; the Item's queued Events get their turn`,{runId:n,attemptId:r}),yield*t.continueWithNewest(n))},zg),f=O(`RunEngine.revoke`)(function*(n,r){let i=yield*e.revoke(n,r);return yield*Ph(i,t.stop,{concurrency:`unbounded`,discard:!0}),i},zg),p=O(`RunEngine.inspect`)(function*(t){return yield*e.snapshot(t)}),m=O(`RunEngine.transcript`)(function*(t){return yield*e.transcript(t)}),h=O(`RunEngine.discardLeftovers`)(function*(t){if(yield*D({worker:t}),(yield*r.workers).includes(t)){let n=yield*e.openAttempts(t);return yield*k(`Leftovers kept; the Worker is configured or still runs Attempts, so its Attempts stay tracked`,{worker:t,running:n}),yield*new dz({worker:t,running:n})}let n=yield*e.discardLeftovers(t);return yield*k(`Discarded the leftovers of the Attempts on a Worker that is not configured; startup no longer reconciles them`,{worker:t,attempts:n.length}),yield*r.discard(t,n),n.length});return yield*t.recoverWorkspaces(),yield*t.reconcile(),yield*_g(yield*O0).pipe(Zh(t.reconcile()),pg(e=>t_(`Periodic Run reconcile failed; the next one tries again`,{errorTag:e._tag})),gg,Vg,qg),{approve:o,cancel:l,discardLeftovers:h,drain:n.drain,inspect:p,intervene:u,reconcile:t.reconcile,retry:s,resolveFailure:d,revoke:f,runAgain:c,submit:a,transcript:m}});var k0=class extends Rr()(`@usine/engine/RunEngine`){},A0=(e,t)=>e.changes.pipe(RO(e=>e!==t),KO,E(vr({onNone:()=>Hh,onSome:e=>w(e)}))),j0=Zk.make(`HEAD`),M0=class extends NE(`@usine/orchestrator/LoopAgentResolutionError`)(`LoopAgentResolutionError`,{loop:aA,agent:fN,message:z}){},N0=O(`TriggerRouting.resolveLoop`)(function*(e,t){yield*D({loop:t.name,agent:t.agent});let n=new Map(e.agents.map(e=>[e.name,e])).get(t.agent);if(n===void 0)return yield*new M0({loop:t.name,agent:t.agent,message:`Loop "${t.name}" references agent "${t.agent}", which is not in the roster`});let r=n.agent;return{agent:r,loop:t,parentModel:hN(r,e.config.settings.parentModel)}}),P0=O(`TriggerRouting.resolveLoops`)(function*(e){let t=[];for(let n of e.loops){let r=yield*$h(N0(e,n));Oi(r)?t.push(r.success):yield*t_(`Loaded loop lost its rostered Agent; skipping the loop`,{loop:r.failure.loop,agent:r.failure.agent,errorTag:r.failure._tag,message:r.failure.message})}return t}),F0=e=>e.trigger.on===`schedule`?y():b(e.maxCycles),I0=e=>new kR({event:new iA({id:nA.make(e.dedupKey),dedupKey:e.dedupKey,payload:e.payload,receivedAt:e.receivedAt}),itemKey:e.itemKey,cycleGeneration:e.cycleGeneration,loop:e.loop.name,step:e.loop.step,approval:e.loop.approval,permissions:e.loop.permissions,cycleLimit:F0(e.loop),repository:e.repository.name,revision:e.revision,task:e.task,agent:e.agent,parentModel:e.parentModel}),L0=e=>kk(e,{Claimed:({runId:e})=>({runId:e}),Queued:()=>({}),Suppressed:({runId:e})=>({suppressedBy:e}),Ignored:({reason:e})=>({reason:e}),CycleBlocked:({ask:e})=>({askId:e.id,reason:`cycle-budget-exhausted`})}),R0=e=>vr(e.expression,{onNone:()=>({configFile:e.file,configStage:e.stage}),onSome:t=>({configFile:e.file,configStage:e.stage,expression:t})}),z0=class extends V(`@usine/orchestrator/RepositoryPollFailure`)({repository:Xk,errorTag:z,message:j}){},B0=class extends V(`@usine/orchestrator/RepositoryPoll`)({repository:Xk,completedAt:_E}){},V0=class extends V(`@usine/orchestrator/PollCycle`)({repositoryPolls:N(B0).pipe(TT(w([]))),repositories:R.check(HT(0)),changedItems:R.check(HT(0)),submissions:N(BR),revokedRuns:R.check(HT(0)),failures:N(z0),preflightFindings:N(Hq),nextPollAt:B(_E)}){},H0=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...R0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},U0=e=>{let t=e.flatMap(e=>vr(e,{onNone:()=>[],onSome:e=>[K_(e)]}));return t.length===0?y():z_(Math.max(...t))},W0=class extends V(`@usine/orchestrator/LoopEvaluationFailure`)({loop:aA,stage:F([`if`,`prompt`]),expression:yE(ZH),errorTag:z,message:j}){},G0=class extends V(`@usine/orchestrator/FailingItem`)({stream:F([`issue`,`pr`]),number:rI,updatedAt:vE,contentHash:U1,failures:yT(W0)}){},K0=e=>e.stream===`issue`?new kK({number:e.number,updatedAt:e.updatedAt}):new AK({number:e.number,updatedAt:e.updatedAt}),q0=(e,t,n)=>{let[r,...i]=n;return r===void 0?y():b(new G0({stream:e._tag===`ChangedIssue`?`issue`:`pr`,number:rI.make(e.number),updatedAt:e.updatedAt,contentHash:t,failures:[r,...i]}))},J0=e=>e.stage===`if`?`if:`:vr(e.expression,{onNone:()=>`prompt`,onSome:e=>`prompt {{ ${e} }}`}),Y0=(e,t)=>t.failures.map(n=>new z0({repository:e,errorTag:n.errorTag,message:`Loop "${n.loop}": ${J0(n)} failed on ${t.stream===`issue`?`issue`:`pull request`} #${t.number}: ${n.message}`})),X0=e=>vr(e,{onNone:()=>[],onSome:({failures:e})=>e}),Z0=(e,t)=>e.loop===t.loop&&e.stage===t.stage,Q0=O(`PollingTriggers.logItemEvaluation`)(function*(e,t,n,r){yield*D({repository:e,item:t});for(let i of Mr(r)){let r=vr(n,{onNone:()=>[],onSome:e=>e.contentHash===i.contentHash?e.failures:[]});for(let n of i.failures){let a={repository:e,item:t,contentHash:i.contentHash,loop:n.loop,stage:n.stage,expression:C(n.expression),errorTag:n.errorTag,message:n.message};r.some(e=>Z0(e,n))?yield*A(`Loop evaluation still fails on unchanged Item content`,a):yield*t_(`Loop evaluation failed on an Item; its other Loops and the repository's other Items continue`,a)}}let i=X0(r);for(let r of X0(n))i.some(e=>Z0(e,r))||(yield*k(`Loop evaluation no longer fails on the Item`,{repository:e,item:t,loop:r.loop,stage:r.stage}))}),$0=Hw(N(fz)),e2=M({labels:iq.fields.labels}),t2=M({labels:cq.fields.labels}),n2=(e,t)=>Hw(e===`issue`?e2:t2)(t).pipe(E(({labels:e})=>$0(e.nodes.map(({name:e})=>e)))),r2=(e,t)=>new RH({repository:e.repository,itemKey:e.itemKey,message:t}),i2=e=>T(function*(){let t=S(e.goneAt);if(e.source===`issue`){let n=yield*Hw(iq)(e.payload).pipe(dg(t=>r2(e,t.message)));return{itemKey:e.itemKey,kind:`issue`,number:rI.make(e.number),title:n.title,url:n.url,state:n.state===`OPEN`&&!t?`issue-open`:`issue-closed`,linkedPullRequests:n.closedByPullRequestsReferences.nodes.map(({url:e})=>e),labels:yield*$0(n.labels.nodes.map(({name:e})=>e)).pipe(dg(t=>r2(e,t.message))),conflicting:!1}}if(e.source===`pr`){let n=yield*Hw(cq)(e.payload).pipe(dg(t=>r2(e,t.message))),r=n.merged?`pr-merged`:n.state===`OPEN`&&!t?`pr-open`:`pr-closed`;return{itemKey:e.itemKey,kind:`pr`,number:rI.make(e.number),title:n.title,url:n.url,state:r,linkedPullRequests:[],labels:yield*$0(n.labels.nodes.map(({name:e})=>e)).pipe(dg(t=>r2(e,t.message))),conflicting:r===`pr-open`&&n.mergeable===`CONFLICTING`}}return yield*r2(e,`Unsupported item projection source: ${e.source}`)}),a2=O(`settledItemState`)(function*(e){yield*D({itemKey:e});let t=yield*(yield*e0).get(e);if(x(t))return y();let n=yield*$h(i2(t.value));if(Di(n))return yield*A(`Stored Item payload doesn't decode; treating the Item as open`,{itemKey:e,message:n.failure.message}),y();let{state:r}=n.success;return Cz(r)?b(r):y()}),o2=(e,t)=>e.canApprove||e.canResolveFailure&&!t,s2=O(`PollingTriggers.closeAsksOfClosedItems`)(function*(e){yield*D({repository:e});let t=yield*p1,n=(yield*t.asks()).filter(t=>tA(t.repository)===tA(e));for(let e of n){let n={askId:e.id,itemKey:e.itemKey,repository:e.repository},r=yield*a2(e.itemKey);x(r)?yield*A(`Cycle-budget Ask stays open; its Item is open or not stored`,n):(yield*t.close(e.id,`ItemClosed`))&&(yield*k(`Item is closed; its cycle-budget Ask leaves Needs attention`,{...n,itemState:r.value}))}}),c2=tT(nI).pipe(ST(aE(vT([rT(`github`),Xk,rI])))),l2=Xw(c2),u2=(e,t)=>l2([`github`,Xk.make(tA(e)),rI.make(t)]),d2={labels:[],findings:[],catalogChanged:!1,nextPollAt:y()},f2=O(`PollingTriggers.applyLabelCatalog`)(function*(e,t,n){yield*D({repository:e});let r=yield*yU,i=yield*bU,a={labelEntityTag:t,entityTagChanged:!1,confirmedLabels:y(),failures:[],nextPollAt:y()};if(Di(n)){let t=n.failure;return t._tag===`GitHubRateLimitError`?(yield*e_(`Label catalog rate-limited; kept the stored catalog and deferred label provisioning`,{repository:e,operation:t.operation,retryAt:J_(t.retryAt)}),{...a,nextPollAt:b(t.retryAt)}):(yield*t_(`Label catalog request failed; kept the stored catalog, deferred label provisioning, and evaluated items anyway`,{repository:e,...H0(t)}),{...a,failures:[new z0({repository:e,errorTag:t._tag,message:t.message})]})}let o=n.success;if(!(o instanceof RK)){let t=yield*r.get(e);return x(t)?(yield*e_(`Repository label catalog unchanged (304) but its projection is missing; refetching next cycle and deferring label provisioning`,{repository:e}),{...a,labelEntityTag:y(),entityTagChanged:!0}):(yield*A(`Repository label catalog unchanged (304)`,{repository:e}),{...a,confirmedLabels:b(t.value.labels)})}let s=o.labels.map(({name:e,color:t,description:n})=>new oU({name:e,color:b(t),description:n}));return yield*i.replace(new lU({repository:e,labels:s})),{...a,labelEntityTag:o.entityTag,entityTagChanged:!0,confirmedLabels:b(s)}}),p2=O(`PollingTriggers.synchronizeLabels`)(function*(e,t,n){yield*D({repository:e});let r=yield*Bq,i=yield*Gq,a=yield*bU,o=yield*f2(e,n,yield*$h(r.labels(e,n))),s=yield*vr(o.confirmedLabels,{onNone:()=>w(d2),onSome:n=>i.reconcile(e,t,n)}),c={labelEntityTag:s.catalogChanged?y():o.labelEntityTag,entityTagChanged:o.entityTagChanged||s.catalogChanged,failures:o.failures,preflightFindings:s.findings,nextPollAt:U0([o.nextPollAt,s.nextPollAt])};return s.catalogChanged&&(yield*a.replace(new lU({repository:e,labels:s.labels})).pipe(dg(e=>({_tag:`InterruptedRepositoryCycle`,error:e,failures:c.failures,preflightFindings:c.preflightFindings,nextPollAt:c.nextPollAt})))),c}),m2=O(`PollingTriggers.observeItem`)(function*(e,t){yield*D({repository:e,item:t.number});let n=yield*Bq,r=yield*t0,i=yield*p1,a=u2(e,t.number),o=yield*i.generation(a),s=yield*n.snapshot(e,t),c=new W1({itemKey:a,repository:e,source:H1.make(t._tag===`ChangedIssue`?`issue`:`pr`),number:rI.make(t.number),contentHash:U1.make(s.contentHash),payload:s.payload});return yield*r.upsert(c),yield*A(`Fetched changed-item snapshot`,{repository:e,item:c.number,stream:c.source,contentHash:c.contentHash}),{snapshot:s,projection:c,cycleGeneration:o}}),h2=O(`PollingTriggers.markItemGone`)(function*(e,t){return yield*D({repository:e,item:t}),yield*(yield*t0).markGone(u2(e,t),yield*B_)}),g2=(e,t,{projection:n,cycleGeneration:r})=>rA.make(JSON.stringify([e.name,tA(t.name),n.number,n.contentHash,...r===0?[]:[r]])),_2=(e,t,n)=>T(function*(){return yield*(yield*eU).evaluateBoolean(e.trigger.if,zY(e.trigger.on),{repo:BY(t),item:n})}),v2=(e,t,n)=>T(function*(){let r=yield*eU,i=BY(t);return yield*r.evaluateBooleanEach(e.trigger.if,zY(e.trigger.on),n.map(e=>({repo:i,item:e})))}),y2=O(`PollingTriggers.evaluateItem`)(function*(e,t,n){let{projection:r,cycleGeneration:i}=n;yield*D({repository:e.name,item:r.number});let a=yield*o1,o=yield*k0,s=t.filter(({loop:e})=>e.trigger.on===r.source),c=r.payload,l={repo:BY(e),item:c};if(s.length===0)return yield*A(`Item projected without any matching repository Loop`,{repository:e.name,item:r.number,stream:r.source}),{submissions:[],revokedRuns:0,failures:[]};let u=[],d=r.source===`pr`?Zk.make(yield*Hw(Qk)(c.headRefOid).pipe(dg(()=>new eK({operation:`fetch-pull-request-snapshot`,message:`The pull request payload has no valid head commit`,detail:`pull request #${r.number} has no full headRefOid`})))):j0,f=[],p=0;for(let{agent:t,loop:m,parentModel:h}of s){yield*D({loop:m.name,agent:t.name});let s=yield*$h(_2(m,e,c));if(Di(s)){f.push(new W0({loop:m.name,stage:`if`,expression:b(s.failure.source),errorTag:s.failure._tag,message:s.failure.message}));continue}if(!s.success){yield*A(`Item did not match its loop expression`,{repository:e.name,loop:m.name,agent:t.name,item:r.number});let n=yield*o.revoke(m.name,r.itemKey);p+=n.length,n.length>0&&(yield*k(`Item stopped matching; revoked its unstarted runs`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,runIds:n.join(`, `)}));continue}let g=g2(m,e,n),_=yield*B_,v=yield*$h(a.renderPrompt(m,l));if(Di(v)){f.push(new W0({loop:m.name,stage:`prompt`,expression:v.failure.expression,errorTag:v.failure._tag,message:v.failure.message}));continue}let ee=yield*o.submit(I0({dedupKey:g,cycleGeneration:i,itemKey:r.itemKey,loop:m,payload:c,receivedAt:_,repository:e,revision:d,task:lF.make(v.success),agent:t,parentModel:h}));yield*k(`Submitted matching item state`,{repository:e.name,loop:m.name,agent:t.name,item:r.number,contentHash:r.contentHash,revision:d,result:ee._tag,...L0(ee)}),u.push(ee)}return{submissions:u,revokedRuns:p,failures:f}}),b2=O(`PollingTriggers.revokeMissingItem`)(function*(e,t,n,r){yield*D({repository:e.name,item:r});let i=yield*k0,a=u2(e.name,r),o=0;for(let{agent:s,loop:c}of t.filter(({loop:e})=>e.trigger.on===n)){let t=yield*i.revoke(c.name,a);o+=t.length,t.length>0&&(yield*k(`Item is gone from GitHub; revoked its unstarted runs`,{repository:e.name,loop:c.name,agent:s.name,item:r,runIds:t.join(`, `)}))}return o}),x2=T(function*(){let e=new Set,t=yield*sD({capacity:128,strategy:`dropping`}),n=yield*Lk(0),r=({repository:e,item:t})=>`${tA(e)}:${t.number}`,i=e=>vr(e,{onNone:()=>Bh,onSome:e=>Vk(n,t=>Math.max(t,K_(e)))});return{offer:O(`PollingTriggers.hint`)(function*(n,a,o=y()){yield*D({repository:n,item:a.number}),yield*i(o);let s={repository:n,item:a},c=r(s);e.has(c)?yield*A(`Self-write Hint coalesced with a pending Item fetch`,{repository:n,item:a.number}):(e.add(c),(yield*lD(t,s))?yield*A(`Self-write Hint queued`,{repository:n,item:a.number}):(e.delete(c),yield*e_(`Self-write Hint queue full; the normal poll will refresh the Item`,{repository:n,item:a.number})))},zg),take:Bg(n=>n(hD(t)).pipe(Qh(t=>zh(()=>e.delete(r(t)))))),defer:i,awaitBackoff:T(function*(){for(;;){let e=yield*Rk(n),t=yield*op;if(e<=t)return;yield*k(`GitHub request backoff delays polling and self-write Hints`,{sleepMs:e-t}),yield*_g(eo(e-t))}})}}),S2=class e extends Rr()(`@usine/orchestrator/ItemHints`){static layer=Xf(e,x2)},C2=no(10),w2={revokedRuns:0,failures:[],nextPollAt:y()},T2=O(`PollingTriggers.checkOpenIssues`)(function*(e,t){yield*D({repository:e.name});let n=yield*e0,r=yield*Bq,i=yield*n.openIssues(e.name);if(i.length===0)return yield*A(`No open issues to check against GitHub`,{repository:e.name}),w2;let a=yield*$h(r.missingIssues(e.name,i));if(Di(a)){let t=a.failure;return t._tag===`GitHubRateLimitError`?(yield*e_(`Open-issue check rate-limited; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,operation:t.operation,retryAt:J_(t.retryAt)}),{...w2,nextPollAt:b(t.retryAt)}):(yield*t_(`Open-issue check failed; checking again in 10 minutes`,{repository:e.name,openIssues:i.length,...H0(t)}),{...w2,failures:[new z0({repository:e.name,errorTag:t._tag,message:t.message})]})}let o=0;for(let n of a.success){let r=yield*b2(e,t,`issue`,n),i=yield*h2(e.name,n);o+=r,yield*k(`GitHub no longer has an open issue; it leaves the open lanes`,{repository:e.name,item:n,revokedRuns:r,projectionMarkedGone:i})}return yield*A(`Checked open issues against GitHub`,{repository:e.name,openIssues:i.length,missingIssues:a.success.length}),{...w2,revokedRuns:o}}),E2=4,D2=class extends V(`@usine/orchestrator/OpenPullRequest`)({number:AK.fields.number,updatedAt:vE,baseRefName:xE(EK),mergeable:j.pipe(DT(w(`UNKNOWN`))),checksUnsettled:lT.pipe(DT(w(!0)))}){},O2=(e,t)=>t._tag===`PullRequestSnapshot`&&t.payload.state===`OPEN`?b(new D2({number:e.number,updatedAt:e.updatedAt,baseRefName:b(t.payload.baseRefName),mergeable:t.payload.mergeable,checksUnsettled:t.payload.statusCheckRollup?.state===`PENDING`||t.payload.statusCheckRollup?.state===`EXPECTED`||t.payload.statusCheckRollup===null&&t.payload.mergeStateStatus===`BLOCKED`})):y(),k2=O(`PollingTriggers.readBaseRef`)(function*(e,t,n,r){yield*D({repository:e,baseRefName:t});let i=yield*$h((yield*Bq).baseRefHead(e,t,n));if(Di(i)){let a=i.failure;return a._tag===`GitHubRateLimitError`?yield*a:(yield*e_(`Could not read the base branch head; refreshing its open pull requests in this poll`,{repository:e,baseRefName:t,pullRequests:r.join(`, `),...H0(a)}),{_tag:`Unreadable`,recorded:n})}let a=i.success;return x(n)?(yield*k(`Base branch head recorded; refreshing its open pull requests once`,{repository:e,baseRefName:t,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a}):n.value.sha===a.sha?{_tag:`Unchanged`,head:a}:(yield*k(`Base branch head moved; refreshing its open pull requests`,{repository:e,baseRefName:t,previousHead:n.value.sha,head:a.sha,pullRequests:r.join(`, `)}),{_tag:`Moved`,head:a})}),A2=(e,t)=>{if(x(e.baseRefName))return b(`baseUnrecorded`);let n=t.get(e.baseRefName.value);return n?._tag===`Moved`?b(`baseMoved`):n?._tag===`Unreadable`?b(`baseUnreadable`):e.mergeable===`UNKNOWN`?b(`mergeableUnknown`):e.checksUnsettled?b(`checksUnsettled`):y()},j2=O(`PollingTriggers.openPullRequestRefresh`)(function*(e,t,n,r){if(yield*D({repository:e}),t.length===0)return{refreshed:[],baseRefHeads:[]};let i=new Map;for(let{number:e,baseRefName:n}of t){if(x(n))continue;let t=i.get(n.value)??[];t.push(e),i.set(n.value,t)}let a=new Map(yield*Ph(i,([t,r])=>k2(e,t,Sr(n.find(e=>e.baseRefName===t)),r).pipe(ng(e=>[t,e])),{concurrency:E2})),o=t.filter(({number:e})=>!r.has(e)),s=o.flatMap(e=>Mr(Or(A2(e,a),t=>({pullRequest:e,reason:t}))));if(s.length===0)yield*A(`No open pull request needs a refresh`,{repository:e,openPullRequests:t.length,baseRefReads:a.size});else{let t=da(s,({reason:e})=>e);yield*k(`Refreshing open pull requests`,{repository:e,baseRefReads:a.size,refreshed:s.length,skipped:o.length-s.length,...Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.map(({pullRequest:e})=>e.number).join(`, `)]))})}return{refreshed:s.map(({pullRequest:e})=>e),baseRefHeads:[...a.values()].flatMap(e=>e._tag===`Unreadable`?Mr(e.recorded):[e.head]).sort((e,t)=>e.baseRefName.localeCompare(t.baseRefName))}}),M2=4,N2=4,P2=z.pipe(L(`GitHubPollWatchKey`)),F2=class extends V(`@usine/orchestrator/StoredPollCursor`)({boardVersion:rT(5),openPullRequests:N(D2),baseRefHeads:N(DK).pipe(DT(w([]))),cursor:OK,labelEntityTag:yE(TK),watches:N(P2).check(XT()),failingItems:N(G0).pipe(DT(w([])))}){},I2=e=>c1.make(`github-poll:${tA(e.name)}`),L2=({loop:e})=>P2.make(JSON.stringify([e.name,e.trigger.on,e.trigger.if])),R2=(e,t)=>e.config.repos.map(n=>{let r=t.filter(({loop:e})=>e.trigger.on!==`schedule`&&BJ(e.selector,n));return{repository:n,declaredLabels:e.config.labels,loops:r,watches:r.map(L2).sort()}}),z2=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),B2=class e extends Rr()(`@usine/orchestrator/PollingTriggers`){static layer=Xf(e,T(function*(){let e=yield*d1,t=yield*p1,n=yield*Bq,r=yield*o0,i=yield*Lk(y()),a=yield*Lk(new Map),o=yield*S2,s=yield*ID(1),c=yield*Lk({instance:y(),repositories:new Set}),l=yield*Lk(new Map),u=e=>new F2({boardVersion:5,openPullRequests:[],baseRefHeads:[],cursor:OK.empty,labelEntityTag:y(),watches:e,failingItems:[]}),d=O(`PollingTriggers.readCursor`)(function*(t){yield*D({repository:t.repository.name});let n=yield*e.read(I2(t.repository),F2);return x(n)?u(t.watches):z2(n.value.watches,t.watches)?n.value:(yield*k(`Watched loops changed; re-polling the repository from scratch`,{repository:t.repository.name,previousWatches:n.value.watches.length,currentWatches:t.watches.length}),u(t.watches))}),f=O(`PollingTriggers.writeCursor`)(function*(t,n){yield*D({repository:t.repository.name}),yield*e.write(I2(t.repository),F2,n)}),p=O(`PollingTriggers.checkOpenIssuesWhenDue`)(function*(e){yield*D({repository:e.repository.name});let t=I2(e.repository),n=yield*op,r=(yield*Rk(l)).get(t);return r!==void 0&&n-r<ro(C2)?(yield*A(`Open issues were checked less than 10 minutes ago; skipped`,{repository:e.repository.name,lastCheckedAt:J_(R_(r))}),w2):(yield*Vk(l,e=>new Map(e).set(t,n)),yield*T2(e.repository,e.loops))}),m=O(`PollingTriggers.pollRepository`)(function*(e){yield*D({repository:e.repository.name});let r=(yield*t.pendingResets()).filter(({repository:t})=>tA(t)===tA(e.repository.name)),i=r.length>0?u(e.watches):yield*d(e);r.length>0&&(yield*k(`Cycle budget reset requests fresh repository polling`,{repository:e.repository.name,items:r.map(({itemKey:e})=>e)}));let a=yield*p2(e.repository.name,e.declaredLabels,i.labelEntityTag);return yield*o.defer(a.nextPollAt),yield*T(function*(){let s=yield*n.changes(e.repository.name,i.cursor);yield*o.defer(s.backoffUntil);let l=(yield*Rk(c)).repositories.has(I2(e.repository))?[]:i.failingItems,u=s._tag===`RepositoryChanges`?s.items:[],d=new Set(u.map(({number:e})=>e)),m=yield*j2(e.repository.name,i.openPullRequests,i.baseRefHeads,new Set([...d,...l.map(({number:e})=>e)])),h=new Map([...l.map(e=>[e.number,K0(e)]),...m.refreshed.map(({number:e,updatedAt:t})=>[e,new AK({number:e,updatedAt:t})])]);for(let e of u)h.set(e.number,e);s._tag===`RepositoryChanges`&&(yield*k(`Repository changed`,{repository:e.repository.name,changedItems:s.items.length,backlog:s.backlog}));let g=new Set([...m.refreshed,...l].map(({number:e})=>e).filter(e=>!d.has(e)));l.length>0&&(yield*k(`Evaluating Items whose Loops failed before this process started or the instance was reloaded`,{repository:e.repository.name,items:l.map(({number:e})=>e).join(`, `)}));let _=U0([s.nextPollAt,a.nextPollAt]);yield*A(`Refreshing detected Items and open pull requests`,{repository:e.repository.name,detection:s._tag,openPullRequests:i.openPullRequests.length,refreshedPullRequests:m.refreshed.length,items:h.size});let v=new Map(i.failingItems.map(e=>[e.number,e])),ee=yield*Ph(h.values(),t=>T(function*(){let n=yield*m2(e.repository.name,t),r=yield*y2(e.repository,e.loops,n),i=q0(t,n.projection.contentHash,r.failures);return yield*Q0(e.repository.name,t.number,Sr(v.get(t.number)),i),{_tag:`Evaluated`,item:t,observation:n,cycle:r,failing:i}}).pipe(sg(`GitHubItemNotFoundError`,n=>T(function*(){if(!g.has(t.number))return yield*n;let r=yield*b2(e.repository,e.loops,t._tag===`ChangedIssue`?`issue`:`pr`,t.number),a=yield*h2(e.repository.name,t.number);return yield*e_(`GitHub no longer has an Item the poll cursor kept; it is dropped from the cursor`,{repository:e.repository.name,item:t.number,openPullRequest:i.openPullRequests.some(({number:e})=>e===t.number),revokedRuns:r,projectionMarkedGone:a,errorTag:n._tag,message:n.message}),{_tag:`Missing`,revokedRuns:r}}))),{concurrency:N2}),te=ee.flatMap(e=>e._tag===`Evaluated`?[e]:[]),ne=ee.reduce((e,t)=>e+(t._tag===`Missing`?t.revokedRuns:0),0),re=te.map(({cycle:e})=>e),ie=yield*p(e);yield*o.defer(ie.nextPollAt),yield*s2(e.repository.name);let ae=[...i.failingItems.filter(({number:e})=>!h.has(e)),...te.flatMap(({failing:e})=>Mr(e))].sort((e,t)=>e.number-t.number),oe=[...i.openPullRequests.filter(({number:e})=>!h.has(e)),...te.flatMap(({item:e,observation:t})=>Mr(O2(e,t.snapshot)))],se=m.baseRefHeads.filter(({baseRefName:e})=>oe.some(t=>Fr(t.baseRefName,e))),ce=new F2({boardVersion:5,cursor:s.cursor,labelEntityTag:a.labelEntityTag,watches:e.watches,openPullRequests:oe,baseRefHeads:se,failingItems:ae});return(s._tag===`RepositoryChanges`||h.size>0||a.entityTagChanged||!Le(se,i.baseRefHeads))&&(yield*f(e,ce)),yield*Vk(c,t=>({...t,repositories:new Set([...t.repositories,I2(e.repository)])})),yield*Ph(r,t.acknowledgeReset,{discard:!0}),{changedItems:s._tag===`RepositoryChanges`?s.items.length:0,submissions:re.flatMap(({submissions:e})=>e),revokedRuns:re.reduce((e,t)=>e+t.revokedRuns,ne+ie.revokedRuns),failures:[...a.failures,...ie.failures,...ae.flatMap(t=>Y0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:U0([_,ie.nextPollAt])}}).pipe(dg(t=>({_tag:`InterruptedRepositoryCycle`,error:t,failures:[...a.failures,...i.failingItems.flatMap(t=>Y0(e.repository.name,t))],preflightFindings:a.preflightFindings,nextPollAt:a.nextPollAt})))}),h=(yield*Cg()).pipe(_i(o1,p1,eU,Bq,e0,t0,Gq,yU,bU,k0)),g=O(`PollingTriggers.poll`)(function*(e){yield*o.awaitBackoff,yield*Vk(c,t=>Fr(t.instance,e)?t:{instance:b(e),repositories:new Set});let t=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let n of e.loops)n.trigger.on!==`schedule`&&t.has(n.name)&&(yield*A(`Paused Loop skipped during repository polling`,{loop:n.name}));let n=R2(e,(yield*P0(e)).filter(({loop:e})=>!t.has(e.name))),s=yield*Ph(n,e=>$h(m(e)).pipe(ng(t=>({repository:e,result:t}))),{concurrency:M2}),l=[],u=[],d=[],f=[],p=yield*B_;for(let{repository:e,result:t}of s){if(Oi(t)){l.push(t.success),f.push(...t.success.preflightFindings),yield*Vk(a,t=>new Map(t).set(tA(e.repository.name),new B0({repository:e.repository.name,completedAt:p})));continue}let n=t.failure._tag===`InterruptedRepositoryCycle`,r=n?t.failure.error:t.failure;n&&(u.push(...t.failure.failures),f.push(...t.failure.preflightFindings),d.push(t.failure.nextPollAt),yield*o.defer(t.failure.nextPollAt)),r._tag===`GitHubRateLimitError`?(yield*e_(`GitHub rate limit reached; delaying the next cycle`,{repository:e.repository.name,operation:r.operation,retryAt:J_(r.retryAt)}),d.push(b(r.retryAt)),yield*o.defer(b(r.retryAt))):(yield*t_(`Repository poll cycle failed; siblings were unaffected`,{repository:e.repository.name,...H0(r)}),u.push(new z0({repository:e.repository.name,errorTag:r._tag,message:r.message})))}let h=yield*Rk(a),g=new V0({repositoryPolls:n.flatMap(({repository:e})=>Mr(Sr(h.get(tA(e.name))))),repositories:n.length,changedItems:l.reduce((e,t)=>e+t.changedItems,0),submissions:l.flatMap(({submissions:e})=>e),revokedRuns:l.reduce((e,t)=>e+t.revokedRuns,0),failures:[...l.flatMap(({failures:e})=>e),...u],preflightFindings:f,nextPollAt:U0([...l.map(({nextPollAt:e})=>e),...d])});return yield*zk(i,b(g)),g},Eg(h),s.withPermits(1)),_=O(`PollingTriggers.refreshHint`)(function*(e,t){yield*D({repository:t.repository,item:t.item.number}),yield*o.awaitBackoff;let n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop)),i=R2(e,(yield*P0(e)).filter(({loop:e})=>!n.has(e.name))).find(({repository:e})=>tA(e.name)===tA(t.repository));if(i===void 0){yield*k(`Self-write Hint ignored for an unmanaged repository`,{repository:t.repository,item:t.item.number});return}let a=yield*m2(i.repository.name,t.item),s=yield*y2(i.repository,i.loops,a);for(let e of s.failures)yield*e_(`Self-write Hint could not evaluate a Loop on the Item`,{repository:t.repository,item:t.item.number,loop:e.loop,stage:e.stage,errorTag:e.errorTag,message:e.message});yield*k(`Self-write Hint refreshed the Item`,{repository:t.repository,item:t.item.number,submissions:s.submissions.length,revokedRuns:s.revokedRuns,failures:s.failures.length})},Eg(h),(e,t,n)=>e.pipe(og(e=>T(function*(){e._tag===`GitHubRateLimitError`&&(yield*o.defer(b(e.retryAt))),yield*e_(`Self-write Hint refresh failed; the normal poll will retry`,{repository:n.repository,item:n.item.number,...H0(e)})})),s.withPermits(1))),v=(e,t,n,r)=>T(function*(){let i=Math.max(n,r),a=t;for(;;){let t=i-(yield*op);if(t<=0)return;let n=yield*vg([_g(eo(t)).pipe(ng(()=>({_tag:`Due`}))),o.take.pipe(ng(e=>({_tag:`Hint`,hint:e}))),A0(e,a).pipe(ng(e=>({_tag:`Reloaded`,instance:e})))]);if(n._tag===`Due`)return;if(n._tag===`Hint`){yield*_(yield*e.get,n.hint);continue}a=n.instance,i=r;let s=r-(yield*op);s>0?yield*k(`Instance reloaded; the next poll waits for the time GitHub asked for`,{sleepMs:s}):yield*k(`Instance reloaded; polling now instead of after poll_interval`)}});return{latest:Rk(i),poll:g,run:e=>T(function*(){let t=yield*e.get,n=yield*op,r=yield*$h(g(t));if(Di(r)){let e=t.config.settings.pollInterval*1e3;yield*t_(`Poll cycle could not read Loop runtime state; retrying`,{errorTag:r.failure._tag,message:r.failure.message,operation:r.failure.operation,sleepMs:e}),yield*_g(eo(e));return}let i=r.success,a=n+t.config.settings.pollInterval*1e3,o=vr(i.nextPollAt,{onNone:()=>0,onSome:K_}),s=yield*op,c=Math.max(0,Math.max(a,o)-s);yield*k(`Poll cycle complete`,{repositories:i.repositories,changedItems:i.changedItems,submissions:i.submissions.length,revokedRuns:i.revokedRuns,failures:i.failures.length,preflightFindings:i.preflightFindings.length,sleepMs:c}),yield*v(e,t,a,o)}).pipe(Vg),hint:o.offer}})).pipe(rp(S2.layer))},V2=4,H2=6e4,U2=e=>{let t={errorTag:e._tag,message:e.message};return e._tag===`ConfigFileError`?{...t,...R0(e)}:e._tag===`ExpressionCheckError`||e._tag===`ExpressionEvaluationError`?{...t,expression:e.source}:t},W2=class extends H(`@usine/orchestrator/ScheduleAgentFailure`)(`ScheduleAgentFailure`,{loop:aA,agent:fN,message:j}){},G2=class extends H(`@usine/orchestrator/ScheduleTickFailure`)(`ScheduleTickFailure`,{loop:aA,repository:Xk,scheduledAt:_E,errorTag:z,message:j}){},K2=class extends H(`@usine/orchestrator/ScheduleCronFailure`)(`ScheduleCronFailure`,{loop:aA,cron:j,tz:j,message:j}){},q2=P([W2,K2,G2]),J2=class extends V(`@usine/orchestrator/ScheduleCycle`)({loops:R.check(HT(0)),fanout:R.check(HT(0)),submissions:N(BR),skipped:R.check(HT(0)),alreadyFired:R.check(HT(0)),failures:N(q2),nextTickAt:B(_E)}){},Y2=e=>e.loops.flatMap(t=>{let n=t.trigger;return n.on===`schedule`?[{loop:t,repositories:e.config.repos.filter(e=>BJ(t.selector,e)),trigger:n}]:[]}),X2=(e,t)=>{let n=W_(t);return n.setUTCSeconds(0,0),L_(km(e,n)?n:Mm(e,n))},Z2=(e,t)=>L_(jm(e,W_(t))),Q2=(e,t)=>vr(U_(e,t),{onNone:()=>J_(e),onSome:Y_}),$2=e=>e.length===0?y():z_(Math.min(...e.map(K_))),e4=e=>nI.make(JSON.stringify([`github`,tA(e.name)])),t4=(e,t,n)=>rA.make(JSON.stringify([e.name,tA(t.name),J_(n)])),n4=e=>({tick:{scheduledAt:J_(e.scheduledAt),scheduledAtLocal:e.scheduledAtLocal,cron:e.trigger.cron,tz:e.trigger.tz}});(class e extends Rr()(`@usine/orchestrator/ScheduleTriggers`){static layer=Xf(e,T(function*(){let e=yield*o1,t=yield*eU,n=yield*k0,r=yield*o0,i=yield*Lk(y()),a=yield*Lk({instance:y(),ticks:new Map}),o=new WeakMap,s=e=>{let t=o.get(e);if(t!==void 0)return t;let n=Om(e.cron,e.tz);return o.set(e,n),n},c=O(`ScheduleTriggers.submitTick`)(function*(r,i){yield*D({loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt)});let a=n4(r),o={repo:BY(r.repository),item:a};if(!(yield*t.evaluateBoolean(r.trigger.if,zY(`schedule`),o)))return yield*A(`Scheduled Tick did not match its expression`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt)}),y();let s=t4(r.loop,r.repository,r.scheduledAt),c=yield*e.renderPrompt(r.loop,o),l=yield*n.submit(I0({cycleGeneration:aI.make(0),agent:r.agent,dedupKey:s,itemKey:e4(r.repository),loop:r.loop,payload:a,receivedAt:i,repository:r.repository,revision:j0,task:lF.make(c),parentModel:r.parentModel}));return yield*k(`Submitted scheduled Tick`,{loop:r.loop.name,repository:r.repository.name,agent:r.agent.name,scheduledAt:J_(r.scheduledAt),scheduledAtLocal:r.scheduledAtLocal,result:l._tag,...L0(l)}),b(l)}),l=O(`ScheduleTriggers.tick`)(function*(e){let t=yield*B_,n=new Set((yield*r.states).filter(e=>e.paused).map(e=>e.loop));for(let t of e.loops)t.trigger.on===`schedule`&&n.has(t.name)&&(yield*A(`Paused Loop skipped during schedule evaluation`,{loop:t.name}));let o=Y2(e).filter(({loop:e})=>!n.has(e.name)),l=yield*Bk(a,t=>{let n=Fr(t.instance,e)?t:{instance:b(e),ticks:new Map};return[n.ticks,n]}),u=[],d=[],f=[],p=new Map,m=[],h=0;for(let n of o){n.repositories.length===0&&(yield*e_(`Schedule loop selected no repositories`,{loop:n.loop.name}));let r=yield*qh({try:()=>{let e=s(n.trigger),r=X2(e,t);return{latest:r,latestLocal:Q2(r,n.trigger.tz),next:Z2(e,t)}},catch:e=>e}).pipe($h);if(Di(r)){yield*t_(`Schedule cron boundaries could not be computed`,{loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}),f.push(new K2({loop:n.loop.name,cron:n.trigger.cron,tz:n.trigger.tz,message:String(r.failure)}));continue}let i=r.success;m.push(i.next);let a=K_(i.latest),o=l.get(n.loop.name);if(o!==void 0&&o>=a){h+=1,yield*A(`Tick already fired`,{loop:n.loop.name,scheduledAt:J_(i.latest)});continue}let c=yield*$h(N0(e,n.loop));if(Di(c)){let e=c.failure;yield*t_(`Schedule loop could not resolve its Agent`,{loop:e.loop,agent:e.agent,errorTag:e._tag,message:e.message}),d.push(new W2({loop:e.loop,agent:e.agent,message:e.message}))}else if(n.repositories.length!==0){p.set(n.loop.name,a),yield*k(`Schedule tick due`,{loop:n.loop.name,agent:c.success.agent.name,cron:n.trigger.cron,tz:n.trigger.tz,scheduledAt:J_(i.latest),scheduledAtLocal:i.latestLocal,repositories:n.repositories.length,nextTickAt:J_(i.next)});for(let e of n.repositories)u.push({agent:c.success.agent,loop:n.loop,parentModel:c.success.parentModel,repository:e,scheduledAt:i.latest,scheduledAtLocal:i.latestLocal,trigger:n.trigger})}}yield*D({schedules:o.length,fanout:u.length});let g=yield*Ph(u,e=>$h(c(e,t)).pipe(ng(t=>({candidate:e,result:t}))),{concurrency:V2}),_=[],v=[],ee=new Set,te=new Set,ne=0;for(let{candidate:e,result:t}of g){if(Oi(t)){S(t.success)?(_.push(t.success.value),ee.add(e.loop.name)):ne+=1;continue}let n=t.failure;te.add(e.loop.name),yield*t_(`Scheduled Tick failed; sibling fanout was unaffected`,{loop:e.loop.name,repository:e.repository.name,agent:e.agent.name,scheduledAt:J_(e.scheduledAt),...U2(n)}),v.push(new G2({loop:e.loop.name,repository:e.repository.name,scheduledAt:e.scheduledAt,errorTag:n._tag,message:n.message}))}yield*Vk(a,e=>{let t=new Map(e.ticks);for(let[e,n]of p)ee.has(e)&&!te.has(e)&&t.set(e,n);return{...e,ticks:t}});let re=new J2({loops:o.length,fanout:u.length,submissions:_,skipped:ne,alreadyFired:h,failures:[...d,...f,...v],nextTickAt:$2(m)});return yield*zk(i,b(re)),re}),u=(e,t,n)=>yg(_g(eo(n)),A0(e,t).pipe(Zh(k(`Instance reloaded; evaluating schedules now instead of after the sleep`))));return{latest:Rk(i),run:e=>T(function*(){let t=yield*e.get,n=yield*$h(l(t));if(Di(n)){yield*t_(`Schedule cycle could not read Loop runtime state; retrying`,{errorTag:n.failure._tag,message:n.failure.message,operation:n.failure.operation,sleepMs:H2}),yield*u(e,t,H2);return}let r=n.success,i=yield*op,a=vr(r.nextTickAt,{onNone:()=>i+H2,onSome:K_}),o=Math.min(H2,Math.max(0,a-i)),s={loops:r.loops,fanout:r.fanout,submissions:r.submissions.length,skipped:r.skipped,alreadyFired:r.alreadyFired,failures:r.failures.length,nextTickAt:vr(r.nextTickAt,{onNone:()=>`none`,onSome:J_}),sleepMs:o};r.fanout===0&&r.failures.length===0?yield*A(`Schedule cycle complete`,s):yield*k(`Schedule cycle complete`,s),yield*u(e,t,o)}).pipe(Vg),tick:l}}))});var r4=class extends H(`@usine/orchestrator/ApprovalNeed`)(`ApprovalNeed`,{id:j,repository:Xk,runId:HA,loop:aA,item:I(jH)}){},i4=class extends H(`@usine/orchestrator/RunFailureNeed`)(`RunFailureNeed`,{id:j,repository:Xk,runId:HA,loop:aA,failure:Iz}){},a4=class extends H(`@usine/orchestrator/PollFailureNeed`)(`PollFailureNeed`,{id:j,failure:z0}){},o4=class extends H(`@usine/orchestrator/PreflightFindingNeed`)(`PreflightFindingNeed`,{id:j,finding:Hq}){},s4=class extends H(`@usine/orchestrator/BoardProjectionNeed`)(`BoardProjectionNeed`,{id:j,failure:RH}){},c4=class extends H(`@usine/orchestrator/ScheduleFailureNeed`)(`ScheduleFailureNeed`,{id:j,failure:q2}){},l4=class extends H(`@usine/orchestrator/ConfigFileNeed`)(`ConfigFileNeed`,{id:j,kind:F([`loop`,`agent`]),error:rU}){},u4=class extends H(`@usine/orchestrator/UnconfiguredWorkerNeed`)(`UnconfiguredWorkerNeed`,M({id:j,worker:EN,attempts:R.check(HT(1)),running:R.check(HT(0))}).check(NT(({attempts:e,running:t})=>t<=e,{message:`Expected no more open attempts than attempts`}))){},d4=class extends H(`@usine/orchestrator/UnconfirmedStopNeed`)(`UnconfirmedStopNeed`,{id:j,repository:Xk,runId:HA,loop:aA,attemptNumber:cF,worker:EN}){},f4=class extends H(`@usine/orchestrator/UnresponsiveWorkerNeed`)(`UnresponsiveWorkerNeed`,{id:j,worker:EN,lastAnsweredAt:j,attempts:N(M({attemptId:sF,attemptNumber:cF,runId:HA,repository:Xk,loop:aA})).check(GT(1))}){},p4=P([class extends H(`CycleBudgetNeed`)(`CycleBudgetNeed`,{id:j,ask:uI,itemLabel:j,itemUrl:I(j)}){},r4,s4,i4,a4,o4,c4,l4,u4,d4,f4,class extends H(`@usine/orchestrator/WorkerPreflightNeed`)(`WorkerPreflightNeed`,{id:j,worker:EN,message:j}){}]),m4=F([`clear`,`active`,`needs-you`]),h4=class extends V(`@usine/orchestrator/ProjectView`)({repository:Xk,status:m4,runs:N(CH),board:zH,labels:N(BH),preflightFindings:N(Hq)}){},g4=class extends V(`@usine/orchestrator/LoopView`)({name:aA,trigger:j,agent:fN,paused:lT}){},_4=class extends H(`@usine/orchestrator/ReadyOverview`)(`Ready`,{projects:N(h4),loops:N(g4),needsYou:N(p4),dismissedNeeds:N(p4).pipe(TT(w([])))}){},v4=class extends H(`@usine/orchestrator/NeedsSetupOverview`)(`NeedsSetup`,{errorTag:z,projects:N(h4),loops:N(g4),needsYou:N(p4),dismissedNeeds:N(p4).pipe(TT(w([])))}){},y4=P([_4,v4]),b4=500,x4=500,S4=e=>kk(e,{GitHubPushFailure:({message:e})=>new Oz({message:e}),InfraFailure:({message:e})=>new kz({message:e}),DefectFailure:({message:e})=>new Az({message:e}),AgentFailure:({message:e})=>new jz({message:e}),BlockedFailure:({message:e})=>new Mz({message:e}),QuestionFailure:({question:e})=>new Nz({question:e}),RunawayFailure:({ceiling:e})=>new Pz({ceiling:e}),ChildSessionBudgetFailure:({attemptedChildren:e,maxChildren:t})=>new Fz({attemptedChildren:e,maxChildren:t})}),C4=e=>kk(e,{Succeeded:()=>new Lz,Failed:({failure:e})=>new Rz({failure:S4(e)}),Canceled:()=>new zz}),w4=e=>{switch(e.kind){case`local`:return new Vz;case`ssh`:return vr(e.provisioner,{onSome:({provider:e})=>new Uz({provider:e}),onNone:()=>new Hz({destination:yr(e.destination,()=>jN.make(e.name)),port:C(e.port)})});case`exe.dev`:return new Hz({destination:jN.make(`${e.name}.exe.xyz`),port:null});case`cloudflare`:return new Wz}},T4=e=>new Map(e.map(e=>[e.name,w4(e)])),E4=(e,t)=>new Kz({id:e.id,number:e.number,worker:e.worker,workerAccess:t.get(e.worker)??null,brain:e.brain,task:e.task,agent:e.agent,operatorIntervened:e.operatorIntervened,startedAt:J_(e.startedAt),outcome:vr(e.outcome,{onNone:()=>null,onSome:C4}),endedAt:vr(e.endedAt,{onNone:()=>null,onSome:J_}),salvage:C(e.salvage),start:C(e.start),reattachedAt:vr(e.reattachedAt,{onNone:()=>null,onSome:J_}),outOfMemory:C(e.outOfMemory)});O(`Operator.readUnrecordedEnds`)(function*(e,t){let n=yield*Ph(t.attempts.filter(e=>S(e.outcome)&&x(e.endedAt)),t=>e.transcript(new TB({attemptId:t.id,before:y(),limit:1})).pipe(ng(e=>[t.id,e.at(-1)?.receivedAt])),{concurrency:4});return new Map(n.flatMap(([e,t])=>t===void 0?[]:[[e,t]]))});var D4=O(`Operator.readRunningEvents`)(function*(e,t){let n=t.flatMap(({run:e})=>e.state._tag===`Running`?[e.id]:[]),r=yield*e.events(n);return yield*A(`Read the Events of the running Runs`,{running:n.length,events:r.length}),new Map(r.map(({runId:e,event:t})=>[e,t]))}),O4=(e,t,n)=>{let r=OA(e.run.state),i=C(e.step.result),a=i?.facts.find(e=>e._tag===`PullRequest`);return new CH({id:e.run.id,itemKey:e.itemKey,loop:e.run.loop,repository:e.repository,agent:e.agent.name,agentBrain:e.agent.brain,state:e.run.state._tag,loopPaused:t.has(e.run.loop),openedAt:J_(e.run.openedAt),closedAt:vr(e.closedAt,{onNone:()=>null,onSome:J_}),task:e.task,attempts:e.attempts.map(e=>E4(e,n)),approval:vr(e.approval,{onNone:()=>null,onSome:({approvedAt:e,source:t})=>new SH({approvedAt:J_(e),source:C(t)})}),runAgain:C(e.runAgain),resultMessage:i?.message??null,pullRequestUrl:a?.url.toString()??null,...r,canResolveFailure:r.canResolveFailure&&!Fr(e.resolvedFailureAttemptId,e.attempts.at(-1)?.id)})},k4=e=>kk(e,{Started:e=>e,SessionEvent:e=>e,Final:e=>e,Failed:({failure:e})=>new EB({failure:S4(e)}),Interrupted:e=>e,Steer:e=>e,Interrupt:e=>e,OperatorMessage:e=>e,Release:e=>e,Cancel:e=>e,InterventionApplied:e=>e,InterventionRejected:e=>e,WorkerUnresponsive:e=>e,WorkerResponsive:e=>e}),A4=e=>{let t={sequence:e.sequence,attemptId:e.attemptId,receivedAt:J_(e.receivedAt),direction:e.direction,payload:k4(e.envelope.payload)};return e.envelope._tag===`InboundEnvelope`&&`target`in e.envelope?new OB({...t,target:e.envelope.target,operator:e.envelope.operator}):new OB(t)},j4=e=>[...e].sort((e,t)=>e.sequence-t.sequence).map(A4),M4=O(`Operator.readTranscriptPage`)(function*(e,t,n){yield*D({attemptId:t,before:C(n)});let r=yield*e.transcript(new TB({attemptId:t,before:n,limit:501})),i=r.length>b4,a=i?r.slice(1):r,o=a[0];return yield*A(`Read operator transcript page`,{attemptId:t,before:C(n),returned:a.length,hasEarlier:i}),{events:j4(a),earlier:i&&o!==void 0?[new kB({attemptId:t,before:o.sequence})]:[]}});O(`Operator.readTranscript`)(function*(e,t,n){yield*D({runId:t.run.id,request:n._tag});let r=yield*kk(n,{ColdTranscriptRequest:()=>Ph(t.attempts,t=>M4(e,t.id,y()),{concurrency:4}).pipe(ng(e=>({events:e.flatMap(({events:e})=>e).sort((e,t)=>e.sequence-t.sequence),earlier:e.flatMap(({earlier:e})=>e)}))),TailTranscriptRequest:({after:n})=>Ph(t.attempts,t=>e.transcript(new wB({attemptId:t.id,after:n,limit:x4})),{concurrency:4}).pipe(ng(e=>({events:j4(e.flat()).slice(0,x4),earlier:[]}))),EarlierTranscriptRequest:({attemptId:n,before:r})=>t.attempts.some(e=>e.id===n)?M4(e,n,b(r)):new NB({runId:t.run.id,attemptId:n})});return yield*A(`Read operator transcript`,{runId:t.run.id,request:n._tag,events:r.events.length,earlier:r.earlier.length}),r});var N4=Ww(rE),P4=e=>new jH({itemKey:e.itemKey,kind:e.kind,number:e.number,title:e.title,url:e.url,state:e.state}),F4=(e,t,n,r,i,a)=>{let o=da(n,({itemKey:e})=>e),s=t.map(e=>({item:e,runs:o[e.itemKey]??[],related:new Set})),c=`/${tA(e)}/pull/`,l=new Map(s.filter(({item:e})=>e.kind===`pr`).map(e=>[`${c}${e.item.number}`,e])),u=new Set(r);for(let e of s){if(e.item.kind!==`issue`)continue;let t=[...e.item.linkedPullRequests,...e.runs.flatMap(({pullRequestUrl:e})=>e===null?[]:[e])];for(let n of t){let t=N4(n);if(x(t)||t.value.protocol!==`https:`||t.value.host!==`github.com`)continue;let r=l.get(t.value.pathname.toLowerCase());r!==void 0&&(e.related.add(r),r.related.add(e))}}let d=new Set,f=[];for(let e of s){if(d.has(e))continue;d.add(e);let t=[e];for(let e of t)for(let n of e.related)d.has(n)||(d.add(n),t.push(n));let n=ia(t,({item:e},{item:t})=>(e.kind===t.kind?0:e.kind===`issue`?-1:1)||lr(e.number,t.number)),r=n[0],o=t.flatMap(({item:e,runs:t})=>t.map(t=>({item:e,run:t}))).sort(({run:e},{run:t})=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),s=o.find(({run:e})=>e.canCancel),c=t.filter(({item:e})=>e.kind===`pr`).sort(({item:e},{item:t})=>Number(t.state===`pr-open`)-Number(e.state===`pr-open`)||t.number-e.number),l=s?.item??c[0]?.item??r.item,[p=null]=c.flatMap(({item:{number:e,url:t,state:n}})=>n===`pr-open`||n===`pr-merged`?[new MH({number:e,url:t,state:n})]:[]),m=o.find(({item:e,run:t})=>o2(t,Cz(e.state)))??s??o[0],h=o.map(({run:e})=>e).reverse(),g=new NH({...P4(l),title:r.item.title,labels:l.labels,items:n.map(({item:e})=>P4(e)),pullRequest:p,runs:h,run:m?.run??null,needsYou:o.some(({item:e,run:t})=>o2(t,Cz(e.state)))||t.some(({item:e})=>u.has(e.itemKey)),conflicting:l.conflicting,loops:[...new Set(n.flatMap(({item:e})=>i.get(e.itemKey)??[]))],usage:gH(h,a)});f.push({view:g,running:s?.run.state===`Running`?s.run:void 0})}return f},I4=e=>e.flatMap(e=>`label`in e?[e.label]:[]),L4=e=>e.flatMap(e=>`state`in e?[e.state]:[]),R4=e=>[...e].sort((e,t)=>e.localeCompare(t)).map(e=>fz.make(e)).map(e=>({lane:new Ez({name:yz.make(e),sources:[new wz({label:e})]}),origin:`proposed`})),z4=(e,t)=>e.lanes.length>0?e.lanes.map(e=>({lane:e,origin:`authored`})):R4(t),B4=e=>kH.make(`${e.origin}:${e.lane.name}`),V4=(e,t)=>{let n=new Set(e.labels.map(pz));return t.find(({lane:e})=>I4(e.sources).some(e=>n.has(pz(e))))},H4=(e,t)=>t.find(({lane:t})=>L4(t.sources).includes(e.state)),U4=(e,t)=>Cz(e.state)?H4(e,t):V4(e,t)??H4(e,t),W4=O(`Board.runningLane`)(function*(e,t,n,r,i){let a={repository:e.name,itemKey:t.itemKey,runId:n.id,loop:n.loop};if(yield*D(a),Cz(t.state))return;let o=V4(t,r);if(o!==void 0)return yield*A(`Placing the running card in the lane its Item's labels match`,{...a,lane:o.lane.name}),o;let s=i.get(n.id);if(s===void 0){yield*A(`No Event read for the card's running Run; placing it by its Item's state`,a);return}let c=yield*n2(t.kind,s.payload).pipe(ng(b),og(e=>e_(`The running Run's Event has no labels to read; placing its card by its Item's state`,{...a,eventId:s.id,errorTag:e._tag,message:e.message}).pipe(rg(y()))));if(x(c))return;let l=V4({labels:c.value},r);return yield*A(l===void 0?`No lane label when the card's running Run was triggered; placing it by its Item's state`:`Keeping the card in the lane its running Run was triggered from`,{...a,lane:l?.lane.name??`none`}),l}),G4=O(`Board.project`)((e,t,n,r,i=[],a=new Map,o=new Map,s=new Map)=>T(function*(){yield*D({repository:e.name});let c=yield*Ph(n,e=>i2(e).pipe($h)),l=[],u=[];for(let e of c)Oi(e)?l.push(e.success):(u.push(e.failure),yield*t_(`Item projection quarantined from Board; siblings continue`,{repository:e.failure.repository,itemKey:e.failure.itemKey,errorTag:e.failure._tag,message:e.failure.message}));let d=z4(e,t),f=F4(e.name,l,r,i,a,o);yield*A(`Projected Task cards from linked Items`,{repository:e.name,items:l.length,tasks:f.length,runs:r.length,watchedTasks:f.filter(({view:e})=>e.loops.length>0).length,runningTasks:f.filter(({running:e})=>e!==void 0).length});let p=new Map;for(let e of d)p.set(B4(e),[]);let m=[];for(let{view:t,running:n}of f){let r=(n===void 0?void 0:yield*W4(e,t,n,d,s))??U4(t,d);r===void 0?m.push(t):p.get(B4(r))?.push(t)}let h=e=>e.sort((e,t)=>t.number-e.number);return new zH({failures:u,lanes:[...d.map(e=>{let t=I4(e.lane.sources),n={id:B4(e),name:e.lane.name,sources:e.lane.sources,origin:e.origin,items:h(p.get(B4(e))??[])};return e.origin===`authored`&&t.length>0?new FH({...n,origin:e.origin,labels:t}):new IH(n)}),new IH({id:kH.make(`fallback:unmapped`),name:yz.make(`Unmapped`),sources:[],origin:`fallback`,items:h(m)})]})})),K4=class e extends Rr()(`@usine/orchestrator/LoopMatches`){static layer=Xf(e,T(function*(){let e=yield*eU;return{matching:O(`LoopMatches.matching`)(function*(e,t,n){yield*D({repository:t.name,items:n.length});let r=e.loops.filter(e=>e.trigger.on!==`schedule`&&BJ(e.selector,t)),i=n.filter(({goneAt:e})=>x(e)),a=new Map,o=0;for(let e of r){let n=i.filter(({source:t})=>t===e.trigger.on);if(n.length===0)continue;let r=yield*$h(v2(e,t,n.map(({payload:e})=>e)));if(Di(r)){o+=n.length,yield*A(`Loop trigger could not be checked; it matches no stored Item`,{repository:t.name,loop:e.name,items:n.length,errorTag:r.failure._tag,message:r.failure.message});continue}let s=new Set;for(let[i,a]of aa(n,r.success))Oi(a)?a.success&&s.add(i):(o+=1,yield*A(`Loop trigger could not be evaluated on a stored Item`,{repository:t.name,loop:e.name,item:i.number,errorTag:a.failure._tag,message:a.failure.message}));a.set(e,s)}let s=[];for(let e of i)for(let t of r)a.get(t)?.has(e)===!0&&s.push({loop:t,item:e});return yield*A(`Matched Loop triggers against stored Items`,{repository:t.name,loops:r.length,items:n.length,matches:s.length,failures:o}),s},kg(eU,e))}}))},q4=10,J4=class extends H(`@usine/github/LabelAdded`)(`LabelAdded`,{at:_E,label:IK}){},Y4=class extends H(`@usine/github/LabelRemoved`)(`LabelRemoved`,{at:_E,label:IK}){},X4=class extends H(`@usine/github/Commented`)(`Commented`,{at:_E,url:z}){},Z4=F([`APPROVED`,`CHANGES_REQUESTED`,`COMMENTED`,`DISMISSED`]),Q4=class extends H(`@usine/github/Reviewed`)(`Reviewed`,{at:_E,url:z,state:Z4}){};P([J4,Y4,X4,Q4]);var $4=`
277
285
  __typename
278
286
  ... on LabeledEvent { createdAt actor { __typename login } label { name color description } }
279
287
  ... on UnlabeledEvent { createdAt actor { __typename login } label { name color description } }
280
- ... on IssueComment { createdAt url author { __typename login } }`,G4=`
288
+ ... on IssueComment { createdAt url author { __typename login } }`,e3=`
281
289
  query UsineItemTimeline($owner: String!, $name: String!, $number: Int!, $since: DateTime!, $after: String) {
282
290
  repository(owner: $owner, name: $name) {
283
291
  issueOrPullRequest(number: $number) {
284
292
  ... on Issue {
285
293
  timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT]) {
286
294
  pageInfo { hasNextPage endCursor }
287
- nodes {${W4}
295
+ nodes {${$4}
288
296
  }
289
297
  }
290
298
  }
291
299
  ... on PullRequest {
292
300
  timelineItems(first: 100, after: $after, since: $since, itemTypes: [LABELED_EVENT, UNLABELED_EVENT, ISSUE_COMMENT, PULL_REQUEST_REVIEW]) {
293
301
  pageInfo { hasNextPage endCursor }
294
- nodes {${W4}
302
+ nodes {${$4}
295
303
  ... on PullRequestReview { createdAt submittedAt url state author { __typename login } }
296
304
  }
297
305
  }
@@ -299,5 +307,5 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
299
307
  }
300
308
  }
301
309
  }
302
- `,K4=I(M({__typename:j,login:j})),q4=M({name:PK,color:FK,description:I(j)}),J4=e=>M({__typename:rT(e),createdAt:vE,actor:K4,label:q4}),Y4=P([J4(`LabeledEvent`),J4(`UnlabeledEvent`),M({__typename:rT(`IssueComment`),createdAt:vE,url:z,author:K4}),M({__typename:rT(`PullRequestReview`),createdAt:vE,submittedAt:I(vE),url:z,state:F([...H4.literals,`PENDING`]),author:K4})]),X4=M({repository:yE(M({issueOrPullRequest:yE(M({timelineItems:M({pageInfo:M({hasNextPage:lT,endCursor:I(j)}),nodes:N(I(Y4))})}))}))}),Z4=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e,r=e=>new IK({name:e.name,color:e.color,description:Sr(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new z4({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new B4({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new V4({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new U4({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},Q4=class e extends Rr()(`@usine/github/GitHubItemHistory`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*LW,n=O(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){let o=yield*e.installationToken(),{name:s,owner:c}=eA(n),l=yield*JK(t,o,`fetch-item-timeline`,G4,{owner:c,name:s,number:r,since:i,after:a},X4);if(x(l.repository))return yield*cK(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(x(u))return yield*new tK({operation:`fetch-item-timeline`,item:r,message:`Issue or pull request ${n}#${r} was not found on GitHub. It was deleted or transferred, or the GitHub App can no longer read it.`});let{pageInfo:d,nodes:f}=u.value.timelineItems;return d.hasNextPage?d.endCursor===null?yield*cK(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:b(d.endCursor)}:{nodes:f,next:y()}});return{appChanges:O(`GitHubItemHistory.appChanges`)(function*(t,r,i){yield*D({repository:t,item:r});let{appSlug:a}=yield*e.installation(),o=J_(i),s=[],c=y(),l=0;do{let e=yield*n(t,r,o,C(c));s.push(...e.nodes),c=e.next,l+=1}while(S(c)&&l<R4);if(S(c))return yield*cK(`fetch-item-timeline`,`the timeline of ${t}#${r} since ${o} has more than ${R4} pages`);let u=s.flatMap(e=>e===null?[]:Z4(a,e));return yield*A(`Read the App's changes from an Item timeline`,{repository:t,item:r,since:o,pages:l,timelineItems:s.length,appChanges:u.length}),u})}}))},$4=class extends H(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:j,label:BH}){},e3=class extends H(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:j,label:BH}){},t3=class extends H(`@usine/orchestrator/CommentedView`)(`Commented`,{at:j,url:j}){},n3=class extends H(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:j,url:j,state:H4}){},r3=class extends H(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:j,fromLane:yz,toLane:yz}){},i3=P([$4,e3,t3,n3,r3]),a3=class extends V(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:sF,changes:N(i3)}){},o3=class extends V(`@usine/orchestrator/RunGitHubChangesView`)({attempts:N(a3)}){},s3=1e3,c3=6e4,l3=1e3,u3=1e4,d3=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>SF(e,i.at));t!==void 0&&(a.length>0?r.push(i):n.set(t.attemptId,[...n.get(t.attemptId)??[],i]))}return{attributed:n,ambiguous:r}},f3=e=>t=>{let n=K_(t.at),r=n-l3,i=K_(e.at),a=pz(e.label.name);return r-r%1e3<=i&&i<=n+u3&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>pz(e)===a)},p3=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(f3(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},m3=e=>new BH({name:fz.make(e.name),color:e.color,description:C(e.description)}),h3=e=>kk(e,{LabelAdded:({at:e,label:t})=>new $4({at:J_(e),label:m3(t)}),LabelRemoved:({at:e,label:t})=>new e3({at:J_(e),label:m3(t)}),Commented:({at:e,url:t})=>new t3({at:J_(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new n3({at:J_(e),url:t,state:n})}),g3=e=>new r3({at:J_(e.at),fromLane:yz.make(e.fromLane),toLane:yz.make(e.toLane)}),_3=T(function*(){let e=yield*aH,t=yield*Q4,n=yield*a0,r=yield*Lk(new Map),i=O(`RunGitHubChanges.windowFor`)(function*(t){let n=yF(t);if(S(n))return n;let[r]=yield*e.transcript(new TB({attemptId:t.id,before:y(),limit:1}));return r===void 0?(yield*k(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),y()):b(new vF({attemptId:t.id,startedAt:t.startedAt,endedAt:b(r.receivedAt)}))});return{read:O(`RunGitHubChanges.read`)(function*(a){yield*D({runId:a});let o=yield*e.inspect(a),s=Gw($0)(o.itemKey);if(x(s))return yield*A(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:a}),new o3({attempts:[]});let[,,c]=s.value,l=o.repository;yield*D({repository:l,item:c});let u=e=>new o3({attempts:o.attempts.map(({id:t})=>new a3({attemptId:t,changes:e.get(t)??[]}))}),d=yield*Rk(r),f=o.attempts.filter(({id:e})=>!d.has(e));if(f.length===0)return yield*A(`Served the Run's GitHub changes from the Attempt cache`,{runId:a,attempts:o.attempts.length}),u(d);let p=yield*e.forItems([o.itemKey]),m=(yield*Ph([...new Map([...p.flatMap(({attempts:e})=>e),...o.attempts].map(e=>[e.id,e])).values()],i)).flatMap(Mr),h=yield*op,g=new Map,_=[],v=f.flatMap(e=>{let t=m.find(({attemptId:t})=>t===e.id);return t===void 0?(g.set(e.id,[]),_.push(e.id),[]):[t]});if(v.length>0){let e=Math.min(...v.map(({startedAt:e})=>K_(e))),r=R_(e-e%1e3),[i,s]=yield*Nh([t.appChanges(l,c,r),n.onItem(o.itemKey,q_(r,{milliseconds:u3}))],{concurrency:`unbounded`}),{moves:u,rest:d}=p3(s,i),{attributed:f,ambiguous:p}=d3(m,d);p.length>0&&(yield*k(`Left out GitHub changes that overlapping Attempts on the Item could each have made`,{runId:a,repository:l,item:c,changes:p.length,at:p.map(({at:e})=>J_(e)).join(`, `)}));for(let e of v){let t=[...(f.get(e.attemptId)??[]).map(e=>({at:K_(e.at),view:h3(e)})),...u.flatMap(t=>{let n=K_(t.at);return K_(e.startedAt)<=n&&vr(e.endedAt,{onNone:()=>!0,onSome:e=>n<=K_(e)})?[{at:n,view:g3(t)}]:[]})];g.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),S(e.endedAt)&&h-K_(e.endedAt.value)>=c3&&_.push(e.attemptId)}yield*k(`Read the App's GitHub changes on a Run's Item`,{runId:a,repository:l,item:c,since:J_(r),appChanges:i.length,boardMoves:s.length,boardMoveChanges:i.length-d.length,placed:v.reduce((e,{attemptId:t})=>e+(f.get(t)?.length??0),0),cachedAttempts:_.length})}let ee=yield*Hk(r,e=>{let t=new Map(e);for(let e of _)t.set(e,g.get(e)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-s3)))t.delete(e);return t});return u(new Map([...ee,...g]))})}});(class e extends Rr()(`@usine/orchestrator/RunGitHubChanges`){static layer=Xf(e,_3)});var v3=500,y3=class extends V(`@usine/orchestrator/TaskItemView`)({...jH.fields,labels:N(fz),conflicting:lT}){},b3=class extends V(`@usine/orchestrator/TaskLaneView`)({id:kH,name:yz}){},x3=class extends V(`@usine/orchestrator/TaskCommentView`)({runId:HA,kind:bN,url:j,postedAt:I(j),attemptEndedAt:I(j)}){},S3=class extends V(`@usine/orchestrator/TaskView`)({repository:Xk,number:rI,title:j,current:nI,lane:b3,needsYou:lT,items:yT(y3),runs:N(CH),comments:N(x3)}){},C3=vr({onNone:()=>null,onSome:J_}),w3=e=>{let t=(t,n)=>new x3({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:C3(t.at),attemptEndedAt:C3(n)}),n=ra(e.attempts,e=>Ir(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(kr(({endedAt:e})=>e)),r=vr(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return va([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},T3=T(function*(){let e=yield*aH,t=yield*Z1,n=yield*G1,r=yield*yU,i=yield*i1;return{read:O(`TaskReader.read`)(function*(a,o,s){yield*D({repository:o,item:s});let c=a.config.repos.find(({name:e})=>tA(e)===tA(o));if(c===void 0)return yield*k(`Task read refused; the repository is not a registered Project`,{repository:o,item:s}),yield*new VH({repository:o});let[l,u,d,f]=yield*Nh([n.list(c.name,{limit:v3}),r.get(c.name),t.states,i.asks()],{concurrency:`unbounded`}),p=yield*e.forItems(l.map(({itemKey:e})=>e)),m=yield*v4(e,p),h=new Set(d.filter(e=>e.paused).map(e=>e.loop)),g=g4(a.config.workers),_=(yield*I4(c,vr(u,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),l,p.map(e=>y4(e,h,g)),f.map(({itemKey:e})=>e),new Map,new Map,m)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===s));if(_===void 0)return yield*k(`Task read found no Task; the Item is not among the Project's newest Board Items`,{repository:c.name,item:s,window:v3}),yield*new HH({repository:c.name,item:s});let{lane:v,task:ee}=_,te=new Set(ee.items.map(({itemKey:e})=>e)),ne=yield*Ph(l.filter(({itemKey:e})=>te.has(e)),e=>Y0(e).pipe($h)),re=new Map;for(let e of ne){if(Di(e)){yield*t_(`Task Item could not be projected; the other Items are shown`,{repository:c.name,itemKey:e.failure.itemKey,message:e.failure.message});continue}let{itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}=e.success;re.set(t,new y3({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}))}let[ie,...ae]=ee.items.flatMap(({itemKey:e})=>{let t=re.get(e);return t===void 0?[]:[t]});if(ie===void 0)return yield*new HH({repository:c.name,item:s});let oe=new Set(ee.runs.map(({id:e})=>e)),se=p.filter(({run:e})=>oe.has(e.id)).sort((e,t)=>K_(t.run.openedAt)-K_(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(w3),ce=new S3({repository:c.name,number:ie.number,title:ee.title,current:ee.itemKey,lane:new b3({id:v.id,name:v.name}),needsYou:ee.needsYou,items:[ie,...ae],runs:[...ee.runs].reverse(),comments:se});return yield*A(`Read a Task`,{repository:c.name,item:s,origin:ce.number,lane:v.name,items:ce.items.length,runs:ce.runs.length,comments:se.length}),ce})}});(class e extends Rr()(`@usine/orchestrator/TaskReader`){static layer=Xf(e,T3)});var E3=F([`binary`,`version`,`login`]),D3=class extends NE(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:lN,capability:E3,message:z}){};P([class extends H(`HarnessReady`)(`HarnessReady`,{harness:lN}){},D3]),Vw(D3),fr(cr,({harness:e})=>e);var O3=class e extends Rr()(`@usine/orchestrator/WorkerStatus`){static idle=Jf(e)({slots:w([]),queue:w([]),preflights:w([]),unavailable:w([]),machines:w([]),provisioning:w([])})},k3=class extends V(`@usine/orchestrator/LoopSelectorView`)({repos:I(N(Xk)),tags:I(N(nJ))}){},A3=class extends V(`@usine/orchestrator/LoopFileView`)({name:aA,file:tU,stream:F([`issue`,`pr`,`schedule`]),condition:ZH,cron:I(BJ),timeZone:I(VJ),selector:I(k3),repositories:N(Xk),approval:sA,maxCycles:iI,permissions:lA,priority:I(YJ),step:wN,agent:fN,prompt:JJ,paused:lT,undeclaredLabels:N(fz)}){},j3=class extends V(`@usine/orchestrator/QuarantinedLoopView`)({name:z,file:tU,error:rU}){},M3=class extends V(`@usine/orchestrator/AgentFileView`)({name:fN,file:tU,harness:lN,model:cN,effort:uN,parentModel:I(cN),parentEffort:I(uN),resolvedParentModel:I(cN),resolvedParentEffort:uN,persona:pN,loops:N(aA)}){},N3=class extends V(`@usine/orchestrator/InvalidAgentView`)({name:z,file:tU,error:rU}){},P3=class extends V(`@usine/orchestrator/GatewayView`)({domain:FN,destination:jN,adminPort:IN,adminTokenEnv:z,llmProviders:N(LN)}){},F3=class extends V(`@usine/orchestrator/WorkerSlotsView`)({capacity:R,leased:R}){},I3=class extends H(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:j}){},L3=class extends H(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:j,message:j}){},R3=class extends H(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:j,message:j}){},z3=class extends H(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:j,capability:I(Jz),message:j}){},B3=P([I3,L3,R3,z3]),V3=class extends V(`@usine/orchestrator/HarnessPreflightView`)({harness:lN,check:B3}){},H3=class extends V(`@usine/orchestrator/ContainerView`)({image:I(zN),cpus:I(VN),memoryMib:I(HN),pids:I(UN)}){},U3=class extends V(`@usine/orchestrator/WorkerConfigurationView`)({name:EN,kind:DN,maxConcurrentAttempts:R,destination:I(jN),port:I(MN),identityFile:I(NN),root:I(PN),gateway:I(P3),container:I(H3),containerLimits:I(WN).pipe(TT(w(null))),provisioner:I(lB).pipe(TT(w(null))),machines:N(aB).pipe(TT(w([]))),provisioning:I(oB).pipe(TT(w(null))),slots:I(F3),prerequisites:I(B3),harnesses:N(V3)}){},W3=class extends V(`@usine/orchestrator/RemovedWorkerView`)({name:EN,running:R}){},G3=class extends V(`@usine/orchestrator/LabelStateView`)({name:fz,onGitHub:I(lT),color:I(j),description:I(j),declared:lT,failure:I(Hq)}){},K3=class extends H(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:G3}){},q3=class extends H(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:bz}){},J3=P([K3,q3]),Y3=class extends V(`@usine/orchestrator/LaneConfigurationView`)({name:yz,sources:N(J3)}){},X3=class extends V(`@usine/orchestrator/RepositoryConfigurationView`)({name:Xk,tags:N(nJ),lanes:N(Y3),declaredLabels:N(G3),loops:N(aA)}){},Z3=class extends V(`@usine/orchestrator/SettingsView`)({pollInterval:R,maxChildren:R,maxAttemptMinutes:I(R),maxAttemptTokens:I(R),parentModel:I(cN),parentEffort:I(uN),operator:I(aN),webhooks:F([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:I(j),tracing:I(M({otlpUrl:j,serviceName:j}))}){},Q3=class extends V(`@usine/orchestrator/ConfigurationView`)({loops:N(A3),quarantinedLoops:N(j3),agents:N(M3),invalidAgents:N(N3),workers:N(U3),removedWorkers:N(W3),repositories:N(X3),settings:Z3}){},$3=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},e6=e=>kk(e,{Passed:({checkedAt:e})=>new I3({checkedAt:J_(e)}),Degraded:({checkedAt:e,message:t})=>new L3({checkedAt:J_(e),message:t}),Deferred:({checkedAt:e,message:t})=>new R3({checkedAt:J_(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new z3({checkedAt:J_(e),capability:C(t),message:n})}),t6=e=>e.kind===`ssh`?{destination:C(e.destination),provisioner:fB(e),port:C(e.port),identityFile:C(e.identityFile),root:e.root,gateway:vr(e.gateway,{onNone:()=>null,onSome:e=>new P3({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new H3({image:C(e.container.image),cpus:C(e.container.cpus),memoryMib:C(e.container.memoryMib),pids:C(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},n6=T(function*(){let e=yield*Z1,t=yield*yU,n=yield*j2,r=yield*O3,i=O(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Or(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[pz(e.name),e]))),a=new Map(e.config.labels.map(e=>[pz(e.name),e])),o=e=>{let t=pz(e),o=kr(i,e=>Sr(e.get(t))),s=a.get(t);return new G3({name:e,onGitHub:vr(i,{onNone:()=>null,onSome:()=>S(o)}),color:C(br(kr(o,({color:e})=>e),()=>kr(Sr(s),({color:e})=>e))),description:C(br(kr(o,({description:e})=>e),()=>kr(Sr(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&pz(e.label)===t)??null})};return new X3({name:n.name,tags:n.tags,lanes:n.lanes.map(e=>new Y3({name:e.name,sources:e.sources.map(e=>`label`in e?new K3({label:o(e.label)}):new q3({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(e=>zJ(e.selector,n)).map(({name:e})=>e)})});return{view:O(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*Nh([e.states,n.latest,r.slots,r.preflights,r.machines,r.provisioning],{concurrency:`unbounded`}),f=new Set(o.filter(e=>e.paused).map(e=>e.loop)),p=vr(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*Ph(a.repos,e=>i(t,e,p),{concurrency:4}),h=e=>t.warnings.flatMap(t=>t._tag===`UndeclaredTriggerLabelWarning`&&t.loop===e?[t.label]:[]),g=t.loops.map(e=>new A3({name:e.name,file:tU.make(`loops/${e.name}.md`),stream:e.trigger.on,condition:e.trigger.if,cron:e.trigger.on===`schedule`?e.trigger.cron:null,timeZone:e.trigger.on===`schedule`?e.trigger.tz:null,selector:vr(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new k3({repos:C(e),tags:C(t)})}),repositories:a.repos.filter(t=>zJ(e.selector,t)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:C(e.priority),step:e.step,agent:e.agent,prompt:e.body,paused:f.has(e.name),undeclaredLabels:h(e.name)})),_=t.agents.map(e=>new M3({name:e.name,file:tU.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:C(e.parentModel),parentEffort:C(e.parentEffort),resolvedParentModel:C(hN(e.agent,a.settings.parentModel)),resolvedParentEffort:gN(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),v=new Map(c.map(e=>[e.worker,e])),ee=new Map(l.map(e=>[e.worker,e])),te=new Set(a.workers.map(({name:e})=>e)),ne=a.workers.map(e=>{let t=v.get(e.name),n=ee.get(e.name);return new U3({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...t6(e),slots:t===void 0?null:new F3({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:C(Or(n.prerequisites,e6)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new V3({harness:e,check:e6(t)})),containerLimits:n===void 0?null:C(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(uB),provisioning:C(Or(Sr(d.find(t=>t.worker===e.name)),dB))})}),{settings:re,webhooks:ie,tracing:ae}=a,oe=new Q3({loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new j3({name:$3(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new N3({name:$3(e),file:e,error:t})),workers:ne,removedWorkers:c.filter(({worker:e,leased:t})=>!te.has(e)&&t>0).map(({worker:e,leased:t})=>new W3({name:e,running:t})),repositories:m,settings:new Z3({pollInterval:re.pollInterval,maxChildren:re.maxChildren,maxAttemptMinutes:C(re.maxAttemptMinutes),maxAttemptTokens:C(re.maxAttemptTokens),parentModel:C(re.parentModel),parentEffort:C(re.parentEffort),operator:C(a.operator),webhooks:ie.mode,webhooksPublicUrl:ie.mode===`endpoint`?ie.publicUrl.href:null,tracing:vr(ae,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*A(`Read the configuration view`,{loops:g.length,quarantinedLoops:oe.quarantinedLoops.length,agents:_.length,invalidAgents:oe.invalidAgents.length,workers:ne.length,runningWorkers:c.length,repositories:m.length}),oe})}});(class e extends Rr()(`@usine/orchestrator/OperatorConfiguration`){static layer=Xf(e,n6)});var r6=200,i6=10,a6=100,o6=500,s6=class extends H(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:EN,lastAnsweredAt:j}){},c6=class extends H(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:fN,message:z,retries:FP,since:j}){},l6=P([s6,c6]),u6=class extends V(`@usine/orchestrator/RunningAttemptView`)({run:CH,attempt:Kz,item:I(jH),lastActivityAt:I(j),warnings:N(l6)}){},d6=class extends H(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:CH}){},f6=class extends H(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:CH}){},p6=class extends H(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:CH}){},m6=class extends H(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},h6=class extends H(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:uI}){},g6=class extends H(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:CH}){},_6=class extends H(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:CH,ahead:I(R.check(HT(0))),creating:I(aB).pipe(TT(w(null)))}){},v6=class extends H(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:CH,stop:DH}){},y6=class extends H(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},b6=P([g6,d6,h6,p6,f6,m6,v6,_6,y6]),x6=class extends V(`@usine/orchestrator/StalledItemView`)({repository:Xk,loop:aA,item:jH,reason:b6}){},S6=class extends V(`@usine/orchestrator/ClosedRunView`)({run:CH,item:I(jH),closedAt:j}){},C6=class extends V(`@usine/orchestrator/WorkerView`)({name:EN,slots:F3,preflight:I(B3),machines:N(aB).pipe(TT(w([]))),provisioning:I(oB).pipe(TT(w(null)))}){},w6=class extends V(`@usine/orchestrator/RepositoryPollView`)({repository:Xk,polledAt:I(j)}){},T6=class extends V(`@usine/orchestrator/DeskView`)({running:N(u6),notMoving:N(x6),lastOutcomes:N(S6),workers:N(C6),polls:N(w6)}){},E6=({runs:e,sighting:t,paused:n,ask:r,ahead:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>AA.some(t=>t===e));if(s!==void 0){let e=s.attempts.at(-1)?.outcome===null;if(S(o)&&s.state!==`Waiting`&&!e)return b(new v6({run:s,stop:o.value}));switch(s.state){case`Running`:return y();case`Waiting`:return b(new g6({run:s}));default:return b(new _6({run:s,ahead:i.get(s.id)??null,creating:a.get(s.id)??null}))}}if(n)return b(new m6);let c=t=>Sr(e.find(({id:e})=>e===t)),l=kr(kr(t,({suppressedBy:e})=>e),c);if(S(l))return b(new d6({run:l.value}));if(S(r))return b(new h6({ask:r.value}));let u=kr(kr(t,({run:e})=>e),c);return S(u)?b(u.value.state===`Failed`?new p6({run:u.value}):new f6({run:u.value})):b(new y6)},D6=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],O6=dr([fr(lr,({reason:e})=>D6.indexOf(e._tag)),fr(cr,({repository:e})=>e),fr(ur(lr),({item:e})=>e.number),fr(cr,({loop:e})=>e)]),k6=({direction:e,envelope:t})=>{let n=t.payload;return e===`outbound`&&n._tag!==`WorkerUnresponsive`&&n._tag!==`WorkerResponsive`&&(n._tag!==`SessionEvent`||n.event._tag!==`PoolRateLimitsUpdated`&&n.event._tag!==`ProviderRetrying`)},A6=e=>{let t=null,n=new Map,r=null;for(let i of e){k6(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new s6({worker:e.worker,lastAnsweredAt:J_(e.lastAnsweredAt)});else if(e._tag===`WorkerResponsive`)t=null;else if(e._tag===`SessionEvent`){let t=e.event;t._tag===`ProviderRetrying`?n.set(t.session.id,new c6({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??J_(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:J_(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},j6=e=>K_(e.checkedAt),M6=e=>{let t=[...Mr(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return Sr((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||j6(t)>j6(e)?t:e,void 0))},N6=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},P6=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,F6=T(function*(){let e=yield*aH,t=yield*Z1,n=yield*i1,r=yield*G1,i=yield*j2,a=yield*L4,o=yield*O3,s=yield*f0,c=O(`Operator.desk.recentActivity`)(function*(t){yield*D({attemptId:t.id});let[n,r]=yield*Nh([e.transcript(new TB({attemptId:t.id,before:y(),limit:r6})),e.transcript(new SB({attemptId:t.id}))],{concurrency:`unbounded`});return A6([...n,...r])});return{desk:O(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,v,ee,te]=yield*Nh([e.list({closedLimit:0}),e.closed({limit:a6}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),ne=ee.map(uB),re=new Map(ne.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),ie=new Map(h.map(({runId:e,ahead:t})=>[e,t])),ae=new Set(f.filter(e=>e.paused).map(e=>e.loop)),oe=g4(l.config.workers),se=yield*Ph(l.config.repos,e=>T(function*(){let t=yield*r.list(e.name,{limit:o6});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),ce=new Map;for(let{items:e}of se)for(let t of e){let e=yield*$h(Y0(t));if(Di(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;ce.set(n,new jH({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let le=se.flatMap(({matches:e})=>e),ue=[...new Set(le.map(({item:e})=>e.itemKey))],[de,fe]=yield*Nh([e.forItems(ue),e.sightings(ue)],{concurrency:`unbounded`}),pe=new Map([...u,...de].map(e=>[e.run.id,y4(e,ae,oe)])),me=[...pe.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),he=e=>kr(Sr(v.find(t=>t.itemKey===e)),e=>Or(Sr(pe.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new DH({runId:e.runId,attemptNumber:t,worker:e.worker}))),ge=[];for(let{loop:e,item:t}of le){let n=ce.get(t.itemKey);if(n===void 0)continue;let r=E6({runs:me.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:Sr(fe.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:ae.has(e.name),ask:Sr(p.find(({itemKey:e})=>e===t.itemKey)),ahead:ie,creating:re,stop:he(t.itemKey)});x(r)||(yield*A(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...kk(r.value,{AwaitingApproval:({run:e})=>({runId:e.id}),SuppressedForOperator:({run:e})=>({runId:e.id}),CycleBudgetUsedUp:({ask:e})=>({askId:e.id}),RunFailed:({run:e})=>({runId:e.id}),ClosedUnchanged:({run:e})=>({runId:e.id,state:e.state}),LoopPaused:()=>({}),WaitingForStop:({run:e,stop:t})=>({runId:e.id,unstoppedRunId:t.runId,attemptNumber:t.attemptNumber,worker:t.worker}),QueuedForWorker:({run:e,ahead:t})=>({runId:e.id,ahead:t}),AwaitingPoll:()=>({})})}),ge.push(new x6({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let _e=yield*Ph(me.flatMap(e=>{let t=e.attempts.at(-1);return e.state===`Running`&&t!==void 0&&t.outcome===null?[{run:e,attempt:t}]:[]}),({run:e,attempt:t})=>ng(c(t),n=>new u6({run:e,attempt:t,item:ce.get(e.itemKey)??null,...n})),{concurrency:4}),ve=d.filter(e=>!P6(e)).map(e=>{let t=y4(e,ae,oe);return new S6({run:t,item:ce.get(t.itemKey)??null,closedAt:N6(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,i6),ye=new Map(m.map(e=>[e.worker,e])),be=new Map(g.map(e=>[e.worker,e])),xe=new Set(l.config.workers.map(({name:e})=>e)),Se=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!xe.has(e))].map(e=>{let t=ye.get(e),n=be.get(e);return new C6({name:e,slots:new F3({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:C(Or(kr(Sr(n),M6),e6)),machines:ne.filter(t=>t.worker===e),provisioning:C(Or(Sr(te.find(t=>t.worker===e)),dB))})}),Ce=vr(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),we=l.config.repos.map(({name:e})=>{let t=Ce.find(({repository:t})=>tA(t)===tA(e));return new w6({repository:e,polledAt:t===void 0?null:J_(t.completedAt)})});return yield*A(`Built the operator desk`,{running:_e.length,matches:le.length,notMoving:ge.length,lastOutcomes:ve.length,workers:Se.length}),new T6({running:_e,notMoving:[...ge].sort(O6),lastOutcomes:ve,workers:Se,polls:we})})}});(class e extends Rr()(`@usine/orchestrator/OperatorDesk`){static layer=Xf(e,F6).pipe(rp(L4.layer))});var I6=R.check(HT(0)),L6=R.check(HT(1)),R6=R.check(HT(0)),z6=FT.check(UT({minimum:0,maximum:1})),B6=j.check(PT(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),V6=F([`7d`,`30d`,`all`]),H6=F([`day`,`week`]),U6=class extends V(`@usine/orchestrator/TaskDoneView`)({repository:Xk,number:rI,mergedAt:j,durationMillis:R6}){},W6=class extends V(`@usine/orchestrator/TaskPeriodView`)({start:B6,tasks:I6,medianMillis:I(R6),firstTimeRight:I6,operatorActions:I6}){},G6=class extends V(`@usine/orchestrator/LoopShareView`)({loop:aA,share:z6}){},K6=class extends V(`@usine/orchestrator/LoopRunTimeView`)({loop:aA,runs:L6,medianMillis:R6}){},q6=class extends V(`@usine/orchestrator/TaskTimeView`)({tasks:L6,loops:N(G6),waiting:z6,runs:N(K6)}){},J6=class extends V(`@usine/orchestrator/TaskCostView`)({tasks:L6,medianUsd:TP,estimate:lT}){},Y6=class extends V(`@usine/orchestrator/TaskTokensView`)({tasks:L6,medianTokens:dP,loops:N(G6),cost:I(J6)}){},X6=class extends V(`@usine/orchestrator/UntimedTasksView`)({tasks:L6,before:B6}){},Z6=class extends V(`@usine/orchestrator/StatisticsView`)({window:V6,from:j,to:j,bucket:H6,loops:N(aA),tasks:N(U6),medianMillis:I(R6),periods:N(W6),firstTimeRight:I6,operatorActions:I6,time:I(q6),tokens:I(Y6),untimed:I(X6),unmetered:I6}){},Q6=class extends V(`@usine/orchestrator/DurationSummaryView`)({count:L6,medianMillis:R6}){},$6=class extends V(`@usine/orchestrator/OutcomeCountsView`)({succeeded:I6,failed:I6,canceled:I6}){},e8=class extends V(`@usine/orchestrator/PoolTokensView`)({pool:kP,tokens:dP}){},t8=class extends V(`@usine/orchestrator/CostSummaryView`)({usd:TP,meanUsd:TP,estimate:lT,priced:L6}){},n8=class extends V(`@usine/orchestrator/UsageSummaryView`)({measured:I6,tokens:dP,meanTokens:I(dP),pools:N(e8),cost:I(t8)}){},r8={outcomes:$6,time:I(Q6),usage:n8},i8=class extends V(`@usine/orchestrator/LoopStatisticsView`)({loop:aA,...r8}){},a8=class extends V(`@usine/orchestrator/AgentStatisticsView`)({agent:fN,...r8}){},o8=class extends V(`@usine/orchestrator/BrainStatisticsView`)({brain:dN,...r8}){},s8=class extends V(`@usine/orchestrator/ThroughputPeriodView`)({start:B6,...$6.fields}){},c8=class extends V(`@usine/orchestrator/WorkerQueueWaitView`)({worker:EN,wait:Q6}){},l8=class extends V(`@usine/orchestrator/AttemptCountView`)({attempts:L6,runs:I6}){},u8=class extends V(`@usine/orchestrator/WorkerUtilizationView`)({worker:EN,slots:L6,occupiedMillis:R6,share:z6}){},d8=class extends V(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:B6,approvals:I6,failures:I6}){},f8=class extends V(`@usine/orchestrator/NeedsAttentionView`)({approvals:I6,failures:I6,periods:N(d8),approvalWait:I(Q6),retryWait:I(Q6),resolutionWait:I(Q6),failureWait:I(Q6)}){},p8=class extends V(`@usine/orchestrator/RunStatisticsView`)({window:V6,from:j,to:j,bucket:H6,runs:$6,runTime:I(Q6),attemptTime:I(Q6),unmeasuredAttempts:I6,throughput:N(s8),loops:N(i8),agents:N(a8),brains:N(o8),queueWait:N(c8),attemptsPerRun:N(l8),utilization:N(u8),needsAttention:f8}){},m8=(e,t)=>({agentNames:new Set(t.map(({name:e})=>e)),registryTags:new Set(e.repos.flatMap(({tags:e})=>e)),repoNames:new Set(e.repos.map(({name:e})=>tA(e)))}),h8=e=>e.map(e=>`"${e}"`).join(`, `),g8=(e,t,n)=>{let r=[],i=()=>r.length===0?y():b(new rU({file:e,stage:`reference`,expression:y(),message:r.map(({message:e})=>e).join(`
303
- `),details:r}));if(n.agentNames.has(t.agent)||r.push({path:[`agent`],message:`Unknown agent "${t.agent}": agents/${t.agent}.md is missing or invalid. Fix the agent file, or set agent to an existing agent.`}),x(t.selector))return i();if(S(t.selector.value.repos)){let e=t.selector.value.repos.value.filter(e=>!n.repoNames.has(tA(e)));e.length>0&&r.push({path:[`selector`,`repos`],message:`Unknown repositories in selector.repos: ${h8(e)}. Add them under repos in usine.yaml.`})}if(S(t.selector.value.tags)){let e=t.selector.value.tags.value.filter(e=>!n.registryTags.has(e));e.length>0&&r.push({path:[`selector`,`tags`],message:`Unknown tags in selector.tags: ${h8(e)}. Add them to a repository's tags in usine.yaml.`})}return i()},_8=class extends V(`@usine/config/LoadedInstance`)(M({config:LJ,agents:N(Jq),invalidAgents:N(Yq),loops:N(XJ),quarantinedLoops:N(ZJ),warnings:N(tY)}).check(NT(({agents:e,config:t,loops:n})=>{let r=m8(t,e);return n.every(e=>x(g8(QJ(e.name),e,r)))},{message:`Expected every loop to reference only loaded agents and registry entries`}))){},v8=R.check(HT(0)).pipe(L(`ConfigurationRevisionNumber`)),y8=F([`settings`,`worker`,`repository`,`label`,`loop`,`agent`]),b8=z.pipe(L(`ConfigurationEntityId`)),x8=class extends V(`@usine/config/ConfigurationEntityKey`)({kind:y8,identifier:b8}){get key(){return`${this.kind}:${this.identifier}`}};V(`@usine/config/ConfigurationEntity`)({key:x8,value:IE});var S8=class extends V(`@usine/config/ConfigurationChange`)({key:x8,before:B(IE),after:B(IE),position:$w(R.check(HT(0)))}){};(class e extends V(`@usine/config/Configuration`)(M({number:v8,instance:B(_8)}).check(NT(({number:e,instance:t})=>e===0===x(t),{message:`Only an uninitialized configuration has revision zero`}))){get actor(){return kr(this.instance,({config:e})=>e.operator)}static empty=new e({number:v8.make(0),instance:y()})}),V(`@usine/config/ConfigurationRevision`)({number:v8.check(VT(0)),actor:B(aN),time:_E,message:B(j),changes:N(S8)}),NE(`@usine/config/StaleRevision`)(`StaleRevision`,{expected:v8,actual:v8}),NE(`@usine/config/ConfigurationInvalid`)(`ConfigurationInvalid`,{problems:yT(rU)}),NE(`@usine/config/ConfigurationStoreError`)(`ConfigurationStoreError`,{operation:j,cause:eE()}),NE(`@usine/config/ConfigurationRevertBlocked`)(`ConfigurationRevertBlocked`,{entities:yT(x8)});var C8=F([`workers`,`webhooks`,`tracing`]),w8=e=>M({added:N(e),removed:N(e),changed:N(e)}),T8=class extends V(`@usine/orchestrator/InstanceReload`)({loops:w8(aA),agents:w8(fN),labels:w8(fz),repos:w8(Xk),workers:w8(EN),settingsChanged:lT,operatorChanged:lT,quarantinedLoops:N(ZJ),invalidAgents:N(Yq)}){},E8=class extends V(`ConfigurationEntityRequest`)({kind:j,identifier:b8}){},D8=class extends V(`ConfigurationRevisionQuery`)({kind:$w(j),identifier:$w(b8),before:$w(v8),limit:R.check(UT({minimum:1,maximum:100}))}){},O8=class extends V(`ConfigurationWrite`)({expected:v8,message:$w(j)}){},k8=P([M({...O8.fields,value:IE,text:$w(iT),position:$w(R.check(HT(0)))}),M({...O8.fields,text:j,value:$w(iT),position:$w(R.check(HT(0)))})]),A8=class extends V(`ConfigurationEntityView`)({key:x8,value:IE,text:j,number:v8}){},j8=class extends V(`ConfigurationRevisionSummary`)({number:v8,actor:I(aN),time:_E,message:I(j),entities:N(x8)}){},M8=class extends V(`ConfigurationRevisionPage`)({revisions:N(j8),nextBefore:I(v8)}){};NE(`ConfigurationNotFound`)(`ConfigurationNotFound`,{message:j});var N8=class e extends V(`ConfigurationRevisionView`)({...j8.fields,changes:N(M({key:x8,before:I(IE),after:I(IE),position:$w(R)}))}){static fromRevision(t){return new e({...t,actor:C(t.actor),message:C(t.message),entities:t.changes.map(({key:e})=>e),changes:t.changes.map(e=>({...e,before:C(e.before),after:C(e.after)}))})}},P8=class extends V(`@usine/orchestrator/UpgradeRequest`)({timing:$q,version:xE(Qq)}){},F8=class extends V(`@usine/orchestrator/UpgradeView`)({running:j,channel:Xq,mode:Zq,supported:lT,available:I(Qq),phase:F([`idle`,`waiting`,`installing`,`failed`]),message:I(j),outcome:I(tJ)}){},I8=`~effect/http-api/HttpApiSchema/Stream`;function L8(e){let t=typeof e==`string`?gG(e):e;return e=>e.ast.checks!==void 0||r5(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var R8=(e=>dT.pipe(L8(e)))(204),z8=e=>Qw(e)&&pe(e,I8),B8=e=>z8(e)&&e._tag===`StreamSse`,V8=e=>z8(e)&&e._tag===`StreamUint8Array`,H8=e=>z8(e)&&e._tag===`StreamNdjson`,U8=`~effect/http-api/HttpApiSchema/Upgrade`,W8=e=>Qw(e)&&pe(e,U8),G8=`~effect/http-api/HttpApiSchema/WithHeaders`,K8=`~effect/http-api/HttpApiSchema/WithHeadersValue`,q8=e=>({[K8]:K8,body:e.body,headers:e.headers}),J8=e=>Qw(e)&&pe(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function Y8(e,t,n){return Zw(e.ast,{[G8]:G8,schema:t,headers:n})}function X8(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??Z8(t._tag)}})}function Z8(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function Q8(e){return t=>X8(t,{_tag:`FormUrlEncoded`,...e})}var $8=e=>{if(qb(e)||qb(GS(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&qb(t)},e5=dC(`~httpApiEncoding`),t5=dC(`~httpApiWithHeaders`),n5=dC(`httpApiStatus`);function r5(e){let t=uC(e);return t!==void 0&&`httpApiStatus`in t}function i5(e){return r5(e)?n5(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var a5={_tag:`Json`,contentType:`application/json`},o5={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function s5(e){return e5(e)??a5}function c5(e,t){return e5(e)||(qU(t)?a5:o5)}function l5(e){let t=s5(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function u5(e){return i5(e)??200}function d5(e){return J8(e)?i5(e.ast)??u5(e.schema.ast):u5(e.ast)}function f5(e){return J8(e)&&e5(e.ast)===void 0?l5(e.schema.ast):l5(e.ast)}function p5(e){return i5(e)??500}function m5(e){return J8(e)?i5(e.ast)??p5(e.schema.ast):p5(e.ast)}function h5(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var g5=`~effect/http-api/HttpApiEndpoint`;function _5(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function v5(e){let t=Array.from(e.success);return Yi(t)?t:[R8]}function y5(e){let t=new Set(e.error),n=e.disableCodecs?i:O5;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var b5={[g5]:g5,pipe(){return e(this,arguments)},prefix(e){return S5({...x5(this),path:oG(this.path,e)})},middleware(e){return S5({...x5(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return S5({...x5(this),annotations:ai(this.annotations,e,t)})},annotateMerge(e){return S5({...x5(this),annotations:hi(this.annotations,e)})}},x5=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function S5(e){function t(){}return Object.setPrototypeOf(t,b5),Object.assign(t,e)}var C5=e=>(t,n,r)=>{let a=r?.disableCodecs??!1,o=a?i:FE;return S5({identifier:t,path:n,method:e,params:w5(r?.params,o),query:w5(r?.query,o),headers:w5(r?.headers,o),payload:T5(r?.payload,e,a),success:D5(r?.success,e,r?.payload!==void 0,a),error:k5(r?.error,a),annotations:ni(),middlewares:new Set,disableCodecs:a})};function w5(e,t){if(e!==void 0)return Qw(e)?t(e):t(M(e))}function T5(e,t,n){let r=new Map;if(e===void 0)return r;let a=Array.isArray(e)?e:Qw(e)?[e]:[M(e).pipe(Q8())],o=n?i:z5,s=!1;for(let e of a){if(z8(e)){if(B8(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!qU(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(s)throw Error(`Multiple streaming payloads are not supported`);s=!0;let n=h5(e.contentType);if(r.has(n))throw Error(`Cannot combine buffered and streaming payloads for content-type: ${e.contentType}`);r.set(n,{encoding:{_tag:`Stream`,contentType:e.contentType},schemas:[e]});continue}let n=c5(e.ast,t),i=h5(n.contentType),a=r.get(i);if(a){if(a.encoding._tag===`Stream`)throw Error(`Cannot combine buffered and streaming payloads for content-type: ${n.contentType}`);if(a.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(a.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);a.schemas.push(o(e,t))}else r.set(i,{encoding:n,schemas:[o(e,t)]})}return r}var E5=`effect/http-api/stream/failure`;function D5(e,t,n,r){if(e===void 0)return new Set;let i=Gi(e);return A5(i,t,n),new Set(r?i:i.map(O5))}var O5=f(e=>z8(e)||W8(e)?e:J8(e)?Y8(e,z8(e.schema)?e.schema:R5(e.schema,f5(e)),FE(e.headers)):L5(e));function k5(e,t){if(e===void 0)return new Set;let n=Gi(e);for(let e of n){let t=J8(e)?e.schema:e;if(z8(t))throw Error(`Streaming schemas are not supported in error responses`);if(W8(t))throw Error(`Upgrade schemas are not supported in error responses`)}return M5(n,m5),new Set(t?n:n.map(O5))}function A5(e,t,n){if(e.some(W8)){if(e.length>1)throw Error(`Cannot combine an upgrade with other success responses`);if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare an upgrade`);if(n)throw Error(`Upgrade endpoints cannot declare a payload`);return}let r=!1,i=new Map;for(let n of e){let e=J8(n)?n.schema:n,a=d5(n);if(z8(e)){if(N5(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=j5(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(h5(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);i.set(a,{...n,stream:e})}else{let t=j5(i,a),r=$8(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=f5(n);if(h5(e.contentType)===h5(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(h5(f5(n).contentType)),t.noContent=t.noContent||r}}M5(e,d5)}function j5(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function M5(e,t){let n=new Map;for(let r of e){let e=t(r),i=t5(r.ast),a=J8(r)?r.schema:i?.body??r,o=$8(a.ast)?``:h5(z8(a)?a.contentType:f5(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:new Set},n.set(e,s));let c=()=>Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(J8(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function N5(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(B8(e)&&P5(e.events.ast))throw Error(`SSE event name is reserved: ${E5}`)}function P5(e){return F5(GS(e),new Set)}function F5(e,t){if(t.has(e))return!1;if(t.add(e),$b(e))return e.types.some(e=>F5(e,t));if(ex(e))return F5(e.thunk(),t);if(!Qb(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&I5(n.type,t)}function I5(e,t){if(t.has(e))return!1;t.add(e);let n=GS(e);return n===e?Yb(e)?e.literal===E5:$b(e)?e.types.some(e=>I5(e,t)):ex(e)?I5(e.thunk(),t):!1:I5(n,t)}function L5(e){let t=l5(e.ast),n=t5(e.ast);return n===void 0?R5(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:R5(n.body,t),headersCodec:FE(n.headers)}})}function R5(e,t){switch(t._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:return e}}function z5(e,t){switch(c5(e.ast,t)._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var B5=C5(`GET`),V5=C5(`POST`),H5=C5(`PUT`),U5=C5(`DELETE`),W5=`~effect/http-api/HttpApi`,G5={[W5]:W5,pipe(){return e(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Et(t,n.identifier,n);return q5({...K5(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];Et(t,n,r.annotateMerge(hi(e.annotations,r.annotations)))}return q5({...K5(this),groups:t})},prefix(e){return q5({...K5(this),groups:zi(this.groups,t=>t.prefix(e))})},middleware(e){return q5({...K5(this),groups:zi(this.groups,t=>t.middleware(e))})},annotate(e,t){return q5({...K5(this),annotations:ai(this.annotations,e,t)})},annotateMerge(e){return q5({...K5(this),annotations:hi(this.annotations,e)})}},K5=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),q5=e=>{function t(){}return Object.setPrototypeOf(t,G5),Object.assign(t,e)},J5=e=>q5({identifier:e,groups:{},annotations:ni()}),Y5=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=hi(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:hi(n,e.annotations),successes:X5(v5(e),d5),errors:X5(y5(e),m5)})}},X5=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=J8(e)?e.schema:e;if(z8(r)||W8(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},Z5=class extends Rr()(`effect/http-api/HttpApi/ParseOptions`){},Q5=class extends Rr()(`effect/http-api/HttpApi/ParamsParseOptions`){},$5=class extends Rr()(`effect/http-api/HttpApi/QueryParseOptions`){},e7=class extends Rr()(`effect/http-api/HttpApi/HeadersParseOptions`){},t7=class extends Rr()(`effect/http-api/HttpApi/PayloadParseOptions`){},n7=class extends Rr()(`effect/http-api/HttpApi/SuccessParseOptions`){},r7=class extends Rr()(`effect/http-api/HttpApi/ErrorParseOptions`){},i7=e=>{let t=si(e,Z5);return{params:si(e,Q5)??t,query:si(e,$5)??t,headers:si(e,e7)??t,payload:si(e,t7)??t,success:si(e,n7)??t,error:si(e,r7)??t}},a7=`~effect/http-api/HttpApiMiddleware`,o7=`~effect/http-api/HttpApiMiddleware/Security`,s7=()=>(e,t)=>{let n=St(),r;n!==0&&(Ct(2),r=new globalThis.Error,Ct(n));class i extends Rr()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[a7]=a7,a.error=c7(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[o7]=o7,a.security=t.security}return a};function c7(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var l7=new Set;function u7(e){if(e===void 0)return l7;let t=xS(e.ast);return Qb(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function d7(e,t,n){let r=/::|:(\w+)/g,i=``,a=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let s=o[1];if(s===void 0||t!==void 0&&!t.has(s))continue;let c=r.lastIndex;e[c]===`(`&&(c=tG(e,c)+1);let l=e[c]===`?`;l&&c++;let u=n(s,l),d=o.index;u===void 0&&e[d-1]===`/`&&d--,i+=e.slice(a,d)+(u??``),r.lastIndex=c,a=c}return i+e.slice(a)}var f7=(e,t)=>T(function*(){let n=yield*Cg(),r=t.httpClient.pipe(t?.baseUrl===void 0?i:UW(mW(t.baseUrl.toString())));function a(e,t,i,o,s){if(s===-1)return r.execute(i);let c=n.mapUnsafe.get(o[s]);return c===void 0?a(e,t,i,o,s-1):c({endpoint:t,group:e,request:i,next(n){return a(e,t,n,o,s-1)}})}Y5(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:i,successes:o,mergedAnnotations:s}=e,c=i7(s),l=h7(r.path,r.params),u={orElse:z7},d=new Map;for(let[e,t]of i.entries()){let n=x7(t);for(let[t,r]of n.entries())y7(d,e,t,g7(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=b7(t);u[e]=e=>E(lg(n(e),t=>Wh(ef(qd(new RU({reason:new WU({request:e.request,response:e})})),t))),Uh)}let f=new Map;for(let[e,t]of o.entries()){let n=x7(t);for(let[t,r]of n.entries())y7(f,e,t,g7(r,c.success,c.headers))}for(let e of E7(r)){let t=w7(e)?e.schema:e;y7(f,d5(e),t.contentType,D7(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=b7(t);let p=T7(r);p!==void 0&&(u[101]=e=>ng(e.upgrade,t=>({headers:e.headers,socket:t})));let m=Uk(r.params,e=>qw(e,c.params)),h=[],g;for(let e of _5(r))V8(e)||H8(e)?g=e:h.push(e);let _=Uk(g,e=>({contentType:e.contentType,encode:V7(e,c.payload)})),v=Yi(h)?qw(qU(r.method)?H7(h,r.method):P(h),c.payload):void 0,ee=Uk(r.headers,e=>qw(e,c.headers)),te=Uk(r.query,e=>qw(e,c.query)),ne=Array.from(e.middleware,e=>`${e.key}/Client`),re=$g(function*(e){let i=rW(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);i=pW(i,l(t))}if(_!==void 0&&EO(e.payload)){let t=yield*Cg();i=yW(i,IU(GO(_.encode(e.payload),t),_.contentType))}else if(v!==void 0){if(qU(r.method)){if(e.payload instanceof FormData)i=xW(i,e.payload);else{let t=yield*v(e.payload);i=yW(i,t)}}else{let t=yield*v(e.payload);i=_W(i,t)}}else if(_!==void 0)return yield*new Pw(new My({message:`Expected a Stream payload`},e.payload));if(ee!==void 0){let t=yield*ee(e.headers);i=lW(i,t)}if(te!==void 0){let t=yield*te(e.query);i=_W(i,t)}}p!==void 0&&(i=fW(i,p.protocol));let o=yield*a(n,r,i,ne,ne.length-1);if(e?.responseMode===`response-only`)return o;let s=(u[o.status]??u.orElse)(o,e?.sseOptions),c=yield*t.transformResponse===void 0?s:t.transformResponse(s);return e?.responseMode===`decoded-and-response`?[c,o]:c});t.onEndpoint({...e,endpointFn:re})}})}),p7=(e,t)=>E(LW,n=>m7(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),m7=(e,t)=>{let n={};return f7(e,{...t,onGroup({group:e}){e.topLevel||Et(n,e.identifier,{})},onEndpoint({endpoint:e,endpointFn:t,group:r}){Et(r.topLevel?n:n[r.identifier],e.identifier,t)}}).pipe(rg(n))},h7=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=u7(t);return t=>d7(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function g7(e,t,n){let r=e.some(e=>J8(e)||t5(e.ast)!==void 0),i=Hw(r?P(e.map(e=>v7(e,t,n))):L7(e),t);return e=>E(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var _7=M({body:aT,headers:aT});function v7(e,t,n){let r=t5(e.ast),i=r===void 0?J8(e)?{body:e.schema,headers:e.headers,toValue:q8}:{body:e,headers:aT,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=Hw(R7(i.body).pipe(ST(i.body)),t),o=Hw(i.headers,n);return _7.pipe(ST(J8(e)?e:tT(e),Tb({decode:e=>Nh({body:a(e.body),headers:o(e.headers)}).pipe(ng(i.toValue),dg(e=>e.issue)),encode:(e,t)=>Uh(new Py({message:`Decode only schema`},e,t))})))}function y7(e,t,n,r){let i=h5(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function b7(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:(t,n)=>{let r=h5(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?S7(t,r,e):i.decode(t,n)}}function x7(e){let t=new Map;for(let n of e){let e=$8((J8(n)?n.schema:n).ast)?``:h5(f5(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function S7(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return Uh(new RU({reason:new GU({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var C7=`effect/http-api/stream/failure`,w7=e=>J8(e);function T7(e){for(let t of e.success)if(W8(t))return t}function E7(e){let t=[];for(let n of e.success)z8(J8(n)?n.schema:n)&&t.push(n);return t}function D7(e,t,n){let r=w7(e),i=O7(r?e.schema:e,t),a=(e,t)=>ng(Cg(),n=>GO(i(e,t),n));if(!r)return a;let o=Hw(e.headers,n);return(e,t)=>E(o(e.headers),n=>ng(a(e,t),e=>q8({body:e,headers:n})))}function O7(e,t){if(V8(e))return e=>e.stream;if(H8(e)){let n=Hw(PE(e.schema),t),r=P_(e.maxElementBytes);return e=>e.stream.pipe(VO(pR({ignoreEmptyLines:!0,maxLineBytes:r})),BO(t=>aR(t)?t.reason===`LineTooLarge`?new RU({reason:new GU({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):A7(t):t),IO(e=>n(e)))}let n=j7(e,t);return(t,r)=>M7(t.stream,e,n(r))}var k7=e=>aR(e)&&e.kind===`Pack`,A7=e=>new Pw(new My({message:e.reason===`InvalidUtf8`?`Expected valid UTF-8`:e.unterminated?`Expected a valid JSON line, got an unterminated final line`:`Expected a valid JSON line`}));function j7(e,t){let n=P([M({id:eT(j),event:rT(C7),data:aE(PE(dE(e.error,eE())))}),e.events]),r=yR(n,void 0,t);return e=>e===void 0?r:yR(n,e,t)}function M7(e,t,n){let r=OO(e.pipe(HO,VO(n)),e=>zh(()=>{let t;return Rh(()=>t===void 0?E(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===C7&&Ud(r.data)){if(n===0)return Wh(r.data);t=r.data,e=e.slice(0,n);break}}return w(e)}):Wh(t))}));return t.sseMode===`data`?FO(r,e=>e.data):r}var N7=jT(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),P7=N7.pipe(ST(lE,Eb({decode(e){return new Uint8Array(e)},encode(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}))),F7=N7.pipe(ST(j,Eb({decode(e){return new TextDecoder().decode(e)},encode(e){let t=new TextEncoder().encode(e);return t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}))),I7=F7.pipe(ST(P([rT(``).pipe(ST(sT,Eb({decode:()=>void 0,encode:()=>``}))),oE])));function L7(e){return P(e.map(t));function t(e){return R7(e).pipe(ST(e))}}function R7(e){switch(l5(e.ast)._tag){case`Json`:return Kb(GS(e.ast))?I7.pipe(ST(aT,Eb({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):I7;case`FormUrlEncoded`:return F7.pipe(ST(bE,Eb({decode:e=>Vv(new URLSearchParams(e)),encode:Xv})));case`Uint8Array`:return P7;case`Text`:return F7}}var z7=e=>Uh(new RU({reason:new GU({request:e.request,response:e})})),B7=Nw(SU);function V7(e,t){if(V8(e))return e=>e;let n=qw(yT(PE(e.schema)),t);return e=>e.pipe(LO(e=>n(e)),VO(sR()),zO(k7,NO))}function H7(e,t){return P(e.map(e=>W7(e,t)))}var U7=new WeakMap;function W7(e,t){let n=e.ast,r=U7.get(n);if(r!==void 0)return r;let i=c5(n,t),a=B7.pipe(ST(e,Tb({decode(e,t){return Uh(new Py({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return Uh(new Py({message:`Payload must be a FormData`},e,t));case`Json`:try{return w(AU(JSON.stringify(e),i.contentType))}catch{return Uh(new My({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?w(AU(e,i.contentType)):Uh(new My({message:`Expected a string`},e,t));case`FormUrlEncoded`:return de(e)?w(MU(Vv(e),i.contentType)):Uh(new My({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?w(EU(e,i.contentType)):Uh(new My({message:`Expected a Uint8Array`},e,t))}}})));return U7.set(n,a),a}var G7=`~effect/http-api/HttpApiGroup`,K7={[G7]:G7,add(...e){let t={...this.endpoints};for(let n of e)Et(t,n.identifier,n);return J7({...q7(this),endpoints:t})},prefix(e){return J7({...q7(this),endpoints:zi(this.endpoints,t=>t.prefix(e))})},middleware(e){return J7({...q7(this),endpoints:zi(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return J7({...q7(this),annotations:hi(this.annotations,e)})},annotate(e,t){return J7({...q7(this),annotations:ai(this.annotations,e,t)})},annotateEndpointsMerge(e){return J7({...q7(this),endpoints:zi(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return J7({...q7(this),endpoints:zi(this.endpoints,n=>n.annotate(e,t))})},pipe(){return e(this,arguments)}},q7=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),J7=e=>{function t(){}return Object.setPrototypeOf(t,K7),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},Y7=(e,t)=>J7({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ni()}),X7={UpgradeError:409,ConfigurationNotFound:404,ConfigurationStoreError:500,SchemaError:400,InvalidRequestError:400,CrossSiteRequestError:403,RunNotFoundError:404,TranscriptAttemptNotFoundError:404,BoardProjectNotFoundError:404,BoardItemNotFoundError:404,BoardLaneNotFoundError:404,GitHubItemNotFoundError:404,RunOperationRejectedError:409,RunRetryBlockedError:409,RunInterventionRejectedError:409,LeftoversDiscardRejectedError:409,RosterAgentNotFoundError:404,LoopNotFoundError:404,CycleBudgetResetRejectedError:409,BoardLaneReadOnlyError:409,RestartRequiredError:409,ReloadPreflightError:409,FactoryConfigError:422,EnginePersistenceError:500,AttemptCancellationError:500,HttpBodyError:500,GitHubApiError:502,InvalidGitHubResponseError:502,BackendUnavailableError:503,InstallationDiscoveryError:503,AppPermissionError:503,GitHubRateLimitError:503},Z7=class extends ME(`@usine/orchestrator/OperatorHttpError`)({error:F(Bi(X7)),message:j}){get status(){return X7[this.error]}},Q7=[...new Set(Object.values(X7))].map(e=>Z7.check(NT(t=>t.status===e)).annotate({httpApiStatus:e})),$7=class extends s7()(`@usine/orchestrator/OperatorHttpPolicy`,{error:Q7}){},e9=P([AT(`WorkerCapabilityError`,{worker:EN,capability:Jz,message:j}),AT(`ExecutorOperationError`,{operation:qz,message:j}),AT(`CredentialUnavailableError`,{repository:Xk,message:j})]),t9=class extends ME(`@usine/orchestrator/RestartRequiredRefusal`)({error:rT(`RestartRequiredError`),message:j,blocks:yT(C8),fields:yT(z)},{httpApiStatus:409}){},n9=class extends ME(`@usine/orchestrator/ReloadPreflightRefusal`)({error:rT(`ReloadPreflightError`),message:j,agents:N(fN),workers:N(EN),cause:e9},{httpApiStatus:409}){},r9=class extends ME(`@usine/orchestrator/FactoryConfigRefusal`)({error:rT(`FactoryConfigError`),message:j,file:tU,stage:nU},{httpApiStatus:422}){},i9=[class extends ME(`StaleRevisionRefusal`)({error:rT(`StaleRevision`),message:j,expected:v8,current:v8},{httpApiStatus:409}){},class extends ME(`ConfigurationInvalidRefusal`)({error:rT(`ConfigurationInvalid`),message:j,problems:yT(M({entity:x8,path:N(P([j,cT])),message:j}))},{httpApiStatus:422}){},class extends ME(`ConfigurationRevertRefusal`)({error:rT(`ConfigurationRevertBlocked`),message:j,entities:yT(x8)},{httpApiStatus:409}){},t9,n9,r9],a9={number:sE.pipe(ST(v8))},o9=E8.fields,s9=$w(iT),c9=P([j,yT(j).pipe(ST(j,Eb({decode:e=>e[0],encode:e=>[e]})))]),l9=c9.pipe(ST(sE),ST(pB)),u9=P([M({after:s9,before:s9,attempt:s9}).pipe(ST(tT(AB),Eb({decode:()=>new AB,encode:()=>({})}))),M({after:l9,before:s9,attempt:s9}).pipe(ST(tT(jB),Eb({decode:({after:e})=>new jB({after:e}),encode:({after:e})=>({after:e})}))),M({after:s9,before:l9,attempt:c9.pipe(ST(sF))}).pipe(ST(tT(MB),Eb({decode:({before:e,attempt:t})=>new MB({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),d9=j.check(PT(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),f9=M({ok:rT(!0)}),p9={runId:HA},m9={loop:aA},h9=M({window:c9.pipe(ST(V6),DT(w(`30d`)))}),g9=J5(`OperatorApi`).add(Y7(`operator`).add(B5(`upgradeStatus`,`/api/upgrade`,{success:F8}),B5(`serverVersion`,`/api/version`,{success:j}),V5(`requestUpgrade`,`/api/upgrade`,{payload:P8,success:f9}),B5(`overview`,`/api/overview`,{success:u4}),V5(`dismissNeed`,`/api/attention/dismiss`,{payload:sN,success:f9}),V5(`undoDismissNeed`,`/api/attention/undo`,{payload:sN,success:f9}),B5(`agents`,`/api/agents`,{success:N(fN)}),V5(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:p9,payload:bH,success:f9}),V5(`runAgain`,`/api/runs/:runId/run-again`,{params:p9,payload:bH,success:o1}),V5(`intervene`,`/api/runs/:runId/intervene`,{params:p9,payload:xH,success:f9}),V5(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:M({askId:lI}),success:f9}),B5(`detail`,`/api/runs/:runId`,{params:p9,query:u9,success:OH}),B5(`githubChanges`,`/api/runs/:runId/github-changes`,{params:p9,success:o3}),V5(`approve`,`/api/runs/:runId/approve`,{params:p9,success:f9}),V5(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:p9,payload:M({attemptId:sF}),success:f9}),V5(`retry`,`/api/runs/:runId/retry`,{params:p9,success:f9}),V5(`cancel`,`/api/runs/:runId/cancel`,{params:p9,success:f9}),V5(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:d9,repository:d9,item:sE.pipe(ST(rI))},payload:M({toLane:kH}),success:f9}),V5(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:EN},success:f9}),V5(`pause`,`/api/loops/:loop/pause`,{params:m9,success:f9}),V5(`unpause`,`/api/loops/:loop/unpause`,{params:m9,success:f9}),V5(`reload`,`/api/instance/reload`,{success:T8,error:[t9,n9,r9]})).add(B5(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:d9,repository:d9,item:sE.pipe(ST(rI))},success:S3})).add(B5(`configurationRevisions`,`/api/configuration/revisions`,{query:M({kind:$w(c9),identifier:$w(c9.pipe(ST(b8))),before:$w(c9.pipe(ST(sE),ST(v8))),limit:c9.pipe(ST(sE),ST(D8.fields.limit),DT(w(`50`)))}),success:M8,error:i9}),B5(`configurationRevision`,`/api/configuration/revisions/:number`,{params:a9,success:N8,error:i9}),B5(`configurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:o9,success:A8,error:i9}),H5(`replaceConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:o9,payload:k8,success:N8,error:i9}),U5(`deleteConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:o9,payload:O8,success:N8,error:i9}),V5(`revertConfigurationRevision`,`/api/configuration/revisions/:number/revert`,{params:a9,payload:O8,success:N8,error:i9})).add(B5(`configuration`,`/api/configuration`,{success:Q3})).add(B5(`desk`,`/api/desk`,{success:T6})).add(B5(`statistics`,`/api/statistics`,{query:h9,success:Z6}),B5(`runStatistics`,`/api/statistics/runs`,{query:h9,success:p8})).annotate(t7,{onExcessProperty:`error`}).middleware($7)),_9=()=>p7(g9,{baseUrl:globalThis.location.origin}),v9=e=>Xg(E(_9(),t=>e(t.operator)).pipe(kg(KW,!1),Tg(eG))),y9=e=>e instanceof Error?e.message:String(e),b9=e=>`${e.harness} · ${e.model} · ${e.effort}`,x9=e=>{switch(e){case`issue`:return`Issue`;case`pr`:return`PR`;case`schedule`:return`Schedule`;default:return e}},S9=(e,t=Date.now())=>{let n=Math.max(0,t-Date.parse(e));return n<6e4?`now`:n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:`${Math.floor(n/864e5)}d`},C9=(e,t)=>{let n=S9(e,t);return n===`now`?`just now`:`${n} ago`},w9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`},T9=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],E9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getDate()} ${T9[t.getMonth()]} ${n(t.getHours())}:${n(t.getMinutes())}`},D9=e=>`${e.getDate()} ${T9[e.getMonth()]}`,O9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},k9=e=>{let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.round(t/60);return n<60?`${n} min`:n%60==0?`${Math.floor(n/60)} h`:`${Math.floor(n/60)} h ${n%60} min`},A9=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}).format(e),j9=e=>e>0&&e<.005?`under $0.01`:`$${e.toFixed(2)}`,M9=e=>({claude:`Claude Code`,codex:`Codex`,pi:`Pi`})[e],N9=e=>({apiKeys:`API keys`,claudePlan:`Claude plan`,chatgptPlan:`ChatGPT plan`})[e],P9=e=>e%1440==0?`${e/1440}-day`:e%60==0?`${e/60}-hour`:`${e}-minute`,F9=`Loading…`,I9=`Could not load the page`,L9=`Try again`;export{HA as $,vr as $t,NH as A,Bw as At,pB as B,ga as Bt,t9 as C,UT as Ct,c4 as D,GT as Dt,o4 as E,JT as Et,OH as F,og as Ft,RF as G,kr as Gt,rI as H,jr as Ht,xH as I,e_ as It,lF as J,C as Jt,HF as K,Sr as Kt,AB as L,Zg as Lt,IH as M,G_ as Mt,FH as N,K_ as Nt,i4 as O,eT as Ot,bH as P,rg as Pt,oN as Q,Or as Qt,MB as R,qh as Rt,n9 as S,Vw as St,l4 as T,HT as Tt,UF as U,Ir as Ut,Cz as V,Xi as Vt,IF as W,Nr as Wt,fN as X,x as Xt,GN as Y,Tr as Yt,sN as Z,S as Zt,P9 as _,Gw as _t,E9 as a,lT as at,r9 as b,Xw as bt,M9 as c,IE as ct,N9 as d,I as dt,y as en,AA as et,w9 as f,cT as ft,j9 as g,P as gt,L9 as h,M as ht,D9 as i,N as it,zH as j,J_ as jt,$0 as k,$w as kt,F9 as l,rT as lt,x9 as m,j as mt,b9 as n,b as nn,eA as nt,k9 as o,sE as ot,A9 as p,hT as pt,zF as q,yr as qt,O9 as r,Mr as rn,kk as rt,S9 as s,R as st,C9 as t,br as tn,Xk as tt,I9 as u,F as ut,v9 as v,ST as vt,P8 as w,IT as wt,Z7 as x,aE as xt,y9 as y,Ww as yt,jB as z,Wg as zt};
310
+ `,t3=I(M({__typename:j,login:j})),n3=M({name:PK,color:FK,description:I(j)}),r3=e=>M({__typename:rT(e),createdAt:vE,actor:t3,label:n3}),i3=P([r3(`LabeledEvent`),r3(`UnlabeledEvent`),M({__typename:rT(`IssueComment`),createdAt:vE,url:z,author:t3}),M({__typename:rT(`PullRequestReview`),createdAt:vE,submittedAt:I(vE),url:z,state:F([...Z4.literals,`PENDING`]),author:t3})]),a3=M({repository:yE(M({issueOrPullRequest:yE(M({timelineItems:M({pageInfo:M({hasNextPage:lT,endCursor:I(j)}),nodes:N(I(i3))})}))}))}),o3=(e,t)=>{let n=t=>t!==null&&t.__typename===`Bot`&&t.login===e,r=e=>new IK({name:e.name,color:e.color,description:Sr(e.description)});switch(t.__typename){case`LabeledEvent`:return n(t.actor)?[new J4({at:t.createdAt,label:r(t.label)})]:[];case`UnlabeledEvent`:return n(t.actor)?[new Y4({at:t.createdAt,label:r(t.label)})]:[];case`IssueComment`:return n(t.author)?[new X4({at:t.createdAt,url:t.url})]:[];case`PullRequestReview`:{let e=t.state;return!n(t.author)||e===`PENDING`?[]:[new Q4({at:t.submittedAt??t.createdAt,url:t.url,state:e})]}}},s3=class e extends Rr()(`@usine/github/GitHubItemHistory`){static layer=Xf(e,T(function*(){let e=yield*wK,t=yield*LW,n=O(`GitHubItemHistory.timelinePage`)(function*(n,r,i,a){let o=yield*e.installationToken(),{name:s,owner:c}=eA(n),l=yield*JK(t,o,`fetch-item-timeline`,e3,{owner:c,name:s,number:r,since:i,after:a},a3);if(x(l.repository))return yield*cK(`fetch-item-timeline`,`repository "${n}" is null: deleted, renamed, or no longer accessible`);let u=l.repository.value.issueOrPullRequest;if(x(u))return yield*new tK({operation:`fetch-item-timeline`,item:r,message:`Issue or pull request ${n}#${r} was not found on GitHub. It was deleted or transferred, or the GitHub App can no longer read it.`});let{pageInfo:d,nodes:f}=u.value.timelineItems;return d.hasNextPage?d.endCursor===null?yield*cK(`fetch-item-timeline`,`GitHub returned hasNextPage for the timeline without an endCursor`):{nodes:f,next:b(d.endCursor)}:{nodes:f,next:y()}});return{appChanges:O(`GitHubItemHistory.appChanges`)(function*(t,r,i){yield*D({repository:t,item:r});let{appSlug:a}=yield*e.installation(),o=J_(i),s=[],c=y(),l=0;do{let e=yield*n(t,r,o,C(c));s.push(...e.nodes),c=e.next,l+=1}while(S(c)&&l<q4);if(S(c))return yield*cK(`fetch-item-timeline`,`the timeline of ${t}#${r} since ${o} has more than ${q4} pages`);let u=s.flatMap(e=>e===null?[]:o3(a,e));return yield*A(`Read the App's changes from an Item timeline`,{repository:t,item:r,since:o,pages:l,timelineItems:s.length,appChanges:u.length}),u})}}))},c3=class extends H(`@usine/orchestrator/LabelAddedView`)(`LabelAdded`,{at:j,label:BH}){},l3=class extends H(`@usine/orchestrator/LabelRemovedView`)(`LabelRemoved`,{at:j,label:BH}){},u3=class extends H(`@usine/orchestrator/CommentedView`)(`Commented`,{at:j,url:j}){},d3=class extends H(`@usine/orchestrator/ReviewedView`)(`Reviewed`,{at:j,url:j,state:Z4}){},f3=class extends H(`@usine/orchestrator/BoardMovedView`)(`BoardMoved`,{at:j,fromLane:yz,toLane:yz}){},p3=P([c3,l3,u3,d3,f3]),m3=class extends V(`@usine/orchestrator/AttemptGitHubChangesView`)({attemptId:sF,changes:N(p3)}){},h3=class extends V(`@usine/orchestrator/RunGitHubChangesView`)({attempts:N(m3)}){},g3=1e3,_3=6e4,v3=1e3,y3=1e4,b3=(e,t)=>{let n=new Map,r=[];for(let i of t){let[t,...a]=e.filter(e=>SF(e,i.at));t!==void 0&&(a.length>0?r.push(i):n.set(t.attemptId,[...n.get(t.attemptId)??[],i]))}return{attributed:n,ambiguous:r}},x3=e=>t=>{let n=K_(t.at),r=n-v3,i=K_(e.at),a=pz(e.label.name);return r-r%1e3<=i&&i<=n+y3&&(e._tag===`LabelAdded`?t.added:t.removed).some(e=>pz(e)===a)},S3=(e,t)=>{let n=new Set,r=[];for(let i of t){let t=i._tag===`LabelAdded`||i._tag===`LabelRemoved`?e.find(x3(i)):void 0;t===void 0?r.push(i):n.add(t)}return{moves:e.filter(e=>n.has(e)),rest:r}},C3=e=>new BH({name:fz.make(e.name),color:e.color,description:C(e.description)}),w3=e=>kk(e,{LabelAdded:({at:e,label:t})=>new c3({at:J_(e),label:C3(t)}),LabelRemoved:({at:e,label:t})=>new l3({at:J_(e),label:C3(t)}),Commented:({at:e,url:t})=>new u3({at:J_(e),url:t}),Reviewed:({at:e,url:t,state:n})=>new d3({at:J_(e),url:t,state:n})}),T3=e=>new f3({at:J_(e.at),fromLane:yz.make(e.fromLane),toLane:yz.make(e.toLane)}),E3=T(function*(){let e=yield*aH,t=yield*s3,n=yield*m0,r=yield*Lk(new Map),i=O(`RunGitHubChanges.windowFor`)(function*(t){let n=yF(t);if(S(n))return n;let[r]=yield*e.transcript(new TB({attemptId:t.id,before:y(),limit:1}));return r===void 0?(yield*k(`An ended Attempt has neither an end time nor a transcript; no GitHub change is placed in it`,{attemptId:t.id}),y()):b(new vF({attemptId:t.id,startedAt:t.startedAt,endedAt:b(r.receivedAt)}))});return{read:O(`RunGitHubChanges.read`)(function*(a){yield*D({runId:a});let o=yield*e.inspect(a),s=Gw(c2)(o.itemKey);if(x(s))return yield*A(`The Run has no GitHub Item, so it has no GitHub changes`,{runId:a}),new h3({attempts:[]});let[,,c]=s.value,l=o.repository;yield*D({repository:l,item:c});let u=e=>new h3({attempts:o.attempts.map(({id:t})=>new m3({attemptId:t,changes:e.get(t)??[]}))}),d=yield*Rk(r),f=o.attempts.filter(({id:e})=>!d.has(e));if(f.length===0)return yield*A(`Served the Run's GitHub changes from the Attempt cache`,{runId:a,attempts:o.attempts.length}),u(d);let p=yield*e.forItems([o.itemKey]),m=(yield*Ph([...new Map([...p.flatMap(({attempts:e})=>e),...o.attempts].map(e=>[e.id,e])).values()],i)).flatMap(Mr),h=yield*op,g=new Map,_=[],v=f.flatMap(e=>{let t=m.find(({attemptId:t})=>t===e.id);return t===void 0?(g.set(e.id,[]),_.push(e.id),[]):[t]});if(v.length>0){let e=Math.min(...v.map(({startedAt:e})=>K_(e))),r=R_(e-e%1e3),[i,s]=yield*Nh([t.appChanges(l,c,r),n.onItem(o.itemKey,q_(r,{milliseconds:y3}))],{concurrency:`unbounded`}),{moves:u,rest:d}=S3(s,i),{attributed:f,ambiguous:p}=b3(m,d);p.length>0&&(yield*k(`Left out GitHub changes that overlapping Attempts on the Item could each have made`,{runId:a,repository:l,item:c,changes:p.length,at:p.map(({at:e})=>J_(e)).join(`, `)}));for(let e of v){let t=[...(f.get(e.attemptId)??[]).map(e=>({at:K_(e.at),view:w3(e)})),...u.flatMap(t=>{let n=K_(t.at);return K_(e.startedAt)<=n&&vr(e.endedAt,{onNone:()=>!0,onSome:e=>n<=K_(e)})?[{at:n,view:T3(t)}]:[]})];g.set(e.attemptId,t.sort((e,t)=>e.at-t.at).map(({view:e})=>e)),S(e.endedAt)&&h-K_(e.endedAt.value)>=_3&&_.push(e.attemptId)}yield*k(`Read the App's GitHub changes on a Run's Item`,{runId:a,repository:l,item:c,since:J_(r),appChanges:i.length,boardMoves:s.length,boardMoveChanges:i.length-d.length,placed:v.reduce((e,{attemptId:t})=>e+(f.get(t)?.length??0),0),cachedAttempts:_.length})}let ee=yield*Hk(r,e=>{let t=new Map(e);for(let e of _)t.set(e,g.get(e)??[]);for(let e of[...t.keys()].slice(0,Math.max(0,t.size-g3)))t.delete(e);return t});return u(new Map([...ee,...g]))})}});(class e extends Rr()(`@usine/orchestrator/RunGitHubChanges`){static layer=Xf(e,E3)});var D3=500,O3=class extends V(`@usine/orchestrator/TaskItemView`)({...jH.fields,labels:N(fz),conflicting:lT}){},k3=class extends V(`@usine/orchestrator/TaskLaneView`)({id:kH,name:yz}){},A3=class extends V(`@usine/orchestrator/TaskCommentView`)({runId:HA,kind:bN,url:j,postedAt:I(j),attemptEndedAt:I(j)}){},j3=class extends V(`@usine/orchestrator/TaskView`)({repository:Xk,number:rI,title:j,current:nI,lane:k3,needsYou:lT,items:yT(O3),runs:N(CH),comments:N(A3)}){},M3=vr({onNone:()=>null,onSome:J_}),N3=e=>{let t=(t,n)=>new A3({runId:e.run.id,kind:t.kind,url:t.url.toString(),postedAt:M3(t.at),attemptEndedAt:M3(n)}),n=ra(e.attempts,e=>Ir(e.outcome,({_tag:e})=>e===`Succeeded`)).pipe(kr(({endedAt:e})=>e)),r=vr(e.step.result,{onNone:()=>[],onSome:({facts:e})=>e.flatMap(e=>e._tag===`Comment`?[t(e,n)]:[])}),i=e.attempts.flatMap(e=>e.comments.map(n=>t(n,e.endedAt))),a=({postedAt:e,attemptEndedAt:t})=>e??t??``;return va([...r,...i].sort((e,t)=>a(t).localeCompare(a(e))),(e,t)=>e.url===t.url)},P3=T(function*(){let e=yield*aH,t=yield*o0,n=yield*e0,r=yield*yU,i=yield*p1;return{read:O(`TaskReader.read`)(function*(a,o,s){yield*D({repository:o,item:s});let c=a.config.repos.find(({name:e})=>tA(e)===tA(o));if(c===void 0)return yield*k(`Task read refused; the repository is not a registered Project`,{repository:o,item:s}),yield*new VH({repository:o});let[l,u,d,f]=yield*Nh([n.list(c.name,{limit:D3}),r.get(c.name),t.states,i.asks()],{concurrency:`unbounded`}),p=yield*e.forItems(l.map(({itemKey:e})=>e)),m=yield*D4(e,p),h=new Set(d.filter(e=>e.paused).map(e=>e.loop)),g=T4(a.config.workers),_=(yield*G4(c,vr(u,{onNone:()=>[],onSome:({labels:e})=>e.map(({name:e})=>e)}),l,p.map(e=>O4(e,h,g)),f.map(({itemKey:e})=>e),new Map,new Map,m)).lanes.flatMap(e=>e.items.map(t=>({lane:e,task:t}))).find(({task:e})=>e.items.some(e=>e.number===s));if(_===void 0)return yield*k(`Task read found no Task; the Item is not among the Project's newest Board Items`,{repository:c.name,item:s,window:D3}),yield*new HH({repository:c.name,item:s});let{lane:v,task:ee}=_,te=new Set(ee.items.map(({itemKey:e})=>e)),ne=yield*Ph(l.filter(({itemKey:e})=>te.has(e)),e=>i2(e).pipe($h)),re=new Map;for(let e of ne){if(Di(e)){yield*t_(`Task Item could not be projected; the other Items are shown`,{repository:c.name,itemKey:e.failure.itemKey,message:e.failure.message});continue}let{itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}=e.success;re.set(t,new O3({itemKey:t,kind:n,number:r,title:i,url:a,state:o,labels:s,conflicting:l}))}let[ie,...ae]=ee.items.flatMap(({itemKey:e})=>{let t=re.get(e);return t===void 0?[]:[t]});if(ie===void 0)return yield*new HH({repository:c.name,item:s});let oe=new Set(ee.runs.map(({id:e})=>e)),se=p.filter(({run:e})=>oe.has(e.id)).sort((e,t)=>K_(t.run.openedAt)-K_(e.run.openedAt)||t.run.id.localeCompare(e.run.id)).flatMap(N3),ce=new j3({repository:c.name,number:ie.number,title:ee.title,current:ee.itemKey,lane:new k3({id:v.id,name:v.name}),needsYou:ee.needsYou,items:[ie,...ae],runs:[...ee.runs].reverse(),comments:se});return yield*A(`Read a Task`,{repository:c.name,item:s,origin:ce.number,lane:v.name,items:ce.items.length,runs:ce.runs.length,comments:se.length}),ce})}});(class e extends Rr()(`@usine/orchestrator/TaskReader`){static layer=Xf(e,P3)});var F3=F([`binary`,`version`,`login`]),I3=class extends NE(`HarnessUnavailableError`)(`HarnessUnavailableError`,{harness:lN,capability:F3,message:z}){};P([class extends H(`HarnessReady`)(`HarnessReady`,{harness:lN}){},I3]),Vw(I3),fr(cr,({harness:e})=>e);var L3=class e extends Rr()(`@usine/orchestrator/WorkerStatus`){static idle=Jf(e)({slots:w([]),queue:w([]),preflights:w([]),unavailable:w([]),machines:w([]),provisioning:w([])})},R3=class extends V(`@usine/orchestrator/LoopSelectorView`)({repos:I(N(Xk)),tags:I(N(nJ))}){},z3=class extends V(`@usine/orchestrator/LoopFileView`)({name:aA,file:tU,stream:F([`issue`,`pr`,`schedule`]),condition:ZH,cron:I(VJ),timeZone:I(HJ),selector:I(R3),repositories:N(Xk),approval:sA,maxCycles:iI,permissions:lA,priority:I(XJ),step:wN,agent:fN,prompt:YJ,paused:lT,undeclaredLabels:N(fz)}){},B3=class extends V(`@usine/orchestrator/QuarantinedLoopView`)({name:z,file:tU,error:rU}){},V3=class extends V(`@usine/orchestrator/AgentFileView`)({name:fN,file:tU,harness:lN,model:cN,effort:uN,parentModel:I(cN),parentEffort:I(uN),resolvedParentModel:I(cN),resolvedParentEffort:uN,persona:pN,loops:N(aA)}){},H3=class extends V(`@usine/orchestrator/InvalidAgentView`)({name:z,file:tU,error:rU}){},U3=class extends V(`@usine/orchestrator/GatewayView`)({domain:FN,destination:jN,adminPort:IN,adminTokenEnv:z,llmProviders:N(LN)}){},W3=class extends V(`@usine/orchestrator/WorkerSlotsView`)({capacity:R,leased:R}){},G3=class extends H(`@usine/orchestrator/PassedCheckView`)(`Passed`,{checkedAt:j}){},K3=class extends H(`@usine/orchestrator/DegradedCheckView`)(`Degraded`,{checkedAt:j,message:j}){},q3=class extends H(`@usine/orchestrator/DeferredCheckView`)(`Deferred`,{checkedAt:j,message:j}){},J3=class extends H(`@usine/orchestrator/FailedCheckView`)(`Failed`,{checkedAt:j,capability:I(Jz),message:j}){},Y3=P([G3,K3,q3,J3]),X3=class extends V(`@usine/orchestrator/HarnessPreflightView`)({harness:lN,check:Y3}){},Z3=class extends V(`@usine/orchestrator/ContainerView`)({image:I(zN),cpus:I(VN),memoryMib:I(HN),pids:I(UN)}){},Q3=class extends V(`@usine/orchestrator/WorkerConfigurationView`)({name:EN,kind:DN,maxConcurrentAttempts:R,destination:I(jN),port:I(MN),identityFile:I(NN),root:I(PN),gateway:I(U3),container:I(Z3),containerLimits:I(WN).pipe(TT(w(null))),provisioner:I(lB).pipe(TT(w(null))),machines:N(aB).pipe(TT(w([]))),provisioning:I(oB).pipe(TT(w(null))),slots:I(W3),prerequisites:I(Y3),harnesses:N(X3)}){},$3=class extends V(`@usine/orchestrator/RemovedWorkerView`)({name:EN,running:R}){},e6=class extends V(`@usine/orchestrator/LabelStateView`)({name:fz,onGitHub:I(lT),color:I(j),description:I(j),declared:lT,failure:I(Hq)}){},t6=class extends H(`@usine/orchestrator/LabelLaneSourceView`)(`Label`,{label:e6}){},n6=class extends H(`@usine/orchestrator/StateLaneSourceView`)(`State`,{state:bz}){},r6=P([t6,n6]),i6=class extends V(`@usine/orchestrator/LaneConfigurationView`)({name:yz,sources:N(r6)}){},a6=class extends V(`@usine/orchestrator/RepositoryConfigurationView`)({name:Xk,tags:N(nJ),lanes:N(i6),declaredLabels:N(e6),loops:N(aA)}){},o6=class extends V(`@usine/orchestrator/SettingsView`)({pollInterval:R,maxChildren:R,maxAttemptMinutes:I(R),maxAttemptTokens:I(R),parentModel:I(cN),parentEffort:I(uN),operator:I(aN),webhooks:F([`off`,`deliveries`,`endpoint`]),webhooksPublicUrl:I(j),tracing:I(M({otlpUrl:j,serviceName:j}))}){},s6=class extends V(`@usine/orchestrator/ConfigurationView`)({labels:N(gz),loops:N(z3),quarantinedLoops:N(B3),agents:N(V3),invalidAgents:N(H3),workers:N(Q3),removedWorkers:N($3),repositories:N(a6),settings:o6}){},c6=e=>{let t=e.slice(e.lastIndexOf(`/`)+1).replace(/\.md$/u,``);return t===``?e:t},l6=e=>kk(e,{Passed:({checkedAt:e})=>new G3({checkedAt:J_(e)}),Degraded:({checkedAt:e,message:t})=>new K3({checkedAt:J_(e),message:t}),Deferred:({checkedAt:e,message:t})=>new q3({checkedAt:J_(e),message:t}),Failed:({checkedAt:e,capability:t,message:n})=>new J3({checkedAt:J_(e),capability:C(t),message:n})}),u6=e=>e.kind===`ssh`?{destination:C(e.destination),provisioner:fB(e),port:C(e.port),identityFile:C(e.identityFile),root:e.root,gateway:vr(e.gateway,{onNone:()=>null,onSome:e=>new U3({domain:e.domain,destination:e.destination,adminPort:e.adminPort,adminTokenEnv:e.adminTokenEnv,llmProviders:e.llmProviders})}),container:new Z3({image:C(e.container.image),cpus:C(e.container.cpus),memoryMib:C(e.container.memoryMib),pids:C(e.container.pids)})}:{destination:null,provisioner:null,port:null,identityFile:null,root:null,gateway:null,container:null},d6=T(function*(){let e=yield*o0,t=yield*yU,n=yield*B2,r=yield*L3,i=O(`OperatorConfiguration.repository`)(function*(e,n,r){let i=Or(yield*t.get(n.name),({labels:e})=>new Map(e.map(e=>[pz(e.name),e]))),a=new Map(e.config.labels.map(e=>[pz(e.name),e])),o=e=>{let t=pz(e),o=kr(i,e=>Sr(e.get(t))),s=a.get(t);return new e6({name:e,onGitHub:vr(i,{onNone:()=>null,onSome:()=>S(o)}),color:C(br(kr(o,({color:e})=>e),()=>kr(Sr(s),({color:e})=>e))),description:C(br(kr(o,({description:e})=>e),()=>kr(Sr(s),({description:e})=>e))),declared:s!==void 0,failure:r.find(e=>e.repository===n.name&&pz(e.label)===t)??null})};return new a6({name:n.name,tags:n.tags,lanes:n.lanes.map(e=>new i6({name:e.name,sources:e.sources.map(e=>`label`in e?new t6({label:o(e.label)}):new n6({state:e.state}))})),declaredLabels:e.config.labels.map(({name:e})=>o(e)),loops:e.loops.filter(e=>BJ(e.selector,n)).map(({name:e})=>e)})});return{view:O(`OperatorConfiguration.view`)(function*(t){let{config:a}=t,[o,s,c,l,u,d]=yield*Nh([e.states,n.latest,r.slots,r.preflights,r.machines,r.provisioning],{concurrency:`unbounded`}),f=new Set(o.filter(e=>e.paused).map(e=>e.loop)),p=vr(s,{onNone:()=>[],onSome:({preflightFindings:e})=>e}),m=yield*Ph(a.repos,e=>i(t,e,p),{concurrency:4}),h=e=>t.warnings.flatMap(t=>t._tag===`UndeclaredTriggerLabelWarning`&&t.loop===e?[t.label]:[]),g=t.loops.map(e=>new z3({name:e.name,file:tU.make(`loops/${e.name}.md`),stream:e.trigger.on,condition:e.trigger.if,cron:e.trigger.on===`schedule`?e.trigger.cron:null,timeZone:e.trigger.on===`schedule`?e.trigger.tz:null,selector:vr(e.selector,{onNone:()=>null,onSome:({repos:e,tags:t})=>new R3({repos:C(e),tags:C(t)})}),repositories:a.repos.filter(t=>BJ(e.selector,t)).map(({name:e})=>e),approval:e.approval,maxCycles:e.maxCycles,permissions:e.permissions,priority:C(e.priority),step:e.step,agent:e.agent,prompt:e.body,paused:f.has(e.name),undeclaredLabels:h(e.name)})),_=t.agents.map(e=>new V3({name:e.name,file:tU.make(`agents/${e.name}.md`),harness:e.harness,model:e.model,effort:e.effort,parentModel:C(e.parentModel),parentEffort:C(e.parentEffort),resolvedParentModel:C(hN(e.agent,a.settings.parentModel)),resolvedParentEffort:gN(e.agent,a.settings.parentEffort),persona:e.persona,loops:t.loops.filter(({agent:t})=>t===e.name).map(({name:e})=>e)})),v=new Map(c.map(e=>[e.worker,e])),ee=new Map(l.map(e=>[e.worker,e])),te=new Set(a.workers.map(({name:e})=>e)),ne=a.workers.map(e=>{let t=v.get(e.name),n=ee.get(e.name);return new Q3({name:e.name,kind:e.kind,maxConcurrentAttempts:e.maxConcurrentAttempts,...u6(e),slots:t===void 0?null:new W3({capacity:t.capacity,leased:t.leased}),prerequisites:n===void 0?null:C(Or(n.prerequisites,l6)),harnesses:(n?.harnesses??[]).map(({harness:e,check:t})=>new X3({harness:e,check:l6(t)})),containerLimits:n===void 0?null:C(n.containerLimits),machines:u.filter(t=>t.worker===e.name).map(uB),provisioning:C(Or(Sr(d.find(t=>t.worker===e.name)),dB))})}),{settings:re,webhooks:ie,tracing:ae}=a,oe=new s6({labels:t.config.labels,loops:g,quarantinedLoops:t.quarantinedLoops.map(({file:e,error:t})=>new B3({name:c6(e),file:e,error:t})),agents:_,invalidAgents:t.invalidAgents.map(({file:e,error:t})=>new H3({name:c6(e),file:e,error:t})),workers:ne,removedWorkers:c.filter(({worker:e,leased:t})=>!te.has(e)&&t>0).map(({worker:e,leased:t})=>new $3({name:e,running:t})),repositories:m,settings:new o6({pollInterval:re.pollInterval,maxChildren:re.maxChildren,maxAttemptMinutes:C(re.maxAttemptMinutes),maxAttemptTokens:C(re.maxAttemptTokens),parentModel:C(re.parentModel),parentEffort:C(re.parentEffort),operator:C(a.operator),webhooks:ie.mode,webhooksPublicUrl:ie.mode===`endpoint`?ie.publicUrl.href:null,tracing:vr(ae,{onNone:()=>null,onSome:({otlpUrl:e,serviceName:t})=>({otlpUrl:e.href,serviceName:t})})})});return yield*A(`Read the configuration view`,{loops:g.length,quarantinedLoops:oe.quarantinedLoops.length,agents:_.length,invalidAgents:oe.invalidAgents.length,workers:ne.length,runningWorkers:c.length,repositories:m.length}),oe})}});(class e extends Rr()(`@usine/orchestrator/OperatorConfiguration`){static layer=Xf(e,d6)});var f6=200,p6=10,m6=100,h6=500,g6=class extends H(`@usine/orchestrator/WorkerSilentView`)(`WorkerSilent`,{worker:EN,lastAnsweredAt:j}){},_6=class extends H(`@usine/orchestrator/ProviderRetryingView`)(`ProviderRetrying`,{agent:fN,message:z,retries:FP,since:j}){},v6=P([g6,_6]),y6=class extends V(`@usine/orchestrator/RunningAttemptView`)({run:CH,attempt:Kz,item:I(jH),lastActivityAt:I(j),warnings:N(v6)}){},b6=class extends H(`@usine/orchestrator/SuppressedForOperatorView`)(`SuppressedForOperator`,{run:CH}){},x6=class extends H(`@usine/orchestrator/ClosedUnchangedView`)(`ClosedUnchanged`,{run:CH}){},S6=class extends H(`@usine/orchestrator/RunFailedView`)(`RunFailed`,{run:CH}){},C6=class extends H(`@usine/orchestrator/LoopPausedView`)(`LoopPaused`,{}){},w6=class extends H(`@usine/orchestrator/CycleBudgetUsedUpView`)(`CycleBudgetUsedUp`,{ask:uI}){},T6=class extends H(`@usine/orchestrator/AwaitingApprovalView`)(`AwaitingApproval`,{run:CH}){},E6=class extends H(`@usine/orchestrator/QueuedForWorkerView`)(`QueuedForWorker`,{run:CH,ahead:I(R.check(HT(0))),creating:I(aB).pipe(TT(w(null)))}){},D6=class extends H(`@usine/orchestrator/WaitingForStopView`)(`WaitingForStop`,{run:CH,stop:DH}){},O6=class extends H(`@usine/orchestrator/AwaitingPollView`)(`AwaitingPoll`,{}){},k6=P([T6,b6,w6,S6,x6,C6,D6,E6,O6]),A6=class extends V(`@usine/orchestrator/StalledItemView`)({repository:Xk,loop:aA,item:jH,reason:k6}){},j6=class extends V(`@usine/orchestrator/ClosedRunView`)({run:CH,item:I(jH),closedAt:j}){},M6=class extends V(`@usine/orchestrator/WorkerView`)({name:EN,slots:W3,preflight:I(Y3),machines:N(aB).pipe(TT(w([]))),provisioning:I(oB).pipe(TT(w(null)))}){},N6=class extends V(`@usine/orchestrator/RepositoryPollView`)({repository:Xk,polledAt:I(j)}){},P6=class extends V(`@usine/orchestrator/DeskView`)({running:N(y6),notMoving:N(A6),lastOutcomes:N(j6),workers:N(M6),polls:N(N6)}){},F6=({runs:e,sighting:t,paused:n,ask:r,ahead:i,creating:a,stop:o})=>{let s=e.find(({state:e})=>AA.some(t=>t===e));if(s!==void 0){let e=s.attempts.at(-1)?.outcome===null;if(S(o)&&s.state!==`Waiting`&&!e)return b(new D6({run:s,stop:o.value}));switch(s.state){case`Running`:return y();case`Waiting`:return b(new T6({run:s}));default:return b(new E6({run:s,ahead:i.get(s.id)??null,creating:a.get(s.id)??null}))}}if(n)return b(new C6);let c=t=>Sr(e.find(({id:e})=>e===t)),l=kr(kr(t,({suppressedBy:e})=>e),c);if(S(l))return b(new b6({run:l.value}));if(S(r))return b(new w6({ask:r.value}));let u=kr(kr(t,({run:e})=>e),c);return S(u)?b(u.value.state===`Failed`?new S6({run:u.value}):new x6({run:u.value})):b(new O6)},I6=[`AwaitingApproval`,`SuppressedForOperator`,`CycleBudgetUsedUp`,`RunFailed`,`ClosedUnchanged`,`LoopPaused`,`WaitingForStop`,`QueuedForWorker`,`AwaitingPoll`],L6=dr([fr(lr,({reason:e})=>I6.indexOf(e._tag)),fr(cr,({repository:e})=>e),fr(ur(lr),({item:e})=>e.number),fr(cr,({loop:e})=>e)]),R6=({direction:e,envelope:t})=>{let n=t.payload;return e===`outbound`&&n._tag!==`WorkerUnresponsive`&&n._tag!==`WorkerResponsive`&&(n._tag!==`SessionEvent`||n.event._tag!==`PoolRateLimitsUpdated`&&n.event._tag!==`ProviderRetrying`)},z6=e=>{let t=null,n=new Map,r=null;for(let i of e){R6(i)&&(r=i);let e=i.envelope.payload;if(e._tag===`WorkerUnresponsive`)t=new g6({worker:e.worker,lastAnsweredAt:J_(e.lastAnsweredAt)});else if(e._tag===`WorkerResponsive`)t=null;else if(e._tag===`SessionEvent`){let t=e.event;t._tag===`ProviderRetrying`?n.set(t.session.id,new _6({agent:t.session.agent,message:t.message,retries:t.retries,since:n.get(t.session.id)?.since??J_(i.receivedAt)})):(t._tag===`ProviderRecovered`||t._tag===`SessionIdle`||t._tag===`SessionFinished`)&&n.delete(t.session.id)}}return{lastActivityAt:r===null?null:J_(r.receivedAt),warnings:[...t===null?[]:[t],...n.values()]}},B6=e=>K_(e.checkedAt),V6=e=>{let t=[...Mr(e.prerequisites),...e.harnesses.map(({check:e})=>e)],n=t.filter(({_tag:e})=>e===`Failed`),r=t.filter(({_tag:e})=>e===`Degraded`);return Sr((n.length>0?n:r.length>0?r:t).reduce((e,t)=>e===void 0||B6(t)>B6(e)?t:e,void 0))},H6=e=>{let t=e.attempts.at(-1);return e.closedAt??t?.endedAt??t?.startedAt??e.openedAt},U6=({run:e,attempts:t})=>t.length===0&&e.state._tag===`Canceled`&&e.state.reason._tag!==`OperatorCanceled`,W6=T(function*(){let e=yield*aH,t=yield*o0,n=yield*p1,r=yield*e0,i=yield*B2,a=yield*K4,o=yield*L3,s=yield*x0,c=O(`Operator.desk.recentActivity`)(function*(t){yield*D({attemptId:t.id});let[n,r]=yield*Nh([e.transcript(new TB({attemptId:t.id,before:y(),limit:f6})),e.transcript(new SB({attemptId:t.id}))],{concurrency:`unbounded`});return z6([...n,...r])});return{desk:O(`Operator.desk`)(function*(l){let[u,d,f,p,m,h,g,_,v,ee,te]=yield*Nh([e.list({closedLimit:0}),e.closed({limit:m6}),t.states,n.asks(),o.slots,o.queue,o.preflights,i.latest,s.list,o.machines,o.provisioning],{concurrency:`unbounded`}),ne=ee.map(uB),re=new Map(ne.flatMap(e=>e.state===`creating`&&e.runId!==null?[[e.runId,e]]:[])),ie=new Map(h.map(({runId:e,ahead:t})=>[e,t])),ae=new Set(f.filter(e=>e.paused).map(e=>e.loop)),oe=T4(l.config.workers),se=yield*Ph(l.config.repos,e=>T(function*(){let t=yield*r.list(e.name,{limit:h6});return{repository:e,items:t,matches:yield*a.matching(l,e,t)}}),{concurrency:4}),ce=new Map;for(let{items:e}of se)for(let t of e){let e=yield*$h(i2(t));if(Di(e))continue;let{itemKey:n,kind:r,number:i,title:a,url:o,state:s}=e.success;ce.set(n,new jH({itemKey:n,kind:r,number:i,title:a,url:o,state:s}))}let le=se.flatMap(({matches:e})=>e),ue=[...new Set(le.map(({item:e})=>e.itemKey))],[de,fe]=yield*Nh([e.forItems(ue),e.sightings(ue)],{concurrency:`unbounded`}),pe=new Map([...u,...de].map(e=>[e.run.id,O4(e,ae,oe)])),me=[...pe.values()].sort((e,t)=>t.openedAt.localeCompare(e.openedAt)||t.id.localeCompare(e.id)),he=e=>kr(Sr(v.find(t=>t.itemKey===e)),e=>Or(Sr(pe.get(e.runId)?.attempts.find(({id:t})=>t===e.attemptId)),({number:t})=>new DH({runId:e.runId,attemptNumber:t,worker:e.worker}))),ge=[];for(let{loop:e,item:t}of le){let n=ce.get(t.itemKey);if(n===void 0)continue;let r=F6({runs:me.filter(n=>n.loop===e.name&&n.itemKey===t.itemKey),sighting:Sr(fe.find(n=>n.loop===e.name&&n.itemKey===t.itemKey)),paused:ae.has(e.name),ask:Sr(p.find(({itemKey:e})=>e===t.itemKey)),ahead:ie,creating:re,stop:he(t.itemKey)});x(r)||(yield*A(`Matched Item is not moving`,{repository:t.repository,loop:e.name,item:t.number,reason:r.value._tag,...kk(r.value,{AwaitingApproval:({run:e})=>({runId:e.id}),SuppressedForOperator:({run:e})=>({runId:e.id}),CycleBudgetUsedUp:({ask:e})=>({askId:e.id}),RunFailed:({run:e})=>({runId:e.id}),ClosedUnchanged:({run:e})=>({runId:e.id,state:e.state}),LoopPaused:()=>({}),WaitingForStop:({run:e,stop:t})=>({runId:e.id,unstoppedRunId:t.runId,attemptNumber:t.attemptNumber,worker:t.worker}),QueuedForWorker:({run:e,ahead:t})=>({runId:e.id,ahead:t}),AwaitingPoll:()=>({})})}),ge.push(new A6({repository:t.repository,loop:e.name,item:n,reason:r.value})))}let _e=yield*Ph(me.flatMap(e=>{let t=e.attempts.at(-1);return e.state===`Running`&&t!==void 0&&t.outcome===null?[{run:e,attempt:t}]:[]}),({run:e,attempt:t})=>ng(c(t),n=>new y6({run:e,attempt:t,item:ce.get(e.itemKey)??null,...n})),{concurrency:4}),ve=d.filter(e=>!U6(e)).map(e=>{let t=O4(e,ae,oe);return new j6({run:t,item:ce.get(t.itemKey)??null,closedAt:H6(t)})}).sort((e,t)=>t.closedAt.localeCompare(e.closedAt)).slice(0,p6),ye=new Map(m.map(e=>[e.worker,e])),be=new Map(g.map(e=>[e.worker,e])),xe=new Set(l.config.workers.map(({name:e})=>e)),Se=[...l.config.workers.map(({name:e})=>e),...m.map(({worker:e})=>e).filter(e=>!xe.has(e))].map(e=>{let t=ye.get(e),n=be.get(e);return new M6({name:e,slots:new W3({capacity:t?.capacity??l.config.workers.find(t=>t.name===e)?.maxConcurrentAttempts??0,leased:t?.leased??0}),preflight:C(Or(kr(Sr(n),V6),l6)),machines:ne.filter(t=>t.worker===e),provisioning:C(Or(Sr(te.find(t=>t.worker===e)),dB))})}),Ce=vr(_,{onNone:()=>[],onSome:({repositoryPolls:e})=>e}),we=l.config.repos.map(({name:e})=>{let t=Ce.find(({repository:t})=>tA(t)===tA(e));return new N6({repository:e,polledAt:t===void 0?null:J_(t.completedAt)})});return yield*A(`Built the operator desk`,{running:_e.length,matches:le.length,notMoving:ge.length,lastOutcomes:ve.length,workers:Se.length}),new P6({running:_e,notMoving:[...ge].sort(L6),lastOutcomes:ve,workers:Se,polls:we})})}});(class e extends Rr()(`@usine/orchestrator/OperatorDesk`){static layer=Xf(e,W6).pipe(rp(K4.layer))});var G6=R.check(HT(0)),K6=R.check(HT(1)),q6=R.check(HT(0)),J6=FT.check(UT({minimum:0,maximum:1})),Y6=j.check(PT(/^\d{4}-\d{2}-\d{2}$/u,{message:`Expected a UTC day as YYYY-MM-DD`})),X6=F([`7d`,`30d`,`all`]),Z6=F([`day`,`week`]),Q6=class extends V(`@usine/orchestrator/TaskDoneView`)({repository:Xk,number:rI,mergedAt:j,durationMillis:q6}){},$6=class extends V(`@usine/orchestrator/TaskPeriodView`)({start:Y6,tasks:G6,medianMillis:I(q6),firstTimeRight:G6,operatorActions:G6}){},e8=class extends V(`@usine/orchestrator/LoopShareView`)({loop:aA,share:J6}){},t8=class extends V(`@usine/orchestrator/LoopRunTimeView`)({loop:aA,runs:K6,medianMillis:q6}){},n8=class extends V(`@usine/orchestrator/TaskTimeView`)({tasks:K6,loops:N(e8),waiting:J6,runs:N(t8)}){},r8=class extends V(`@usine/orchestrator/TaskCostView`)({tasks:K6,medianUsd:TP,estimate:lT}){},i8=class extends V(`@usine/orchestrator/TaskTokensView`)({tasks:K6,medianTokens:dP,loops:N(e8),cost:I(r8)}){},a8=class extends V(`@usine/orchestrator/UntimedTasksView`)({tasks:K6,before:Y6}){},o8=class extends V(`@usine/orchestrator/StatisticsView`)({window:X6,from:j,to:j,bucket:Z6,loops:N(aA),tasks:N(Q6),medianMillis:I(q6),periods:N($6),firstTimeRight:G6,operatorActions:G6,time:I(n8),tokens:I(i8),untimed:I(a8),unmetered:G6}){},s8=class extends V(`@usine/orchestrator/DurationSummaryView`)({count:K6,medianMillis:q6}){},c8=class extends V(`@usine/orchestrator/OutcomeCountsView`)({succeeded:G6,failed:G6,canceled:G6}){},l8=class extends V(`@usine/orchestrator/PoolTokensView`)({pool:kP,tokens:dP}){},u8=class extends V(`@usine/orchestrator/CostSummaryView`)({usd:TP,meanUsd:TP,estimate:lT,priced:K6}){},d8=class extends V(`@usine/orchestrator/UsageSummaryView`)({measured:G6,tokens:dP,meanTokens:I(dP),pools:N(l8),cost:I(u8)}){},f8={outcomes:c8,time:I(s8),usage:d8},p8=class extends V(`@usine/orchestrator/LoopStatisticsView`)({loop:aA,...f8}){},m8=class extends V(`@usine/orchestrator/AgentStatisticsView`)({agent:fN,...f8}){},h8=class extends V(`@usine/orchestrator/BrainStatisticsView`)({brain:dN,...f8}){},g8=class extends V(`@usine/orchestrator/ThroughputPeriodView`)({start:Y6,...c8.fields}){},_8=class extends V(`@usine/orchestrator/WorkerQueueWaitView`)({worker:EN,wait:s8}){},v8=class extends V(`@usine/orchestrator/AttemptCountView`)({attempts:K6,runs:G6}){},y8=class extends V(`@usine/orchestrator/WorkerUtilizationView`)({worker:EN,slots:K6,occupiedMillis:q6,share:J6}){},b8=class extends V(`@usine/orchestrator/NeedsAttentionPeriodView`)({start:Y6,approvals:G6,failures:G6}){},x8=class extends V(`@usine/orchestrator/NeedsAttentionView`)({approvals:G6,failures:G6,periods:N(b8),approvalWait:I(s8),retryWait:I(s8),resolutionWait:I(s8),failureWait:I(s8)}){},S8=class extends V(`@usine/orchestrator/RunStatisticsView`)({window:X6,from:j,to:j,bucket:Z6,runs:c8,runTime:I(s8),attemptTime:I(s8),unmeasuredAttempts:G6,throughput:N(g8),loops:N(p8),agents:N(m8),brains:N(h8),queueWait:N(_8),attemptsPerRun:N(v8),utilization:N(y8),needsAttention:x8}){},C8=(e,t)=>({agentNames:new Set(t.map(({name:e})=>e)),registryTags:new Set(e.repos.flatMap(({tags:e})=>e)),repoNames:new Set(e.repos.map(({name:e})=>tA(e)))}),w8=e=>e.map(e=>`"${e}"`).join(`, `),T8=(e,t,n)=>{let r=[],i=()=>r.length===0?y():b(new rU({file:e,stage:`reference`,expression:y(),message:r.map(({message:e})=>e).join(`
311
+ `),details:r}));if(n.agentNames.has(t.agent)||r.push({path:[`agent`],message:`Unknown agent "${t.agent}": agents/${t.agent}.md is missing or invalid. Fix the agent file, or set agent to an existing agent.`}),x(t.selector))return i();if(S(t.selector.value.repos)){let e=t.selector.value.repos.value.filter(e=>!n.repoNames.has(tA(e)));e.length>0&&r.push({path:[`selector`,`repos`],message:`Unknown repositories in selector.repos: ${w8(e)}. Add them under repos in usine.yaml.`})}if(S(t.selector.value.tags)){let e=t.selector.value.tags.value.filter(e=>!n.registryTags.has(e));e.length>0&&r.push({path:[`selector`,`tags`],message:`Unknown tags in selector.tags: ${w8(e)}. Add them to a repository's tags in usine.yaml.`})}return i()},E8=class extends V(`@usine/config/LoadedInstance`)(M({config:RJ,agents:N(Jq),invalidAgents:N(Yq),loops:N(ZJ),quarantinedLoops:N(QJ),warnings:N(nY)}).check(NT(({agents:e,config:t,loops:n})=>{let r=C8(t,e);return n.every(e=>x(T8($J(e.name),e,r)))},{message:`Expected every loop to reference only loaded agents and registry entries`}))){},D8=R.check(HT(0)).pipe(L(`ConfigurationRevisionNumber`)),O8=F([`settings`,`worker`,`repository`,`label`,`loop`,`agent`]),k8=z.pipe(L(`ConfigurationEntityId`)),A8=class extends V(`@usine/config/ConfigurationEntityKey`)({kind:O8,identifier:k8}){get key(){return`${this.kind}:${this.identifier}`}},j8=class extends V(`@usine/config/ConfigurationEntity`)({key:A8,value:IE}){},M8=class extends V(`@usine/config/ConfigurationChange`)({key:A8,before:B(IE),after:B(IE),position:$w(R.check(HT(0)))}){};(class e extends V(`@usine/config/Configuration`)(M({number:D8,instance:B(E8)}).check(NT(({number:e,instance:t})=>e===0===x(t),{message:`Only an uninitialized configuration has revision zero`}))){get actor(){return kr(this.instance,({config:e})=>e.operator)}static empty=new e({number:D8.make(0),instance:y()})}),V(`@usine/config/ConfigurationRevision`)({number:D8.check(VT(0)),actor:B(aN),time:_E,message:B(j),changes:N(M8)}),NE(`@usine/config/StaleRevision`)(`StaleRevision`,{expected:D8,actual:D8});var N8=class extends NE(`@usine/config/ConfigurationInvalid`)(`ConfigurationInvalid`,{problems:yT(rU)}){};NE(`@usine/config/ConfigurationStoreError`)(`ConfigurationStoreError`,{operation:j,cause:eE()}),NE(`@usine/config/ConfigurationRevertBlocked`)(`ConfigurationRevertBlocked`,{entities:yT(A8)});var P8=F([`workers`,`webhooks`,`tracing`]),F8=e=>M({added:N(e),removed:N(e),changed:N(e)});V(`@usine/orchestrator/InstanceReload`)({loops:F8(aA),agents:F8(fN),labels:F8(fz),repos:F8(Xk),workers:F8(EN),settingsChanged:lT,operatorChanged:lT,quarantinedLoops:N(QJ),invalidAgents:N(Yq)});var I8=class extends V(`ConfigurationEntityRequest`)({kind:j,identifier:k8}){},L8=class extends V(`ConfigurationRevisionQuery`)({kind:$w(j),identifier:$w(k8),before:$w(D8),limit:R.check(UT({minimum:1,maximum:100}))}){},R8=class extends V(`ConfigurationWrite`)({expected:D8,message:$w(j)}){},z8=P([M({...R8.fields,value:IE,text:$w(iT),position:$w(R.check(HT(0)))}),M({...R8.fields,text:j,value:$w(iT),position:$w(R.check(HT(0)))})]),B8=class extends V(`ConfigurationEntityView`)({key:A8,value:IE,text:j,number:D8}){},V8=class extends V(`ConfigurationRevisionSummary`)({number:D8,actor:I(aN),time:_E,message:I(j),entities:N(A8)}){},H8=class extends V(`ConfigurationRevisionPage`)({revisions:N(V8),nextBefore:I(D8)}){};NE(`ConfigurationNotFound`)(`ConfigurationNotFound`,{message:j});var U8=class e extends V(`ConfigurationRevisionView`)({...V8.fields,changes:N(M({key:A8,before:I(IE),after:I(IE),position:$w(R)}))}){static fromRevision(t){return new e({...t,actor:C(t.actor),message:C(t.message),entities:t.changes.map(({key:e})=>e),changes:t.changes.map(e=>({...e,before:C(e.before),after:C(e.after)}))})}},W8=class extends V(`@usine/orchestrator/UpgradeRequest`)({timing:$q,version:xE(Qq)}){},G8=class extends V(`@usine/orchestrator/UpgradeView`)({running:j,channel:Xq,mode:Zq,supported:lT,available:I(Qq),phase:F([`idle`,`waiting`,`installing`,`failed`]),message:I(j),outcome:I(tJ)}){},K8=`~effect/http-api/HttpApiSchema/Stream`;function q8(e){let t=typeof e==`string`?gG(e):e;return e=>e.ast.checks!==void 0||p5(e.ast)?e.annotate({httpApiStatus:t}):e.annotateKey({httpApiStatus:t})}var J8=(e=>dT.pipe(q8(e)))(204),Y8=e=>Qw(e)&&pe(e,K8),X8=e=>Y8(e)&&e._tag===`StreamSse`,Z8=e=>Y8(e)&&e._tag===`StreamUint8Array`,Q8=e=>Y8(e)&&e._tag===`StreamNdjson`,$8=`~effect/http-api/HttpApiSchema/Upgrade`,e5=e=>Qw(e)&&pe(e,$8),t5=`~effect/http-api/HttpApiSchema/WithHeaders`,n5=`~effect/http-api/HttpApiSchema/WithHeadersValue`,r5=e=>({[n5]:n5,body:e.body,headers:e.headers}),i5=e=>Qw(e)&&pe(e,`~effect/http-api/HttpApiSchema/WithHeaders`);function a5(e,t,n){return Zw(e.ast,{[t5]:t5,schema:t,headers:n})}function o5(e,t){return e.annotate({"~httpApiEncoding":{_tag:t._tag,contentType:t.contentType??s5(t._tag)}})}function s5(e){switch(e){case`Multipart`:return`multipart/form-data`;case`Json`:return`application/json`;case`FormUrlEncoded`:return`application/x-www-form-urlencoded`;case`Uint8Array`:return`application/octet-stream`;case`Text`:return`text/plain`}}function c5(e){return t=>o5(t,{_tag:`FormUrlEncoded`,...e})}var l5=e=>{if(qb(e)||qb(GS(e)))return!0;let t=e.encoding?.[0].to;return t!==void 0&&qb(t)},u5=dC(`~httpApiEncoding`),d5=dC(`~httpApiWithHeaders`),f5=dC(`httpApiStatus`);function p5(e){let t=uC(e);return t!==void 0&&`httpApiStatus`in t}function m5(e){return p5(e)?f5(e):e.checks===void 0?e.context?.annotations?.httpApiStatus:void 0}var h5={_tag:`Json`,contentType:`application/json`},g5={_tag:`FormUrlEncoded`,contentType:`application/x-www-form-urlencoded`};function _5(e){return u5(e)??h5}function v5(e,t){return u5(e)||(qU(t)?h5:g5)}function y5(e){let t=_5(e);if(t._tag===`Multipart`)throw Error(`Multipart is not supported in response`);return t}function b5(e){return m5(e)??200}function x5(e){return i5(e)?m5(e.ast)??b5(e.schema.ast):b5(e.ast)}function S5(e){return i5(e)&&u5(e.ast)===void 0?y5(e.schema.ast):y5(e.ast)}function C5(e){return m5(e)??500}function w5(e){return i5(e)?m5(e.ast)??C5(e.schema.ast):C5(e.ast)}function T5(e){let t=e.toLowerCase().trim(),n=t.indexOf(`;`);return n===-1?t:t.slice(0,n).trim()}var E5=`~effect/http-api/HttpApiEndpoint`;function D5(e){let t=[];for(let{schemas:n}of e.payload.values())t.push(...n);return t}function O5(e){let t=Array.from(e.success);return Yi(t)?t:[J8]}function k5(e){let t=new Set(e.error),n=e.disableCodecs?i:R5;for(let r of e.middlewares){let e=r;for(let r of e.error)t.add(n(r))}return Array.from(t)}var A5={[E5]:E5,pipe(){return e(this,arguments)},prefix(e){return M5({...j5(this),path:oG(this.path,e)})},middleware(e){return M5({...j5(this),middlewares:new Set([...this.middlewares,e])})},annotate(e,t){return M5({...j5(this),annotations:ai(this.annotations,e,t)})},annotateMerge(e){return M5({...j5(this),annotations:hi(this.annotations,e)})}},j5=e=>({identifier:e.identifier,path:e.path,method:e.method,params:e.params,query:e.query,headers:e.headers,payload:e.payload,success:e.success,error:e.error,annotations:e.annotations,middlewares:e.middlewares,disableCodecs:e.disableCodecs});function M5(e){function t(){}return Object.setPrototypeOf(t,A5),Object.assign(t,e)}var N5=e=>(t,n,r)=>{let a=r?.disableCodecs??!1,o=a?i:FE;return M5({identifier:t,path:n,method:e,params:P5(r?.params,o),query:P5(r?.query,o),headers:P5(r?.headers,o),payload:F5(r?.payload,e,a),success:L5(r?.success,e,r?.payload!==void 0,a),error:z5(r?.error,a),annotations:ni(),middlewares:new Set,disableCodecs:a})};function P5(e,t){if(e!==void 0)return Qw(e)?t(e):t(M(e))}function F5(e,t,n){let r=new Map;if(e===void 0)return r;let a=Array.isArray(e)?e:Qw(e)?[e]:[M(e).pipe(c5())],o=n?i:Y5,s=!1;for(let e of a){if(Y8(e)){if(X8(e))throw Error(`StreamSse is response-only and cannot be used as a payload`);if(!qU(t))throw Error(`${t} endpoints cannot declare a streaming payload`);if(s)throw Error(`Multiple streaming payloads are not supported`);s=!0;let n=T5(e.contentType);if(r.has(n))throw Error(`Cannot combine buffered and streaming payloads for content-type: ${e.contentType}`);r.set(n,{encoding:{_tag:`Stream`,contentType:e.contentType},schemas:[e]});continue}let n=v5(e.ast,t),i=T5(n.contentType),a=r.get(i);if(a){if(a.encoding._tag===`Stream`)throw Error(`Cannot combine buffered and streaming payloads for content-type: ${n.contentType}`);if(a.encoding._tag!==n._tag)throw Error(`Multiple payload encodings for content-type: ${n.contentType}`);if(a.encoding._tag===`Multipart`)throw Error(`Multiple multipart payloads for content-type: ${n.contentType}`);a.schemas.push(o(e,t))}else r.set(i,{encoding:n,schemas:[o(e,t)]})}return r}var I5=`effect/http-api/stream/failure`;function L5(e,t,n,r){if(e===void 0)return new Set;let i=Gi(e);return B5(i,t,n),new Set(r?i:i.map(R5))}var R5=f(e=>Y8(e)||e5(e)?e:i5(e)?a5(e,Y8(e.schema)?e.schema:J5(e.schema,S5(e)),FE(e.headers)):q5(e));function z5(e,t){if(e===void 0)return new Set;let n=Gi(e);for(let e of n){let t=i5(e)?e.schema:e;if(Y8(t))throw Error(`Streaming schemas are not supported in error responses`);if(e5(t))throw Error(`Upgrade schemas are not supported in error responses`)}return H5(n,w5),new Set(t?n:n.map(R5))}function B5(e,t,n){if(e.some(e5)){if(e.length>1)throw Error(`Cannot combine an upgrade with other success responses`);if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare an upgrade`);if(n)throw Error(`Upgrade endpoints cannot declare a payload`);return}let r=!1,i=new Map;for(let n of e){let e=i5(n)?n.schema:n,a=x5(n);if(Y8(e)){if(U5(e,t),r)throw Error(`Multiple streaming success responses are not supported`);r=!0;let n=V5(i,a);if(n.noContent)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);if(n.bufferedContentTypes.has(T5(e.contentType)))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`);i.set(a,{...n,stream:e})}else{let t=V5(i,a),r=l5(e.ast);if(t.stream!==void 0){if(r)throw Error(`Cannot combine no-content and streaming success responses for status: ${a}`);let e=S5(n);if(T5(e.contentType)===T5(t.stream.contentType))throw Error(`Cannot combine buffered and streaming success responses for status ${a} and content-type: ${e.contentType}`)}r||t.bufferedContentTypes.add(T5(S5(n).contentType)),t.noContent=t.noContent||r}}H5(e,x5)}function V5(e,t){let n=e.get(t);return n===void 0&&(n={bufferedContentTypes:new Set,noContent:!1},e.set(t,n)),n}function H5(e,t){let n=new Map;for(let r of e){let e=t(r),i=d5(r.ast),a=i5(r)?r.schema:i?.body??r,o=l5(a.ast)?``:T5(Y8(a)?a.contentType:S5(r).contentType),s=n.get(e);s===void 0&&(s={headerContentType:void 0,plainContentTypes:new Set},n.set(e,s));let c=()=>Error(`Cannot combine a response with headers with another response for status ${e} and content-type: ${o||`<no content>`}`);if(i5(r)||i!==void 0){if(s.headerContentType!==void 0)throw Error(`Cannot declare multiple responses with headers for status ${e}`);if(s.plainContentTypes.has(o))throw c();s.headerContentType=o}else{if(s.headerContentType===o)throw c();s.plainContentTypes.add(o)}}}function U5(e,t){if(t===`HEAD`)throw Error(`HEAD endpoints cannot declare streaming success responses`);if(X8(e)&&W5(e.events.ast))throw Error(`SSE event name is reserved: ${I5}`)}function W5(e){return G5(GS(e),new Set)}function G5(e,t){if(t.has(e))return!1;if(t.add(e),$b(e))return e.types.some(e=>G5(e,t));if(ex(e))return G5(e.thunk(),t);if(!Qb(e))return!1;let n=e.propertySignatures.find(e=>e.name===`event`);return n!==void 0&&K5(n.type,t)}function K5(e,t){if(t.has(e))return!1;t.add(e);let n=GS(e);return n===e?Yb(e)?e.literal===I5:$b(e)?e.types.some(e=>K5(e,t)):ex(e)?K5(e.thunk(),t):!1:K5(n,t)}function q5(e){let t=y5(e.ast),n=d5(e.ast);return n===void 0?J5(e,t):e.annotate({"~httpApiWithHeaders":{...n,bodyCodec:J5(n.body,t),headersCodec:FE(n.headers)}})}function J5(e,t){switch(t._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:return e}}function Y5(e,t){switch(v5(e.ast,t)._tag){case`Json`:return PE(e);case`FormUrlEncoded`:return FE(e);case`Text`:case`Uint8Array`:case`Multipart`:return e}}var X5=N5(`GET`),Z5=N5(`POST`),Q5=N5(`PUT`),$5=N5(`DELETE`),e7=`~effect/http-api/HttpApi`,t7={[e7]:e7,pipe(){return e(this,arguments)},add(...e){let t={...this.groups};for(let n of e)Et(t,n.identifier,n);return r7({...n7(this),groups:t})},addHttpApi(e){let t={...this.groups};for(let n of Object.keys(e.groups)){let r=e.groups[n];Et(t,n,r.annotateMerge(hi(e.annotations,r.annotations)))}return r7({...n7(this),groups:t})},prefix(e){return r7({...n7(this),groups:zi(this.groups,t=>t.prefix(e))})},middleware(e){return r7({...n7(this),groups:zi(this.groups,t=>t.middleware(e))})},annotate(e,t){return r7({...n7(this),annotations:ai(this.annotations,e,t)})},annotateMerge(e){return r7({...n7(this),annotations:hi(this.annotations,e)})}},n7=e=>({identifier:e.identifier,groups:e.groups,annotations:e.annotations}),r7=e=>{function t(){}return Object.setPrototypeOf(t,t7),Object.assign(t,e)},i7=e=>r7({identifier:e,groups:{},annotations:ni()}),a7=(e,t)=>{let n=Object.values(e.groups);for(let r of n){let n=hi(e.annotations,r.annotations);t.onGroup({group:r,mergedAnnotations:n});let i=Object.values(r.endpoints);for(let e of i)(!t.predicate||t.predicate({endpoint:e,group:r}))&&t.onEndpoint({group:r,endpoint:e,middleware:e.middlewares,mergedAnnotations:hi(n,e.annotations),successes:o7(O5(e),x5),errors:o7(k5(e),w5)})}},o7=(e,t)=>{let n=new Map;return e.forEach(r),n;function r(e){let r=i5(e)?e.schema:e;if(Y8(r)||e5(r))return;let i=t(e),a=n.get(i);a===void 0?n.set(i,[e]):a.push(e)}},s7=class extends Rr()(`effect/http-api/HttpApi/ParseOptions`){},c7=class extends Rr()(`effect/http-api/HttpApi/ParamsParseOptions`){},l7=class extends Rr()(`effect/http-api/HttpApi/QueryParseOptions`){},u7=class extends Rr()(`effect/http-api/HttpApi/HeadersParseOptions`){},d7=class extends Rr()(`effect/http-api/HttpApi/PayloadParseOptions`){},f7=class extends Rr()(`effect/http-api/HttpApi/SuccessParseOptions`){},p7=class extends Rr()(`effect/http-api/HttpApi/ErrorParseOptions`){},m7=e=>{let t=si(e,s7);return{params:si(e,c7)??t,query:si(e,l7)??t,headers:si(e,u7)??t,payload:si(e,d7)??t,success:si(e,f7)??t,error:si(e,p7)??t}},h7=`~effect/http-api/HttpApiMiddleware`,g7=`~effect/http-api/HttpApiMiddleware/Security`,_7=()=>(e,t)=>{let n=St(),r;n!==0&&(Ct(2),r=new globalThis.Error,Ct(n));class i extends Rr()(e){}let a=i;if(Object.defineProperty(i,"stack",{get(){return r?.stack}}),a[h7]=h7,a.error=v7(t?.error),a.requiredForClient=t?.requiredForClient??!1,t?.security!==void 0){if(Object.keys(t.security).length===0)throw Error(`HttpApiMiddleware.Service: security object must not be empty`);a[g7]=g7,a.security=t.security}return a};function v7(e){return e===void 0?new Set:new Set(Array.isArray(e)?e:[e])}var y7=new Set;function b7(e){if(e===void 0)return y7;let t=xS(e.ast);return Qb(t)&&t.indexSignatures.length===0?new Set(t.propertySignatures.map(e=>String(e.name))):void 0}function x7(e,t,n){let r=/::|:(\w+)/g,i=``,a=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let s=o[1];if(s===void 0||t!==void 0&&!t.has(s))continue;let c=r.lastIndex;e[c]===`(`&&(c=tG(e,c)+1);let l=e[c]===`?`;l&&c++;let u=n(s,l),d=o.index;u===void 0&&e[d-1]===`/`&&d--,i+=e.slice(a,d)+(u??``),r.lastIndex=c,a=c}return i+e.slice(a)}var S7=(e,t)=>T(function*(){let n=yield*Cg(),r=t.httpClient.pipe(t?.baseUrl===void 0?i:UW(mW(t.baseUrl.toString())));function a(e,t,i,o,s){if(s===-1)return r.execute(i);let c=n.mapUnsafe.get(o[s]);return c===void 0?a(e,t,i,o,s-1):c({endpoint:t,group:e,request:i,next(n){return a(e,t,n,o,s-1)}})}a7(e,{predicate:t?.predicate,onGroup(e){t.onGroup?.(e)},onEndpoint(e){let{group:n,endpoint:r,errors:i,successes:o,mergedAnnotations:s}=e,c=m7(s),l=T7(r.path,r.params),u={orElse:Y7},d=new Map;for(let[e,t]of i.entries()){let n=j7(t);for(let[t,r]of n.entries())k7(d,e,t,E7(r,c.error,c.headers))}for(let[e,t]of d.entries()){let n=A7(t);u[e]=e=>E(lg(n(e),t=>Wh(ef(qd(new RU({reason:new WU({request:e.request,response:e})})),t))),Uh)}let f=new Map;for(let[e,t]of o.entries()){let n=j7(t);for(let[t,r]of n.entries())k7(f,e,t,E7(r,c.success,c.headers))}for(let e of I7(r)){let t=P7(e)?e.schema:e;k7(f,x5(e),t.contentType,L7(e,c.success,c.headers))}for(let[e,t]of f.entries())u[e]=A7(t);let p=F7(r);p!==void 0&&(u[101]=e=>ng(e.upgrade,t=>({headers:e.headers,socket:t})));let m=Uk(r.params,e=>qw(e,c.params)),h=[],g;for(let e of D5(r))Z8(e)||Q8(e)?g=e:h.push(e);let _=Uk(g,e=>({contentType:e.contentType,encode:Z7(e,c.payload)})),v=Yi(h)?qw(qU(r.method)?Q7(h,r.method):P(h),c.payload):void 0,ee=Uk(r.headers,e=>qw(e,c.headers)),te=Uk(r.query,e=>qw(e,c.query)),ne=Array.from(e.middleware,e=>`${e.key}/Client`),re=$g(function*(e){let i=rW(r.method)(r.path);if(e!==void 0){if(m!==void 0){let t=yield*m(e.params);i=pW(i,l(t))}if(_!==void 0&&EO(e.payload)){let t=yield*Cg();i=yW(i,IU(GO(_.encode(e.payload),t),_.contentType))}else if(v!==void 0){if(qU(r.method)){if(e.payload instanceof FormData)i=xW(i,e.payload);else{let t=yield*v(e.payload);i=yW(i,t)}}else{let t=yield*v(e.payload);i=_W(i,t)}}else if(_!==void 0)return yield*new Pw(new My({message:`Expected a Stream payload`},e.payload));if(ee!==void 0){let t=yield*ee(e.headers);i=lW(i,t)}if(te!==void 0){let t=yield*te(e.query);i=_W(i,t)}}p!==void 0&&(i=fW(i,p.protocol));let o=yield*a(n,r,i,ne,ne.length-1);if(e?.responseMode===`response-only`)return o;let s=(u[o.status]??u.orElse)(o,e?.sseOptions),c=yield*t.transformResponse===void 0?s:t.transformResponse(s);return e?.responseMode===`decoded-and-response`?[c,o]:c});t.onEndpoint({...e,endpointFn:re})}})}),C7=(e,t)=>E(LW,n=>w7(e,{...t,httpClient:t?.transformClient?t.transformClient(n):n})),w7=(e,t)=>{let n={};return S7(e,{...t,onGroup({group:e}){e.topLevel||Et(n,e.identifier,{})},onEndpoint({endpoint:e,endpointFn:t,group:r}){Et(r.topLevel?n:n[r.identifier],e.identifier,t)}}).pipe(rg(n))},T7=(e,t)=>{if(t===void 0||!e.includes(`:`))return t=>e;let n=b7(t);return t=>x7(e,n,(e,n)=>{let r=t[e];if(r!==void 0)return encodeURIComponent(r);if(!n)throw Error(`Missing path parameter: ${e}`)})};function E7(e,t,n){let r=e.some(e=>i5(e)||d5(e.ast)!==void 0),i=Hw(r?P(e.map(e=>O7(e,t,n))):q7(e),t);return e=>E(e.arrayBuffer,r?t=>i({body:t,headers:e.headers}):i)}var D7=M({body:aT,headers:aT});function O7(e,t,n){let r=d5(e.ast),i=r===void 0?i5(e)?{body:e.schema,headers:e.headers,toValue:r5}:{body:e,headers:aT,toValue:e=>e.body}:{body:r.bodyCodec,headers:r.headersCodec,toValue:r.transformation.decode},a=Hw(J7(i.body).pipe(ST(i.body)),t),o=Hw(i.headers,n);return D7.pipe(ST(i5(e)?e:tT(e),Tb({decode:e=>Nh({body:a(e.body),headers:o(e.headers)}).pipe(ng(i.toValue),dg(e=>e.issue)),encode:(e,t)=>Uh(new Py({message:`Decode only schema`},e,t))})))}function k7(e,t,n,r){let i=T5(n),a=e.get(t);a===void 0?e.set(t,[{contentType:i,decode:r}]):a.push({contentType:i,decode:r})}function A7(e){let t=e[0];return e.length===1&&t!==void 0?t.decode:(t,n)=>{let r=T5(t.headers[`content-type`]??``),i=e.find(e=>e.contentType===r);return i===void 0?M7(t,r,e):i.decode(t,n)}}function j7(e){let t=new Map;for(let n of e){let e=l5((i5(n)?n.schema:n).ast)?``:T5(S5(n).contentType),r=t.get(e);r===void 0?t.set(e,[n]):r.push(n)}return t}function M7(e,t,n){let r=Array.from(new Set(n.map(e=>e.contentType))).join(`, `);return Uh(new RU({reason:new GU({request:e.request,response:e,description:`Unsupported response content-type for status ${e.status}: ${t||`<missing>`}. Expected one of: ${r}`})}))}var N7=`effect/http-api/stream/failure`,P7=e=>i5(e);function F7(e){for(let t of e.success)if(e5(t))return t}function I7(e){let t=[];for(let n of e.success)Y8(i5(n)?n.schema:n)&&t.push(n);return t}function L7(e,t,n){let r=P7(e),i=R7(r?e.schema:e,t),a=(e,t)=>ng(Cg(),n=>GO(i(e,t),n));if(!r)return a;let o=Hw(e.headers,n);return(e,t)=>E(o(e.headers),n=>ng(a(e,t),e=>r5({body:e,headers:n})))}function R7(e,t){if(Z8(e))return e=>e.stream;if(Q8(e)){let n=Hw(PE(e.schema),t),r=P_(e.maxElementBytes);return e=>e.stream.pipe(VO(pR({ignoreEmptyLines:!0,maxLineBytes:r})),BO(t=>aR(t)?t.reason===`LineTooLarge`?new RU({reason:new GU({request:e.request,response:e,description:`NDJSON line exceeds maxElementBytes of ${r} bytes`})}):B7(t):t),IO(e=>n(e)))}let n=V7(e,t);return(t,r)=>H7(t.stream,e,n(r))}var z7=e=>aR(e)&&e.kind===`Pack`,B7=e=>new Pw(new My({message:e.reason===`InvalidUtf8`?`Expected valid UTF-8`:e.unterminated?`Expected a valid JSON line, got an unterminated final line`:`Expected a valid JSON line`}));function V7(e,t){let n=P([M({id:eT(j),event:rT(N7),data:aE(PE(dE(e.error,eE())))}),e.events]),r=yR(n,void 0,t);return e=>e===void 0?r:yR(n,e,t)}function H7(e,t,n){let r=OO(e.pipe(HO,VO(n)),e=>zh(()=>{let t;return Rh(()=>t===void 0?E(e,e=>{for(let n=0;n<e.length;n++){let r=e[n];if(r.event===N7&&Ud(r.data)){if(n===0)return Wh(r.data);t=r.data,e=e.slice(0,n);break}}return w(e)}):Wh(t))}));return t.sseMode===`data`?FO(r,e=>e.data):r}var U7=jT(globalThis.ArrayBuffer,{expected:`ArrayBuffer`}),W7=U7.pipe(ST(lE,Eb({decode(e){return new Uint8Array(e)},encode(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}}))),G7=U7.pipe(ST(j,Eb({decode(e){return new TextDecoder().decode(e)},encode(e){let t=new TextEncoder().encode(e);return t.byteLength===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}))),K7=G7.pipe(ST(P([rT(``).pipe(ST(sT,Eb({decode:()=>void 0,encode:()=>``}))),oE])));function q7(e){return P(e.map(t));function t(e){return J7(e).pipe(ST(e))}}function J7(e){switch(y5(e.ast)._tag){case`Json`:return Kb(GS(e.ast))?K7.pipe(ST(aT,Eb({decode:e=>e===void 0?null:e,encode:e=>e===null?void 0:e}))):K7;case`FormUrlEncoded`:return G7.pipe(ST(bE,Eb({decode:e=>Vv(new URLSearchParams(e)),encode:Xv})));case`Uint8Array`:return W7;case`Text`:return G7}}var Y7=e=>Uh(new RU({reason:new GU({request:e.request,response:e})})),X7=Nw(SU);function Z7(e,t){if(Z8(e))return e=>e;let n=qw(yT(PE(e.schema)),t);return e=>e.pipe(LO(e=>n(e)),VO(sR()),zO(z7,NO))}function Q7(e,t){return P(e.map(e=>e9(e,t)))}var $7=new WeakMap;function e9(e,t){let n=e.ast,r=$7.get(n);if(r!==void 0)return r;let i=v5(n,t),a=X7.pipe(ST(e,Tb({decode(e,t){return Uh(new Py({message:`Encode only schema`},e,t))},encode(e,t){switch(i._tag){case`Multipart`:return Uh(new Py({message:`Payload must be a FormData`},e,t));case`Json`:try{return w(AU(JSON.stringify(e),i.contentType))}catch{return Uh(new My({expected:`a JSON-serializable request body`},e,t))}case`Text`:return typeof e==`string`?w(AU(e,i.contentType)):Uh(new My({message:`Expected a string`},e,t));case`FormUrlEncoded`:return de(e)?w(MU(Vv(e),i.contentType)):Uh(new My({message:`Expected a record`},e,t));case`Uint8Array`:return e instanceof Uint8Array?w(EU(e,i.contentType)):Uh(new My({message:`Expected a Uint8Array`},e,t))}}})));return $7.set(n,a),a}var t9=`~effect/http-api/HttpApiGroup`,n9={[t9]:t9,add(...e){let t={...this.endpoints};for(let n of e)Et(t,n.identifier,n);return i9({...r9(this),endpoints:t})},prefix(e){return i9({...r9(this),endpoints:zi(this.endpoints,t=>t.prefix(e))})},middleware(e){return i9({...r9(this),endpoints:zi(this.endpoints,t=>t.middleware(e))})},annotateMerge(e){return i9({...r9(this),annotations:hi(this.annotations,e)})},annotate(e,t){return i9({...r9(this),annotations:ai(this.annotations,e,t)})},annotateEndpointsMerge(e){return i9({...r9(this),endpoints:zi(this.endpoints,t=>t.annotateMerge(e))})},annotateEndpoints(e,t){return i9({...r9(this),endpoints:zi(this.endpoints,n=>n.annotate(e,t))})},pipe(){return e(this,arguments)}},r9=e=>({identifier:e.identifier,topLevel:e.topLevel,endpoints:e.endpoints,annotations:e.annotations}),i9=e=>{function t(){}return Object.setPrototypeOf(t,n9),t.key=`effect/http-api/HttpApiGroup/${e.identifier}`,Object.assign(t,e)},a9=(e,t)=>i9({identifier:e,topLevel:t?.topLevel??!1,endpoints:{},annotations:ni()}),o9={UpgradeError:409,ConfigurationNotFound:404,ConfigurationStoreError:500,SchemaError:400,InvalidRequestError:400,CrossSiteRequestError:403,RunNotFoundError:404,TranscriptAttemptNotFoundError:404,BoardProjectNotFoundError:404,BoardItemNotFoundError:404,BoardLaneNotFoundError:404,GitHubItemNotFoundError:404,RunOperationRejectedError:409,RunRetryBlockedError:409,RunInterventionRejectedError:409,LeftoversDiscardRejectedError:409,RosterAgentNotFoundError:404,LoopNotFoundError:404,CycleBudgetResetRejectedError:409,BoardLaneReadOnlyError:409,RestartRequiredError:409,ReloadPreflightError:409,FactoryConfigError:422,EnginePersistenceError:500,AttemptCancellationError:500,HttpBodyError:500,GitHubApiError:502,InvalidGitHubResponseError:502,BackendUnavailableError:503,InstallationDiscoveryError:503,AppPermissionError:503,GitHubRateLimitError:503},s9=class extends ME(`@usine/orchestrator/OperatorHttpError`)({error:F(Bi(o9)),message:j}){get status(){return o9[this.error]}},c9=[...new Set(Object.values(o9))].map(e=>s9.check(NT(t=>t.status===e)).annotate({httpApiStatus:e})),l9=class extends _7()(`@usine/orchestrator/OperatorHttpPolicy`,{error:c9}){},u9=P([AT(`WorkerCapabilityError`,{worker:EN,capability:Jz,message:j}),AT(`ExecutorOperationError`,{operation:qz,message:j}),AT(`CredentialUnavailableError`,{repository:Xk,message:j})]),d9=class extends ME(`@usine/orchestrator/RestartRequiredRefusal`)({error:rT(`RestartRequiredError`),message:j,blocks:yT(P8),fields:yT(z)},{httpApiStatus:409}){},f9=class extends ME(`@usine/orchestrator/ReloadPreflightRefusal`)({error:rT(`ReloadPreflightError`),message:j,agents:N(fN),workers:N(EN),cause:u9},{httpApiStatus:409}){},p9=class extends ME(`@usine/orchestrator/FactoryConfigRefusal`)({error:rT(`FactoryConfigError`),message:j,file:tU,stage:nU},{httpApiStatus:422}){},m9=class extends ME(`StaleRevisionRefusal`)({error:rT(`StaleRevision`),message:j,expected:D8,current:D8},{httpApiStatus:409}){},h9=class extends ME(`ConfigurationInvalidRefusal`)({error:rT(`ConfigurationInvalid`),message:j,problems:yT(M({entity:A8,path:N(P([j,cT])),message:j}))},{httpApiStatus:422}){},g9=class extends ME(`ConfigurationRevertRefusal`)({error:rT(`ConfigurationRevertBlocked`),message:j,entities:yT(A8)},{httpApiStatus:409}){},_9=[m9,h9,g9,d9,f9,p9],v9={number:sE.pipe(ST(D8))},y9=I8.fields,b9=$w(iT),x9=P([j,yT(j).pipe(ST(j,Eb({decode:e=>e[0],encode:e=>[e]})))]),S9=x9.pipe(ST(sE),ST(pB)),C9=P([M({after:b9,before:b9,attempt:b9}).pipe(ST(tT(AB),Eb({decode:()=>new AB,encode:()=>({})}))),M({after:S9,before:b9,attempt:b9}).pipe(ST(tT(jB),Eb({decode:({after:e})=>new jB({after:e}),encode:({after:e})=>({after:e})}))),M({after:b9,before:S9,attempt:x9.pipe(ST(sF))}).pipe(ST(tT(MB),Eb({decode:({before:e,attempt:t})=>new MB({before:e,attemptId:t}),encode:({before:e,attemptId:t})=>({before:e,attempt:t})})))]),w9=j.check(PT(/^[A-Za-z0-9_.-]+$/u,{message:`Expected a repository path segment`})),T9=M({ok:rT(!0)}),E9={runId:HA},D9={loop:aA},O9=M({window:x9.pipe(ST(X6),DT(w(`30d`)))}),k9=i7(`OperatorApi`).add(a9(`operator`).add(X5(`upgradeStatus`,`/api/upgrade`,{success:G8}),X5(`serverVersion`,`/api/version`,{success:j}),Z5(`requestUpgrade`,`/api/upgrade`,{payload:W8,success:T9}),X5(`overview`,`/api/overview`,{success:y4}),Z5(`dismissNeed`,`/api/attention/dismiss`,{payload:sN,success:T9}),Z5(`undoDismissNeed`,`/api/attention/undo`,{payload:sN,success:T9}),X5(`agents`,`/api/agents`,{success:N(fN)}),Z5(`editAndRetry`,`/api/runs/:runId/edit-and-retry`,{params:E9,payload:bH,success:T9}),Z5(`runAgain`,`/api/runs/:runId/run-again`,{params:E9,payload:bH,success:h1}),Z5(`intervene`,`/api/runs/:runId/intervene`,{params:E9,payload:xH,success:T9}),Z5(`resetCycleBudget`,`/api/cycle-budgets/reset`,{payload:M({askId:lI}),success:T9}),X5(`detail`,`/api/runs/:runId`,{params:E9,query:C9,success:OH}),X5(`githubChanges`,`/api/runs/:runId/github-changes`,{params:E9,success:h3}),Z5(`approve`,`/api/runs/:runId/approve`,{params:E9,success:T9}),Z5(`resolveFailure`,`/api/runs/:runId/resolve-failure`,{params:E9,payload:M({attemptId:sF}),success:T9}),Z5(`retry`,`/api/runs/:runId/retry`,{params:E9,success:T9}),Z5(`cancel`,`/api/runs/:runId/cancel`,{params:E9,success:T9}),Z5(`moveBoardItem`,`/api/projects/:owner/:repository/items/:item/lane`,{params:{owner:w9,repository:w9,item:sE.pipe(ST(rI))},payload:M({toLane:kH}),success:T9}),Z5(`discardLeftovers`,`/api/workers/:worker/discard-leftovers`,{params:{worker:EN},success:T9}),Z5(`pause`,`/api/loops/:loop/pause`,{params:D9,success:T9}),Z5(`unpause`,`/api/loops/:loop/unpause`,{params:D9,success:T9})).add(X5(`task`,`/api/projects/:owner/:repository/tasks/:item`,{params:{owner:w9,repository:w9,item:sE.pipe(ST(rI))},success:j3})).add(X5(`configurationCapabilities`,`/api/configuration/capabilities`,{success:M({harnesses:N(lN),efforts:N(uN)})}),X5(`configurationRepositories`,`/api/configuration/repositories`,{success:N(Xk)}),X5(`configurationLabels`,`/api/configuration/labels/:repository`,{params:{repository:Xk},success:N(IK)}),X5(`configurationRevisions`,`/api/configuration/revisions`,{query:M({kind:$w(x9),identifier:$w(x9.pipe(ST(k8))),before:$w(x9.pipe(ST(sE),ST(D8))),limit:x9.pipe(ST(sE),ST(L8.fields.limit),DT(w(`50`)))}),success:H8,error:_9}),X5(`configurationRevision`,`/api/configuration/revisions/:number`,{params:v9,success:U8,error:_9}),X5(`configurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:y9,success:B8,error:_9}),Q5(`replaceConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:y9,payload:z8,success:U8,error:_9}),$5(`deleteConfigurationEntity`,`/api/configuration/entities/:kind/:identifier`,{params:y9,payload:R8,success:U8,error:_9}),Z5(`revertConfigurationRevision`,`/api/configuration/revisions/:number/revert`,{params:v9,payload:R8,success:U8,error:_9})).add(X5(`configuration`,`/api/configuration`,{success:s6})).add(X5(`desk`,`/api/desk`,{success:P6})).add(X5(`statistics`,`/api/statistics`,{query:O9,success:o8}),X5(`runStatistics`,`/api/statistics/runs`,{query:O9,success:S8})).annotate(d7,{onExcessProperty:`error`}).middleware(l9)),A9=()=>C7(k9,{baseUrl:globalThis.location.origin}),j9=e=>Xg(E(A9(),t=>e(t.operator)).pipe(kg(KW,!1),Tg(eG))),M9=e=>e instanceof Error?e.message:String(e),N9=e=>`${e.harness} · ${e.model} · ${e.effort}`,P9=e=>{switch(e){case`issue`:return`Issue`;case`pr`:return`PR`;case`schedule`:return`Schedule`;default:return e}},F9=(e,t=Date.now())=>{let n=Math.max(0,t-Date.parse(e));return n<6e4?`now`:n<36e5?`${Math.floor(n/6e4)}m`:n<864e5?`${Math.floor(n/36e5)}h`:`${Math.floor(n/864e5)}d`},I9=(e,t)=>{let n=F9(e,t);return n===`now`?`just now`:`${n} ago`},L9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`},R9=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],z9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getDate()} ${R9[t.getMonth()]} ${n(t.getHours())}:${n(t.getMinutes())}`},B9=e=>`${e.getDate()} ${R9[e.getMonth()]}`,V9=e=>{let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`},H9=e=>{let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.round(t/60);return n<60?`${n} min`:n%60==0?`${Math.floor(n/60)} h`:`${Math.floor(n/60)} h ${n%60} min`},U9=e=>new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}).format(e),W9=e=>e>0&&e<.005?`under $0.01`:`$${e.toFixed(2)}`,G9=e=>({claude:`Claude Code`,codex:`Codex`,pi:`Pi`})[e],K9=e=>({apiKeys:`API keys`,claudePlan:`Claude plan`,chatgptPlan:`ChatGPT plan`})[e],q9=e=>e%1440==0?`${e/1440}-day`:e%60==0?`${e/60}-hour`:`${e}-minute`,J9=`Loading…`,Y9=`Could not load the page`,X9=`Try again`;export{FH as $,JT as $t,v4 as A,Nr as An,lT as At,ZJ as B,y as Bn,j as Bt,m9 as C,ga as Cn,oN as Ct,k8 as D,Oi as Dn,eA as Dt,j8 as E,Di as En,Xk as Et,W$ as F,Tr as Fn,rT as Ft,Xq as G,Hw as Gt,RJ as H,b as Hn,P as Ht,G$ as I,x as In,F as It,rU as J,aE as Jt,Zq as K,Ww as Kt,n1 as L,S as Ln,I as Lt,_4 as M,Sr as Mn,R as Mt,p4 as N,yr as Nn,IE as Nt,A8 as O,jr as On,kk as Ot,c2 as P,C as Pn,LE as Pt,IH as Q,HT as Qt,P$ as R,Or as Rn,cT as Rt,s9 as S,Wg as Sn,sN as St,R8 as T,Bi as Tn,AA as Tt,kJ as U,Mr as Un,Gw as Ut,uJ as V,br as Vn,M as Vt,FJ as W,ST as Wt,NH as X,UT as Xt,tU as Y,Vw as Yt,zH as Z,IT as Zt,q9 as _,$h as _n,GN as _t,z9 as a,J_ as an,jB as at,h9 as b,w as bn,fN as bt,G9 as c,K_ as cn,Cz as ct,K9 as d,og as dn,UF as dt,GT as en,bH as et,L9 as f,Uh as fn,IF as ft,W9 as g,dg as gn,lF as gt,X9 as h,ng as hn,zF as ht,B9 as i,Bw as in,MB as it,h4 as j,kr as jn,sE as jt,N8 as k,Ir as kn,N as kt,J9 as l,rg as ln,fz as lt,P9 as m,e_ as mn,HF as mt,N9 as n,$w as nn,xH as nt,H9 as o,G_ as on,pB as ot,U9 as p,E as pn,RF as pt,Jq as q,Xw as qt,V9 as r,PE as rn,AB as rt,F9 as s,W_ as sn,bz as st,I9 as t,eT as tn,OH as tt,Y9 as u,sg as un,rI as ut,j9 as v,Xg as vn,KN as vt,W8 as w,Xi as wn,HA as wt,g9 as x,qh as xn,uN as xt,M9 as y,Zg as yn,JN as yt,N$ as z,vr as zn,hT as zt};